lib.rs 27.4 KB
Newer Older
Fedor Sakharov's avatar
Fedor Sakharov committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2020 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/>.

17
//! The Rococo runtime for v1 parachains.
Fedor Sakharov's avatar
Fedor Sakharov committed
18
19
20

#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
21
#![recursion_limit = "256"]
Fedor Sakharov's avatar
Fedor Sakharov committed
22

Albrecht's avatar
Albrecht committed
23
use pallet_transaction_payment::CurrencyAdapter;
Fedor Sakharov's avatar
Fedor Sakharov committed
24
use sp_std::prelude::*;
Sergey Pepyakin's avatar
Sergey Pepyakin committed
25
use sp_std::collections::btree_map::BTreeMap;
26
use parity_scale_codec::Encode;
Fedor Sakharov's avatar
Fedor Sakharov committed
27
28
use primitives::v1::{
	AccountId, AccountIndex, Balance, BlockNumber, Hash, Nonce, Signature, Moment,
29
	GroupRotationInfo, CoreState, Id, ValidationData, ValidationCode, CandidateEvent,
Fedor Sakharov's avatar
Fedor Sakharov committed
30
	ValidatorId, ValidatorIndex, CommittedCandidateReceipt, OccupiedCoreAssumption,
31
32
	PersistedValidationData, InboundDownwardMessage, InboundHrmpMessage,
	SessionInfo as SessionInfoData,
Fedor Sakharov's avatar
Fedor Sakharov committed
33
34
35
};
use runtime_common::{
	SlowAdjustingFeeUpdate,
36
	impls::ToAuthor,
37
	BlockHashCount, BlockWeights, BlockLength, RocksDbWeight, OffchainSolutionWeightLimit,
Fedor Sakharov's avatar
Fedor Sakharov committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
};
use runtime_parachains::{
	self,
	runtime_api_impl::v1 as runtime_api_impl,
};
use frame_support::{
	parameter_types, construct_runtime, debug,
	traits::{KeyOwnerProofSystem, Filter},
	weights::Weight,
};
use sp_runtime::{
	create_runtime_str, generic, impl_opaque_keys,
	ApplyExtrinsicResult, KeyTypeId, Perbill, curve::PiecewiseLinear,
	transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
	traits::{
		BlakeTwo256, Block as BlockT, OpaqueKeys, IdentityLookup,
		Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
	},
};
57
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
Fedor Sakharov's avatar
Fedor Sakharov committed
58
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
59
60
#[cfg(any(feature = "std", test))]
use sp_version::NativeVersion;
61
62
63
use sp_version::RuntimeVersion;
use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
Fedor Sakharov's avatar
Fedor Sakharov committed
64
65
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
66
67
use pallet_session::historical as session_historical;
use frame_system::EnsureRoot;
68
use runtime_common::{paras_sudo_wrapper, paras_registrar};
Fedor Sakharov's avatar
Fedor Sakharov committed
69

70
use runtime_parachains::origin as parachains_origin;
Fedor Sakharov's avatar
Fedor Sakharov committed
71
72
73
74
use runtime_parachains::configuration as parachains_configuration;
use runtime_parachains::inclusion as parachains_inclusion;
use runtime_parachains::inclusion_inherent as parachains_inclusion_inherent;
use runtime_parachains::initializer as parachains_initializer;
75
use runtime_parachains::session_info as parachains_session_info;
Fedor Sakharov's avatar
Fedor Sakharov committed
76
use runtime_parachains::paras as parachains_paras;
77
78
79
use runtime_parachains::dmp as parachains_dmp;
use runtime_parachains::ump as parachains_ump;
use runtime_parachains::hrmp as parachains_hrmp;
Fedor Sakharov's avatar
Fedor Sakharov committed
80
use runtime_parachains::scheduler as parachains_scheduler;
81
use runtime_parachains::reward_points::RewardValidatorsWithEraPoints;
Fedor Sakharov's avatar
Fedor Sakharov committed
82

83
pub use pallet_balances::Call as BalancesCall;
84
pub use pallet_staking::StakerStatus;
Fedor Sakharov's avatar
Fedor Sakharov committed
85

Shawn Tabrizi's avatar
Shawn Tabrizi committed
86
87
88
89
90
91
92
93
94
use polkadot_parachain::primitives::Id as ParaId;
use xcm::v0::{MultiLocation, NetworkId};
use xcm_executor::traits::IsConcrete;
use xcm_builder::{
	AccountId32Aliases, ChildParachainConvertsVia, SovereignSignedViaLocation,
	CurrencyAdapter as XcmCurrencyAdapter, ChildParachainAsNative,
	SignedAccountId32AsNative, ChildSystemParachainAsSuperuser, LocationInverter,
};

Fedor Sakharov's avatar
Fedor Sakharov committed
95
96
97
98
99
100
101
102
/// Constant values used within the runtime.
pub mod constants;
use constants::{time::*, currency::*, fee::*};

// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

103
104
105
106
107
/// Runtime version (Rococo).
pub const VERSION: RuntimeVersion = RuntimeVersion {
	spec_name: create_runtime_str!("rococo"),
	impl_name: create_runtime_str!("parity-rococo-v1"),
	authoring_version: 0,
asynchronous rob's avatar
asynchronous rob committed
108
	spec_version: 12,
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
	impl_version: 0,
	#[cfg(not(feature = "disable-runtime-api"))]
	apis: RUNTIME_API_VERSIONS,
	#[cfg(feature = "disable-runtime-api")]
	apis: sp_version::create_apis_vec![[]],
	transaction_version: 0,
};

/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
	NativeVersion {
		runtime_version: VERSION,
		can_author_with: Default::default(),
	}
}

Fedor Sakharov's avatar
Fedor Sakharov committed
126
127
128
129
130
131
132
133
134
135
136
137
/// The address format for describing accounts.
pub type Address = AccountId;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
138
139
140
141
142
143
144
	frame_system::CheckSpecVersion<Runtime>,
	frame_system::CheckTxVersion<Runtime>,
	frame_system::CheckGenesis<Runtime>,
	frame_system::CheckMortality<Runtime>,
	frame_system::CheckNonce<Runtime>,
	frame_system::CheckWeight<Runtime>,
	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
Fedor Sakharov's avatar
Fedor Sakharov committed
145
146
147
148
149
150
151
);

/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Nonce, Call>;
/// Executive: handles dispatch to the various modules.
152
pub type Executive = frame_executive::Executive<Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllModules>;
Fedor Sakharov's avatar
Fedor Sakharov committed
153
154
155
156
157
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;

impl_opaque_keys! {
	pub struct SessionKeys {
158
		pub grandpa: Grandpa,
Fedor Sakharov's avatar
Fedor Sakharov committed
159
160
		pub babe: Babe,
		pub im_online: ImOnline,
161
162
		pub para_validator: Initializer,
		pub para_assignment: SessionInfo,
163
		pub authority_discovery: AuthorityDiscovery,
Fedor Sakharov's avatar
Fedor Sakharov committed
164
165
166
167
168
169
170
171
172
	}
}

construct_runtime! {
	pub enum Runtime where
		Block = Block,
		NodeBlock = primitives::v1::Block,
		UncheckedExtrinsic = UncheckedExtrinsic
	{
173
		System: frame_system::{Module, Call, Storage, Config, Event<T>},
Fedor Sakharov's avatar
Fedor Sakharov committed
174
175

		// Must be before session.
176
		Babe: pallet_babe::{Module, Call, Storage, Config, Inherent, ValidateUnsigned},
Fedor Sakharov's avatar
Fedor Sakharov committed
177

178
179
180
181
		Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},
		Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>},
		Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},
		TransactionPayment: pallet_transaction_payment::{Module, Storage},
Fedor Sakharov's avatar
Fedor Sakharov committed
182
183

		// Consensus support.
184
185
186
		Authorship: pallet_authorship::{Module, Call, Storage},
		Staking: pallet_staking::{Module, Call, Storage, Config<T>, Event<T>, ValidateUnsigned},
		Offences: pallet_offences::{Module, Call, Storage, Event},
Fedor Sakharov's avatar
Fedor Sakharov committed
187
		Historical: session_historical::{Module},
188
189
190
191
		Session: pallet_session::{Module, Call, Storage, Event, Config<T>},
		Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event, ValidateUnsigned},
		ImOnline: pallet_im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>},
		AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config},
Fedor Sakharov's avatar
Fedor Sakharov committed
192
193

		// Parachains modules.
194
195
		ParachainsOrigin: parachains_origin::{Module, Origin},
		ParachainsConfiguration: parachains_configuration::{Module, Call, Storage, Config<T>},
Fedor Sakharov's avatar
Fedor Sakharov committed
196
		Inclusion: parachains_inclusion::{Module, Call, Storage, Event<T>},
197
		InclusionInherent: parachains_inclusion_inherent::{Module, Call, Storage, Inherent},
Fedor Sakharov's avatar
Fedor Sakharov committed
198
		Scheduler: parachains_scheduler::{Module, Call, Storage},
199
200
		Paras: parachains_paras::{Module, Call, Storage},
		Initializer: parachains_initializer::{Module, Call, Storage},
201
202
203
		Dmp: parachains_dmp::{Module, Call, Storage},
		Ump: parachains_ump::{Module, Call, Storage},
		Hrmp: parachains_hrmp::{Module, Call, Storage},
204
		SessionInfo: parachains_session_info::{Module, Call, Storage},
Fedor Sakharov's avatar
Fedor Sakharov committed
205

206
207
208
209
210
		Registrar: paras_registrar::{Module, Call, Storage},
		ParasSudoWrapper: paras_sudo_wrapper::{Module, Call},

		// Sudo
		Sudo: pallet_sudo::{Module, Call, Storage, Event<T>, Config<T>},
211
212
213
	}
}

214
215
216
217
218
219
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
	fn filter(_call: &Call) -> bool {
		true
	}
}
220

Fedor Sakharov's avatar
Fedor Sakharov committed
221
222
223
224
parameter_types! {
	pub const Version: RuntimeVersion = VERSION;
}

225
impl frame_system::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
226
	type BaseCallFilter = BaseFilter;
227
228
229
	type BlockWeights = BlockWeights;
	type BlockLength = BlockLength;
	type DbWeight = RocksDbWeight;
Fedor Sakharov's avatar
Fedor Sakharov committed
230
231
232
233
234
235
236
237
238
239
240
241
	type Origin = Origin;
	type Call = Call;
	type Index = Nonce;
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
	type Lookup = IdentityLookup<Self::AccountId>;
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
	type Event = Event;
	type BlockHashCount = BlockHashCount;
	type Version = Version;
242
	type PalletInfo = PalletInfo;
243
	type AccountData = pallet_balances::AccountData<Balance>;
Fedor Sakharov's avatar
Fedor Sakharov committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
	type OnNewAccount = ();
	type OnKilledAccount = ();
	type SystemWeightInfo = ();
}

parameter_types! {
	pub const MaxCodeSize: u32 = 10 * 1024 * 1024; // 10 MB
	pub const MaxHeadDataSize: u32 = 20 * 1024; // 20 KB
	pub const ValidationUpgradeFrequency: BlockNumber = 2 * DAYS;
	pub const ValidationUpgradeDelay: BlockNumber = 8 * HOURS;
	pub const SlashPeriod: BlockNumber = 7 * DAYS;
}

/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
259
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
Fedor Sakharov's avatar
Fedor Sakharov committed
260
261
	Call: From<LocalCall>,
{
262
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
Fedor Sakharov's avatar
Fedor Sakharov committed
263
264
265
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
266
		nonce: <Runtime as frame_system::Config>::Index,
Fedor Sakharov's avatar
Fedor Sakharov committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
		// take the biggest period possible.
		let period = BlockHashCount::get()
			.checked_next_power_of_two()
			.map(|c| c / 2)
			.unwrap_or(2) as u64;

		let current_block = System::block_number()
			.saturated_into::<u64>()
			// The `System::block_number` is initialized with `n+1`,
			// so the actual block number is `n`.
			.saturating_sub(1);
		let tip = 0;
		let extra: SignedExtra = (
281
282
283
284
285
286
287
			frame_system::CheckSpecVersion::<Runtime>::new(),
			frame_system::CheckTxVersion::<Runtime>::new(),
			frame_system::CheckGenesis::<Runtime>::new(),
			frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
			frame_system::CheckNonce::<Runtime>::from(nonce),
			frame_system::CheckWeight::<Runtime>::new(),
			pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
Fedor Sakharov's avatar
Fedor Sakharov committed
288
289
290
291
292
293
294
295
296
297
298
299
		);
		let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
			debug::warn!("Unable to create signed payload: {:?}", e);
		}).ok()?;
		let signature = raw_payload.using_encoded(|payload| {
			C::sign(payload, public)
		})?;
		let (call, extra, _) = raw_payload.deconstruct();
		Some((call, (account, signature, extra)))
	}
}

300
impl frame_system::offchain::SigningTypes for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
301
302
303
304
	type Public = <Signature as Verify>::Signer;
	type Signature = Signature;
}

305
impl pallet_session::historical::Config for Runtime {
306
307
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
Fedor Sakharov's avatar
Fedor Sakharov committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
}

pallet_staking_reward_curve::build! {
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
		ideal_stake: 0_500_000,
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

parameter_types! {
	// Six sessions in an era (6 hours).
	pub const SessionsPerEra: SessionIndex = 6;
	// 28 eras for unbonding (7 days).
325
	pub const BondingDuration: pallet_staking::EraIndex = 28;
Fedor Sakharov's avatar
Fedor Sakharov committed
326
	// 27 eras in which slashes can be cancelled (~7 days).
327
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
Fedor Sakharov's avatar
Fedor Sakharov committed
328
329
330
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
	pub const MaxNominatorRewardedPerValidator: u32 = 64;
	// quarter of the last session will be for election.
331
	pub ElectionLookahead: BlockNumber = EpochDurationInBlocks::get() / 4;
Fedor Sakharov's avatar
Fedor Sakharov committed
332
333
334
335
336
	pub const MaxIterations: u32 = 10;
	pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000);
}

parameter_types! {
337
	pub SessionDuration: BlockNumber = EpochDurationInBlocks::get() as _;
Fedor Sakharov's avatar
Fedor Sakharov committed
338
339
340
341
342
343
344
}

parameter_types! {
	pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2;
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

345
impl pallet_im_online::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
346
347
348
349
350
351
352
353
	type AuthorityId = ImOnlineId;
	type Event = Event;
	type ReportUnresponsiveness = Offences;
	type SessionDuration = SessionDuration;
	type UnsignedPriority = StakingUnsignedPriority;
	type WeightInfo = ();
}

354
impl pallet_staking::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
355
356
	type Currency = Balances;
	type UnixTime = Timestamp;
357
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Fedor Sakharov's avatar
Fedor Sakharov committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
	type RewardRemainder = ();
	type Event = Event;
	type Slash = ();
	type Reward = ();
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
	type SlashDeferDuration = SlashDeferDuration;
	// A majority of the council can cancel the slash.
	type SlashCancelOrigin = EnsureRoot<AccountId>;
	type SessionInterface = Self;
	type RewardCurve = RewardCurve;
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
	type NextNewSession = Session;
	type ElectionLookahead = ElectionLookahead;
	type Call = Call;
	type UnsignedPriority = StakingUnsignedPriority;
	type MaxIterations = MaxIterations;
375
	type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit;
Fedor Sakharov's avatar
Fedor Sakharov committed
376
377
378
379
380
381
	type MinSolutionScoreBump = MinSolutionScoreBump;
	type WeightInfo = ();
}

parameter_types! {
	pub const ExistentialDeposit: Balance = 1 * CENTS;
382
	pub const MaxLocks: u32 = 50;
Fedor Sakharov's avatar
Fedor Sakharov committed
383
384
}

385
impl pallet_balances::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
386
387
388
389
390
	type Balance = Balance;
	type DustRemoval = ();
	type Event = Event;
	type ExistentialDeposit = ExistentialDeposit;
	type AccountStore = System;
391
	type MaxLocks = MaxLocks;
Fedor Sakharov's avatar
Fedor Sakharov committed
392
393
394
	type WeightInfo = ();
}

395
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where
Fedor Sakharov's avatar
Fedor Sakharov committed
396
397
398
399
400
401
402
403
404
405
406
407
408
	Call: From<C>,
{
	type OverarchingCall = Call;
	type Extrinsic = UncheckedExtrinsic;
}

parameter_types! {
	pub const ParathreadDeposit: Balance = 5 * DOLLARS;
	pub const QueueSize: usize = 2;
	pub const MaxRetries: u32 = 3;
}

parameter_types! {
409
	pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * BlockWeights::get().max_block;
Fedor Sakharov's avatar
Fedor Sakharov committed
410
411
}

412
impl pallet_offences::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
413
	type Event = Event;
414
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
Fedor Sakharov's avatar
Fedor Sakharov committed
415
416
417
418
	type OnOffenceHandler = Staking;
	type WeightSoftLimit = OffencesWeightSoftLimit;
}

419
impl pallet_authority_discovery::Config for Runtime {}
Fedor Sakharov's avatar
Fedor Sakharov committed
420
421
422
423

parameter_types! {
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
}
424
impl pallet_timestamp::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
425
426
427
428
429
430
431
432
433
434
	type Moment = u64;
	type OnTimestampSet = Babe;
	type MinimumPeriod = MinimumPeriod;
	type WeightInfo = ();
}

parameter_types! {
	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
}

435
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
436
	type OnChargeTransaction = CurrencyAdapter<Balances, ToAuthor<Runtime>>;
Fedor Sakharov's avatar
Fedor Sakharov committed
437
438
439
440
441
442
443
444
445
	type TransactionByteFee = TransactionByteFee;
	type WeightToFee = WeightToFee;
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
}

parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

446
impl pallet_session::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
447
448
	type Event = Event;
	type ValidatorId = AccountId;
449
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
Fedor Sakharov's avatar
Fedor Sakharov committed
450
451
	type ShouldEndSession = Babe;
	type NextSessionRotation = Babe;
452
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
Fedor Sakharov's avatar
Fedor Sakharov committed
453
454
455
456
457
458
459
460
461
462
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
	type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
	type WeightInfo = ();
}

parameter_types! {
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
}

463
impl pallet_babe::Config for Runtime {
464
	type EpochDuration = EpochDurationInBlocks;
Fedor Sakharov's avatar
Fedor Sakharov committed
465
466
467
	type ExpectedBlockTime = ExpectedBlockTime;

	// session module is the trigger
468
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
Fedor Sakharov's avatar
Fedor Sakharov committed
469
470
471
472
473

	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
474
		pallet_babe::AuthorityId,
Fedor Sakharov's avatar
Fedor Sakharov committed
475
476
477
478
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
479
		pallet_babe::AuthorityId,
Fedor Sakharov's avatar
Fedor Sakharov committed
480
481
482
	)>>::IdentificationTuple;

	type HandleEquivocation =
483
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences>;
484
485

	type WeightInfo = ();
Fedor Sakharov's avatar
Fedor Sakharov committed
486
487
488
489
490
491
}

parameter_types! {
	pub const IndexDeposit: Balance = 1 * DOLLARS;
}

492
impl pallet_indices::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
493
494
495
496
497
498
499
500
501
502
503
	type AccountIndex = AccountIndex;
	type Currency = Balances;
	type Deposit = IndexDeposit;
	type Event = Event;
	type WeightInfo = ();
}

parameter_types! {
	pub const AttestationPeriod: BlockNumber = 50;
}

504
impl pallet_grandpa::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
505
506
507
508
509
510
511
512
513
514
515
516
517
	type Event = Event;
	type Call = Call;

	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof =
		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
		GrandpaId,
	)>>::IdentificationTuple;

518
	type HandleEquivocation = pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences>;
519
520

	type WeightInfo = ();
Fedor Sakharov's avatar
Fedor Sakharov committed
521
522
523
524
525
526
527
}

parameter_types! {
	pub const UncleGenerations: u32 = 0;
}

// TODO: substrate#2986 implement this properly
528
impl pallet_authorship::Config for Runtime {
529
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Fedor Sakharov's avatar
Fedor Sakharov committed
530
531
532
533
534
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
	type EventHandler = (Staking, ImOnline);
}

535
impl parachains_origin::Config for Runtime {}
536

537
impl parachains_configuration::Config for Runtime {}
Fedor Sakharov's avatar
Fedor Sakharov committed
538

539
impl parachains_inclusion::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
540
	type Event = Event;
541
	type RewardValidators = RewardValidatorsWithEraPoints<Runtime>;
Fedor Sakharov's avatar
Fedor Sakharov committed
542
543
}

544
impl parachains_paras::Config for Runtime {
545
546
	type Origin = Origin;
}
Fedor Sakharov's avatar
Fedor Sakharov committed
547

Shawn Tabrizi's avatar
Shawn Tabrizi committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
parameter_types! {
	pub const RocLocation: MultiLocation = MultiLocation::Null;
	pub const RococoNetwork: NetworkId = NetworkId::Polkadot;
	pub const Ancestry: MultiLocation = MultiLocation::Null;
}

pub type LocationConverter = (
	ChildParachainConvertsVia<ParaId, AccountId>,
	AccountId32Aliases<RococoNetwork, AccountId>,
);

pub type LocalAssetTransactor =
	XcmCurrencyAdapter<
		// Use this currency:
		Balances,
		// Use this currency when it is a fungible asset matching the given location or name:
		IsConcrete<RocLocation>,
		// We can convert the MultiLocations with our converter above:
		LocationConverter,
		// Our chain's account ID type (we can't get away without mentioning it explicitly):
		AccountId,
	>;

type LocalOriginConverter = (
	SovereignSignedViaLocation<LocationConverter, Origin>,
	ChildParachainAsNative<parachains_origin::Origin, Origin>,
	SignedAccountId32AsNative<RococoNetwork, Origin>,
	ChildSystemParachainAsSuperuser<ParaId, Origin>,
);

pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
	type Call = Call;
	type XcmSender = ();
	type AssetTransactor = LocalAssetTransactor;
	type OriginConverter = LocalOriginConverter;
	type IsReserve = ();
	type IsTeleporter = ();
	type LocationInverter = LocationInverter<Ancestry>;
}

589
impl parachains_session_info::Config for Runtime {}
590

591
impl parachains_ump::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
592
	type UmpSink = crate::parachains_ump::XcmSink<XcmConfig>;
593
}
594

595
impl parachains_dmp::Config for Runtime {}
596

597
impl parachains_hrmp::Config for Runtime {
598
599
600
	type Origin = Origin;
}

601
impl parachains_inclusion_inherent::Config for Runtime {}
Fedor Sakharov's avatar
Fedor Sakharov committed
602

603
impl parachains_scheduler::Config for Runtime {}
Fedor Sakharov's avatar
Fedor Sakharov committed
604

605
impl parachains_initializer::Config for Runtime {
Fedor Sakharov's avatar
Fedor Sakharov committed
606
607
	type Randomness = Babe;
}
608

609
impl paras_sudo_wrapper::Config for Runtime {}
610

611
impl paras_registrar::Config for Runtime {
612
613
614
615
	type Currency = Balances;
	type ParathreadDeposit = ParathreadDeposit;
	type Origin = Origin;
}
616

617
impl pallet_sudo::Config for Runtime {
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
	type Event = Event;
	type Call = Call;
}

#[cfg(not(feature = "disable-runtime-api"))]
sp_api::impl_runtime_apis! {
	impl sp_api::Core<Block> for Runtime {
		fn version() -> RuntimeVersion {
			VERSION
		}

		fn execute_block(block: Block) {
			Executive::execute_block(block)
		}

		fn initialize_block(header: &<Block as BlockT>::Header) {
			Executive::initialize_block(header)
		}
	}

	impl sp_api::Metadata<Block> for Runtime {
		fn metadata() -> OpaqueMetadata {
			Runtime::metadata().into()
		}
	}

	impl block_builder_api::BlockBuilder<Block> for Runtime {
		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
			Executive::apply_extrinsic(extrinsic)
		}

		fn finalize_block() -> <Block as BlockT>::Header {
			Executive::finalize_block()
		}

		fn inherent_extrinsics(data: inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
			data.create_extrinsics()
		}

		fn check_inherents(
			block: Block,
			data: inherents::InherentData,
		) -> inherents::CheckInherentsResult {
			data.check_extrinsics(&block)
		}

		fn random_seed() -> <Block as BlockT>::Hash {
			Babe::randomness().into()
		}
	}

	impl tx_pool_api::runtime_api::TaggedTransactionQueue<Block> for Runtime {
		fn validate_transaction(
			source: TransactionSource,
			tx: <Block as BlockT>::Extrinsic,
		) -> TransactionValidity {
			Executive::validate_transaction(source, tx)
		}
	}

	impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
		fn offchain_worker(header: &<Block as BlockT>::Header) {
			Executive::offchain_worker(header)
		}
	}

	impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
		fn validators() -> Vec<ValidatorId> {
			runtime_api_impl::validators::<Runtime>()
		}

		fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
			runtime_api_impl::validator_groups::<Runtime>()
		}

693
		fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
			runtime_api_impl::availability_cores::<Runtime>()
		}

		fn full_validation_data(para_id: Id, assumption: OccupiedCoreAssumption)
			-> Option<ValidationData<BlockNumber>> {
			runtime_api_impl::full_validation_data::<Runtime>(para_id, assumption)
		}

		fn persisted_validation_data(para_id: Id, assumption: OccupiedCoreAssumption)
			-> Option<PersistedValidationData<BlockNumber>> {
			runtime_api_impl::persisted_validation_data::<Runtime>(para_id, assumption)
		}

		fn check_validation_outputs(
			para_id: Id,
709
			outputs: primitives::v1::CandidateCommitments,
710
711
712
713
714
715
716
717
718
719
720
721
722
		) -> bool {
			runtime_api_impl::check_validation_outputs::<Runtime>(para_id, outputs)
		}

		fn session_index_for_child() -> SessionIndex {
			runtime_api_impl::session_index_for_child::<Runtime>()
		}

		fn validation_code(para_id: Id, assumption: OccupiedCoreAssumption)
			-> Option<ValidationCode> {
			runtime_api_impl::validation_code::<Runtime>(para_id, assumption)
		}

723
724
725
726
727
728
		fn historical_validation_code(para_id: Id, context_height: BlockNumber)
			-> Option<ValidationCode>
		{
			runtime_api_impl::historical_validation_code::<Runtime>(para_id, context_height)
		}

729
730
731
732
733
734
735
736
737
738
739
740
741
742
		fn candidate_pending_availability(para_id: Id) -> Option<CommittedCandidateReceipt<Hash>> {
			runtime_api_impl::candidate_pending_availability::<Runtime>(para_id)
		}

		fn candidate_events() -> Vec<CandidateEvent<Hash>> {
			runtime_api_impl::candidate_events::<Runtime, _>(|ev| {
				match ev {
					Event::parachains_inclusion(ev) => {
						Some(ev)
					}
					_ => None,
				}
			})
		}
743

744
		fn session_info(index: SessionIndex) -> Option<SessionInfoData> {
745
			runtime_api_impl::session_info::<Runtime>(index)
746
747
		}

Sergey Pepyakin's avatar
Sergey Pepyakin committed
748
		fn dmq_contents(recipient: Id) -> Vec<InboundDownwardMessage<BlockNumber>> {
749
750
			runtime_api_impl::dmq_contents::<Runtime>(recipient)
		}
Sergey Pepyakin's avatar
Sergey Pepyakin committed
751
752
753
754
755
756

		fn inbound_hrmp_channels_contents(
			recipient: Id
		) -> BTreeMap<Id, Vec<InboundHrmpMessage<BlockNumber>>> {
			runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
		}
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
	}

	impl fg_primitives::GrandpaApi<Block> for Runtime {
		fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
			Grandpa::grandpa_authorities()
		}

		fn submit_report_equivocation_unsigned_extrinsic(
			equivocation_proof: fg_primitives::EquivocationProof<
				<Block as BlockT>::Hash,
				sp_runtime::traits::NumberFor<Block>,
			>,
			key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
		) -> Option<()> {
			let key_owner_proof = key_owner_proof.decode()?;

			Grandpa::submit_unsigned_equivocation_report(
				equivocation_proof,
				key_owner_proof,
			)
		}

		fn generate_key_ownership_proof(
			_set_id: fg_primitives::SetId,
			authority_id: fg_primitives::AuthorityId,
		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
783
			use parity_scale_codec::Encode;
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799

			Historical::prove((fg_primitives::KEY_TYPE, authority_id))
				.map(|p| p.encode())
				.map(fg_primitives::OpaqueKeyOwnershipProof::new)
		}
	}

	impl babe_primitives::BabeApi<Block> for Runtime {
		fn configuration() -> babe_primitives::BabeGenesisConfiguration {
			// The choice of `c` parameter (where `1 - c` represents the
			// probability of a slot being empty), is done in accordance to the
			// slot duration and expected target block time, for safely
			// resisting network delays of maximum two seconds.
			// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
			babe_primitives::BabeGenesisConfiguration {
				slot_duration: Babe::slot_duration(),
800
				epoch_length: EpochDurationInBlocks::get().into(),
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
				c: PRIMARY_PROBABILITY,
				genesis_authorities: Babe::authorities(),
				randomness: Babe::randomness(),
				allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryPlainSlots,
			}
		}

		fn current_epoch_start() -> babe_primitives::SlotNumber {
			Babe::current_epoch_start()
		}

		fn generate_key_ownership_proof(
			_slot_number: babe_primitives::SlotNumber,
			authority_id: babe_primitives::AuthorityId,
		) -> Option<babe_primitives::OpaqueKeyOwnershipProof> {
816
			use parity_scale_codec::Encode;
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868

			Historical::prove((babe_primitives::KEY_TYPE, authority_id))
				.map(|p| p.encode())
				.map(babe_primitives::OpaqueKeyOwnershipProof::new)
		}

		fn submit_report_equivocation_unsigned_extrinsic(
			equivocation_proof: babe_primitives::EquivocationProof<<Block as BlockT>::Header>,
			key_owner_proof: babe_primitives::OpaqueKeyOwnershipProof,
		) -> Option<()> {
			let key_owner_proof = key_owner_proof.decode()?;

			Babe::submit_unsigned_equivocation_report(
				equivocation_proof,
				key_owner_proof,
			)
		}
	}

	impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
		fn authorities() -> Vec<AuthorityDiscoveryId> {
			AuthorityDiscovery::authorities()
		}
	}

	impl sp_session::SessionKeys<Block> for Runtime {
		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
			SessionKeys::generate(seed)
		}

		fn decode_session_keys(
			encoded: Vec<u8>,
		) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
			SessionKeys::decode_into_raw_public_keys(&encoded)
		}
	}

	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
		fn account_nonce(account: AccountId) -> Nonce {
			System::account_nonce(account)
		}
	}

	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
		Block,
		Balance,
	> for Runtime {
		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
			TransactionPayment::query_info(uxt, len)
		}
	}
}