v0.rs 29.9 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
Gav's avatar
Gav committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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
18
//! Primitives which are necessary for parachain execution from a relay-chain
//! perspective.
Gav Wood's avatar
Gav Wood committed
19

Shawn Tabrizi's avatar
Shawn Tabrizi committed
20
use sp_std::{cmp::Ordering, prelude::*};
21

22
use bitvec::vec::BitVec;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
23
use parity_scale_codec::{Decode, Encode};
24
25
#[cfg(feature = "std")]
use parity_util_mem::{MallocSizeOf, MallocSizeOfOps};
26
use scale_info::TypeInfo;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
27
28
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
29

Shawn Tabrizi's avatar
Shawn Tabrizi committed
30
31
use application_crypto::KeyTypeId;
use inherents::InherentIdentifier;
32
use primitives::RuntimeDebug;
33
use runtime_primitives::traits::{AppVerify, Block as BlockT};
asynchronous rob's avatar
asynchronous rob committed
34
35

pub use parity_scale_codec::Compact;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
36
37
pub use polkadot_core_primitives::*;
pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT, IdentifyAccount, Verify};
Gav Wood's avatar
Gav Wood committed
38

39
pub use polkadot_parachain::primitives::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
40
	BlockData, HeadData, Id, UpwardMessage, ValidationCode, LOWEST_USER_ID,
41
};
42

43
44
45
/// The key type ID for a collator key.
pub const COLLATOR_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"coll");

46
47
48
49
/// An identifier for inherent data that provides new minimally-attested
/// parachain heads.
pub const NEW_HEADS_IDENTIFIER: InherentIdentifier = *b"newheads";

50
51
52
53
54
mod collator_app {
	use application_crypto::{app_crypto, sr25519};
	app_crypto!(sr25519, super::COLLATOR_KEY_TYPE_ID);
}

Gav Wood's avatar
Gav Wood committed
55
/// Identity that collators use.
56
57
pub type CollatorId = collator_app::Public;

58
59
60
61
62
63
64
65
66
67
#[cfg(feature = "std")]
impl MallocSizeOf for CollatorId {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

68
69
70
/// A Parachain collator keypair.
#[cfg(feature = "std")]
pub type CollatorPair = collator_app::Pair;
Gav Wood's avatar
Gav Wood committed
71

72
/// Signature on candidate's block data by a collator.
73
74
pub type CollatorSignature = collator_app::Signature;

75
76
77
78
79
80
81
82
83
84
#[cfg(feature = "std")]
impl MallocSizeOf for CollatorSignature {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

85
86
87
88
89
90
91
/// The key type ID for a parachain validator key.
pub const PARACHAIN_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"para");

mod validator_app {
	use application_crypto::{app_crypto, sr25519};
	app_crypto!(sr25519, super::PARACHAIN_KEY_TYPE_ID);
}
Gav Wood's avatar
Gav Wood committed
92
93
94

/// Identity that parachain validators use when signing validation messages.
///
joe petrowski's avatar
joe petrowski committed
95
/// For now we assert that parachain validator set is exactly equivalent to the authority set, and
Gav Wood's avatar
Gav Wood committed
96
/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto.
97
pub type ValidatorId = validator_app::Public;
Gav Wood's avatar
Gav Wood committed
98

99
100
101
102
103
104
105
106
107
108
#[cfg(feature = "std")]
impl MallocSizeOf for ValidatorId {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

109
/// Index of the validator is used as a lightweight replacement of the `ValidatorId` when appropriate.
110
#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone, Encode, Decode, TypeInfo)]
111
112
113
114
115
116
117
118
119
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, Hash, MallocSizeOf))]
pub struct ValidatorIndex(pub u32);

// We should really get https://github.com/paritytech/polkadot/issues/2403 going ..
impl From<u32> for ValidatorIndex {
	fn from(n: u32) -> Self {
		ValidatorIndex(n)
	}
}
120

121
122
123
124
application_crypto::with_pair! {
	/// A Parachain validator keypair.
	pub type ValidatorPair = validator_app::Pair;
}
125

joe petrowski's avatar
joe petrowski committed
126
/// Signature with which parachain validators sign blocks.
Gav Wood's avatar
Gav Wood committed
127
///
joe petrowski's avatar
joe petrowski committed
128
/// For now we assert that parachain validator set is exactly equivalent to the authority set, and
Gav Wood's avatar
Gav Wood committed
129
/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto.
130
pub type ValidatorSignature = validator_app::Signature;
Gav's avatar
Gav committed
131

132
133
134
135
136
137
138
139
140
141
#[cfg(feature = "std")]
impl MallocSizeOf for ValidatorSignature {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

142
/// Retriability for a given active para.
143
#[derive(Clone, Eq, PartialEq, Encode, Decode, TypeInfo)]
144
145
#[cfg_attr(feature = "std", derive(Debug))]
pub enum Retriable {
joe petrowski's avatar
joe petrowski committed
146
	/// Ineligible for retry. This means it's either a parachain that is always scheduled anyway or
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
	/// has been removed/swapped.
	Never,
	/// Eligible for retry; the associated value is the number of retries that the para already had.
	WithRetries(u32),
}

/// Type determining the active set of parachains in current block.
pub trait ActiveParas {
	/// Return the active set of parachains in current block. This attempts to keep any IDs in the
	/// same place between sequential blocks. It is therefore unordered. The second item in the
	/// tuple is the required collator ID, if any. If `Some`, then it is invalid to include any
	/// other collator's block.
	///
	/// NOTE: The initial implementation simply concatenates the (ordered) set of (permanent)
	/// parachain IDs with the (unordered) set of parathread IDs selected for this block.
	fn active_paras() -> Vec<(Id, Option<(CollatorId, Retriable)>)>;
}

/// Description of how often/when this parachain is scheduled for progression.
166
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
167
168
169
170
171
172
173
174
pub enum Scheduling {
	/// Scheduled every block.
	Always,
	/// Scheduled dynamically (i.e. a parathread).
	Dynamic,
}

/// Information regarding a deployed parachain/thread.
175
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
176
177
178
179
180
181
pub struct Info {
	/// Scheduling info.
	pub scheduling: Scheduling,
}

/// An `Info` value for a standard leased parachain.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
182
pub const PARACHAIN_INFO: Info = Info { scheduling: Scheduling::Always };
183

Bernhard Schuster's avatar
Bernhard Schuster committed
184
/// Auxiliary for when there's an attempt to swap two parachains/parathreads.
185
186
187
188
189
pub trait SwapAux {
	/// Result describing whether it is possible to swap two parachains. Doesn't mutate state.
	fn ensure_can_swap(one: Id, other: Id) -> Result<(), &'static str>;

	/// Updates any needed state/references to enact a logical swap of two parachains. Identity,
joe petrowski's avatar
joe petrowski committed
190
	/// code and `head_data` remain equivalent for all parachains/threads, however other properties
191
192
193
194
195
196
197
198
	/// such as leases, deposits held and thread/chain nature are swapped.
	///
	/// May only be called on a state that `ensure_can_swap` has previously returned `Ok` for: if this is
	/// not the case, the result is undefined. May only return an error if `ensure_can_swap` also returns
	/// an error.
	fn on_swap(one: Id, other: Id) -> Result<(), &'static str>;
}

ddorgan's avatar
ddorgan committed
199
impl SwapAux for () {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
200
201
202
203
204
205
	fn ensure_can_swap(_: Id, _: Id) -> Result<(), &'static str> {
		Err("Swapping disabled")
	}
	fn on_swap(_: Id, _: Id) -> Result<(), &'static str> {
		Err("Swapping disabled")
	}
ddorgan's avatar
ddorgan committed
206
207
}

208
/// Identifier for a chain, either one of a number of parachains or the relay chain.
209
#[derive(Copy, Clone, PartialEq, Encode, Decode, TypeInfo)]
210
211
212
213
214
215
216
217
218
#[cfg_attr(feature = "std", derive(Debug))]
pub enum Chain {
	/// The relay chain.
	Relay,
	/// A parachain of the given index.
	Parachain(Id),
}

/// The duty roster specifying what jobs each validator must do.
219
#[derive(Clone, PartialEq, Encode, Decode, TypeInfo)]
220
221
222
223
224
225
#[cfg_attr(feature = "std", derive(Default, Debug))]
pub struct DutyRoster {
	/// Lookup from validator index to chain on which that validator has a duty to validate.
	pub validator_duty: Vec<Chain>,
}

joe petrowski's avatar
joe petrowski committed
226
/// Extra data that is needed along with the other fields in a `CandidateReceipt`
227
228
229
/// to fully validate the candidate.
///
/// These are global parameters that apply to all parachain candidates in a block.
230
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
231
#[cfg_attr(feature = "std", derive(Debug, Default))]
232
pub struct GlobalValidationData<N = BlockNumber> {
233
234
235
236
	/// The maximum code size permitted, in bytes.
	pub max_code_size: u32,
	/// The maximum head-data size permitted, in bytes.
	pub max_head_data_size: u32,
237
	/// The relay-chain block number this is in the context of.
asynchronous rob's avatar
asynchronous rob committed
238
	pub block_number: N,
239
240
}

joe petrowski's avatar
joe petrowski committed
241
/// Extra data that is needed along with the other fields in a `CandidateReceipt`
242
/// to fully validate the candidate. These fields are parachain-specific.
243
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
244
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
245
pub struct LocalValidationData<N = BlockNumber> {
246
247
248
249
	/// The parent head-data.
	pub parent_head: HeadData,
	/// The balance of the parachain at the moment of validation.
	pub balance: Balance,
250
251
252
253
254
255
256
257
258
259
260
	/// Whether the parachain is allowed to upgrade its validation code.
	///
	/// This is `Some` if so, and contains the number of the minimum relay-chain
	/// height at which the upgrade will be applied, if an upgrade is signaled
	/// now.
	///
	/// A parachain should enact its side of the upgrade at the end of the first
	/// parablock executing in the context of a relay-chain block with at least this
	/// height. This may be equal to the current perceived relay-chain block height, in
	/// which case the code upgrade should be applied at the end of the signaling
	/// block.
asynchronous rob's avatar
asynchronous rob committed
261
	pub code_upgrade_allowed: Option<N>,
262
263
264
}

/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation.
265
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
266
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
267
pub struct CandidateCommitments<H = Hash> {
joe petrowski's avatar
joe petrowski committed
268
	/// Fees paid from the chain to the relay chain validators.
269
270
271
272
	pub fees: Balance,
	/// Messages destined to be interpreted by the Relay chain itself.
	pub upward_messages: Vec<UpwardMessage>,
	/// The root of a block's erasure encoding Merkle tree.
asynchronous rob's avatar
asynchronous rob committed
273
	pub erasure_root: H,
274
	/// New validation code.
275
	pub new_validation_code: Option<ValidationCode>,
276
277
278
279
	/// Number of `DownwardMessage`'s that were processed by the Parachain.
	///
	/// It is expected that the Parachain processes them from first to last.
	pub processed_downward_messages: u32,
280
281
282
}

/// Get a collator signature payload on a relay-parent, block-data combo.
asynchronous rob's avatar
asynchronous rob committed
283
284
pub fn collator_signature_payload<H: AsRef<[u8]>>(
	relay_parent: &H,
285
	parachain_index: &Id,
asynchronous rob's avatar
asynchronous rob committed
286
	pov_block_hash: &H,
287
288
289
290
291
292
293
294
295
296
297
) -> [u8; 68] {
	// 32-byte hash length is protected in a test below.
	let mut payload = [0u8; 68];

	payload[0..32].copy_from_slice(relay_parent.as_ref());
	u32::from(*parachain_index).using_encoded(|s| payload[32..32 + s.len()].copy_from_slice(s));
	payload[36..68].copy_from_slice(pov_block_hash.as_ref());

	payload
}

asynchronous rob's avatar
asynchronous rob committed
298
299
fn check_collator_signature<H: AsRef<[u8]>>(
	relay_parent: &H,
300
	parachain_index: &Id,
asynchronous rob's avatar
asynchronous rob committed
301
	pov_block_hash: &H,
302
303
	collator: &CollatorId,
	signature: &CollatorSignature,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
304
) -> Result<(), ()> {
305
306
307
308
309
310
311
312
313
	let payload = collator_signature_payload(relay_parent, parachain_index, pov_block_hash);
	if signature.verify(&payload[..], collator) {
		Ok(())
	} else {
		Err(())
	}
}

/// All data pertaining to the execution of a parachain candidate.
314
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
315
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
316
pub struct CandidateReceipt<H = Hash, N = BlockNumber> {
317
318
	/// The ID of the parachain this is a candidate for.
	pub parachain_index: Id,
319
320
	/// The hash of the relay-chain block this should be executed in
	/// the context of.
asynchronous rob's avatar
asynchronous rob committed
321
	pub relay_parent: H,
322
323
	/// The head-data
	pub head_data: HeadData,
324
325
326
327
	/// The collator's relay-chain account ID
	pub collator: CollatorId,
	/// Signature on blake2-256 of the block data by collator.
	pub signature: CollatorSignature,
328
	/// The hash of the PoV-block.
asynchronous rob's avatar
asynchronous rob committed
329
	pub pov_block_hash: H,
330
	/// The global validation schedule.
331
	pub global_validation: GlobalValidationData<N>,
332
	/// The local validation data.
asynchronous rob's avatar
asynchronous rob committed
333
	pub local_validation: LocalValidationData<N>,
334
	/// Commitments made as a result of validation.
asynchronous rob's avatar
asynchronous rob committed
335
	pub commitments: CandidateCommitments<H>,
336
337
}

asynchronous rob's avatar
asynchronous rob committed
338
impl<H: AsRef<[u8]>, N> CandidateReceipt<H, N> {
339
340
341
342
343
344
345
346
347
348
349
350
351
	/// Check integrity vs. provided block data.
	pub fn check_signature(&self) -> Result<(), ()> {
		check_collator_signature(
			&self.relay_parent,
			&self.parachain_index,
			&self.pov_block_hash,
			&self.collator,
			&self.signature,
		)
	}

	/// Abridge this `CandidateReceipt`, splitting it into an `AbridgedCandidateReceipt`
	/// and its omitted component.
asynchronous rob's avatar
asynchronous rob committed
352
	pub fn abridge(self) -> (AbridgedCandidateReceipt<H>, OmittedValidationData<N>) {
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
		let CandidateReceipt {
			parachain_index,
			relay_parent,
			head_data,
			collator,
			signature,
			pov_block_hash,
			global_validation,
			local_validation,
			commitments,
		} = self;

		let abridged = AbridgedCandidateReceipt {
			parachain_index,
			relay_parent,
			head_data,
			collator,
			signature,
			pov_block_hash,
			commitments,
		};

Shawn Tabrizi's avatar
Shawn Tabrizi committed
375
		let omitted = OmittedValidationData { global_validation, local_validation };
376
377

		(abridged, omitted)
378
379
380
	}
}

381
382
383
384
385
impl PartialOrd for CandidateReceipt {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}
386

387
388
389
390
impl Ord for CandidateReceipt {
	fn cmp(&self, other: &Self) -> Ordering {
		// TODO: compare signatures or something more sane
		// https://github.com/paritytech/polkadot/issues/222
Shawn Tabrizi's avatar
Shawn Tabrizi committed
391
392
		self.parachain_index
			.cmp(&other.parachain_index)
393
			.then_with(|| self.head_data.cmp(&other.head_data))
394
395
396
	}
}

397
398
/// All the data which is omitted in an `AbridgedCandidateReceipt`, but that
/// is necessary for validation of the parachain candidate.
399
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
400
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
401
pub struct OmittedValidationData<N = BlockNumber> {
402
	/// The global validation schedule.
403
	pub global_validation: GlobalValidationData<N>,
404
	/// The local validation data.
asynchronous rob's avatar
asynchronous rob committed
405
	pub local_validation: LocalValidationData<N>,
406
407
408
409
410
411
412
}

/// An abridged candidate-receipt.
///
/// Much info in a candidate-receipt is duplicated from the relay-chain state.
/// When submitting to the relay-chain, this data should be omitted as it can
/// be re-generated from relay-chain state.
413
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
414
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
415
pub struct AbridgedCandidateReceipt<H = Hash> {
Gav's avatar
Gav committed
416
417
	/// The ID of the parachain this is a candidate for.
	pub parachain_index: Id,
418
419
420
421
	/// The hash of the relay-chain block this should be executed in
	/// the context of.
	// NOTE: the fact that the hash includes this value means that code depends
	// on this for deduplication. Removing this field is likely to break things.
asynchronous rob's avatar
asynchronous rob committed
422
	pub relay_parent: H,
423
424
	/// The head-data
	pub head_data: HeadData,
425
	/// The collator's relay-chain account ID
Gav Wood's avatar
Gav Wood committed
426
	pub collator: CollatorId,
427
	/// Signature on blake2-256 of the block data by collator.
Gav Wood's avatar
Gav Wood committed
428
	pub signature: CollatorSignature,
Denis_P's avatar
Denis_P committed
429
	/// The hash of the `pov-block`.
asynchronous rob's avatar
asynchronous rob committed
430
	pub pov_block_hash: H,
431
	/// Commitments made as a result of validation.
asynchronous rob's avatar
asynchronous rob committed
432
	pub commitments: CandidateCommitments<H>,
Gav's avatar
Gav committed
433
434
}

435
436
/// A candidate-receipt with commitments directly included.
pub struct CommitedCandidateReceipt<H = Hash> {
Bernhard Schuster's avatar
Bernhard Schuster committed
437
	/// The descriptor of the candidate.
438
439
440
	pub descriptor: CandidateDescriptor,

	/// The commitments of the candidate receipt.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
441
	pub commitments: CandidateCommitments<H>,
442
443
}

asynchronous rob's avatar
asynchronous rob committed
444
445
446
447
448
449
450
451
452
453
454
455
impl<H: AsRef<[u8]> + Encode> AbridgedCandidateReceipt<H> {
	/// Check integrity vs. provided block data.
	pub fn check_signature(&self) -> Result<(), ()> {
		check_collator_signature(
			&self.relay_parent,
			&self.parachain_index,
			&self.pov_block_hash,
			&self.collator,
			&self.signature,
		)
	}

456
457
458
459
	/// Compute the hash of the abridged candidate receipt.
	///
	/// This is often used as the canonical hash of the receipt, rather than
	/// the hash of the full receipt. The reason being that all data in the full
joe petrowski's avatar
joe petrowski committed
460
	/// receipt is committed to in the abridged receipt; this receipt references
461
462
	/// the relay-chain block in which context it should be executed, which implies
	/// any blockchain state that must be referenced.
463
	pub fn hash(&self) -> Hash {
Gav Wood's avatar
Gav Wood committed
464
		BlakeTwo256::hash_of(self)
465
	}
asynchronous rob's avatar
asynchronous rob committed
466
}
467

asynchronous rob's avatar
asynchronous rob committed
468
impl AbridgedCandidateReceipt {
469
470
471
472
473
474
475
476
477
478
479
480
481
	/// Combine the abridged candidate receipt with the omitted data,
	/// forming a full `CandidateReceipt`.
	pub fn complete(self, omitted: OmittedValidationData) -> CandidateReceipt {
		let AbridgedCandidateReceipt {
			parachain_index,
			relay_parent,
			head_data,
			collator,
			signature,
			pov_block_hash,
			commitments,
		} = self;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
482
		let OmittedValidationData { global_validation, local_validation } = omitted;
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507

		CandidateReceipt {
			parachain_index,
			relay_parent,
			head_data,
			collator,
			signature,
			pov_block_hash,
			local_validation,
			global_validation,
			commitments,
		}
	}

	/// Clone the relevant portions of the `CandidateReceipt` to form a `CollationInfo`.
	pub fn to_collation_info(&self) -> CollationInfo {
		let AbridgedCandidateReceipt {
			parachain_index,
			relay_parent,
			head_data,
			collator,
			signature,
			pov_block_hash,
			commitments: _commitments,
		} = self;
508

509
510
511
512
513
514
515
		CollationInfo {
			parachain_index: *parachain_index,
			relay_parent: *relay_parent,
			head_data: head_data.clone(),
			collator: collator.clone(),
			signature: signature.clone(),
			pov_block_hash: *pov_block_hash,
516
517
		}
	}
518
519
520
521
522
523
524
525
526
527
528

	/// Clone the relevant portions of the `AbridgedCandidateReceipt` to form a `CandidateDescriptor`.
	pub fn to_descriptor(&self) -> CandidateDescriptor {
		CandidateDescriptor {
			para_id: self.parachain_index,
			relay_parent: self.relay_parent,
			collator: self.collator.clone(),
			signature: self.signature.clone(),
			pov_hash: self.pov_block_hash.clone(),
		}
	}
529
530
}

531
impl PartialOrd for AbridgedCandidateReceipt {
532
533
534
535
536
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

537
impl Ord for AbridgedCandidateReceipt {
538
539
	fn cmp(&self, other: &Self) -> Ordering {
		// TODO: compare signatures or something more sane
540
		// https://github.com/paritytech/polkadot/issues/222
Shawn Tabrizi's avatar
Shawn Tabrizi committed
541
542
		self.parachain_index
			.cmp(&other.parachain_index)
543
544
545
546
			.then_with(|| self.head_data.cmp(&other.head_data))
	}
}

547
/// A unique descriptor of the candidate receipt, in a lightweight format.
548
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
549
550
551
552
553
554
555
556
557
558
559
560
#[cfg_attr(feature = "std", derive(Debug, Default))]
pub struct CandidateDescriptor<H = Hash> {
	/// The ID of the para this is a candidate for.
	pub para_id: Id,
	/// The hash of the relay-chain block this should be executed in
	/// the context of.
	// NOTE: the fact that the hash includes this value means that code depends
	// on this for deduplication. Removing this field is likely to break things.
	pub relay_parent: H,
	/// The collator's relay-chain account ID
	pub collator: CollatorId,
	/// Signature on blake2-256 of components of this receipt:
Denis_P's avatar
Denis_P committed
561
	/// The para ID, the relay parent, and the `pov_hash`.
562
	pub signature: CollatorSignature,
Denis_P's avatar
Denis_P committed
563
	/// The hash of the `pov-block`.
564
565
566
	pub pov_hash: H,
}

567
/// A collation sent by a collator.
568
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
569
570
571
572
573
574
575
576
577
578
579
580
581
#[cfg_attr(feature = "std", derive(Debug, Default))]
pub struct CollationInfo {
	/// The ID of the parachain this is a candidate for.
	pub parachain_index: Id,
	/// The relay-chain block hash this block should execute in the
	/// context of.
	pub relay_parent: Hash,
	/// The collator's relay-chain account ID
	pub collator: CollatorId,
	/// Signature on blake2-256 of the block data by collator.
	pub signature: CollatorSignature,
	/// The head-data
	pub head_data: HeadData,
Denis_P's avatar
Denis_P committed
582
	/// blake2-256 Hash of the `pov-block`
583
584
585
586
	pub pov_block_hash: Hash,
}

impl CollationInfo {
Denis_P's avatar
Denis_P committed
587
	/// Check integrity vs. a `pov-block`.
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
	pub fn check_signature(&self) -> Result<(), ()> {
		check_collator_signature(
			&self.relay_parent,
			&self.parachain_index,
			&self.pov_block_hash,
			&self.collator,
			&self.signature,
		)
	}

	/// Turn this into an `AbridgedCandidateReceipt` by supplying a set of commitments.
	pub fn into_receipt(self, commitments: CandidateCommitments) -> AbridgedCandidateReceipt {
		let CollationInfo {
			parachain_index,
			relay_parent,
			collator,
			signature,
			head_data,
			pov_block_hash,
		} = self;

		AbridgedCandidateReceipt {
			parachain_index,
			relay_parent,
			collator,
			signature,
			head_data,
			pov_block_hash,
			commitments,
		}
	}
}

621
/// A full collation.
622
#[derive(PartialEq, Eq, Clone)]
623
#[cfg_attr(feature = "std", derive(Debug, Encode, Decode, TypeInfo))]
624
625
pub struct Collation {
	/// Candidate receipt itself.
626
	pub info: CollationInfo,
627
628
	/// A proof-of-validation for the receipt.
	pub pov: PoVBlock,
629
630
}

631
/// A Proof-of-Validation block.
Gav's avatar
Gav committed
632
#[derive(PartialEq, Eq, Clone)]
633
#[cfg_attr(feature = "std", derive(Debug, Encode, Decode, TypeInfo))]
634
635
636
637
638
pub struct PoVBlock {
	/// Block data.
	pub block_data: BlockData,
}

639
640
641
642
643
644
645
646
impl PoVBlock {
	/// Compute hash of block data.
	#[cfg(feature = "std")]
	pub fn hash(&self) -> Hash {
		BlakeTwo256::hash_of(&self)
	}
}

joe petrowski's avatar
joe petrowski committed
647
/// The data that is kept available about a particular parachain block.
648
#[derive(PartialEq, Eq, Clone)]
649
#[cfg_attr(feature = "std", derive(Debug, Encode, Decode, TypeInfo))]
650
651
652
pub struct AvailableData {
	/// The PoV block.
	pub pov_block: PoVBlock,
joe petrowski's avatar
joe petrowski committed
653
	/// Data that is omitted from an abridged candidate receipt
654
655
656
657
658
	/// that is necessary for validation.
	pub omitted_validation: OmittedValidationData,
	// In the future, outgoing messages as well.
}

659
660
const BACKING_STATEMENT_MAGIC: [u8; 4] = *b"BKNG";

joe petrowski's avatar
joe petrowski committed
661
662
/// Statements that can be made about parachain candidates. These are the
/// actual values that are signed.
663
#[derive(Clone, PartialEq, Eq)]
664
#[cfg_attr(feature = "std", derive(Debug, Hash))]
665
pub enum CompactStatement {
666
	/// Proposal of a parachain candidate.
667
	Seconded(CandidateHash),
668
	/// State that a parachain candidate is valid.
669
	Valid(CandidateHash),
670
671
}

672
673
674
675
676
677
678
679
impl CompactStatement {
	/// Yields the payload used for validator signatures on this kind
	/// of statement.
	pub fn signing_payload(&self, context: &SigningContext) -> Vec<u8> {
		(self, context).encode()
	}
}

680
// Inner helper for codec on `CompactStatement`.
681
#[derive(Encode, Decode, TypeInfo)]
682
683
684
685
686
enum CompactStatementInner {
	#[codec(index = 1)]
	Seconded(CandidateHash),
	#[codec(index = 2)]
	Valid(CandidateHash),
687
}
688

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
impl From<CompactStatement> for CompactStatementInner {
	fn from(s: CompactStatement) -> Self {
		match s {
			CompactStatement::Seconded(h) => CompactStatementInner::Seconded(h),
			CompactStatement::Valid(h) => CompactStatementInner::Valid(h),
		}
	}
}

impl parity_scale_codec::Encode for CompactStatement {
	fn size_hint(&self) -> usize {
		// magic + discriminant + payload
		4 + 1 + 32
	}

	fn encode_to<T: parity_scale_codec::Output + ?Sized>(&self, dest: &mut T) {
		dest.write(&BACKING_STATEMENT_MAGIC);
		CompactStatementInner::from(self.clone()).encode_to(dest)
	}
}

impl parity_scale_codec::Decode for CompactStatement {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
711
712
713
	fn decode<I: parity_scale_codec::Input>(
		input: &mut I,
	) -> Result<Self, parity_scale_codec::Error> {
714
715
		let maybe_magic = <[u8; 4]>::decode(input)?;
		if maybe_magic != BACKING_STATEMENT_MAGIC {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
716
			return Err(parity_scale_codec::Error::from("invalid magic string"))
717
718
719
720
721
722
723
724
725
		}

		Ok(match CompactStatementInner::decode(input)? {
			CompactStatementInner::Seconded(h) => CompactStatement::Seconded(h),
			CompactStatementInner::Valid(h) => CompactStatement::Valid(h),
		})
	}
}

726
727
impl CompactStatement {
	/// Get the underlying candidate hash this references.
728
	pub fn candidate_hash(&self) -> &CandidateHash {
729
		match *self {
730
			CompactStatement::Seconded(ref h) | CompactStatement::Valid(ref h) => h,
731
732
733
734
		}
	}
}

735
736
/// An either implicit or explicit attestation to the validity of a parachain
/// candidate.
737
#[derive(Clone, Eq, PartialEq, Decode, Encode, RuntimeDebug, TypeInfo)]
738
#[cfg_attr(feature = "std", derive(MallocSizeOf))]
739
pub enum ValidityAttestation {
joe petrowski's avatar
joe petrowski committed
740
	/// Implicit validity attestation by issuing.
741
	/// This corresponds to issuance of a `Candidate` statement.
742
	#[codec(index = 1)]
743
	Implicit(ValidatorSignature),
744
745
	/// An explicit attestation. This corresponds to issuance of a
	/// `Valid` statement.
746
	#[codec(index = 2)]
747
	Explicit(ValidatorSignature),
748
749
}

asynchronous rob's avatar
asynchronous rob committed
750
impl ValidityAttestation {
751
752
753
754
755
756
757
758
759
760
761
762
	/// Produce the underlying signed payload of the attestation, given the hash of the candidate,
	/// which should be known in context.
	pub fn to_compact_statement(&self, candidate_hash: CandidateHash) -> CompactStatement {
		// Explicit and implicit map directly from
		// `ValidityVote::Valid` and `ValidityVote::Issued`, and hence there is a
		// `1:1` relationshow which enables the conversion.
		match *self {
			ValidityAttestation::Implicit(_) => CompactStatement::Seconded(candidate_hash),
			ValidityAttestation::Explicit(_) => CompactStatement::Valid(candidate_hash),
		}
	}

asynchronous rob's avatar
asynchronous rob committed
763
764
765
766
767
768
769
770
771
772
773
774
	/// Get a reference to the signature.
	pub fn signature(&self) -> &ValidatorSignature {
		match *self {
			ValidityAttestation::Implicit(ref sig) => sig,
			ValidityAttestation::Explicit(ref sig) => sig,
		}
	}

	/// Produce the underlying signed payload of the attestation, given the hash of the candidate,
	/// which should be known in context.
	pub fn signed_payload<H: Encode>(
		&self,
775
		candidate_hash: CandidateHash,
asynchronous rob's avatar
asynchronous rob committed
776
777
778
		signing_context: &SigningContext<H>,
	) -> Vec<u8> {
		match *self {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
779
780
781
782
			ValidityAttestation::Implicit(_) =>
				(CompactStatement::Seconded(candidate_hash), signing_context).encode(),
			ValidityAttestation::Explicit(_) =>
				(CompactStatement::Valid(candidate_hash), signing_context).encode(),
asynchronous rob's avatar
asynchronous rob committed
783
784
785
786
		}
	}
}

787
788
/// A type returned by runtime with current session index and a parent hash.
#[derive(Clone, Eq, PartialEq, Default, Decode, Encode, RuntimeDebug)]
asynchronous rob's avatar
asynchronous rob committed
789
pub struct SigningContext<H = Hash> {
790
791
792
	/// Current session index.
	pub session_index: sp_staking::SessionIndex,
	/// Hash of the parent.
asynchronous rob's avatar
asynchronous rob committed
793
	pub parent_hash: H,
794
795
}

796
/// An attested candidate. This is submitted to the relay chain by a block author.
797
#[derive(Clone, PartialEq, Decode, Encode, RuntimeDebug)]
798
pub struct AttestedCandidate {
799
800
801
	/// The candidate data. This is abridged, because the omitted data
	/// is already present within the relay chain state.
	pub candidate: AbridgedCandidateReceipt,
802
	/// Validity attestations.
803
804
	pub validity_votes: Vec<ValidityAttestation>,
	/// Indices of the corresponding validity votes.
805
	pub validator_indices: BitVec<bitvec::order::Lsb0, u8>,
806
807
808
809
}

impl AttestedCandidate {
	/// Get the candidate.
810
	pub fn candidate(&self) -> &AbridgedCandidateReceipt {
811
812
813
814
815
816
817
818
819
		&self.candidate
	}

	/// Get the group ID of the candidate.
	pub fn parachain_index(&self) -> Id {
		self.candidate.parachain_index
	}
}

820
/// A fee schedule for messages. This is a linear function in the number of bytes of a message.
821
#[derive(PartialEq, Eq, PartialOrd, Hash, Default, Clone, Copy, Encode, Decode, TypeInfo)]
822
823
824
825
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct FeeSchedule {
	/// The base fee charged for all messages.
	pub base: Balance,
826
	/// The per-byte fee for messages charged on top of that.
827
828
829
830
831
	pub per_byte: Balance,
}

impl FeeSchedule {
	/// Compute the fee for a message of given size.
832
	pub fn compute_message_fee(&self, n_bytes: usize) -> Balance {
833
		use sp_std::mem;
834
835
836
837
838
839
840
		debug_assert!(mem::size_of::<Balance>() >= mem::size_of::<usize>());

		let n_bytes = n_bytes as Balance;
		self.base.saturating_add(n_bytes.saturating_mul(self.per_byte))
	}
}

841
sp_api::decl_runtime_apis! {
842
	/// The API for querying the state of parachains on-chain.
843
	#[api_version(3)]
844
845
	pub trait ParachainHost {
		/// Get the current validators.
Gav Wood's avatar
Gav Wood committed
846
		fn validators() -> Vec<ValidatorId>;
847
848
849
		/// Get the current duty roster.
		fn duty_roster() -> DutyRoster;
		/// Get the currently active parachains.
850
		fn active_parachains() -> Vec<(Id, Option<(CollatorId, Retriable)>)>;
851
852
		/// Get the global validation schedule that all parachains should
		/// be validated under.
853
		fn global_validation_data() -> GlobalValidationData;
854
855
		/// Get the local validation data for a particular parachain.
		fn local_validation_data(id: Id) -> Option<LocalValidationData>;
856
		/// Get the given parachain's head code blob.
857
		fn parachain_code(id: Id) -> Option<ValidationCode>;
858
859
860
		/// Extract the abridged head that was set in the extrinsics.
		fn get_heads(extrinsics: Vec<<Block as BlockT>::Extrinsic>)
			-> Option<Vec<AbridgedCandidateReceipt>>;
861
862
		/// Get a `SigningContext` with current `SessionIndex` and parent hash.
		fn signing_context() -> SigningContext;
863
864
		/// Get the `DownwardMessage`'s for the given parachain.
		fn downward_messages(id: Id) -> Vec<DownwardMessage>;
865
866
867
868
869
	}
}

/// Runtime ID module.
pub mod id {
870
	use sp_version::ApiId;
871
872
873
874

	/// Parachain host runtime API id.
	pub const PARACHAIN_HOST: ApiId = *b"parahost";
}
875

asynchronous rob's avatar
asynchronous rob committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
/// Custom validity errors used in Polkadot while validating transactions.
#[repr(u8)]
pub enum ValidityError {
	/// The Ethereum signature is invalid.
	InvalidEthereumSignature = 0,
	/// The signer has no claim.
	SignerHasNoClaim = 1,
	/// No permission to execute the call.
	NoPermission = 2,
	/// An invalid statement was made for a claim.
	InvalidStatement = 3,
}

impl From<ValidityError> for u8 {
	fn from(err: ValidityError) -> Self {
		err as u8
	}
}

/// App-specific crypto used for reporting equivocation/misbehavior in BABE,
/// GRANDPA and Parachains, described in the white paper as the fisherman role.
/// Any rewards for misbehavior reporting will be paid out to this account.
pub mod fisherman {
	use super::{Signature, Verify};
	use primitives::crypto::KeyTypeId;

	/// Key type for the reporting module. Used for reporting BABE, GRANDPA
	/// and Parachain equivocations.
	pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"fish");

	mod app {
		use application_crypto::{app_crypto, sr25519};
		app_crypto!(sr25519, super::KEY_TYPE);
	}

	/// Identity of the equivocation/misbehavior reporter.
	pub type FishermanId = app::Public;

	/// An `AppCrypto` type to allow submitting signed transactions using the fisherman
	/// application key as signer.
	pub struct FishermanAppCrypto;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
917
918
919
	impl frame_system::offchain::AppCrypto<<Signature as Verify>::Signer, Signature>
		for FishermanAppCrypto
	{
asynchronous rob's avatar
asynchronous rob committed
920
921
922
923
924
925
		type RuntimeAppPublic = FishermanId;
		type GenericSignature = primitives::sr25519::Signature;
		type GenericPublic = primitives::sr25519::Public;
	}
}

926
927
928
929
930
931
932
933
934
935
936
#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn balance_bigger_than_usize() {
		let zero_b: Balance = 0;
		let zero_u: usize = 0;

		assert!(zero_b.leading_zeros() >= zero_u.leading_zeros());
	}
937
938
939
940
941
942
943

	#[test]
	fn collator_signature_payload_is_valid() {
		// if this fails, collator signature verification code has to be updated.
		let h = Hash::default();
		assert_eq!(h.as_ref().len(), 32);

Shawn Tabrizi's avatar
Shawn Tabrizi committed
944
945
		let _payload =
			collator_signature_payload(&Hash::repeat_byte(1), &5u32.into(), &Hash::repeat_byte(2));
946
	}
947
}