lib.rs 9.86 KB
Newer Older
1
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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/>.

//! Common runtime code for Polkadot and Kusama.

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

21
pub mod auctions;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
22
pub mod claims;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
23
pub mod crowdloan;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
24
pub mod elections;
25
pub mod impls;
26
pub mod paras_registrar;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
27
28
pub mod paras_sudo_wrapper;
pub mod purchase;
29
pub mod slot_range;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
30
pub mod slots;
31
pub mod traits;
32
33
pub mod xcm_sender;

34
35
#[cfg(test)]
mod integration_tests;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
36
37
#[cfg(test)]
mod mock;
38

Shawn Tabrizi's avatar
Shawn Tabrizi committed
39
40
41
pub use frame_support::weights::constants::{
	BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
};
42
use frame_support::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
43
44
45
	parameter_types,
	traits::{Currency, OneSessionHandler},
	weights::{constants::WEIGHT_PER_SECOND, DispatchClass, Weight},
46
};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
47
48
49
50
use frame_system::limits;
use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment};
use primitives::v1::{AssignmentId, BlockNumber, ValidatorId};
use sp_runtime::{FixedPointNumber, Perbill, Perquintill};
51
use static_assertions::const_assert;
52

Shawn Tabrizi's avatar
Shawn Tabrizi committed
53
54
pub use elections::{OffchainSolutionLengthLimit, OffchainSolutionWeightLimit};
pub use pallet_balances::Call as BalancesCall;
55
#[cfg(feature = "std")]
56
pub use pallet_staking::StakerStatus;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
57
pub use pallet_timestamp::Call as TimestampCall;
58
59
60
61
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;

/// Implementations of some helper traits passed into runtime modules as associated types.
62
pub use impls::ToAuthor;
63

Shawn Tabrizi's avatar
Shawn Tabrizi committed
64
65
66
pub type NegativeImbalance<T> = <pallet_balances::Pallet<T> as Currency<
	<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
67

68
69
70
/// We assume that an on-initialize consumes 1% of the weight on average, hence a single extrinsic
/// will not be allowed to consume more than `AvailableBlockRatio - 1%`.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(1);
71
72
73
74
75
76
77
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used
/// by  Operational  extrinsics.
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// We allow for 2 seconds of compute with a 6 second average block time.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;

const_assert!(NORMAL_DISPATCH_RATIO.deconstruct() >= AVERAGE_ON_INITIALIZE_RATIO.deconstruct());
78
79

// Common constants used in all runtimes.
80
parameter_types! {
81
	pub const BlockHashCount: BlockNumber = 2400;
82
	/// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less
83
84
85
86
87
88
89
90
	/// than this will decrease the weight and more will increase.
	pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
	/// The adjustment variable of the runtime. Higher values will cause `TargetBlockFullness` to
	/// change the fees more rapidly.
	pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000);
	/// Minimum amount of the multiplier. This value cannot be too low. A test case should ensure
	/// that combined with `AdjustmentVariable`, we can recover from the minimum.
	/// See `multiplier_can_grow_from_zero`.
91
	pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128);
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
	/// Maximum length of block. Up to 5MB.
	pub BlockLength: limits::BlockLength =
		limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
	/// Block weights base values and limits.
	pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder()
		.base_block(BlockExecutionWeight::get())
		.for_class(DispatchClass::all(), |weights| {
			weights.base_extrinsic = ExtrinsicBaseWeight::get();
		})
		.for_class(DispatchClass::Normal, |weights| {
			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
		})
		.for_class(DispatchClass::Operational, |weights| {
			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
			// Operational transactions have an extra reserved space, so that they
			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
			weights.reserved = Some(
				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT,
			);
		})
		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
		.build_or_panic();
114
}
Gavin Wood's avatar
Gavin Wood committed
115

116
117
/// Parameterized slow adjusting fee updated based on
/// https://w3f-research.readthedocs.io/en/latest/polkadot/Token%20Economics.html#-2.-slow-adjusting-mechanism
Shawn Tabrizi's avatar
Shawn Tabrizi committed
118
119
pub type SlowAdjustingFeeUpdate<R> =
	TargetedFeeAdjustment<R, TargetBlockFullness, AdjustmentVariable, MinimumMultiplier>;
120

121
122
/// The type used for currency conversion.
///
Denis_P's avatar
Denis_P committed
123
/// This must only be used as long as the balance type is `u128`.
124
125
126
pub type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
static_assertions::assert_eq_size!(primitives::v1::Balance, u128);

127
128
129
130
131
132
133
/// A placeholder since there is currently no provided session key handler for parachain validator
/// keys.
pub struct ParachainSessionKeyPlaceholder<T>(sp_std::marker::PhantomData<T>);
impl<T> sp_runtime::BoundToRuntimeAppPublic for ParachainSessionKeyPlaceholder<T> {
	type Public = ValidatorId;
}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
134
135
impl<T: pallet_session::Config> OneSessionHandler<T::AccountId>
	for ParachainSessionKeyPlaceholder<T>
136
137
138
{
	type Key = ValidatorId;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
139
140
	fn on_genesis_session<'a, I: 'a>(_validators: I)
	where
141
		I: Iterator<Item = (&'a T::AccountId, ValidatorId)>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
142
		T::AccountId: 'a,
143
144
145
	{
	}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
146
147
	fn on_new_session<'a, I: 'a>(_changed: bool, _v: I, _q: I)
	where
148
		I: Iterator<Item = (&'a T::AccountId, ValidatorId)>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
149
		T::AccountId: 'a,
150
151
152
	{
	}

153
	fn on_disabled(_: u32) {}
154
155
}

156
157
158
159
160
161
162
/// A placeholder since there is currently no provided session key handler for parachain validator
/// keys.
pub struct AssignmentSessionKeyPlaceholder<T>(sp_std::marker::PhantomData<T>);
impl<T> sp_runtime::BoundToRuntimeAppPublic for AssignmentSessionKeyPlaceholder<T> {
	type Public = AssignmentId;
}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
163
164
impl<T: pallet_session::Config> OneSessionHandler<T::AccountId>
	for AssignmentSessionKeyPlaceholder<T>
165
166
167
{
	type Key = AssignmentId;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
168
169
	fn on_genesis_session<'a, I: 'a>(_validators: I)
	where
170
		I: Iterator<Item = (&'a T::AccountId, AssignmentId)>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
171
		T::AccountId: 'a,
172
173
174
	{
	}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
175
176
	fn on_new_session<'a, I: 'a>(_changed: bool, _v: I, _q: I)
	where
177
		I: Iterator<Item = (&'a T::AccountId, AssignmentId)>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
178
		T::AccountId: 'a,
179
180
181
	{
	}

182
	fn on_disabled(_: u32) {}
183
184
}

185
186
187
#[cfg(test)]
mod multiplier_tests {
	use super::*;
188
	use frame_support::{parameter_types, weights::Weight};
189
190
191
	use sp_core::H256;
	use sp_runtime::{
		testing::Header,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
192
		traits::{BlakeTwo256, Convert, IdentityLookup, One},
193
194
195
		Perbill,
	};

196
197
	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>;
	type Block = frame_system::mocking::MockBlock<Runtime>;
198

199
200
201
202
203
204
	frame_support::construct_runtime!(
		pub enum Runtime where
			Block = Block,
			NodeBlock = Block,
			UncheckedExtrinsic = UncheckedExtrinsic,
		{
205
			System: frame_system::{Pallet, Call, Config, Storage, Event<T>}
206
207
		}
	);
208
209
210
211

	parameter_types! {
		pub const BlockHashCount: u64 = 250;
		pub const AvailableBlockRatio: Perbill = Perbill::one();
212
213
214
215
		pub BlockLength: frame_system::limits::BlockLength =
			frame_system::limits::BlockLength::max(2 * 1024);
		pub BlockWeights: frame_system::limits::BlockWeights =
			frame_system::limits::BlockWeights::simple_max(1024);
216
217
	}

218
	impl frame_system::Config for Runtime {
219
		type BaseCallFilter = frame_support::traits::Everything;
220
221
222
		type BlockWeights = BlockWeights;
		type BlockLength = ();
		type DbWeight = ();
223
224
225
		type Origin = Origin;
		type Index = u64;
		type BlockNumber = u64;
226
		type Call = Call;
227
228
229
230
231
		type Hash = H256;
		type Hashing = BlakeTwo256;
		type AccountId = u64;
		type Lookup = IdentityLookup<Self::AccountId>;
		type Header = Header;
232
		type Event = Event;
233
234
		type BlockHashCount = BlockHashCount;
		type Version = ();
235
		type PalletInfo = PalletInfo;
236
237
238
		type AccountData = ();
		type OnNewAccount = ();
		type OnKilledAccount = ();
239
		type SystemWeightInfo = ();
240
		type SS58Prefix = ();
241
		type OnSetCode = ();
242
243
	}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
244
245
246
247
248
249
250
251
	fn run_with_system_weight<F>(w: Weight, mut assertions: F)
	where
		F: FnMut() -> (),
	{
		let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default()
			.build_storage::<Runtime>()
			.unwrap()
			.into();
252
		t.execute_with(|| {
253
			System::set_block_consumed_resources(w, 0);
254
255
256
257
258
259
260
			assertions()
		});
	}

	#[test]
	fn multiplier_can_grow_from_zero() {
		let minimum_multiplier = MinimumMultiplier::get();
261
262
		let target = TargetBlockFullness::get() *
			BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap();
263
		// if the min is too small, then this will not change, and we are doomed forever.
264
		// the weight is 1/100th bigger than target.
265
266
267
268
269
		run_with_system_weight(target * 101 / 100, || {
			let next = SlowAdjustingFeeUpdate::<Runtime>::convert(minimum_multiplier);
			assert!(next > minimum_multiplier, "{:?} !>= {:?}", next, minimum_multiplier);
		})
	}
270
271
272
273
274
275
276

	#[test]
	#[ignore]
	fn multiplier_growth_simulator() {
		// assume the multiplier is initially set to its minimum. We update it with values twice the
		//target (target is 25%, thus 50%) and we see at which point it reaches 1.
		let mut multiplier = MinimumMultiplier::get();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
277
278
279
		let block_weight = TargetBlockFullness::get() *
			BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap() *
			2;
280
281
282
283
284
285
286
287
288
289
290
291
		let mut blocks = 0;
		while multiplier <= Multiplier::one() {
			run_with_system_weight(block_weight, || {
				let next = SlowAdjustingFeeUpdate::<Runtime>::convert(multiplier);
				// ensure that it is growing as well.
				assert!(next > multiplier, "{:?} !>= {:?}", next, multiplier);
				multiplier = next;
			});
			blocks += 1;
			println!("block = {} multiplier {:?}", blocks, multiplier);
		}
	}
292
}