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
1,322 changes: 630 additions & 692 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions collator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ pub fn run_collator<P, E>(
mod tests {
use std::collections::HashMap;
use polkadot_primitives::parachain::{OutgoingMessage, FeeSchedule};
use keyring::AuthorityKeyring;
use keyring::Ed25519Keyring;
use super::*;

#[derive(Default, Clone)]
Expand Down Expand Up @@ -540,7 +540,7 @@ mod tests {
},
context.clone(),
DummyParachainContext,
AuthorityKeyring::Alice.pair().into(),
Ed25519Keyring::Alice.pair().into(),
).wait().unwrap();

// ascending order by root.
Expand Down
6 changes: 3 additions & 3 deletions network/src/tests/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::gossip::GossipMessage;
use substrate_network::Context as NetContext;
use substrate_network::consensus_gossip::TopicNotification;
use substrate_primitives::{NativeOrEncoded, ExecutionContext};
use substrate_keyring::AuthorityKeyring;
use substrate_keyring::Ed25519Keyring;
use crate::PolkadotProtocol;

use polkadot_validation::{SharedTable, MessagesFrom, Network};
Expand Down Expand Up @@ -399,8 +399,8 @@ impl IngressBuilder {
}
}

fn make_table(data: &ApiData, local_key: &AuthorityKeyring, parent_hash: Hash) -> Arc<SharedTable> {
use ::av_store::Store;
fn make_table(data: &ApiData, local_key: &Ed25519Keyring, parent_hash: Hash) -> Arc<SharedTable> {
use av_store::Store;

let store = Store::new_in_memory();
let (group_info, _) = ::polkadot_validation::make_group_info(
Expand Down
16 changes: 2 additions & 14 deletions primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,7 @@

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

#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};

use rstd::prelude::*;
use runtime_primitives::{generic, traits::Extrinsic, AnySignature};
use parity_codec::{Encode, Decode};
use runtime_primitives::{generic, AnySignature};
use primitives::ed25519;

pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT, Verify};
Expand All @@ -34,9 +29,6 @@ pub mod parachain;

pub use parity_codec::Compact;

#[cfg(feature = "std")]
use primitives::bytes;

/// An index to a block.
/// 32-bits will allow for 136 years of blocks assuming 1 block per second.
/// TODO: switch to u32 (https://github.com/paritytech/polkadot/issues/221)
Expand Down Expand Up @@ -92,8 +84,4 @@ pub type Block = generic::Block<Header, UncheckedExtrinsic>;
pub type BlockId = generic::BlockId<Block>;

/// Opaque, encoded, unchecked extrinsic.
#[derive(PartialEq, Eq, Clone, Default, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct UncheckedExtrinsic(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);

impl Extrinsic for UncheckedExtrinsic {}
pub use runtime_primitives::OpaqueExtrinsic as UncheckedExtrinsic;
28 changes: 19 additions & 9 deletions runtime/src/claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@ use system::ensure_none;
use parity_codec::{Encode, Decode};
#[cfg(feature = "std")]
use sr_primitives::traits::Zero;
use sr_primitives::traits::ValidateUnsigned;
use sr_primitives::transaction_validity::{TransactionLongevity, TransactionValidity};
use sr_primitives::{
weights::SimpleDispatchInfo,
traits::ValidateUnsigned,
transaction_validity::{TransactionLongevity, TransactionValidity, ValidTransaction},
};
use system;

type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
Expand Down Expand Up @@ -97,6 +100,7 @@ decl_module! {
fn deposit_event<T>() = default;

/// Make a claim.
#[weight = SimpleDispatchInfo::FixedNormal(1_000_000)]
fn claim(origin, dest: T::AccountId, ethereum_signature: EcdsaSignature) {
ensure_none(origin)?;

Expand Down Expand Up @@ -171,13 +175,13 @@ impl<T: Trait> ValidateUnsigned for Module<T> {
return TransactionValidity::Invalid(SIGNER_HAS_NO_CLAIM);
}

TransactionValidity::Valid {
TransactionValidity::Valid(ValidTransaction {
priority: PRIORITY,
requires: vec![],
provides: vec![],
longevity: TransactionLongevity::max_value(),
propagate: true,
}
})
}
_ => TransactionValidity::Invalid(INVALID_CALL)
}
Expand All @@ -196,9 +200,7 @@ mod tests {
use parity_codec::{Decode, Encode};
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
use sr_primitives::{
traits::{BlakeTwo256, IdentityLookup}, testing::Header
};
use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup, ConvertInto}, testing::Header};
use balances;
use srml_support::{impl_outer_origin, assert_ok, assert_err, assert_noop, parameter_types};

Expand All @@ -213,6 +215,9 @@ mod tests {
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 4 * 1024 * 1024;
pub const MaximumBlockLength: u32 = 4 * 1024 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
}
impl system::Trait for Test {
type Origin = Origin;
Expand All @@ -222,9 +227,13 @@ mod tests {
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<u64>;
type WeightMultiplierUpdate = ();
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
}

parameter_types! {
Expand All @@ -248,6 +257,7 @@ mod tests {
type CreationFee = CreationFee;
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = ConvertInto;
}

parameter_types!{
Expand Down Expand Up @@ -369,13 +379,13 @@ mod tests {
with_externalities(&mut new_test_ext(), || {
assert_eq!(
<Module<Test>>::validate_unsigned(&Call::claim(1, alice_sig(&1u64.encode()))),
TransactionValidity::Valid {
TransactionValidity::Valid(ValidTransaction {
priority: 100,
requires: vec![],
provides: vec![],
longevity: TransactionLongevity::max_value(),
propagate: true,
}
})
);
assert_eq!(
<Module<Test>>::validate_unsigned(&Call::claim(0, EcdsaSignature::from_blob(&[0; 65]))),
Expand Down
41 changes: 41 additions & 0 deletions runtime/src/constants.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.

/// Money matters.
pub mod currency {
use primitives::Balance;

pub const DOTS: Balance = 1_000_000_000_000;
pub const BUCKS: Balance = DOTS / 100;
pub const CENTS: Balance = BUCKS / 100;
pub const MILLICENTS: Balance = CENTS / 1_000;
}

/// Time.
pub mod time {
pub const SECS_PER_BLOCK: u64 = 6;
pub const MINUTES: u64 = 60 / SECS_PER_BLOCK;
pub const HOURS: u64 = MINUTES * 60;
pub const DAYS: u64 = HOURS * 24;
}

/// Fee-related.
pub mod fee {
pub use sr_primitives::Perbill;

/// The block saturation level. Fees will be updates based on this value.
pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25);
}
2 changes: 2 additions & 0 deletions runtime/src/curated_grandpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use {grandpa, system};
use parity_codec::Decode;
use sr_primitives::traits::{Hash as HashT, BlakeTwo256, Zero};
use sr_primitives::weights::SimpleDispatchInfo;
use rstd::prelude::*;
use srml_support::{decl_storage, decl_module};

Expand All @@ -37,6 +38,7 @@ decl_module! {
/// curated GRANDPA set.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// Changes the GRANDPA voter set.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn set_voters(origin, voters: Vec<(grandpa::AuthorityId, u64)>) {
system::ensure_root(origin)?;
grandpa::Module::<T>::schedule_change(voters, T::BlockNumber::zero(), None)?;
Expand Down
128 changes: 128 additions & 0 deletions runtime/src/impls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.

//! Auxillary struct/enums for polkadot runtime.

use primitives::Balance;
use sr_primitives::weights::{Weight, WeightMultiplier};
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;

/// Logic for the author to get a portion of fees.
pub struct ToAuthor;

impl OnUnbalanced<NegativeImbalance> for ToAuthor {
fn on_unbalanced(amount: NegativeImbalance) {
Balances::resolve_creating(&Authorship::author(), amount);
}
}

/// Converter for currencies to votes.
pub struct CurrencyToVoteHandler;

impl CurrencyToVoteHandler {
fn factor() -> u128 { (Balances::total_issuance() / u64::max_value() as u128).max(1) }
}

impl Convert<u128, u64> for CurrencyToVoteHandler {
fn convert(x: u128) -> u64 { (x / Self::factor()) as u64 }
}

impl Convert<u128, u128> for CurrencyToVoteHandler {
fn convert(x: u128) -> u128 { x * Self::factor() }
}

/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
/// node's balance type.
///
/// This should typically create a mapping between the following ranges:
/// - [0, system::MaximumBlockWeight]
/// - [Balance::min, Balance::max]
///
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
/// - Setting it to `0` will essentially disable the weight fee.
/// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
pub struct WeightToFee;
impl Convert<Weight, Balance> for WeightToFee {
fn convert(x: Weight) -> Balance {
// in Polkadot a weight of 10_000 (smallest non-zero weight) to be mapped to 10^7 units of
// fees (1/10 CENT), hence:
Balance::from(x).saturating_mul(1_000)
}
}

/// A struct that updates the weight multiplier based on the saturation level of the previous block.
/// This should typically be called once per-block.
///
/// 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)
/// v = 0.00004
/// next_weight = weight * (1 + (v . diff) + (v . diff)^2 / 2)
///
/// https://research.web3.foundation/en/latest/polkadot/Token%20Economics/#relay-chain-transaction-fees
pub struct WeightMultiplierUpdateHandler;

impl Convert<(Weight, WeightMultiplier), WeightMultiplier> for WeightMultiplierUpdateHandler {
fn convert(previous_state: (Weight, WeightMultiplier)) -> WeightMultiplier {
let (block_weight, multiplier) = previous_state;
let max_weight = MaximumBlockWeight::get();
let target_weight = (TARGET_BLOCK_FULLNESS * max_weight) as u128;
let block_weight = block_weight as u128;

// determines if the first_term is positive
let positive = block_weight >= target_weight;
let diff_abs = block_weight.max(target_weight) - block_weight.min(target_weight);
// diff is within u32, safe.
let diff = Fixed64::from_rational(diff_abs as i64, max_weight as u64);
let diff_squared = diff.saturating_mul(diff);

// 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.
let v_squared_2 = Fixed64::from_rational(1, 1_000_000_000);

let first_term = v.saturating_mul(diff);
// It is very unlikely that this will exist (in our poor perbill estimate) but we are giving
// it a shot.
let second_term = v_squared_2.saturating_mul(diff_squared);

if positive {
// Note: this is merely bounded by how big the multiplier and the inner value can go,
// not by any economical reasoning.
let excess = first_term.saturating_add(second_term);
multiplier.saturating_add(WeightMultiplier::from_fixed(excess))
} else {
// first_term > second_term
let negative = first_term - second_term;
multiplier.saturating_sub(WeightMultiplier::from_fixed(negative))
// despite the fact that apply_to saturates weight (final fee cannot go below 0)
// it is crucially important to stop here and don't further reduce the weight fee
// multiplier. While at -1, it means that the network is so un-congested that all
// transactions have no weight fee. We stop here and only increase if the network
// became more busy.
.max(WeightMultiplier::from_rational(-1, 1))
}
}
}
Loading