lib.rs 35.1 KB
Newer Older
ddorgan's avatar
ddorgan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Copyright 2017-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/>.

//! The Polkadot runtime. This can be compiled with `#[no_std]`, ready for Wasm.

#![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"]
ddorgan's avatar
ddorgan committed
22

Albrecht's avatar
Albrecht committed
23
use pallet_transaction_payment::CurrencyAdapter;
ddorgan's avatar
ddorgan 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, Decode};
27
use primitives::v1::{
28
29
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
	CoreState, GroupRotationInfo, Hash, Id, Moment, Nonce, OccupiedCoreAssumption,
30
	PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
31
	InboundDownwardMessage, InboundHrmpMessage, SessionInfo, AssignmentId,
ddorgan's avatar
ddorgan committed
32
};
33
use runtime_common::{
34
35
	SlowAdjustingFeeUpdate, CurrencyToVote,
	impls::ToAuthor,
36
	BlockHashCount, BlockWeights, BlockLength, RocksDbWeight, OffchainSolutionWeightLimit,
37
	ParachainSessionKeyPlaceholder, AssignmentSessionKeyPlaceholder,
ddorgan's avatar
ddorgan committed
38
39
40
};
use sp_runtime::{
	create_runtime_str, generic, impl_opaque_keys,
41
	ApplyExtrinsicResult, KeyTypeId, Perbill, curve::PiecewiseLinear,
Gavin Wood's avatar
Gavin Wood committed
42
	transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
ddorgan's avatar
ddorgan committed
43
	traits::{
44
		BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
Gavin Wood's avatar
Gavin Wood committed
45
		Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
ddorgan's avatar
ddorgan committed
46
47
48
49
	},
};
#[cfg(feature = "runtime-benchmarks")]
use sp_runtime::RuntimeString;
50
51
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
ddorgan's avatar
ddorgan committed
52
#[cfg(any(feature = "std", test))]
53
use sp_version::NativeVersion;
ddorgan's avatar
ddorgan committed
54
55
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
56
use frame_support::{
57
	parameter_types, construct_runtime, debug, RuntimeDebug,
58
	traits::{KeyOwnerProofSystem, Randomness, Filter, InstanceFilter},
59
	weights::Weight,
60
};
61
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
ddorgan's avatar
ddorgan committed
62
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
63
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
64
use pallet_session::historical as session_historical;
65
use frame_system::{EnsureRoot};
ddorgan's avatar
ddorgan committed
66
67

#[cfg(feature = "std")]
68
pub use pallet_staking::StakerStatus;
ddorgan's avatar
ddorgan committed
69
70
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
71
72
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
ddorgan's avatar
ddorgan committed
73
74
75
76
77

/// Constant values used within the runtime.
pub mod constants;
use constants::{time::*, currency::*, fee::*};

78
79
80
// Weights used in the runtime
mod weights;

ddorgan's avatar
ddorgan committed
81
82
83
84
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

85
/// Runtime version (Westend).
ddorgan's avatar
ddorgan committed
86
87
88
89
pub const VERSION: RuntimeVersion = RuntimeVersion {
	spec_name: create_runtime_str!("westend"),
	impl_name: create_runtime_str!("parity-westend"),
	authoring_version: 2,
90
	spec_version: 48,
91
	impl_version: 0,
92
	#[cfg(not(feature = "disable-runtime-api"))]
ddorgan's avatar
ddorgan committed
93
	apis: RUNTIME_API_VERSIONS,
94
	#[cfg(feature = "disable-runtime-api")]
95
	apis: version::create_apis_vec![[]],
96
	transaction_version: 4,
ddorgan's avatar
ddorgan committed
97
98
99
100
101
102
103
104
105
106
107
};

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

108
/// Accept all transactions.
109
110
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
111
112
	fn filter(_: &Call) -> bool {
		true
ddorgan's avatar
ddorgan committed
113
114
115
116
117
	}
}

parameter_types! {
	pub const Version: RuntimeVersion = VERSION;
118
	pub const SS58Prefix: u8 = 42;
ddorgan's avatar
ddorgan committed
119
120
}

121
impl frame_system::Config for Runtime {
122
	type BaseCallFilter = BaseFilter;
123
124
	type BlockWeights = BlockWeights;
	type BlockLength = BlockLength;
ddorgan's avatar
ddorgan committed
125
126
127
128
129
130
131
	type Origin = Origin;
	type Call = Call;
	type Index = Nonce;
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
132
	type Lookup = AccountIdLookup<AccountId, ()>;
ddorgan's avatar
ddorgan committed
133
134
135
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
	type Event = Event;
	type BlockHashCount = BlockHashCount;
136
	type DbWeight = RocksDbWeight;
ddorgan's avatar
ddorgan committed
137
	type Version = Version;
138
	type PalletInfo = PalletInfo;
139
	type AccountData = pallet_balances::AccountData<Balance>;
ddorgan's avatar
ddorgan committed
140
141
	type OnNewAccount = ();
	type OnKilledAccount = ();
142
	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
143
	type SS58Prefix = SS58Prefix;
ddorgan's avatar
ddorgan committed
144
145
}

146
parameter_types! {
147
148
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
149
150
151
	pub const MaxScheduledPerBlock: u32 = 50;
}

152
impl pallet_scheduler::Config for Runtime {
ddorgan's avatar
ddorgan committed
153
154
	type Event = Event;
	type Origin = Origin;
155
	type PalletsOrigin = OriginCaller;
ddorgan's avatar
ddorgan committed
156
	type Call = Call;
157
	type MaximumWeight = MaximumSchedulerWeight;
158
	type ScheduleOrigin = EnsureRoot<AccountId>;
159
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
160
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
161
162
163
164
165
166
167
}

parameter_types! {
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64;
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
}

168
impl pallet_babe::Config for Runtime {
ddorgan's avatar
ddorgan committed
169
170
171
172
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;

	// session module is the trigger
173
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
174
175
176
177
178

	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
179
		pallet_babe::AuthorityId,
180
181
182
183
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
184
		pallet_babe::AuthorityId,
185
186
187
	)>>::IdentificationTuple;

	type HandleEquivocation =
188
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences>;
189
190

	type WeightInfo = ();
ddorgan's avatar
ddorgan committed
191
192
193
194
195
196
}

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

197
impl pallet_indices::Config for Runtime {
ddorgan's avatar
ddorgan committed
198
199
200
201
	type AccountIndex = AccountIndex;
	type Currency = Balances;
	type Deposit = IndexDeposit;
	type Event = Event;
202
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
203
204
205
206
}

parameter_types! {
	pub const ExistentialDeposit: Balance = 1 * CENTS;
207
	pub const MaxLocks: u32 = 50;
ddorgan's avatar
ddorgan committed
208
209
}

210
impl pallet_balances::Config for Runtime {
ddorgan's avatar
ddorgan committed
211
212
213
214
215
	type Balance = Balance;
	type DustRemoval = ();
	type Event = Event;
	type ExistentialDeposit = ExistentialDeposit;
	type AccountStore = System;
216
	type MaxLocks = MaxLocks;
217
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
218
219
220
221
222
223
}

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

224
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
225
	type OnChargeTransaction = CurrencyAdapter<Balances, ToAuthor<Runtime>>;
ddorgan's avatar
ddorgan committed
226
227
	type TransactionByteFee = TransactionByteFee;
	type WeightToFee = WeightToFee;
228
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
ddorgan's avatar
ddorgan committed
229
230
231
232
233
}

parameter_types! {
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
}
234
impl pallet_timestamp::Config for Runtime {
ddorgan's avatar
ddorgan committed
235
236
237
	type Moment = u64;
	type OnTimestampSet = Babe;
	type MinimumPeriod = MinimumPeriod;
238
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
239
240
241
242
243
244
245
}

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

// TODO: substrate#2986 implement this properly
246
impl pallet_authorship::Config for Runtime {
247
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
ddorgan's avatar
ddorgan committed
248
249
250
251
252
253
254
255
256
257
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
	type EventHandler = (Staking, ImOnline);
}

parameter_types! {
	pub const Period: BlockNumber = 10 * MINUTES;
	pub const Offset: BlockNumber = 0;
}

258
259
260
261
262
263
264
265
266
267
impl_opaque_keys! {
	pub struct OldSessionKeys {
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub authority_discovery: AuthorityDiscovery,
	}
}

ddorgan's avatar
ddorgan committed
268
269
270
271
272
impl_opaque_keys! {
	pub struct SessionKeys {
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
273
274
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub para_assignment: AssignmentSessionKeyPlaceholder<Runtime>,
ddorgan's avatar
ddorgan committed
275
276
277
278
		pub authority_discovery: AuthorityDiscovery,
	}
}

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
fn transform_session_keys(v: AccountId, old: OldSessionKeys) -> SessionKeys {
	SessionKeys {
		grandpa: old.grandpa,
		babe: old.babe,
		im_online: old.im_online,
		para_validator: old.para_validator,
		para_assignment: {
			// We need to produce a dummy value that's unique for the validator.
			let mut id = AssignmentId::default();
			let id_raw: &mut [u8] = id.as_mut();
			id_raw.copy_from_slice(v.as_ref());
			id_raw[0..4].copy_from_slice(b"asgn");

			id
		},
		authority_discovery: old.authority_discovery,
	}
}

ddorgan's avatar
ddorgan committed
298
299
300
301
parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

302
impl pallet_session::Config for Runtime {
ddorgan's avatar
ddorgan committed
303
304
	type Event = Event;
	type ValidatorId = AccountId;
305
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
ddorgan's avatar
ddorgan committed
306
307
	type ShouldEndSession = Babe;
	type NextSessionRotation = Babe;
308
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
ddorgan's avatar
ddorgan committed
309
310
311
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
	type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
312
	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
313
314
}

315
impl pallet_session::historical::Config for Runtime {
316
317
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
ddorgan's avatar
ddorgan committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
}

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).
335
	pub const BondingDuration: pallet_staking::EraIndex = 28;
336
	// 27 eras in which slashes can be cancelled (slightly less than 7 days).
337
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
ddorgan's avatar
ddorgan committed
338
339
340
341
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
	pub const MaxNominatorRewardedPerValidator: u32 = 64;
	// quarter of the last session will be for election.
	pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4;
342
	pub const MaxIterations: u32 = 10;
343
	pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000);
ddorgan's avatar
ddorgan committed
344
345
}

346
impl pallet_staking::Config for Runtime {
ddorgan's avatar
ddorgan committed
347
348
	type Currency = Balances;
	type UnixTime = Timestamp;
349
	type CurrencyToVote = CurrencyToVote;
ddorgan's avatar
ddorgan committed
350
351
352
353
354
355
356
357
	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.
358
	type SlashCancelOrigin = EnsureRoot<AccountId>;
ddorgan's avatar
ddorgan committed
359
360
361
362
363
364
365
	type SessionInterface = Self;
	type RewardCurve = RewardCurve;
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
	type NextNewSession = Session;
	type ElectionLookahead = ElectionLookahead;
	type Call = Call;
	type UnsignedPriority = StakingUnsignedPriority;
366
	type MaxIterations = MaxIterations;
367
	type MinSolutionScoreBump = MinSolutionScoreBump;
368
	type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit;
369
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
}

parameter_types! {
	pub const LaunchPeriod: BlockNumber = 7 * DAYS;
	pub const VotingPeriod: BlockNumber = 7 * DAYS;
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
	pub const MinimumDeposit: Balance = 1 * DOLLARS;
	pub const EnactmentPeriod: BlockNumber = 8 * DAYS;
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 10 * MILLICENTS;
	pub const InstantAllowed: bool = true;
}

384
parameter_types! {
385
	pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * BlockWeights::get().max_block;
386
387
}

388
impl pallet_offences::Config for Runtime {
ddorgan's avatar
ddorgan committed
389
	type Event = Event;
390
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
ddorgan's avatar
ddorgan committed
391
	type OnOffenceHandler = Staking;
392
	type WeightSoftLimit = OffencesWeightSoftLimit;
ddorgan's avatar
ddorgan committed
393
394
}

395
impl pallet_authority_discovery::Config for Runtime {}
ddorgan's avatar
ddorgan committed
396
397
398
399
400
401
402
403
404
405

parameter_types! {
	pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS as _;
}

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

406
impl pallet_im_online::Config for Runtime {
ddorgan's avatar
ddorgan committed
407
408
409
410
411
	type AuthorityId = ImOnlineId;
	type Event = Event;
	type ReportUnresponsiveness = Offences;
	type SessionDuration = SessionDuration;
	type UnsignedPriority = StakingUnsignedPriority;
412
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
413
414
}

415
impl pallet_grandpa::Config for Runtime {
ddorgan's avatar
ddorgan committed
416
	type Event = Event;
417
418
419
420
421
422
423
424
425
426
427
428
	type Call = Call;

	type KeyOwnerProofSystem = Historical;

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

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

429
	type HandleEquivocation = pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences>;
430
431

	type WeightInfo = ();
ddorgan's avatar
ddorgan committed
432
433
}

434
435
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
436
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
437
438
	Call: From<LocalCall>,
{
439
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
440
441
442
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
443
		nonce: <Runtime as frame_system::Config>::Index,
444
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
445
		use sp_runtime::traits::StaticLookup;
446
		// take the biggest period possible.
447
448
449
450
451
452
453
		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>()
454
455
			// The `System::block_number` is initialized with `n+1`,
			// so the actual block number is `n`.
456
457
458
			.saturating_sub(1);
		let tip = 0;
		let extra: SignedExtra = (
459
460
461
462
463
464
465
			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),
466
467
		);
		let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
468
			debug::warn!("Unable to create signed payload: {:?}", e);
469
		}).ok()?;
470
471
472
		let signature = raw_payload.using_encoded(|payload| {
			C::sign(payload, public)
		})?;
473
		let (call, extra, _) = raw_payload.deconstruct();
474
475
		let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
		Some((call, (address, signature, extra)))
476
	}
ddorgan's avatar
ddorgan committed
477
478
}

479
impl frame_system::offchain::SigningTypes for Runtime {
480
481
482
483
	type Public = <Signature as Verify>::Signer;
	type Signature = Signature;
}

484
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where
485
486
487
488
489
490
	Call: From<C>,
{
	type OverarchingCall = Call;
	type Extrinsic = UncheckedExtrinsic;
}

ddorgan's avatar
ddorgan committed
491
492
493
494
495
496
497
parameter_types! {
	// Minimum 100 bytes/KSM deposited (1 CENT/byte)
	pub const BasicDeposit: Balance = 10 * DOLLARS;       // 258 bytes on-chain
	pub const FieldDeposit: Balance = 250 * CENTS;        // 66 bytes on-chain
	pub const SubAccountDeposit: Balance = 2 * DOLLARS;   // 53 bytes on-chain
	pub const MaxSubAccounts: u32 = 100;
	pub const MaxAdditionalFields: u32 = 100;
498
	pub const MaxRegistrars: u32 = 20;
ddorgan's avatar
ddorgan committed
499
500
}

501
impl pallet_identity::Config for Runtime {
ddorgan's avatar
ddorgan committed
502
503
504
505
506
507
508
509
	type Event = Event;
	type Currency = Balances;
	type Slashed = ();
	type BasicDeposit = BasicDeposit;
	type FieldDeposit = FieldDeposit;
	type SubAccountDeposit = SubAccountDeposit;
	type MaxSubAccounts = MaxSubAccounts;
	type MaxAdditionalFields = MaxAdditionalFields;
510
	type MaxRegistrars = MaxRegistrars;
511
512
	type RegistrarOrigin = frame_system::EnsureRoot<AccountId>;
	type ForceOrigin = frame_system::EnsureRoot<AccountId>;
513
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
514
515
}

516
impl pallet_utility::Config for Runtime {
517
518
	type Event = Event;
	type Call = Call;
519
	type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
520
521
}

ddorgan's avatar
ddorgan committed
522
parameter_types! {
523
524
	// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
	pub const DepositBase: Balance = deposit(1, 88);
ddorgan's avatar
ddorgan committed
525
	// Additional storage item size of 32 bytes.
526
	pub const DepositFactor: Balance = deposit(0, 32);
ddorgan's avatar
ddorgan committed
527
528
529
	pub const MaxSignatories: u16 = 100;
}

530
impl pallet_multisig::Config for Runtime {
ddorgan's avatar
ddorgan committed
531
532
533
	type Event = Event;
	type Call = Call;
	type Currency = Balances;
534
535
	type DepositBase = DepositBase;
	type DepositFactor = DepositFactor;
ddorgan's avatar
ddorgan committed
536
	type MaxSignatories = MaxSignatories;
537
	type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
538
539
540
541
542
543
544
545
546
}

parameter_types! {
	pub const ConfigDepositBase: Balance = 5 * DOLLARS;
	pub const FriendDepositFactor: Balance = 50 * CENTS;
	pub const MaxFriends: u16 = 9;
	pub const RecoveryDeposit: Balance = 5 * DOLLARS;
}

547
impl pallet_recovery::Config for Runtime {
ddorgan's avatar
ddorgan committed
548
549
550
551
552
553
554
555
556
557
558
559
560
	type Event = Event;
	type Call = Call;
	type Currency = Balances;
	type ConfigDepositBase = ConfigDepositBase;
	type FriendDepositFactor = FriendDepositFactor;
	type MaxFriends = MaxFriends;
	type RecoveryDeposit = RecoveryDeposit;
}

parameter_types! {
	pub const MinVestedTransfer: Balance = 100 * DOLLARS;
}

561
impl pallet_vesting::Config for Runtime {
ddorgan's avatar
ddorgan committed
562
563
564
565
	type Event = Event;
	type Currency = Balances;
	type BlockNumberToBalance = ConvertInto;
	type MinVestedTransfer = MinVestedTransfer;
566
	type WeightInfo = weights::pallet_vesting::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
567
568
}

569
impl pallet_sudo::Config for Runtime {
ddorgan's avatar
ddorgan committed
570
571
572
573
	type Event = Event;
	type Call = Call;
}

574
575
576
577
578
579
parameter_types! {
	// One storage item; key size 32, value size 8; .
	pub const ProxyDepositBase: Balance = deposit(1, 8);
	// Additional storage item size of 33 bytes.
	pub const ProxyDepositFactor: Balance = deposit(0, 33);
	pub const MaxProxies: u16 = 32;
580
581
582
	pub const AnnouncementDepositBase: Balance = deposit(1, 8);
	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
	pub const MaxPending: u16 = 32;
583
584
585
586
587
588
589
590
}

/// The type used to represent the kinds of proxying allowed.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug)]
pub enum ProxyType {
	Any,
	NonTransfer,
	Staking,
591
	SudoBalances,
Chevdor's avatar
Chevdor committed
592
	IdentityJudgement,
593
594
595
596
597
598
}
impl Default for ProxyType { fn default() -> Self { Self::Any } }
impl InstanceFilter<Call> for ProxyType {
	fn filter(&self, c: &Call) -> bool {
		match self {
			ProxyType::Any => true,
599
600
601
602
			ProxyType::NonTransfer => matches!(c,
				Call::System(..) |
				Call::Babe(..) |
				Call::Timestamp(..) |
603
604
605
				Call::Indices(pallet_indices::Call::claim(..)) |
				Call::Indices(pallet_indices::Call::free(..)) |
				Call::Indices(pallet_indices::Call::freeze(..)) |
606
607
608
609
610
611
612
613
614
615
616
				// Specifically omitting Indices `transfer`, `force_transfer`
				// Specifically omitting the entire Balances pallet
				Call::Authorship(..) |
				Call::Staking(..) |
				Call::Offences(..) |
				Call::Session(..) |
				Call::Grandpa(..) |
				Call::ImOnline(..) |
				Call::AuthorityDiscovery(..) |
				Call::Utility(..) |
				Call::Identity(..) |
617
618
619
620
621
622
				Call::Recovery(pallet_recovery::Call::as_recovered(..)) |
				Call::Recovery(pallet_recovery::Call::vouch_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::claim_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::close_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::remove_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::cancel_recovered(..)) |
623
				// Specifically omitting Recovery `create_recovery`, `initiate_recovery`
624
625
				Call::Vesting(pallet_vesting::Call::vest(..)) |
				Call::Vesting(pallet_vesting::Call::vest_other(..)) |
626
627
628
629
630
				// Specifically omitting Vesting `vested_transfer`, and `force_vested_transfer`
				Call::Scheduler(..) |
				// Specifically omitting Sudo pallet
				Call::Proxy(..) |
				Call::Multisig(..)
631
632
			),
			ProxyType::Staking => matches!(c,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
633
634
635
				Call::Staking(..) |
				Call::Session(..) |
				Call::Utility(..)
636
			),
637
			ProxyType::SudoBalances => match c {
638
				Call::Sudo(pallet_sudo::Call::sudo(ref x)) => matches!(x.as_ref(), &Call::Balances(..)),
Gavin Wood's avatar
Gavin Wood committed
639
				Call::Utility(..) => true,
640
641
				_ => false,
			},
Chevdor's avatar
Chevdor committed
642
			ProxyType::IdentityJudgement => matches!(c,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
643
644
				Call::Identity(pallet_identity::Call::provide_judgement(..)) |
				Call::Utility(..)
Chevdor's avatar
Chevdor committed
645
			)
646
647
648
649
650
651
652
653
654
		}
	}
	fn is_superset(&self, o: &Self) -> bool {
		match (self, o) {
			(x, y) if x == y => true,
			(ProxyType::Any, _) => true,
			(_, ProxyType::Any) => false,
			(ProxyType::NonTransfer, _) => true,
			_ => false,
655
656
657
658
		}
	}
}

659
impl pallet_proxy::Config for Runtime {
660
661
662
663
664
665
666
	type Event = Event;
	type Call = Call;
	type Currency = Balances;
	type ProxyType = ProxyType;
	type ProxyDepositBase = ProxyDepositBase;
	type ProxyDepositFactor = ProxyDepositFactor;
	type MaxProxies = MaxProxies;
667
	type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
668
669
670
671
	type MaxPending = MaxPending;
	type CallHasher = BlakeTwo256;
	type AnnouncementDepositBase = AnnouncementDepositBase;
	type AnnouncementDepositFactor = AnnouncementDepositFactor;
672
673
}

ddorgan's avatar
ddorgan committed
674
675
676
construct_runtime! {
	pub enum Runtime where
		Block = Block,
677
		NodeBlock = primitives::v1::Block,
ddorgan's avatar
ddorgan committed
678
679
680
		UncheckedExtrinsic = UncheckedExtrinsic
	{
		// Basic stuff; balances is uncallable initially.
681
682
		System: frame_system::{Module, Call, Storage, Config, Event<T>} = 0,
		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Storage} = 25,
ddorgan's avatar
ddorgan committed
683
684

		// Must be before session.
685
		Babe: pallet_babe::{Module, Call, Storage, Config, Inherent, ValidateUnsigned} = 1,
ddorgan's avatar
ddorgan committed
686

687
688
689
690
		Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent} = 2,
		Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>} = 3,
		Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>} = 4,
		TransactionPayment: pallet_transaction_payment::{Module, Storage} = 26,
ddorgan's avatar
ddorgan committed
691
692

		// Consensus support.
693
694
695
696
697
698
699
700
		Authorship: pallet_authorship::{Module, Call, Storage} = 5,
		Staking: pallet_staking::{Module, Call, Storage, Config<T>, Event<T>, ValidateUnsigned} = 6,
		Offences: pallet_offences::{Module, Call, Storage, Event} = 7,
		Historical: session_historical::{Module} = 27,
		Session: pallet_session::{Module, Call, Storage, Event, Config<T>} = 8,
		Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event, ValidateUnsigned} = 10,
		ImOnline: pallet_im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>} = 11,
		AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config} = 12,
ddorgan's avatar
ddorgan committed
701
702

		// Utility module.
703
		Utility: pallet_utility::{Module, Call, Event} = 16,
ddorgan's avatar
ddorgan committed
704
705

		// Less simple identity module.
706
		Identity: pallet_identity::{Module, Call, Storage, Event<T>} = 17,
ddorgan's avatar
ddorgan committed
707
708

		// Social recovery module.
709
		Recovery: pallet_recovery::{Module, Call, Storage, Event<T>} = 18,
ddorgan's avatar
ddorgan committed
710
711

		// Vesting. Usable initially, but removed once all vesting is finished.
712
		Vesting: pallet_vesting::{Module, Call, Storage, Event<T>, Config<T>} = 19,
ddorgan's avatar
ddorgan committed
713
714

		// System scheduler.
715
		Scheduler: pallet_scheduler::{Module, Call, Storage, Event<T>} = 20,
ddorgan's avatar
ddorgan committed
716
717

		// Sudo.
718
		Sudo: pallet_sudo::{Module, Call, Storage, Event<T>, Config<T>} = 21,
719
720

		// Proxy module. Late addition.
721
		Proxy: pallet_proxy::{Module, Call, Storage, Event<T>} = 22,
722
723

		// Multisig module. Late addition.
724
		Multisig: pallet_multisig::{Module, Call, Storage, Event<T>} = 23,
ddorgan's avatar
ddorgan committed
725
726
727
728
	}
}

/// The address format for describing accounts.
729
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
ddorgan's avatar
ddorgan committed
730
731
732
733
734
735
736
737
738
739
/// 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 = (
740
741
742
743
744
745
746
	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>,
ddorgan's avatar
ddorgan committed
747
748
749
750
751
752
);
/// 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.
753
754
755
756
757
758
pub type Executive = frame_executive::Executive<
	Runtime,
	Block,
	frame_system::ChainContext<Runtime>,
	Runtime,
	AllModules,
759
	UpgradeSessionKeys,
760
>;
761
762
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;
ddorgan's avatar
ddorgan committed
763

764
765
766
767
768
769
770
771
772
// When this is removed, should also remove `OldSessionKeys`.
pub struct UpgradeSessionKeys;
impl frame_support::traits::OnRuntimeUpgrade for UpgradeSessionKeys {
	fn on_runtime_upgrade() -> frame_support::weights::Weight {
		Session::upgrade_keys::<OldSessionKeys, _>(transform_session_keys);
		Perbill::from_percent(50) * BlockWeights::get().max_block
	}
}

773
774
775
pub struct CustomOnRuntimeUpgrade;
impl frame_support::traits::OnRuntimeUpgrade for CustomOnRuntimeUpgrade {
	fn on_runtime_upgrade() -> frame_support::weights::Weight {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
776
		0
777
778
779
	}
}

780
#[cfg(not(feature = "disable-runtime-api"))]
ddorgan's avatar
ddorgan committed
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
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
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 {
			RandomnessCollectiveFlip::random_seed()
		}
	}

	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)
		}
	}

842
843
844
	impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
		fn validators() -> Vec<ValidatorId> {
			Vec::new()
ddorgan's avatar
ddorgan committed
845
		}
846
847
848

		fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
			(Vec::new(), GroupRotationInfo { session_start_block: 0, group_rotation_frequency: 0, now: 0 })
ddorgan's avatar
ddorgan committed
849
		}
850

851
		fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
852
			Vec::new()
ddorgan's avatar
ddorgan committed
853
		}
854
855
856

		fn persisted_validation_data(_: Id, _: OccupiedCoreAssumption)
			-> Option<PersistedValidationData<BlockNumber>> {
857
			None
ddorgan's avatar
ddorgan committed
858
		}
859

860
861
862
863
		fn historical_validation_code(_: Id, _: BlockNumber) -> Option<ValidationCode> {
			None
		}

864
865
		fn check_validation_outputs(
			_: Id,
866
			_: primitives::v1::CandidateCommitments
867
868
869
870
		) -> bool {
			false
		}

871
872
873
874
		fn session_index_for_child() -> SessionIndex {
			0
		}

875
876
877
878
		fn session_info(_: SessionIndex) -> Option<SessionInfo> {
			None
		}

879
		fn validation_code(_: Id, _: OccupiedCoreAssumption) -> Option<ValidationCode> {
880
			None
ddorgan's avatar
ddorgan committed
881
		}
882
883
884

		fn candidate_pending_availability(_: Id) -> Option<CommittedCandidateReceipt<Hash>> {
			None
ddorgan's avatar
ddorgan committed
885
		}
886
887

		fn candidate_events() -> Vec<CandidateEvent<Hash>> {
888
			Vec::new()
889
		}
890

891
892
		fn dmq_contents(
			_recipient: Id,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
893
		) -> Vec<InboundDownwardMessage<BlockNumber>> {
894
895
			Vec::new()
		}
Sergey Pepyakin's avatar
Sergey Pepyakin committed
896
897
898
899
900
901

		fn inbound_hrmp_channels_contents(
			_recipient: Id
		) -> BTreeMap<Id, Vec<InboundHrmpMessage<BlockNumber>>> {
			BTreeMap::new()
		}
ddorgan's avatar
ddorgan committed
902
903
904
905
906
907
	}

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

909
		fn submit_report_equivocation_unsigned_extrinsic(
910
911
912
913
914
915
916
917
			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()?;

918
			Grandpa::submit_unsigned_equivocation_report(
919
920
921
922
923
924
925
926
927
				equivocation_proof,
				key_owner_proof,
			)
		}

		fn generate_key_ownership_proof(
			_set_id: fg_primitives::SetId,
			authority_id: fg_primitives::AuthorityId,
		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
928
			use parity_scale_codec::Encode;
929
930
931
932
933

			Historical::prove((fg_primitives::KEY_TYPE, authority_id))
				.map(|p| p.encode())
				.map(fg_primitives::OpaqueKeyOwnershipProof::new)
		}
ddorgan's avatar
ddorgan committed
934
935
936
	}

	impl babe_primitives::BabeApi<Block> for Runtime {
937
		fn configuration() -> babe_primitives::BabeGenesisConfiguration {
ddorgan's avatar
ddorgan committed
938
939
940
941
942
			// 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>
943
			babe_primitives::BabeGenesisConfiguration {
ddorgan's avatar
ddorgan committed
944
945
946
947
948
				slot_duration: Babe::slot_duration(),
				epoch_length: EpochDuration::get(),
				c: PRIMARY_PROBABILITY,
				genesis_authorities: Babe::authorities(),
				randomness: Babe::randomness(),
949
				allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryPlainSlots,
ddorgan's avatar
ddorgan committed
950
951
952
953
954
955
			}
		}

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

957
958
959
960
		fn current_epoch() -> babe_primitives::Epoch {
			Babe::current_epoch()
		}

961
962
963
964
		fn next_epoch() -> babe_primitives::Epoch {
			Babe::next_epoch()
		}

965
966
967
968
		fn generate_key_ownership_proof(
			_slot_number: babe_primitives::SlotNumber,
			authority_id: babe_primitives::AuthorityId,
		) -> Option<babe_primitives::OpaqueKeyOwnershipProof> {
969
			use parity_scale_codec::Encode;
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986

			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,
			)
		}
ddorgan's avatar
ddorgan committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
	}

	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(
For faster browsing, not all history is shown. View entire blame