lib.rs 11.6 KB
Newer Older
Gav's avatar
Gav committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2017 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 Polkadot runtime. This can be compiled with ``#[no_std]`, ready for Wasm.
Gav's avatar
Gav committed
18
19

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

23
mod curated_grandpa;
24
mod parachains;
Gav Wood's avatar
Gav Wood committed
25
mod claims;
Gavin Wood's avatar
Gavin Wood committed
26
27
mod slot_range;
mod slots;
Gav Wood's avatar
Gav Wood committed
28

29
30
use rstd::prelude::*;
use substrate_primitives::u32_trait::{_2, _4};
31
use primitives::{
32
33
	AccountId, AccountIndex, Balance, BlockNumber, Hash, Nonce, SessionKey, Signature,
	parachain, SessionSignature,
34
};
35
use client::{
36
	block_builder::api::{self as block_builder_api, InherentData, CheckInherentsResult},
37
	runtime_api as client_api, impl_runtime_apis,
38
};
Gav Wood's avatar
Gav Wood committed
39
use sr_primitives::{
40
	ApplyResult, generic, transaction_validity::TransactionValidity, create_runtime_str,
41
	traits::{
42
		BlakeTwo256, Block as BlockT, DigestFor, StaticLookup, Convert, AuthorityIdFor
43
	}
Gav Wood's avatar
Gav Wood committed
44
};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
45
use version::RuntimeVersion;
46
use grandpa::fg_primitives::{self, ScheduledChange};
47
use council::{motions as council_motions, voting as council_voting};
48
#[cfg(feature = "std")]
49
50
51
52
use council::seats as council_seats;
#[cfg(any(feature = "std", test))]
use version::NativeVersion;
use substrate_primitives::OpaqueMetadata;
53
use srml_support::{parameter_types, construct_runtime};
54

Gav Wood's avatar
Gav Wood committed
55
56
#[cfg(feature = "std")]
pub use staking::StakerStatus;
57
58
#[cfg(any(feature = "std", test))]
pub use sr_primitives::BuildStorage;
59
60
pub use consensus::Call as ConsensusCall;
pub use timestamp::Call as TimestampCall;
61
pub use balances::Call as BalancesCall;
62
pub use parachains::{Call as ParachainsCall, INHERENT_IDENTIFIER as PARACHAIN_INHERENT_IDENTIFIER};
63
64
pub use sr_primitives::{Permill, Perbill};
pub use timestamp::BlockPeriod;
65
pub use srml_support::StorageValue;
66

67
/// Runtime version.
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
68
pub const VERSION: RuntimeVersion = RuntimeVersion {
69
70
	spec_name: create_runtime_str!("polkadot"),
	impl_name: create_runtime_str!("parity-polkadot"),
Gav Wood's avatar
Gav Wood committed
71
	authoring_version: 1,
André Silva's avatar
André Silva committed
72
	spec_version: 1000,
73
	impl_version: 0,
74
	apis: RUNTIME_API_VERSIONS,
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
75
76
};

77
78
79
80
81
82
83
84
85
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
	NativeVersion {
		runtime_version: VERSION,
		can_author_with: Default::default(),
	}
}

86
87
impl system::Trait for Runtime {
	type Origin = Origin;
Gav Wood's avatar
Gav Wood committed
88
	type Index = Nonce;
89
90
91
92
93
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type Digest = generic::Digest<Log>;
	type AccountId = AccountId;
Gav Wood's avatar
Gav Wood committed
94
	type Lookup = Indices;
95
	type Header = generic::Header<BlockNumber, BlakeTwo256, Log>;
Gav's avatar
Gav committed
96
	type Event = Event;
97
	type Log = Log;
98
99
}

100
101
102
103
impl aura::Trait for Runtime {
	type HandleReport = aura::StakingSlasher<Runtime>;
}

Gav Wood's avatar
Gav Wood committed
104
105
106
107
108
109
110
impl indices::Trait for Runtime {
	type IsDeadAccount = Balances;
	type AccountIndex = AccountIndex;
	type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
	type Event = Event;
}

111
impl balances::Trait for Runtime {
Gav's avatar
Gav committed
112
113
	type Balance = Balance;
	type OnFreeBalanceZero = Staking;
Gav Wood's avatar
Gav Wood committed
114
	type OnNewAccount = Indices;
Gav's avatar
Gav committed
115
	type Event = Event;
116
117
118
	type TransactionPayment = ();
	type DustRemoval = ();
	type TransferPayment = ();
Gav's avatar
Gav committed
119
120
}

121
122
impl consensus::Trait for Runtime {
	type Log = Log;
123
	type SessionKey = SessionKey;
124
125
126
127

	// the aura module handles offline-reports internally
	// rather than using an explicit report system.
	type InherentOfflineReport = ();
128
129
}

130
impl timestamp::Trait for Runtime {
131
	type Moment = u64;
132
	type OnTimestampSet = Aura;
133
134
}

135
impl session::Trait for Runtime {
Gav Wood's avatar
Gav Wood committed
136
	type ConvertAccountIdToSessionKey = ();
137
	type OnSessionChange = Staking;
Gav's avatar
Gav committed
138
	type Event = Event;
139
140
}

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/// 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() }
}


157
158
impl staking::Trait for Runtime {
	type OnRewardMinted = Treasury;
159
	type CurrencyToVote = CurrencyToVoteHandler;
Gav's avatar
Gav committed
160
	type Event = Event;
161
162
163
	type Currency = balances::Module<Self>;
	type Slash = ();
	type Reward = ();
164
165
}

166
167
168
169
170
171
172
173
174
175
const MINUTES: BlockNumber = 6;
const BUCKS: Balance = 1_000_000_000_000;

parameter_types! {
	pub const LaunchPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
	pub const VotingPeriod: BlockNumber = 28 * 24 * 60 * MINUTES;
	pub const MinimumDeposit: Balance = 100 * BUCKS;
	pub const EnactmentPeriod: BlockNumber = 30 * 24 * 60 * MINUTES;
}

176
impl democracy::Trait for Runtime {
177
	type Currency = balances::Module<Self>;
178
179
	type Proposal = Call;
	type Event = Event;
180
181
182
183
	type EnactmentPeriod = EnactmentPeriod;
	type LaunchPeriod = LaunchPeriod;
	type VotingPeriod = VotingPeriod;
	type MinimumDeposit = MinimumDeposit;
184
}
185
186
187

impl council::Trait for Runtime {
	type Event = Event;
188
189
	type BadPresentation = ();
	type BadReaper = ();
190
}
191

192
193
194
195
196
197
198
199
200
201
202
impl council::voting::Trait for Runtime {
	type Event = Event;
}

impl council::motions::Trait for Runtime {
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
}

impl treasury::Trait for Runtime {
203
	type Currency = balances::Module<Self>;
204
205
206
	type ApproveOrigin = council_motions::EnsureMembers<_4>;
	type RejectOrigin = council_motions::EnsureMembers<_2>;
	type Event = Event;
207
208
	type MintedForSpending = ();
	type ProposalRejection = ();
209
}
210

211
212
213
214
215
216
impl grandpa::Trait for Runtime {
	type SessionKey = SessionKey;
	type Log = Log;
	type Event = Event;
}

217
218
219
220
impl parachains::Trait for Runtime {
	type Origin = Origin;
	type Call = Call;
}
221

Gavin Wood's avatar
Gavin Wood committed
222
223
224
225
226
227
228
229
230
231
232
233
234
parameter_types!{
	pub const LeasePeriod: BlockNumber = 100000;
	pub const EndingPeriod: BlockNumber = 1000;
}

impl slots::Trait for Runtime {
	type Event = Event;
	type Currency = balances::Module<Self>;
	type Parachains = parachains::Module<Self>;
	type LeasePeriod = LeasePeriod;
	type EndingPeriod = EndingPeriod;
}

235
236
impl curated_grandpa::Trait for Runtime { }

Gav Wood's avatar
Gav Wood committed
237
238
239
240
241
impl sudo::Trait for Runtime {
	type Event = Event;
	type Proposal = Call;
}

242
construct_runtime!(
Gav Wood's avatar
Gav Wood committed
243
	pub enum Runtime with Log(InternalLog: DigestItem<Hash, SessionKey, SessionSignature>) where
244
		Block = Block,
245
		NodeBlock = primitives::Block,
246
		UncheckedExtrinsic = UncheckedExtrinsic
247
248
	{
		System: system::{default, Log(ChangesTrieRoot)},
249
		Aura: aura::{Module},
250
		Timestamp: timestamp::{Module, Call, Storage, Config<T>, Inherent},
251
252
		// consensus' Inherent is not provided because it assumes instant-finality blocks.
		Consensus: consensus::{Module, Call, Storage, Config<T>, Log(AuthoritiesChange) },
Gav Wood's avatar
Gav Wood committed
253
		Indices: indices,
254
255
256
257
		Balances: balances,
		Session: session,
		Staking: staking,
		Democracy: democracy,
258
		Grandpa: grandpa::{Module, Call, Storage, Config<T>, Log(), Event<T>},
259
		CuratedGrandpa: curated_grandpa::{Module, Call, Config<T>, Storage},
260
261
262
263
264
		Council: council::{Module, Call, Storage, Event<T>},
		CouncilVoting: council_voting,
		CouncilMotions: council_motions::{Module, Call, Storage, Event<T>, Origin},
		CouncilSeats: council_seats::{Config<T>},
		Treasury: treasury,
265
		Parachains: parachains::{Module, Call, Storage, Config<T>, Inherent, Origin},
Gavin Wood's avatar
Gavin Wood committed
266
		Slots: slots::{Module, Call, Storage, Event<T>},
Gav Wood's avatar
Gav Wood committed
267
		Sudo: sudo,
Gav's avatar
Gav committed
268
	}
269
270
271
);

/// The address format for describing accounts.
Gav Wood's avatar
Gav Wood committed
272
pub type Address = <Indices as StaticLookup>::Source;
273
274
275
276
277
278
279
280
281
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256, Log>;
/// 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>;
/// Unchecked extrinsic type as expected by this runtime.
Gav Wood's avatar
Gav Wood committed
282
pub type UncheckedExtrinsic = generic::UncheckedMortalCompactExtrinsic<Address, Nonce, Call, Signature>;
283
/// Extrinsic type that has already been checked.
Gav Wood's avatar
Gav Wood committed
284
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Nonce, Call>;
285
/// Executive: handles dispatch to the various modules.
thiolliere's avatar
thiolliere committed
286
pub type Executive = executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Balances, Runtime, AllModules>;
287
288

impl_runtime_apis! {
289
	impl client_api::Core<Block> for Runtime {
290
291
292
293
294
295
296
		fn version() -> RuntimeVersion {
			VERSION
		}

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

298
299
		fn initialize_block(header: &<Block as BlockT>::Header) {
			Executive::initialize_block(header)
300
301
		}
	}
Gav's avatar
Gav committed
302

303
	impl client_api::Metadata<Block> for Runtime {
304
305
306
		fn metadata() -> OpaqueMetadata {
			Runtime::metadata().into()
		}
Gav's avatar
Gav committed
307
308
	}

309
	impl block_builder_api::BlockBuilder<Block> for Runtime {
310
311
312
313
		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
			Executive::apply_extrinsic(extrinsic)
		}

314
315
		fn finalize_block() -> <Block as BlockT>::Header {
			Executive::finalize_block()
316
		}
317

318
319
		fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
			data.create_extrinsics()
320
		}
321

322
323
		fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
			data.check_extrinsics(&block)
324
		}
325

326
327
328
		fn random_seed() -> <Block as BlockT>::Hash {
			System::random_seed()
		}
329
330
	}

331
	impl client_api::TaggedTransactionQueue<Block> for Runtime {
332
333
334
		fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {
			Executive::validate_transaction(tx)
		}
Gav's avatar
Gav committed
335
	}
336

337
338
339
340
341
342
	impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
		fn offchain_worker(number: sr_primitives::traits::NumberFor<Block>) {
			Executive::offchain_worker(number)
		}
	}

343
	impl parachain::ParachainHost<Block> for Runtime {
Gav Wood's avatar
Gav Wood committed
344
345
		fn validators() -> Vec<parachain::ValidatorId> {
			Consensus::authorities()  // only possible as long as parachain validator crypto === aura crypto
346
347
348
349
350
351
352
353
354
355
356
357
358
		}
		fn duty_roster() -> parachain::DutyRoster {
			Parachains::calculate_duty_roster()
		}
		fn active_parachains() -> Vec<parachain::Id> {
			Parachains::active_parachains()
		}
		fn parachain_head(id: parachain::Id) -> Option<Vec<u8>> {
			Parachains::parachain_head(&id)
		}
		fn parachain_code(id: parachain::Id) -> Option<Vec<u8>> {
			Parachains::parachain_code(&id)
		}
359
360
		fn ingress(to: parachain::Id) -> Option<parachain::ConsolidatedIngressRoots> {
			Parachains::ingress(to).map(Into::into)
361
		}
362
	}
363
364

	impl fg_primitives::GrandpaApi<Block> for Runtime {
Gav Wood's avatar
Gav Wood committed
365
		fn grandpa_pending_change(digest: &DigestFor<Block>)
366
367
368
369
370
371
372
373
374
375
376
377
378
			-> Option<ScheduledChange<BlockNumber>>
		{
			for log in digest.logs.iter().filter_map(|l| match l {
				Log(InternalLog::grandpa(grandpa_signal)) => Some(grandpa_signal),
				_=> None
			}) {
				if let Some(change) = Grandpa::scrape_digest_change(log) {
					return Some(change);
				}
			}
			None
		}

379
380
381
382
383
384
		fn grandpa_forced_change(_digest: &DigestFor<Block>)
			-> Option<(BlockNumber, ScheduledChange<BlockNumber>)>
		{
			None // disable forced changes.
		}

385
386
387
388
389
		fn grandpa_authorities() -> Vec<(SessionKey, u64)> {
			Grandpa::grandpa_authorities()
		}
	}

390
	impl consensus_aura::AuraApi<Block> for Runtime {
391
392
393
394
		fn slot_duration() -> u64 {
			Aura::slot_duration()
		}
	}
395
396
397
398
399
400
401

	impl consensus_authorities::AuthoritiesApi<Block> for Runtime {
		fn authorities() -> Vec<AuthorityIdFor<Block>> {
			Consensus::authorities()
		}
	}

Gav's avatar
Gav committed
402
}