lib.rs 12.9 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
20

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

Gav Wood's avatar
Gav Wood committed
21
22
23
24
25
26
27
#[cfg(feature = "std")]
#[macro_use]
extern crate serde_derive;

#[cfg(feature = "std")]
extern crate serde;

28
29
30
31
#[macro_use]
extern crate substrate_runtime_io as runtime_io;

#[macro_use]
Gav Wood's avatar
Gav Wood committed
32
extern crate substrate_runtime_support;
33
34
35
36

#[macro_use]
extern crate substrate_runtime_primitives as runtime_primitives;

37
#[cfg(test)]
38
39
40
#[macro_use]
extern crate hex_literal;

41
42
43
44
45
#[cfg(test)]
extern crate substrate_serializer;

extern crate substrate_primitives;

Gav Wood's avatar
Gav Wood committed
46
#[macro_use]
47
extern crate substrate_runtime_std as rstd;
Gav's avatar
Gav committed
48
49
#[macro_use]
extern crate substrate_codec_derive;
Gav Wood's avatar
Gav Wood committed
50
51

extern crate polkadot_primitives as primitives;
Gav's avatar
Gav committed
52
extern crate substrate_codec as codec;
Gav's avatar
Gav committed
53
extern crate substrate_runtime_balances as balances;
54
55
56
57
58
59
60
61
extern crate substrate_runtime_consensus as consensus;
extern crate substrate_runtime_council as council;
extern crate substrate_runtime_democracy as democracy;
extern crate substrate_runtime_executive as executive;
extern crate substrate_runtime_session as session;
extern crate substrate_runtime_staking as staking;
extern crate substrate_runtime_system as system;
extern crate substrate_runtime_timestamp as timestamp;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
62
63
#[macro_use]
extern crate substrate_runtime_version as version;
Gav's avatar
Gav committed
64

Gav Wood's avatar
Gav Wood committed
65
66
#[cfg(feature = "std")]
mod checked_block;
67
mod parachains;
Gav Wood's avatar
Gav Wood committed
68
69
70
71
72
mod utils;

#[cfg(feature = "std")]
pub use checked_block::CheckedBlock;
pub use utils::{inherent_extrinsics, check_extrinsic};
Gav's avatar
Gav committed
73
pub use balances::address::Address as RawAddress;
74

Gav Wood's avatar
Gav Wood committed
75
use primitives::{AccountId, AccountIndex, Balance, BlockNumber, Hash, Index, Log, SessionKey, Signature};
Gav Wood's avatar
Gav Wood committed
76
use runtime_primitives::{generic, traits::{HasPublicAux, BlakeTwo256, Convert}};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
77
use version::RuntimeVersion;
78
79

#[cfg(feature = "std")]
Gav Wood's avatar
Gav Wood committed
80
pub use runtime_primitives::BuildStorage;
81
82
83
84

pub use consensus::Call as ConsensusCall;
pub use timestamp::Call as TimestampCall;
pub use parachains::Call as ParachainsCall;
Gav Wood's avatar
Gav Wood committed
85
pub use primitives::Header;
86
87
88
89
90

/// The position of the timestamp set extrinsic.
pub const TIMESTAMP_SET_POSITION: u32 = 0;
/// The position of the parachains set extrinsic.
pub const PARACHAINS_SET_POSITION: u32 = 1;
Gav's avatar
Gav committed
91
92
/// The position of the note_offline in the block, if it exists.
pub const NOTE_OFFLINE_POSITION: u32 = 2;
93

Gav Wood's avatar
Gav Wood committed
94
/// The address format for describing accounts.
Gav's avatar
Gav committed
95
pub type Address = balances::Address<Concrete>;
Gav Wood's avatar
Gav Wood committed
96
97
98
/// Block Id type for this block.
pub type BlockId = generic::BlockId<Block>;
/// Unchecked extrinsic type as expected by this runtime.
Gav Wood's avatar
Gav Wood committed
99
100
101
102
103
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Index, Call, Signature>;
/// Extrinsic type as expected by this runtime. This is not the type that is signed.
pub type Extrinsic = generic::Extrinsic<Address, Index, Call>;
/// Extrinsic type that is signed.
pub type BareExtrinsic = generic::Extrinsic<AccountId, Index, Call>;
Gav Wood's avatar
Gav Wood committed
104
105
106
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;

107
/// Concrete runtime type used to parameterize the various modules.
Gav Wood's avatar
Gav Wood committed
108
109
110
// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
111
pub struct Concrete;
112

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
113
114
115
116
/// Polkadot runtime version.
pub const VERSION: RuntimeVersion = RuntimeVersion {
	spec_name: ver_str!("polkadot"),
	impl_name: ver_str!("parity-polkadot"),
Gav Wood's avatar
Gav Wood committed
117
	authoring_version: 1,
118
	spec_version: 101,
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
119
120
121
122
123
124
125
126
127
128
	impl_version: 0,
};

impl version::Trait for Concrete {
	const VERSION: RuntimeVersion = VERSION;
}

/// Version module for this concrete runtime.
pub type Version = version::Module<Concrete>;

129
130
131
132
133
impl HasPublicAux for Concrete {
	type PublicAux = AccountId;	// TODO: Option<AccountId>
}

impl system::Trait for Concrete {
Gav's avatar
Gav committed
134
	type PublicAux = <Concrete as HasPublicAux>::PublicAux;
135
136
137
138
139
140
	type Index = Index;
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type Digest = generic::Digest<Log>;
	type AccountId = AccountId;
Gav Wood's avatar
Gav Wood committed
141
	type Header = Header;
Gav's avatar
Gav committed
142
	type Event = Event;
143
144
145
146
}
/// System module for this concrete runtime.
pub type System = system::Module<Concrete>;

Gav's avatar
Gav committed
147
148
149
150
151
152
153
154
155
156
impl balances::Trait for Concrete {
	type Balance = Balance;
	type AccountIndex = AccountIndex;
	type OnFreeBalanceZero = Staking;
	type IsAccountLiquid = Staking;
	type Event = Event;
}
/// Staking module for this concrete runtime.
pub type Balances = balances::Module<Concrete>;

157
impl consensus::Trait for Concrete {
Gav's avatar
Gav committed
158
	const NOTE_OFFLINE_POSITION: u32 = NOTE_OFFLINE_POSITION;
159
	type SessionKey = SessionKey;
Gav's avatar
Gav committed
160
	type OnOfflineValidator = Staking;
161
162
163
164
165
}
/// Consensus module for this concrete runtime.
pub type Consensus = consensus::Module<Concrete>;

impl timestamp::Trait for Concrete {
166
167
	const TIMESTAMP_SET_POSITION: u32 = TIMESTAMP_SET_POSITION;
	type Moment = u64;
168
169
170
171
}
/// Timestamp module for this concrete runtime.
pub type Timestamp = timestamp::Module<Concrete>;

Gav Wood's avatar
Gav Wood committed
172
173
174
175
/// Session key conversion.
pub struct SessionKeyConversion;
impl Convert<AccountId, SessionKey> for SessionKeyConversion {
	fn convert(a: AccountId) -> SessionKey {
176
		a.0.into()
Gav Wood's avatar
Gav Wood committed
177
178
179
	}
}

180
impl session::Trait for Concrete {
Gav Wood's avatar
Gav Wood committed
181
	type ConvertAccountIdToSessionKey = SessionKeyConversion;
182
	type OnSessionChange = Staking;
Gav's avatar
Gav committed
183
	type Event = Event;
184
185
186
187
188
}
/// Session module for this concrete runtime.
pub type Session = session::Module<Concrete>;

impl staking::Trait for Concrete {
Gav's avatar
Gav committed
189
	type Event = Event;
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
}
/// Staking module for this concrete runtime.
pub type Staking = staking::Module<Concrete>;

impl democracy::Trait for Concrete {
	type Proposal = PrivCall;
}
/// Democracy module for this concrete runtime.
pub type Democracy = democracy::Module<Concrete>;

impl council::Trait for Concrete {}
/// Council module for this concrete runtime.
pub type Council = council::Module<Concrete>;
/// Council voting module for this concrete runtime.
pub type CouncilVoting = council::voting::Module<Concrete>;

206
207
208
209
210
impl parachains::Trait for Concrete {
	const SET_POSITION: u32 = PARACHAINS_SET_POSITION;

	type PublicAux = <Concrete as HasPublicAux>::PublicAux;
}
211
212
pub type Parachains = parachains::Module<Concrete>;

Gav's avatar
Gav committed
213
214
215
216
217
218
impl_outer_event! {
	pub enum Event for Concrete {
		balances, session, staking
	}
}

219
impl_outer_dispatch! {
Gav Wood's avatar
Gav Wood committed
220
221
222
	/// Call type for polkadot transactions.
	#[derive(Clone, PartialEq, Eq)]
	#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
223
224
	pub enum Call where aux: <Concrete as HasPublicAux>::PublicAux {
		Consensus = 0,
Gav's avatar
Gav committed
225
226
227
228
		Balances = 1,
		Session = 2,
		Staking = 3,
		Timestamp = 4,
229
230
231
		Democracy = 5,
		Council = 6,
		CouncilVoting = 7,
232
		Parachains = 8,
233
234
	}

Gav Wood's avatar
Gav Wood committed
235
236
237
	/// Internal calls.
	#[derive(Clone, PartialEq, Eq)]
	#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
238
239
	pub enum PrivCall {
		Consensus = 0,
Gav's avatar
Gav committed
240
241
242
		Balances = 1,
		Session = 2,
		Staking = 3,
243
244
245
		Democracy = 5,
		Council = 6,
		CouncilVoting = 7,
246
		Parachains = 8,
247
248
249
250
	}
}

/// Executive: handles dispatch to the various modules.
Gav's avatar
Gav committed
251
pub type Executive = executive::Executive<Concrete, Block, Balances, Balances,
252
	(((((((), Parachains), Council), Democracy), Staking), Session), Timestamp)>;
253
254
255
256
257

impl_outer_config! {
	pub struct GenesisConfig for Concrete {
		ConsensusConfig => consensus,
		SystemConfig => system,
Gav's avatar
Gav committed
258
		BalancesConfig => balances,
259
260
261
262
		SessionConfig => session,
		StakingConfig => staking,
		DemocracyConfig => democracy,
		CouncilConfig => council,
263
		TimestampConfig => timestamp,
264
265
266
267
268
269
		ParachainsConfig => parachains,
	}
}

pub mod api {
	impl_stubs!(
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
270
		version => |()| super::Version::version(),
271
272
273
274
275
		authorities => |()| super::Consensus::authorities(),
		initialise_block => |header| super::Executive::initialise_block(&header),
		apply_extrinsic => |extrinsic| super::Executive::apply_extrinsic(extrinsic),
		execute_block => |block| super::Executive::execute_block(block),
		finalise_block => |()| super::Executive::finalise_block(),
Gav's avatar
Gav committed
276
		inherent_extrinsics => |(inherent, spec_version)| super::inherent_extrinsics(inherent, spec_version),
277
278
279
280
		validator_count => |()| super::Session::validator_count(),
		validators => |()| super::Session::validators()
	);
}
281
282

#[cfg(test)]
283
284
285
mod tests {
	use super::*;
	use substrate_primitives as primitives;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
286
	use codec::{Encode, Decode};
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
	use substrate_primitives::hexdisplay::HexDisplay;
	use substrate_serializer as ser;
	use runtime_primitives::traits::{Digest as DigestT, Header as HeaderT};
	type Digest = generic::Digest<Log>;

	#[test]
	fn test_header_serialization() {
		let header = Header {
			parent_hash: 5.into(),
			number: 67,
			state_root: 3.into(),
			extrinsics_root: 6.into(),
			digest: { let mut d = Digest::default(); d.push(Log(vec![1])); d },
		};

		assert_eq!(ser::to_string_pretty(&header), r#"{
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000005",
  "number": 67,
  "stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000003",
  "extrinsicsRoot": "0x0000000000000000000000000000000000000000000000000000000000000006",
  "digest": {
    "logs": [
      "0x01"
    ]
  }
}"#);

		let v = header.encode();
		assert_eq!(Header::decode(&mut &v[..]).unwrap(), header);
Gav's avatar
Gav committed
316
317
	}

318
319
320
321
322
	#[test]
	fn block_encoding_round_trip() {
		let mut block = Block {
			header: Header::new(1, Default::default(), Default::default(), Default::default(), Default::default()),
			extrinsics: vec![
Gav Wood's avatar
Gav Wood committed
323
324
				UncheckedExtrinsic::new(
					generic::Extrinsic {
325
326
327
328
						function: Call::Timestamp(timestamp::Call::set(100_000_000)),
						signed: Default::default(),
						index: Default::default(),
					},
Gav Wood's avatar
Gav Wood committed
329
330
					Default::default(),
				)
331
332
333
334
335
336
337
338
			],
		};

		let raw = block.encode();
		let decoded = Block::decode(&mut &raw[..]).unwrap();

		assert_eq!(block, decoded);

Gav Wood's avatar
Gav Wood committed
339
340
		block.extrinsics.push(UncheckedExtrinsic::new(
			generic::Extrinsic {
341
342
343
344
				function: Call::Staking(staking::Call::stake()),
				signed: Default::default(),
				index: 10101,
			},
Gav Wood's avatar
Gav Wood committed
345
346
			Default::default(),
		));
347
348
349

		let raw = block.encode();
		let decoded = Block::decode(&mut &raw[..]).unwrap();
Gav's avatar
Gav committed
350

351
		assert_eq!(block, decoded);
Gav's avatar
Gav committed
352
353
	}

354
355
356
357
358
	#[test]
	fn block_encoding_substrate_round_trip() {
		let mut block = Block {
			header: Header::new(1, Default::default(), Default::default(), Default::default(), Default::default()),
			extrinsics: vec![
Gav Wood's avatar
Gav Wood committed
359
360
				UncheckedExtrinsic::new(
					generic::Extrinsic {
361
362
363
364
						function: Call::Timestamp(timestamp::Call::set(100_000_000)),
						signed: Default::default(),
						index: Default::default(),
					},
Gav Wood's avatar
Gav Wood committed
365
366
					Default::default(),
				)
367
368
369
			],
		};

Gav Wood's avatar
Gav Wood committed
370
371
		block.extrinsics.push(UncheckedExtrinsic::new(
			generic::Extrinsic {
372
373
374
375
				function: Call::Staking(staking::Call::stake()),
				signed: Default::default(),
				index: 10101,
			},
Gav Wood's avatar
Gav Wood committed
376
377
			Default::default()
		));
378
379

		let raw = block.encode();
Gav Wood's avatar
Gav Wood committed
380
381
382
		let decoded_primitive = ::primitives::Block::decode(&mut &raw[..]).unwrap();
		let encoded_primitive = decoded_primitive.encode();
		let decoded = Block::decode(&mut &encoded_primitive[..]).unwrap();
383
384
385
386
387
388

		assert_eq!(block, decoded);
	}

	#[test]
	fn serialize_unchecked() {
Gav Wood's avatar
Gav Wood committed
389
390
391
		let tx = UncheckedExtrinsic::new(
			Extrinsic {
				signed: AccountId::from([1; 32]).into(),
392
				index: 999,
393
394
				function: Call::Timestamp(TimestampCall::set(135135)),
			},
Gav Wood's avatar
Gav Wood committed
395
396
397
398
399
400
401
			runtime_primitives::Ed25519Signature(primitives::hash::H512([0; 64])).into()
		);

		// 6f000000
		// ff0101010101010101010101010101010101010101010101010101010101010101
		// e7030000
		// 0300
402
403
404
		// df0f0200
		// 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
405
		let v = Encode::encode(&tx);
Gav Wood's avatar
Gav Wood committed
406
		assert_eq!(&v[..], &hex!["6f000000ff0101010101010101010101010101010101010101010101010101010101010101e70300000300df0f02000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"][..]);
407
408
		println!("{}", HexDisplay::from(&v));
		assert_eq!(UncheckedExtrinsic::decode(&mut &v[..]).unwrap(), tx);
Gav's avatar
Gav committed
409
	}
410
411
412
413

	#[test]
	fn serialize_checked() {
		let xt = Extrinsic {
Gav Wood's avatar
Gav Wood committed
414
			signed: AccountId::from(hex!["0d71d1a9cad6f2ab773435a7dec1bac019994d05d1dd5eb3108211dcf25c9d1e"]).into(),
415
			index: 0,
416
417
418
419
420
421
			function: Call::CouncilVoting(council::voting::Call::propose(Box::new(
				PrivCall::Consensus(consensus::PrivCall::set_code(
					vec![]
				))
			))),
		};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
422
		let v = Encode::encode(&xt);
423
424
		assert_eq!(Extrinsic::decode(&mut &v[..]).unwrap(), xt);
	}
425
426
427
428
429
430

	#[test]
	fn parachain_calls_are_privcall() {
		let _register = PrivCall::Parachains(parachains::PrivCall::register_parachain(0.into(), vec![1, 2, 3], vec![]));
		let _deregister = PrivCall::Parachains(parachains::PrivCall::deregister_parachain(0.into()));
	}
Gav's avatar
Gav committed
431
}