lib.rs 14.1 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
46
#[cfg(test)]
extern crate substrate_serializer;

#[cfg_attr(feature = "std", macro_use)]
extern crate substrate_primitives;

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

extern crate polkadot_primitives as primitives;
Gav's avatar
Gav committed
51
extern crate substrate_codec as codec;
52
53
54
55
56
57
58
59
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;
Gav's avatar
Gav committed
60

61
mod parachains;
62

Gav Wood's avatar
Gav Wood committed
63
64
65
66
use rstd::prelude::*;
use primitives::{AccountId, Balance, BlockNumber, Hash, Index, Log, SessionKey, Signature};
use primitives::parachain::CandidateReceipt;
use runtime_primitives::{generic, traits::{HasPublicAux, BlakeTwo256, Convert}};
67
68
69
70
71
72
73

#[cfg(feature = "std")]
pub use runtime_primitives::BuildExternalities;

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
74
pub use primitives::Header;
75
76
77
78
79

/// 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;
80

Gav Wood's avatar
Gav Wood committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/// Block Id type for this block.
pub type BlockId = generic::BlockId<Block>;
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<AccountId, Index, Call, Signature>;
/// Extrinsic type as expected by this runtime.
pub type Extrinsic = generic::Extrinsic<AccountId, Index, Call>;

/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;

/// Provides a type-safe wrapper around a structurally valid block.
#[cfg(feature = "std")]
pub struct CheckedBlock {
	inner: Block,
	file_line: Option<(&'static str, u32)>,
}

#[cfg(feature = "std")]
impl CheckedBlock {
	/// Create a new checked block. Fails if the block is not structurally valid.
	pub fn new(block: Block) -> Result<Self, Block> {
		let has_timestamp = block.extrinsics.get(TIMESTAMP_SET_POSITION as usize).map_or(false, |xt| {
			!xt.is_signed() && match xt.extrinsic.function {
				Call::Timestamp(TimestampCall::set(_)) => true,
				_ => false,
			}
		});

		if !has_timestamp { return Err(block) }

		let has_heads = block.extrinsics.get(PARACHAINS_SET_POSITION as usize).map_or(false, |xt| {
			!xt.is_signed() && match xt.extrinsic.function {
				Call::Parachains(ParachainsCall::set_heads(_)) => true,
				_ => false,
			}
		});

		if !has_heads { return Err(block) }
		Ok(CheckedBlock {
			inner: block,
			file_line: None,
		})
	}

	// Creates a new checked block, asserting that it is valid.
	#[doc(hidden)]
	pub fn new_unchecked(block: Block, file: &'static str, line: u32) -> Self {
		CheckedBlock {
			inner: block,
			file_line: Some((file, line)),
		}
	}

	/// Extract the timestamp from the block.
	pub fn timestamp(&self) -> ::primitives::Timestamp {
		let x = self.inner.extrinsics.get(TIMESTAMP_SET_POSITION as usize).and_then(|xt| match xt.extrinsic.function {
			Call::Timestamp(TimestampCall::set(x)) => Some(x),
			_ => None
		});

		match x {
			Some(x) => x,
			None => panic!("Invalid polkadot block asserted at {:?}", self.file_line),
		}
	}

	/// Extract the parachain heads from the block.
	pub fn parachain_heads(&self) -> &[CandidateReceipt] {
		let x = self.inner.extrinsics.get(PARACHAINS_SET_POSITION as usize).and_then(|xt| match xt.extrinsic.function {
			Call::Parachains(ParachainsCall::set_heads(ref x)) => Some(&x[..]),
			_ => None
		});

		match x {
			Some(x) => x,
			None => panic!("Invalid polkadot block asserted at {:?}", self.file_line),
		}
	}

	/// Convert into inner block.
	pub fn into_inner(self) -> Block { self.inner }
}

#[cfg(feature = "std")]
impl ::std::ops::Deref for CheckedBlock {
	type Target = Block;

	fn deref(&self) -> &Block { &self.inner }
}

/// Assert that a block is structurally valid. May lead to panic in the future
/// in case it isn't.
#[cfg(feature = "std")]
#[macro_export]
macro_rules! assert_polkadot_block {
	($block: expr) => {
		$crate::CheckedBlock::new_unchecked($block, file!(), line!())
	}
}

181
182
/// Concrete runtime type used to parameterize the various modules.
pub struct Concrete;
183

184
185
186
187
188
189
190
191
192
193
194
impl HasPublicAux for Concrete {
	type PublicAux = AccountId;	// TODO: Option<AccountId>
}

impl system::Trait for Concrete {
	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
195
	type Header = Header;
196
197
198
199
200
}
/// System module for this concrete runtime.
pub type System = system::Module<Concrete>;

impl consensus::Trait for Concrete {
201
	type PublicAux = <Concrete as HasPublicAux>::PublicAux;
202
203
204
205
206
207
	type SessionKey = SessionKey;
}
/// Consensus module for this concrete runtime.
pub type Consensus = consensus::Module<Concrete>;

impl timestamp::Trait for Concrete {
208
	const SET_POSITION: u32 = TIMESTAMP_SET_POSITION;
209
210
211
212
213
	type Value = u64;
}
/// Timestamp module for this concrete runtime.
pub type Timestamp = timestamp::Module<Concrete>;

Gav Wood's avatar
Gav Wood committed
214
215
216
217
218
219
220
221
/// Session key conversion.
pub struct SessionKeyConversion;
impl Convert<AccountId, SessionKey> for SessionKeyConversion {
	fn convert(a: AccountId) -> SessionKey {
		a.0
	}
}

222
impl session::Trait for Concrete {
Gav Wood's avatar
Gav Wood committed
223
	type ConvertAccountIdToSessionKey = SessionKeyConversion;
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
}
/// Session module for this concrete runtime.
pub type Session = session::Module<Concrete>;

impl staking::Trait for Concrete {
	type Balance = Balance;
	type DetermineContractAddress = BlakeTwo256;
}
/// 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>;

247
248
249
250
251
impl parachains::Trait for Concrete {
	const SET_POSITION: u32 = PARACHAINS_SET_POSITION;

	type PublicAux = <Concrete as HasPublicAux>::PublicAux;
}
252
253
254
pub type Parachains = parachains::Module<Concrete>;

impl_outer_dispatch! {
Gav Wood's avatar
Gav Wood committed
255
256
257
	/// Call type for polkadot transactions.
	#[derive(Clone, PartialEq, Eq)]
	#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
258
259
260
261
262
263
264
265
	pub enum Call where aux: <Concrete as HasPublicAux>::PublicAux {
		Consensus = 0,
		Session = 1,
		Staking = 2,
		Timestamp = 3,
		Democracy = 5,
		Council = 6,
		CouncilVoting = 7,
266
		Parachains = 8,
267
268
	}

Gav Wood's avatar
Gav Wood committed
269
270
271
	/// Internal calls.
	#[derive(Clone, PartialEq, Eq)]
	#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
272
273
274
275
276
277
278
279
280
281
282
283
	pub enum PrivCall {
		Consensus = 0,
		Session = 1,
		Staking = 2,
		Democracy = 5,
		Council = 6,
		CouncilVoting = 7,
	}
}

/// Executive: handles dispatch to the various modules.
pub type Executive = executive::Executive<Concrete, Block, Staking,
284
	(((((((), Parachains), Council), Democracy), Staking), Session), Timestamp)>;
285
286
287
288
289
290
291
292
293
294
295
296
297

impl_outer_config! {
	pub struct GenesisConfig for Concrete {
		ConsensusConfig => consensus,
		SystemConfig => system,
		SessionConfig => session,
		StakingConfig => staking,
		DemocracyConfig => democracy,
		CouncilConfig => council,
		ParachainsConfig => parachains,
	}
}

Gav Wood's avatar
Gav Wood committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/// Produces the list of inherent extrinsics.
pub fn inherent_extrinsics(timestamp: ::primitives::Timestamp, parachain_heads: Vec<CandidateReceipt>) -> Vec<UncheckedExtrinsic> {
	vec![
		UncheckedExtrinsic {
			extrinsic: Extrinsic {
				signed: Default::default(),
				function: Call::Timestamp(TimestampCall::set(timestamp)),
				index: 0,
			},
			signature: Default::default(),
		},
		UncheckedExtrinsic {
			extrinsic: Extrinsic {
				signed: Default::default(),
				function: Call::Parachains(ParachainsCall::set_heads(parachain_heads)),
				index: 0,
			},
			signature: Default::default(),
		},
	]
}

/// Checks an unchecked extrinsic for validity.
pub fn check_extrinsic(xt: UncheckedExtrinsic) -> bool {
	use runtime_primitives::traits::Checkable;

	xt.check().is_ok()
}

327
328
329
330
331
332
333
pub mod api {
	impl_stubs!(
		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 Wood's avatar
Gav Wood committed
334
		inherent_extrinsics => |(timestamp, heads)| super::inherent_extrinsics(timestamp, heads),
335
336
337
338
		validator_count => |()| super::Session::validator_count(),
		validators => |()| super::Session::validators()
	);
}
339
340

#[cfg(test)]
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
mod tests {
	use super::*;
	use substrate_primitives as primitives;
	use ::codec::Slicable;
	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
374
375
	}

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
	#[test]
	fn block_encoding_round_trip() {
		let mut block = Block {
			header: Header::new(1, Default::default(), Default::default(), Default::default(), Default::default()),
			extrinsics: vec![
				UncheckedExtrinsic {
					extrinsic: Extrinsic {
						function: Call::Timestamp(timestamp::Call::set(100_000_000)),
						signed: Default::default(),
						index: Default::default(),
					},
					signature: Default::default(),
				}
			],
		};

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

		assert_eq!(block, decoded);

		block.extrinsics.push(UncheckedExtrinsic {
			extrinsic: Extrinsic {
				function: Call::Staking(staking::Call::stake()),
				signed: Default::default(),
				index: 10101,
			},
			signature: Default::default(),
		});

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

409
		assert_eq!(block, decoded);
Gav's avatar
Gav committed
410
411
	}

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
	#[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![
				UncheckedExtrinsic {
					extrinsic: Extrinsic {
						function: Call::Timestamp(timestamp::Call::set(100_000_000)),
						signed: Default::default(),
						index: Default::default(),
					},
					signature: Default::default(),
				}
			],
		};

		block.extrinsics.push(UncheckedExtrinsic {
			extrinsic: Extrinsic {
				function: Call::Staking(staking::Call::stake()),
				signed: Default::default(),
				index: 10101,
			},
			signature: Default::default(),
		});

		let raw = block.encode();
Gav Wood's avatar
Gav Wood committed
438
439
440
		let decoded_primitive = ::primitives::Block::decode(&mut &raw[..]).unwrap();
		let encoded_primitive = decoded_primitive.encode();
		let decoded = Block::decode(&mut &encoded_primitive[..]).unwrap();
441
442
443
444
445
446
447
448

		assert_eq!(block, decoded);
	}

	#[test]
	fn serialize_unchecked() {
		let tx = UncheckedExtrinsic {
			extrinsic: Extrinsic {
Gav Wood's avatar
Gav Wood committed
449
				signed: [1; 32].into(),
450
				index: 999,
451
452
				function: Call::Timestamp(TimestampCall::set(135135)),
			},
Gav Wood's avatar
Gav Wood committed
453
			signature: runtime_primitives::Ed25519Signature(primitives::hash::H512([0; 64])).into(),
454
455
456
457
458
459
460
461
462
463
464
		};
		// 71000000
		// 0101010101010101010101010101010101010101010101010101010101010101
		// e703000000000000
		// 00
		// df0f0200
		// 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

		let v = Slicable::encode(&tx);
		println!("{}", HexDisplay::from(&v));
		assert_eq!(UncheckedExtrinsic::decode(&mut &v[..]).unwrap(), tx);
Gav's avatar
Gav committed
465
	}
466
467
468
469

	#[test]
	fn serialize_checked() {
		let xt = Extrinsic {
Gav Wood's avatar
Gav Wood committed
470
			signed: hex!["0d71d1a9cad6f2ab773435a7dec1bac019994d05d1dd5eb3108211dcf25c9d1e"].into(),
471
			index: 0,
472
473
474
475
476
477
478
479
			function: Call::CouncilVoting(council::voting::Call::propose(Box::new(
				PrivCall::Consensus(consensus::PrivCall::set_code(
					vec![]
				))
			))),
		};
		let v = Slicable::encode(&xt);

480
		let data = hex!["e00000000d71d1a9cad6f2ab773435a7dec1bac019994d05d1dd5eb3108211dcf25c9d1e0000000007000000000000006369D39D892B7B87A6769F90E14C618C2B84EBB293E2CC46640136E112C078C75619AC2E0815F2511568736623C055156C8FC427CE2AEE4AE2838F86EFE80208"];
481
482
483
484
485
		let uxt: UncheckedExtrinsic = Slicable::decode(&mut &data[..]).unwrap();
		assert_eq!(uxt.extrinsic, xt);

		assert_eq!(Extrinsic::decode(&mut &v[..]).unwrap(), xt);
	}
Gav's avatar
Gav committed
486
}