Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 88 additions & 86 deletions Cargo.lock

Large diffs are not rendered by default.

20 changes: 12 additions & 8 deletions primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@

#![cfg_attr(not(feature = "std"), no_std)]

use runtime_primitives::{generic, AnySignature};

pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT, Verify};
use runtime_primitives::{generic, MultiSignature};
pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT, Verify, IdentifyAccount};

pub mod parachain;

Expand All @@ -35,12 +34,17 @@ pub type BlockNumber = u32;
/// An instant or duration in time.
pub type Moment = u64;

/// Alias to 512-bit hash when used in the context of a signature on the relay chain.
/// Equipped with logic for possibly "unsigned" messages.
pub type Signature = AnySignature;
/// Alias to type for a signature for a transaction on the relay chain. This allows one of several
/// kinds of underlying crypto to be used, so isn't a fixed size when encoded.
pub type Signature = MultiSignature;

/// Alias to the public key used for this chain, actually a `MultiSigner`. Like the signature, this
/// also isn't a fixed size when encoded, as different cryptos have different size public keys.
pub type AccountPublic = <Signature as Verify>::Signer;

/// Alias to an sr25519 or ed25519 key.
pub type AccountId = <Signature as Verify>::Signer;
/// Alias to the opaque account ID type for this chain, actually a `AccountId32`. This is always
/// 32 bytes.
pub type AccountId = <AccountPublic as IdentifyAccount>::AccountId;

/// The type for looking up accounts. We don't expect more than 4 billion of them.
pub type AccountIndex = u32;
Expand Down
4 changes: 2 additions & 2 deletions runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ balances = { package = "srml-balances", git = "https://github.com/paritytech/sub
transaction-payment = { package = "srml-transaction-payment", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
collective = { package = "srml-collective", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
democracy = { package = "srml-democracy", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
elections = { package = "srml-elections", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
elections-phragmen = { package = "srml-elections-phragmen", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
executive = { package = "srml-executive", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
finality-tracker = { package = "srml-finality-tracker", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
grandpa = { package = "srml-grandpa", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
Expand Down Expand Up @@ -92,7 +92,7 @@ std = [
"balances/std",
"transaction-payment/std",
"collective/std",
"elections/std",
"elections-phragmen/std",
"democracy/std",
"executive/std",
"finality-tracker/std",
Expand Down
33 changes: 13 additions & 20 deletions runtime/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand Down
90 changes: 22 additions & 68 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,14 @@ 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;
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;

Expand All @@ -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;
Expand Down Expand Up @@ -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()),
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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! {
Expand Down Expand Up @@ -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)]
Expand All @@ -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`.
Expand Down Expand Up @@ -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;
}

impl elections::Trait for Runtime {
pub const CandidacyBond: Balance = 100 * DOLLARS;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just pointing out the price bump here; I assume it is intentional;

pub const VotingBond: Balance = 5 * DOLLARS;
}

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;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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>},

Expand Down Expand Up @@ -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"));
Expand Down
Loading