mod.rs 53.6 KB
Newer Older
asynchronous rob's avatar
asynchronous rob committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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/>.

Denis_P's avatar
Denis_P committed
17
//! `V1` Primitives.
asynchronous rob's avatar
asynchronous rob committed
18
19

use bitvec::vec::BitVec;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
20
use parity_scale_codec::{Decode, Encode};
21
use scale_info::TypeInfo;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
22
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
asynchronous rob's avatar
asynchronous rob committed
23

Shawn Tabrizi's avatar
Shawn Tabrizi committed
24
25
use application_crypto::KeyTypeId;
use inherents::InherentIdentifier;
asynchronous rob's avatar
asynchronous rob committed
26
use primitives::RuntimeDebug;
27
use runtime_primitives::traits::{AppVerify, Header as HeaderT};
28
use sp_arithmetic::traits::{BaseArithmetic, Saturating};
asynchronous rob's avatar
asynchronous rob committed
29

30
pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT};
asynchronous rob's avatar
asynchronous rob committed
31
32
33

// Export some core primitives.
pub use polkadot_core_primitives::v1::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
34
35
36
	AccountId, AccountIndex, AccountPublic, Balance, Block, BlockId, BlockNumber, CandidateHash,
	ChainId, DownwardMessage, Hash, Header, InboundDownwardMessage, InboundHrmpMessage, Moment,
	Nonce, OutboundHrmpMessage, Remark, Signature, UncheckedExtrinsic,
asynchronous rob's avatar
asynchronous rob committed
37
38
39
40
};

// Export some polkadot-parachain primitives
pub use polkadot_parachain::primitives::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
41
42
	HeadData, HrmpChannelId, Id, UpwardMessage, ValidationCode, ValidationCodeHash,
	LOWEST_PUBLIC_ID, LOWEST_USER_ID,
asynchronous rob's avatar
asynchronous rob committed
43
44
45
46
};

// Export some basic parachain primitives from v0.
pub use crate::v0::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
47
48
	CollatorId, CollatorSignature, CompactStatement, SigningContext, ValidatorId, ValidatorIndex,
	ValidatorSignature, ValidityAttestation, PARACHAIN_KEY_TYPE_ID,
asynchronous rob's avatar
asynchronous rob committed
49
50
};

51
52
53
#[cfg(feature = "std")]
use parity_util_mem::{MallocSizeOf, MallocSizeOfOps};

asynchronous rob's avatar
asynchronous rob committed
54
55
// More exports from v0 for std.
#[cfg(feature = "std")]
Shawn Tabrizi's avatar
Shawn Tabrizi committed
56
pub use crate::v0::{CollatorPair, ValidatorPair};
asynchronous rob's avatar
asynchronous rob committed
57

58
pub use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
59
pub use sp_consensus_slots::Slot;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
60
pub use sp_staking::SessionIndex;
61

62
63
/// Signed data.
mod signed;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
64
pub use signed::{EncodeAs, Signed, UncheckedSigned};
65

66
67
/// A declarations of storage keys where an external observer can find some interesting data.
pub mod well_known_keys {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
68
	use super::{HrmpChannelId, Id};
69
	use hex_literal::hex;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
70
	use parity_scale_codec::Encode as _;
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
	use sp_io::hashing::twox_64;
	use sp_std::prelude::*;

	// A note on generating these magic values below:
	//
	// The `StorageValue`, such as `ACTIVE_CONFIG` was obtained by calling:
	//
	//     <Self as Store>::ActiveConfig::hashed_key()
	//
	// The `StorageMap` values require `prefix`, and for example for `hrmp_egress_channel_index`,
	// it could be obtained like:
	//
	//     <Hrmp as Store>::HrmpEgressChannelsIndex::prefix_hash();
	//

86
87
88
89
90
91
	/// The current slot number.
	///
	/// The storage entry should be accessed as a `Slot` encoded value.
	pub const CURRENT_SLOT: &[u8] =
		&hex!["1cb6f36e027abb2091cfb5110ab5087f06155b3cd9a8c9e5e9a23fd5dc13a5ed"];

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
	/// The currently active host configuration.
	///
	/// The storage entry should be accessed as an `AbridgedHostConfiguration` encoded value.
	pub const ACTIVE_CONFIG: &[u8] =
		&hex!["06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385"];

	/// The upward message dispatch queue for the given para id.
	///
	/// The storage entry stores a tuple of two values:
	///
	/// - `count: u32`, the number of messages currently in the queue for given para,
	/// - `total_size: u32`, the total size of all messages in the queue.
	pub fn relay_dispatch_queue_size(para_id: Id) -> Vec<u8> {
		let prefix = hex!["f5207f03cfdce586301014700e2c2593fad157e461d71fd4c1f936839a5f1f3e"];

		para_id.using_encoded(|para_id: &[u8]| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
108
109
			prefix
				.as_ref()
110
111
112
113
114
115
116
117
				.iter()
				.chain(twox_64(para_id).iter())
				.chain(para_id.iter())
				.cloned()
				.collect()
		})
	}

Denis_P's avatar
Denis_P committed
118
	/// The HRMP channel for the given identifier.
119
120
121
122
123
124
	///
	/// The storage entry should be accessed as an `AbridgedHrmpChannel` encoded value.
	pub fn hrmp_channels(channel: HrmpChannelId) -> Vec<u8> {
		let prefix = hex!["6a0da05ca59913bc38a8630590f2627cb6604cff828a6e3f579ca6c59ace013d"];

		channel.using_encoded(|channel: &[u8]| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
125
126
			prefix
				.as_ref()
127
128
129
130
131
132
133
134
				.iter()
				.chain(twox_64(channel).iter())
				.chain(channel.iter())
				.cloned()
				.collect()
		})
	}

135
136
137
138
139
140
141
	/// The list of inbound channels for the given para.
	///
	/// The storage entry stores a `Vec<ParaId>`
	pub fn hrmp_ingress_channel_index(para_id: Id) -> Vec<u8> {
		let prefix = hex!["6a0da05ca59913bc38a8630590f2627c1d3719f5b0b12c7105c073c507445948"];

		para_id.using_encoded(|para_id: &[u8]| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
142
143
			prefix
				.as_ref()
144
145
146
147
148
149
150
151
				.iter()
				.chain(twox_64(para_id).iter())
				.chain(para_id.iter())
				.cloned()
				.collect()
		})
	}

152
153
154
155
156
157
158
	/// The list of outbound channels for the given para.
	///
	/// The storage entry stores a `Vec<ParaId>`
	pub fn hrmp_egress_channel_index(para_id: Id) -> Vec<u8> {
		let prefix = hex!["6a0da05ca59913bc38a8630590f2627cf12b746dcf32e843354583c9702cc020"];

		para_id.using_encoded(|para_id: &[u8]| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
159
160
			prefix
				.as_ref()
161
162
163
164
165
166
167
				.iter()
				.chain(twox_64(para_id).iter())
				.chain(para_id.iter())
				.cloned()
				.collect()
		})
	}
168
169
170
171
172
173
174
175
176

	/// The MQC head for the downward message queue of the given para. See more in the `Dmp` module.
	///
	/// The storage entry stores a `Hash`. This is polkadot hash which is at the moment
	/// `blake2b-256`.
	pub fn dmq_mqc_head(para_id: Id) -> Vec<u8> {
		let prefix = hex!["63f78c98723ddc9073523ef3beefda0c4d7fefc408aac59dbfe80a72ac8e3ce5"];

		para_id.using_encoded(|para_id: &[u8]| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
177
178
			prefix
				.as_ref()
179
180
181
182
183
184
185
				.iter()
				.chain(twox_64(para_id).iter())
				.chain(para_id.iter())
				.cloned()
				.collect()
		})
	}
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

	/// The signal that indicates whether the parachain should go-ahead with the proposed validation
	/// code upgrade.
	///
	/// The storage entry stores a value of `UpgradeGoAhead` type.
	pub fn upgrade_go_ahead_signal(para_id: Id) -> Vec<u8> {
		let prefix = hex!["cd710b30bd2eab0352ddcc26417aa1949e94c040f5e73d9b7addd6cb603d15d3"];

		para_id.using_encoded(|para_id: &[u8]| {
			prefix
				.as_ref()
				.iter()
				.chain(twox_64(para_id).iter())
				.chain(para_id.iter())
				.cloned()
				.collect()
		})
	}

	/// The signal that indicates whether the parachain is disallowed to signal an upgrade at this
	/// relay-parent.
	///
	/// The storage entry stores a value of `UpgradeRestriction` type.
	pub fn upgrade_restriction_signal(para_id: Id) -> Vec<u8> {
		let prefix = hex!["cd710b30bd2eab0352ddcc26417aa194f27bbb460270642b5bcaf032ea04d56a"];

		para_id.using_encoded(|para_id: &[u8]| {
			prefix
				.as_ref()
				.iter()
				.chain(twox_64(para_id).iter())
				.chain(para_id.iter())
				.cloned()
				.collect()
		})
	}
222
223
}

224
225
/// Unique identifier for the Parachains Inherent
pub const PARACHAINS_INHERENT_IDENTIFIER: InherentIdentifier = *b"parachn0";
asynchronous rob's avatar
asynchronous rob committed
226

227
228
229
/// The key type ID for parachain assignment key.
pub const ASSIGNMENT_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"asgn");

230
/// Maximum compressed code size we support right now.
Bernhard Schuster's avatar
Bernhard Schuster committed
231
/// At the moment we have runtime upgrade on chain, which restricts scalability severely. If we want
232
/// to have bigger values, we should fix that first.
233
234
235
236
237
///
/// Used for:
/// * initial genesis for the Parachains configuration
/// * checking updates to this stored runtime configuration do not exceed this limit
/// * when detecting a code decompression bomb in the client
238
239
pub const MAX_CODE_SIZE: u32 = 3 * 1024 * 1024;

240
241
242
243
244
245
246
/// Maximum head data size we support right now.
///
/// Used for:
/// * initial genesis for the Parachains configuration
/// * checking updates to this stored runtime configuration do not exceed this limit
pub const MAX_HEAD_DATA_SIZE: u32 = 1 * 1024 * 1024;

247
248
249
250
251
252
253
254
/// Maximum PoV size we support right now.
///
/// Used for:
/// * initial genesis for the Parachains configuration
/// * checking updates to this stored runtime configuration do not exceed this limit
/// * when detecting a PoV decompression bomb in the client
pub const MAX_POV_SIZE: u32 = 5 * 1024 * 1024;

255
256
// The public key of a keypair used by a validator for determining assignments
/// to approve included parachain candidates.
257
mod assignment_app {
258
259
260
261
262
263
	use application_crypto::{app_crypto, sr25519};
	app_crypto!(sr25519, super::ASSIGNMENT_KEY_TYPE_ID);
}

/// The public key of a keypair used by a validator for determining assignments
/// to approve included parachain candidates.
264
265
266
267
268
269
270
pub type AssignmentId = assignment_app::Public;

application_crypto::with_pair! {
	/// The full keypair used by a validator for determining assignments to approve included
	/// parachain candidates.
	pub type AssignmentPair = assignment_app::Pair;
}
271

272
273
274
275
276
277
278
279
280
281
#[cfg(feature = "std")]
impl MallocSizeOf for AssignmentId {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

282
283
284
/// The index of the candidate in the list of candidates fully included as-of the block.
pub type CandidateIndex = u32;

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

	payload[0..32].copy_from_slice(relay_parent.as_ref());
	u32::from(*para_id).using_encoded(|s| payload[32..32 + s.len()].copy_from_slice(s));
298
	payload[36..68].copy_from_slice(persisted_validation_data_hash.as_ref());
299
	payload[68..100].copy_from_slice(pov_hash.as_ref());
300
	payload[100..132].copy_from_slice(validation_code_hash.as_ref());
asynchronous rob's avatar
asynchronous rob committed
301
302
303
304
305
306
307

	payload
}

fn check_collator_signature<H: AsRef<[u8]>>(
	relay_parent: &H,
	para_id: &Id,
308
	persisted_validation_data_hash: &Hash,
asynchronous rob's avatar
asynchronous rob committed
309
	pov_hash: &Hash,
310
	validation_code_hash: &ValidationCodeHash,
asynchronous rob's avatar
asynchronous rob committed
311
312
	collator: &CollatorId,
	signature: &CollatorSignature,
313
) -> Result<(), ()> {
314
315
316
	let payload = collator_signature_payload(
		relay_parent,
		para_id,
317
		persisted_validation_data_hash,
318
		pov_hash,
319
		validation_code_hash,
320
321
	);

asynchronous rob's avatar
asynchronous rob committed
322
323
324
325
326
327
328
329
	if signature.verify(&payload[..], collator) {
		Ok(())
	} else {
		Err(())
	}
}

/// A unique descriptor of the candidate receipt.
330
331
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Default)]
#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))]
asynchronous rob's avatar
asynchronous rob committed
332
333
334
335
336
337
338
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 is executed in the context of.
	pub relay_parent: H,
	/// The collator's sr25519 public key.
	pub collator: CollatorId,
339
	/// The blake2-256 hash of the persisted validation data. This is extra data derived from
340
341
	/// relay-chain state which may vary based on bitfields included before the candidate.
	/// Thus it cannot be derived entirely from the relay-parent.
342
	pub persisted_validation_data_hash: Hash,
Denis_P's avatar
Denis_P committed
343
	/// The blake2-256 hash of the PoV.
asynchronous rob's avatar
asynchronous rob committed
344
	pub pov_hash: Hash,
345
346
	/// The root of a block's erasure encoding Merkle tree.
	pub erasure_root: Hash,
347
	/// Signature on blake2-256 of components of this receipt:
Denis_P's avatar
Denis_P committed
348
	/// The parachain index, the relay parent, the validation data hash, and the `pov_hash`.
349
	pub signature: CollatorSignature,
350
351
	/// Hash of the para header that is being generated by this candidate.
	pub para_head: Hash,
352
	/// The blake2-256 hash of the validation code bytes.
353
	pub validation_code_hash: ValidationCodeHash,
asynchronous rob's avatar
asynchronous rob committed
354
355
356
357
358
359
360
361
}

impl<H: AsRef<[u8]>> CandidateDescriptor<H> {
	/// Check the signature of the collator within this descriptor.
	pub fn check_collator_signature(&self) -> Result<(), ()> {
		check_collator_signature(
			&self.relay_parent,
			&self.para_id,
362
			&self.persisted_validation_data_hash,
asynchronous rob's avatar
asynchronous rob committed
363
			&self.pov_hash,
364
			&self.validation_code_hash,
asynchronous rob's avatar
asynchronous rob committed
365
366
367
368
369
370
371
			&self.collator,
			&self.signature,
		)
	}
}

/// A candidate-receipt.
372
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
373
#[cfg_attr(feature = "std", derive(Debug, Default, MallocSizeOf))]
asynchronous rob's avatar
asynchronous rob committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
pub struct CandidateReceipt<H = Hash> {
	/// The descriptor of the candidate.
	pub descriptor: CandidateDescriptor<H>,
	/// The hash of the encoded commitments made as a result of candidate execution.
	pub commitments_hash: Hash,
}

impl<H> CandidateReceipt<H> {
	/// Get a reference to the candidate descriptor.
	pub fn descriptor(&self) -> &CandidateDescriptor<H> {
		&self.descriptor
	}

	/// Computes the blake2-256 hash of the receipt.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
388
389
390
391
	pub fn hash(&self) -> CandidateHash
	where
		H: Encode,
	{
392
		CandidateHash(BlakeTwo256::hash_of(self))
asynchronous rob's avatar
asynchronous rob committed
393
394
395
396
	}
}

/// All data pertaining to the execution of a para candidate.
397
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
asynchronous rob's avatar
asynchronous rob committed
398
#[cfg_attr(feature = "std", derive(Debug, Default))]
399
pub struct FullCandidateReceipt<H = Hash, N = BlockNumber> {
asynchronous rob's avatar
asynchronous rob committed
400
401
	/// The inner candidate receipt.
	pub inner: CandidateReceipt<H>,
402
403
404
405
	/// The validation data derived from the relay-chain state at that
	/// point. The hash of the persisted validation data should
	/// match the `persisted_validation_data_hash` in the descriptor
	/// of the receipt.
406
	pub validation_data: PersistedValidationData<H, N>,
asynchronous rob's avatar
asynchronous rob committed
407
408
409
}

/// A candidate-receipt with commitments directly included.
410
411
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Default)]
#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))]
asynchronous rob's avatar
asynchronous rob committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
pub struct CommittedCandidateReceipt<H = Hash> {
	/// The descriptor of the candidate.
	pub descriptor: CandidateDescriptor<H>,
	/// The commitments of the candidate receipt.
	pub commitments: CandidateCommitments,
}

impl<H> CommittedCandidateReceipt<H> {
	/// Get a reference to the candidate descriptor.
	pub fn descriptor(&self) -> &CandidateDescriptor<H> {
		&self.descriptor
	}
}

impl<H: Clone> CommittedCandidateReceipt<H> {
Denis_P's avatar
Denis_P committed
427
	/// Transforms this into a plain `CandidateReceipt`.
asynchronous rob's avatar
asynchronous rob committed
428
429
430
431
432
433
434
435
436
437
438
	pub fn to_plain(&self) -> CandidateReceipt<H> {
		CandidateReceipt {
			descriptor: self.descriptor.clone(),
			commitments_hash: self.commitments.hash(),
		}
	}

	/// Computes the hash of the committed candidate receipt.
	///
	/// This computes the canonical hash, not the hash of the directly encoded data.
	/// Thus this is a shortcut for `candidate.to_plain().hash()`.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
439
440
441
442
	pub fn hash(&self) -> CandidateHash
	where
		H: Encode,
	{
asynchronous rob's avatar
asynchronous rob committed
443
444
		self.to_plain().hash()
	}
Bastian Köcher's avatar
Bastian Köcher committed
445

Bernhard Schuster's avatar
Bernhard Schuster committed
446
	/// Does this committed candidate receipt corresponds to the given [`CandidateReceipt`]?
Shawn Tabrizi's avatar
Shawn Tabrizi committed
447
448
449
450
	pub fn corresponds_to(&self, receipt: &CandidateReceipt<H>) -> bool
	where
		H: PartialEq,
	{
Bastian Köcher's avatar
Bastian Köcher committed
451
452
		receipt.descriptor == self.descriptor && receipt.commitments_hash == self.commitments.hash()
	}
asynchronous rob's avatar
asynchronous rob committed
453
454
455
456
457
458
459
460
461
462
463
464
}

impl PartialOrd for CommittedCandidateReceipt {
	fn partial_cmp(&self, other: &Self) -> Option<sp_std::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for CommittedCandidateReceipt {
	fn cmp(&self, other: &Self) -> sp_std::cmp::Ordering {
		// TODO: compare signatures or something more sane
		// https://github.com/paritytech/polkadot/issues/222
Shawn Tabrizi's avatar
Shawn Tabrizi committed
465
466
467
		self.descriptor()
			.para_id
			.cmp(&other.descriptor().para_id)
asynchronous rob's avatar
asynchronous rob committed
468
469
470
471
			.then_with(|| self.commitments.head_data.cmp(&other.commitments.head_data))
	}
}

472
/// The validation data provides information about how to create the inputs for validation of a candidate.
Bernhard Schuster's avatar
Bernhard Schuster committed
473
/// This information is derived from the chain state and will vary from para to para, although some
474
/// fields may be the same for every para.
475
///
476
477
/// Since this data is used to form inputs to the validation function, it needs to be persisted by the
/// availability system to avoid dependence on availability of the relay-chain state.
478
///
479
480
481
482
/// Furthermore, the validation data acts as a way to authorize the additional data the collator needs
/// to pass to the validation function. For example, the validation function can check whether the incoming
/// messages (e.g. downward messages) were actually sent by using the data provided in the validation data
/// using so called MQC heads.
483
///
484
485
486
487
/// Since the commitments of the validation function are checked by the relay-chain, secondary checkers
/// can rely on the invariant that the relay-chain only includes para-blocks for which these checks have
/// already been done. As such, there is no need for the validation data used to inform validators and
/// collators about the checks the relay-chain will perform to be persisted by the availability system.
488
///
Bernhard Schuster's avatar
Bernhard Schuster committed
489
/// The `PersistedValidationData` should be relatively lightweight primarily because it is constructed
490
/// during inclusion for each candidate and therefore lies on the critical path of inclusion.
491
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
492
#[cfg_attr(feature = "std", derive(Debug, Default, MallocSizeOf))]
493
pub struct PersistedValidationData<H = Hash, N = BlockNumber> {
asynchronous rob's avatar
asynchronous rob committed
494
495
	/// The parent head-data.
	pub parent_head: HeadData,
496
	/// The relay-chain block number this is in the context of.
497
	pub relay_parent_number: N,
498
	/// The relay-chain block storage root this is in the context of.
499
	pub relay_parent_storage_root: H,
500
501
	/// The maximum legal size of a POV block, in bytes.
	pub max_pov_size: u32,
502
503
}

504
impl<H: Encode, N: Encode> PersistedValidationData<H, N> {
505
506
507
508
509
510
	/// Compute the blake2-256 hash of the persisted validation data.
	pub fn hash(&self) -> Hash {
		BlakeTwo256::hash_of(self)
	}
}

asynchronous rob's avatar
asynchronous rob committed
511
/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation.
512
513
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Default)]
#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))]
Sergey Pepyakin's avatar
Sergey Pepyakin committed
514
pub struct CandidateCommitments<N = BlockNumber> {
asynchronous rob's avatar
asynchronous rob committed
515
516
	/// Messages destined to be interpreted by the Relay chain itself.
	pub upward_messages: Vec<UpwardMessage>,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
517
518
	/// Horizontal messages sent by the parachain.
	pub horizontal_messages: Vec<OutboundHrmpMessage<Id>>,
asynchronous rob's avatar
asynchronous rob committed
519
520
521
522
	/// New validation code.
	pub new_validation_code: Option<ValidationCode>,
	/// The head-data produced as a result of execution.
	pub head_data: HeadData,
523
524
	/// The number of messages processed from the DMQ.
	pub processed_downward_messages: u32,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
525
526
	/// The mark which specifies the block number up to which all inbound HRMP messages are processed.
	pub hrmp_watermark: N,
asynchronous rob's avatar
asynchronous rob committed
527
528
529
530
531
532
533
534
535
536
}

impl CandidateCommitments {
	/// Compute the blake2-256 hash of the commitments.
	pub fn hash(&self) -> Hash {
		BlakeTwo256::hash_of(self)
	}
}

/// A bitfield concerning availability of backed candidates.
537
538
///
/// Every bit refers to an availability core index.
539
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
asynchronous rob's avatar
asynchronous rob committed
540
541
542
543
544
545
546
547
pub struct AvailabilityBitfield(pub BitVec<bitvec::order::Lsb0, u8>);

impl From<BitVec<bitvec::order::Lsb0, u8>> for AvailabilityBitfield {
	fn from(inner: BitVec<bitvec::order::Lsb0, u8>) -> Self {
		AvailabilityBitfield(inner)
	}
}

548
549
550
/// A signed compact statement, suitable to be sent to the chain.
pub type SignedStatement = Signed<CompactStatement>;

asynchronous rob's avatar
asynchronous rob committed
551
552
/// A bitfield signed by a particular validator about the availability of pending candidates.
pub type SignedAvailabilityBitfield = Signed<AvailabilityBitfield>;
553
554
/// A signed bitfield with signature not yet checked.
pub type UncheckedSignedAvailabilityBitfield = UncheckedSigned<AvailabilityBitfield>;
asynchronous rob's avatar
asynchronous rob committed
555
556
557

/// A set of signed availability bitfields. Should be sorted by validator index, ascending.
pub type SignedAvailabilityBitfields = Vec<SignedAvailabilityBitfield>;
558
559
/// A set of unchecked signed availability bitfields. Should be sorted by validator index, ascending.
pub type UncheckedSignedAvailabilityBitfields = Vec<UncheckedSignedAvailabilityBitfield>;
asynchronous rob's avatar
asynchronous rob committed
560
561

/// A backed (or backable, depending on context) candidate.
562
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
563
#[cfg_attr(feature = "std", derive(Default))]
asynchronous rob's avatar
asynchronous rob committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
pub struct BackedCandidate<H = Hash> {
	/// The candidate referred to.
	pub candidate: CommittedCandidateReceipt<H>,
	/// The validity votes themselves, expressed as signatures.
	pub validity_votes: Vec<ValidityAttestation>,
	/// The indices of the validators within the group, expressed as a bitfield.
	pub validator_indices: BitVec<bitvec::order::Lsb0, u8>,
}

impl<H> BackedCandidate<H> {
	/// Get a reference to the descriptor of the para.
	pub fn descriptor(&self) -> &CandidateDescriptor<H> {
		&self.candidate.descriptor
	}
578
579

	/// Compute this candidate's hash.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
580
581
582
583
	pub fn hash(&self) -> CandidateHash
	where
		H: Clone + Encode,
	{
584
585
586
587
		self.candidate.hash()
	}

	/// Get this candidate's receipt.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
588
589
590
591
	pub fn receipt(&self) -> CandidateReceipt<H>
	where
		H: Clone,
	{
592
593
		self.candidate.to_plain()
	}
asynchronous rob's avatar
asynchronous rob committed
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
}

/// Verify the backing of the given candidate.
///
/// Provide a lookup from the index of a validator within the group assigned to this para,
/// as opposed to the index of the validator within the overall validator set, as well as
/// the number of validators in the group.
///
/// Also provide the signing context.
///
/// Returns either an error, indicating that one of the signatures was invalid or that the index
/// was out-of-bounds, or the number of signatures checked.
pub fn check_candidate_backing<H: AsRef<[u8]> + Clone + Encode>(
	backed: &BackedCandidate<H>,
	signing_context: &SigningContext<H>,
	group_len: usize,
	validator_lookup: impl Fn(usize) -> Option<ValidatorId>,
) -> Result<usize, ()> {
	if backed.validator_indices.len() != group_len {
		return Err(())
	}

	if backed.validity_votes.len() > group_len {
		return Err(())
	}

	// this is known, even in runtime, to be blake2-256.
621
	let hash = backed.candidate.hash();
asynchronous rob's avatar
asynchronous rob committed
622
623

	let mut signed = 0;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
624
625
626
627
	for ((val_in_group_idx, _), attestation) in backed
		.validator_indices
		.iter()
		.enumerate()
asynchronous rob's avatar
asynchronous rob committed
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
		.filter(|(_, signed)| **signed)
		.zip(backed.validity_votes.iter())
	{
		let validator_id = validator_lookup(val_in_group_idx).ok_or(())?;
		let payload = attestation.signed_payload(hash.clone(), signing_context);
		let sig = attestation.signature();

		if sig.verify(&payload[..], &validator_id) {
			signed += 1;
		} else {
			return Err(())
		}
	}

	if signed != backed.validity_votes.len() {
		return Err(())
	}

	Ok(signed)
}

/// The unique (during session) index of a core.
650
#[derive(Encode, Decode, Default, PartialOrd, Ord, Eq, PartialEq, Clone, Copy, TypeInfo)]
651
#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))]
asynchronous rob's avatar
asynchronous rob committed
652
653
654
655
656
657
658
659
660
pub struct CoreIndex(pub u32);

impl From<u32> for CoreIndex {
	fn from(i: u32) -> CoreIndex {
		CoreIndex(i)
	}
}

/// The unique (during session) index of a validator group.
661
#[derive(Encode, Decode, Default, Clone, Copy, Debug, PartialEq, Eq, TypeInfo)]
662
#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))]
asynchronous rob's avatar
asynchronous rob committed
663
664
665
666
667
668
669
670
671
pub struct GroupIndex(pub u32);

impl From<u32> for GroupIndex {
	fn from(i: u32) -> GroupIndex {
		GroupIndex(i)
	}
}

/// A claim on authoring the next block for a given parathread.
672
#[derive(Clone, Encode, Decode, Default, TypeInfo)]
asynchronous rob's avatar
asynchronous rob committed
673
674
675
676
#[cfg_attr(feature = "std", derive(PartialEq, Debug))]
pub struct ParathreadClaim(pub Id, pub CollatorId);

/// An entry tracking a claim to ensure it does not pass the maximum number of retries.
677
#[derive(Clone, Encode, Decode, Default, TypeInfo)]
asynchronous rob's avatar
asynchronous rob committed
678
679
680
681
682
683
684
685
686
#[cfg_attr(feature = "std", derive(PartialEq, Debug))]
pub struct ParathreadEntry {
	/// The claim.
	pub claim: ParathreadClaim,
	/// Number of retries.
	pub retries: u32,
}

/// What is occupying a specific availability core.
687
#[derive(Clone, Encode, Decode, TypeInfo)]
asynchronous rob's avatar
asynchronous rob committed
688
689
690
691
692
693
694
695
#[cfg_attr(feature = "std", derive(PartialEq, Debug))]
pub enum CoreOccupied {
	/// A parathread.
	Parathread(ParathreadEntry),
	/// A parachain.
	Parachain,
}

696
/// A helper data-type for tracking validator-group rotations.
697
#[derive(Clone, Encode, Decode, TypeInfo)]
698
#[cfg_attr(feature = "std", derive(PartialEq, Debug, MallocSizeOf))]
699
700
701
702
703
704
705
706
707
708
709
710
711
pub struct GroupRotationInfo<N = BlockNumber> {
	/// The block number where the session started.
	pub session_start_block: N,
	/// How often groups rotate. 0 means never.
	pub group_rotation_frequency: N,
	/// The current block number.
	pub now: N,
}

impl GroupRotationInfo {
	/// Returns the index of the group needed to validate the core at the given index, assuming
	/// the given number of cores.
	///
Denis_P's avatar
Denis_P committed
712
	/// `core_index` should be less than `cores`, which is capped at `u32::max()`.
713
	pub fn group_for_core(&self, core_index: CoreIndex, cores: usize) -> GroupIndex {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
714
715
716
717
718
719
		if self.group_rotation_frequency == 0 {
			return GroupIndex(core_index.0)
		}
		if cores == 0 {
			return GroupIndex(0)
		}
720

721
		let cores = sp_std::cmp::min(cores, u32::MAX as usize);
722
723
724
		let blocks_since_start = self.now.saturating_sub(self.session_start_block);
		let rotations = blocks_since_start / self.group_rotation_frequency;

725
726
		// g = c + r mod cores

727
728
729
		let idx = (core_index.0 as usize + rotations as usize) % cores;
		GroupIndex(idx as u32)
	}
730
731
732
733

	/// Returns the index of the group assigned to the given core. This does no checking or
	/// whether the group index is in-bounds.
	///
Denis_P's avatar
Denis_P committed
734
	/// `core_index` should be less than `cores`, which is capped at `u32::max()`.
735
	pub fn core_for_group(&self, group_index: GroupIndex, cores: usize) -> CoreIndex {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
736
737
738
739
740
741
		if self.group_rotation_frequency == 0 {
			return CoreIndex(group_index.0)
		}
		if cores == 0 {
			return CoreIndex(0)
		}
742

743
		let cores = sp_std::cmp::min(cores, u32::MAX as usize);
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
		let blocks_since_start = self.now.saturating_sub(self.session_start_block);
		let rotations = blocks_since_start / self.group_rotation_frequency;
		let rotations = rotations % cores as u32;

		// g = c + r mod cores
		// c = g - r mod cores
		// x = x + cores mod cores
		// c = (g + cores) - r mod cores

		let idx = (group_index.0 as usize + cores - rotations as usize) % cores;
		CoreIndex(idx as u32)
	}

	/// Create a new `GroupRotationInfo` with one further rotation applied.
	pub fn bump_rotation(&self) -> Self {
		GroupRotationInfo {
			session_start_block: self.session_start_block,
			group_rotation_frequency: self.group_rotation_frequency,
			now: self.next_rotation_at(),
		}
	}
765
766
767
768
769
770
771
}

impl<N: Saturating + BaseArithmetic + Copy> GroupRotationInfo<N> {
	/// Returns the block number of the next rotation after the current block. If the current block
	/// is 10 and the rotation frequency is 5, this should return 15.
	pub fn next_rotation_at(&self) -> N {
		let cycle_once = self.now + self.group_rotation_frequency;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
772
773
		cycle_once -
			(cycle_once.saturating_sub(self.session_start_block) % self.group_rotation_frequency)
774
775
776
777
778
	}

	/// Returns the block number of the last rotation before or including the current block. If the
	/// current block is 10 and the rotation frequency is 5, this should return 10.
	pub fn last_rotation_at(&self) -> N {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
779
780
		self.now -
			(self.now.saturating_sub(self.session_start_block) % self.group_rotation_frequency)
781
782
783
784
	}
}

/// Information about a core which is currently occupied.
785
#[derive(Clone, Encode, Decode, TypeInfo)]
786
#[cfg_attr(feature = "std", derive(Debug, PartialEq, MallocSizeOf))]
787
pub struct OccupiedCore<H = Hash, N = BlockNumber> {
788
	// NOTE: this has no ParaId as it can be deduced from the candidate descriptor.
789
790
791
792
793
794
795
796
797
798
799
800
801
802
	/// If this core is freed by availability, this is the assignment that is next up on this
	/// core, if any. None if there is nothing queued for this core.
	pub next_up_on_available: Option<ScheduledCore>,
	/// The relay-chain block number this began occupying the core at.
	pub occupied_since: N,
	/// The relay-chain block this will time-out at, if any.
	pub time_out_at: N,
	/// If this core is freed by being timed-out, this is the assignment that is next up on this
	/// core. None if there is nothing queued for this core or there is no possibility of timing
	/// out.
	pub next_up_on_time_out: Option<ScheduledCore>,
	/// A bitfield with 1 bit for each validator in the set. `1` bits mean that the corresponding
	/// validators has attested to availability on-chain. A 2/3+ majority of `1` bits means that
	/// this will be available.
803
	#[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")]
804
805
806
	pub availability: BitVec<bitvec::order::Lsb0, u8>,
	/// The group assigned to distribute availability pieces of this candidate.
	pub group_responsible: GroupIndex,
807
808
809
810
811
812
813
814
815
816
817
	/// The hash of the candidate occupying the core.
	pub candidate_hash: CandidateHash,
	/// The descriptor of the candidate occupying the core.
	pub candidate_descriptor: CandidateDescriptor<H>,
}

impl<H, N> OccupiedCore<H, N> {
	/// Get the Para currently occupying this core.
	pub fn para_id(&self) -> Id {
		self.candidate_descriptor.para_id
	}
818
819
820
}

/// Information about a core which is currently occupied.
821
#[derive(Clone, Encode, Decode, TypeInfo)]
822
#[cfg_attr(feature = "std", derive(Debug, PartialEq, Default, MallocSizeOf))]
823
824
825
826
827
828
829
830
pub struct ScheduledCore {
	/// The ID of a para scheduled.
	pub para_id: Id,
	/// The collator required to author the block, if any.
	pub collator: Option<CollatorId>,
}

/// The state of a particular availability core.
831
#[derive(Clone, Encode, Decode, TypeInfo)]
832
#[cfg_attr(feature = "std", derive(Debug, PartialEq, MallocSizeOf))]
833
pub enum CoreState<H = Hash, N = BlockNumber> {
834
	/// The core is currently occupied.
835
	#[codec(index = 0)]
836
	Occupied(OccupiedCore<H, N>),
837
838
839
840
841
	/// The core is currently free, with a para scheduled and given the opportunity
	/// to occupy.
	///
	/// If a particular Collator is required to author this block, that is also present in this
	/// variant.
842
	#[codec(index = 1)]
843
844
845
	Scheduled(ScheduledCore),
	/// The core is currently free and there is nothing scheduled. This can be the case for parathread
	/// cores when there are no parathread blocks queued. Parachain cores will never be left idle.
846
	#[codec(index = 2)]
847
848
849
	Free,
}

850
851
852
853
impl<N> CoreState<N> {
	/// If this core state has a `para_id`, return it.
	pub fn para_id(&self) -> Option<Id> {
		match self {
854
			Self::Occupied(ref core) => Some(core.para_id()),
855
856
857
858
			Self::Scheduled(ScheduledCore { para_id, .. }) => Some(*para_id),
			Self::Free => None,
		}
	}
859
860
861
862
863

	/// Is this core state `Self::Occupied`?
	pub fn is_occupied(&self) -> bool {
		matches!(self, Self::Occupied(_))
	}
864
865
}

866
/// An assumption being made about the state of an occupied core.
867
#[derive(Clone, Copy, Encode, Decode, TypeInfo)]
868
#[cfg_attr(feature = "std", derive(PartialEq, Eq, Hash, Debug))]
869
870
pub enum OccupiedCoreAssumption {
	/// The candidate occupying the core was made available and included to free the core.
871
	#[codec(index = 0)]
872
873
	Included,
	/// The candidate occupying the core timed out and freed the core without advancing the para.
874
	#[codec(index = 1)]
875
876
	TimedOut,
	/// The core was not occupied to begin with.
877
	#[codec(index = 2)]
878
879
880
881
	Free,
}

/// An even concerning a candidate.
882
#[derive(Clone, Encode, Decode, TypeInfo)]
883
#[cfg_attr(feature = "std", derive(PartialEq, Debug, MallocSizeOf))]
884
885
pub enum CandidateEvent<H = Hash> {
	/// This candidate receipt was backed in the most recent block.
886
	/// This includes the core index the candidate is now occupying.
887
	#[codec(index = 0)]
888
	CandidateBacked(CandidateReceipt<H>, HeadData, CoreIndex, GroupIndex),
889
	/// This candidate receipt was included and became a parablock at the most recent block.
890
891
	/// This includes the core index the candidate was occupying as well as the group responsible
	/// for backing the candidate.
892
	#[codec(index = 1)]
893
	CandidateIncluded(CandidateReceipt<H>, HeadData, CoreIndex, GroupIndex),
894
	/// This candidate receipt was not made available in time and timed out.
895
	/// This includes the core index the candidate was occupying.
896
	#[codec(index = 2)]
897
	CandidateTimedOut(CandidateReceipt<H>, HeadData, CoreIndex),
898
899
}

900
/// Information about validator sets of a session.
901
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
902
#[cfg_attr(feature = "std", derive(PartialEq, Default, MallocSizeOf))]
903
904
pub struct SessionInfo {
	/// Validators in canonical ordering.
905
906
907
908
909
910
	///
	/// NOTE: There might be more authorities in the current session, than `validators` participating
	/// in parachain consensus. See
	/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148).
	///
	/// `SessionInfo::validators` will be limited to to `max_validators` when set.
911
912
	pub validators: Vec<ValidatorId>,
	/// Validators' authority discovery keys for the session in canonical ordering.
913
914
915
916
917
	///
	/// NOTE: The first `validators.len()` entries will match the corresponding validators in
	/// `validators`, afterwards any remaining authorities can be found. This is any authorities not
	/// participating in parachain consensus - see
	/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148)
918
	#[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")]
919
	pub discovery_keys: Vec<AuthorityDiscoveryId>,
920
	/// The assignment keys for validators.
921
922
923
924
925
926
927
928
929
	///
	/// NOTE: There might be more authorities in the current session, than validators participating
	/// in parachain consensus. See
	/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148).
	///
	/// Therefore:
	/// ```ignore
	///		assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len()
	///	```
930
	pub assignment_keys: Vec<AssignmentId>,
931
932
933
934
935
936
937
938
	/// Validators in shuffled ordering - these are the validator groups as produced
	/// by the `Scheduler` module for the session and are typically referred to by
	/// `GroupIndex`.
	pub validator_groups: Vec<Vec<ValidatorIndex>>,
	/// The number of availability cores used by the protocol during this session.
	pub n_cores: u32,
	/// The zeroth delay tranche width.
	pub zeroth_delay_tranche_width: u32,
Denis_P's avatar
Denis_P committed
939
	/// The number of samples we do of `relay_vrf_modulo`.
940
941
942
943
944
945
946
947
948
949
	pub relay_vrf_modulo_samples: u32,
	/// The number of delay tranches in total.
	pub n_delay_tranches: u32,
	/// How many slots (BABE / SASSAFRAS) must pass before an assignment is considered a
	/// no-show.
	pub no_show_slots: u32,
	/// The number of validators needed to approve a block.
	pub needed_approvals: u32,
}

950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
/// Scraped runtime backing votes and resolved disputes.
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(PartialEq, Default, MallocSizeOf))]
pub struct ScrapedOnChainVotes<H: Encode + Decode = Hash> {
	/// The session in which the block was included.
	pub session: SessionIndex,
	/// Set of backing validators for each candidate, represented by its candidate
	/// receipt.
	pub backing_validators_per_candidate:
		Vec<(CandidateReceipt<H>, Vec<(ValidatorIndex, ValidityAttestation)>)>,
	/// On-chain-recorded set of disputes.
	/// Note that the above `backing_validators` are
	/// unrelated to the backers of the disputes candidates.
	pub disputes: MultiDisputeStatementSet,
}

966
967
968
969
970
971
/// A vote of approval on a candidate.
#[derive(Clone, RuntimeDebug)]
pub struct ApprovalVote(pub CandidateHash);

impl ApprovalVote {
	/// Yields the signing payload for this approval vote.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
972
	pub fn signing_payload(&self, session_index: SessionIndex) -> Vec<u8> {
973
974
975
976
977
978
		const MAGIC: [u8; 4] = *b"APPR";

		(MAGIC, &self.0, session_index).encode()
	}
}

979
980
sp_api::decl_runtime_apis! {
	/// The API for querying the state of parachains on-chain.
981
	pub trait ParachainHost<H: Encode + Decode = Hash, N: Encode + Decode = BlockNumber> {
982
983
984
		/// Get the current validators.
		fn validators() -> Vec<ValidatorId>;

985
986
987
		/// Returns the validator groups and rotation info localized based on the hypothetical child
		///  of a block whose state  this is invoked on. Note that `now` in the `GroupRotationInfo`
		/// should be the successor of the number of the block.
988
989
		fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<N>);

990
991
		/// Yields information on all availability cores as relevant to the child block.
		/// Cores are either free or occupied. Free cores can have paras assigned to them.
992
		fn availability_cores() -> Vec<CoreState<H, N>>;
993

Denis_P's avatar
Denis_P committed
994
		/// Yields the persisted validation data for the given `ParaId` along with an assumption that
995
996
997
998
		/// should be used if the para currently occupies a core.
		///
		/// Returns `None` if either the para is not registered or the assumption is `Freed`
		/// and the para already occupies a core.
999
		fn persisted_validation_data(para_id: Id, assumption: OccupiedCoreAssumption)
1000
			-> Option<PersistedValidationData<H, N>>;
1001

1002
1003
1004
1005
1006
1007
1008
1009
		/// Returns the persisted validation data for the given `ParaId` along with the corresponding
		/// validation code hash. Instead of accepting assumption about the para, matches the validation
		/// data hash against an expected one and yields `None` if they're not equal.
		fn assumed_validation_data(
			para_id: Id,
			expected_persisted_validation_data_hash: Hash,
		) -> Option<(PersistedValidationData<H, N>, ValidationCodeHash)>;

1010
		/// Checks if the given validation outputs pass the acceptance criteria.
1011
		fn check_validation_outputs(para_id: Id, outputs: CandidateCommitments) -> bool;
1012

1013
1014
1015
1016
1017
		/// Returns the session index expected at a child of the block.
		///
		/// This can be used to instantiate a `SigningContext`.
		fn session_index_for_child() -> SessionIndex;

1018
1019
1020
		/// Get the session info for the given session, if stored.
		fn session_info(index: SessionIndex) -> Option<SessionInfo>;

1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
		/// Fetch the validation code used by a para, making the given `OccupiedCoreAssumption`.
		///
		/// Returns `None` if either the para is not registered or the assumption is `Freed`
		/// and the para already occupies a core.
		fn validation_code(para_id: Id, assumption: OccupiedCoreAssumption)
			-> Option<ValidationCode>;

		/// Get the receipt of a candidate pending availability. This returns `Some` for any paras
		/// assigned to occupied cores in `availability_cores` and `None` otherwise.
		fn candidate_pending_availability(para_id: Id) -> Option<CommittedCandidateReceipt<H>>;

		/// Get a vector of events concerning candidates that occurred within a block.
		fn candidate_events() -> Vec<CandidateEvent<H>>;
1034

1035
1036
1037
1038
		/// Get all the pending inbound messages in the downward message queue for a para.
		fn dmq_contents(
			recipient: Id,
		) -> Vec<InboundDownwardMessage<N>>;
Sergey Pepyakin's avatar
Sergey Pepyakin committed
1039
1040
1041
1042

		/// Get the contents of all channels addressed to the given recipient. Channels that have no
		/// messages in them are also included.
		fn inbound_hrmp_channels_contents(recipient: Id) -> BTreeMap<Id, Vec<InboundHrmpMessage<N>>>;
1043
1044

		/// Get the validation code from its hash.
1045
		fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode>;
1046
1047
1048

		/// Scrape dispute relevant from on-chain, backing votes and resolved disputes.
		fn on_chain_votes() -> Option<ScrapedOnChainVotes<H>>;
1049
1050
1051
	}
}

1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
/// 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
	}
}

1071
1072
/// Abridged version of `HostConfiguration` (from the `Configuration` parachains host runtime module)
/// meant to be used by a parachain or PDK such as cumulus.
1073
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
#[cfg_attr(feature = "std", derive(PartialEq))]
pub struct AbridgedHostConfiguration {
	/// The maximum validation code size, in bytes.
	pub max_code_size: u32,
	/// The maximum head-data size, in bytes.
	pub max_head_data_size: u32,
	/// Total number of individual messages allowed in the parachain -> relay-chain message queue.
	pub max_upward_queue_count: u32,
	/// Total size of messages allowed in the parachain -> relay-chain message queue before which
	/// no further messages may be added to it. If it exceeds this then the queue may contain only
	/// a single message.
	pub max_upward_queue_size: u32,
	/// The maximum size of an upward message that can be sent by a candidate.
	///
	/// This parameter affects the size upper bound of the `CandidateCommitments`.
	pub max_upward_message_size: u32,
	/// The maximum number of messages that a candidate can contain.
	///
	/// This parameter affects the size upper bound of the `CandidateCommitments`.
	pub max_upward_message_num_per_candidate: u32,
	/// The maximum number of outbound HRMP messages can be sent by a candidate.
	///
	/// This parameter affects the upper bound of size of `CandidateCommitments`.
	pub hrmp_max_message_num_per_candidate: u32,
	/// The minimum frequency at which parachains can update their validation code.
	pub validation_upgrade_frequency: BlockNumber,
	/// The delay, in blocks, before a validation upgrade is applied.
	pub validation_upgrade_delay: BlockNumber,
}

/// Abridged version of `HrmpChannel` (from the `Hrmp` parachains host runtime module) meant to be
/// used by a parachain or PDK such as cumulus.
1106
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
#[cfg_attr(feature = "std", derive(PartialEq))]
pub struct AbridgedHrmpChannel {
	/// The maximum number of messages that can be pending in the channel at once.
	pub max_capacity: u32,
	/// The maximum total size of the messages that can be pending in the channel at once.
	pub max_total_size: u32,
	/// The maximum message size that could be put into the channel.
	pub max_message_size: u32,
	/// The current number of messages pending in the channel.
	/// Invariant: should be less or equal to `max_capacity`.s`.
	pub msg_count: u32,
	/// The total size in bytes of all message payloads in the channel.
	/// Invariant: should be less or equal to `max_total_size`.
	pub total_size: u32,
	/// A head of the Message Queue Chain for this channel. Each link in this chain has a form:
	/// `(prev_head, B, H(M))`, where
	/// - `prev_head`: is the previous value of `mqc_head` or zero if none.
	/// - `B`: is the [relay-chain] block number in which a message was appended
	/// - `H(M)`: is the hash of the message being appended.
	/// This value is initialized to a special value that consists of all zeroes which indicates
	/// that no messages were previously added.
	pub mqc_head: Option<Hash>,
}

1131
/// A possible upgrade restriction that prevents a parachain from performing an upgrade.
1132
#[derive(Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)]
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
pub enum UpgradeRestriction {
	/// There is an upgrade restriction and there are no details about its specifics nor how long
	/// it could last.
	#[codec(index = 0)]
	Present,
}

/// A struct that the relay-chain communicates to a parachain indicating what course of action the
/// parachain should take in the coordinated parachain validation code upgrade process.
///
/// This data type appears in the last step of the upgrade process. After the parachain observes it
/// and reacts to it the upgrade process concludes.
1145
#[derive(Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)]
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
pub enum UpgradeGoAhead {
	/// Abort the upgrade process. There is something wrong with the validation code previously
	/// submitted by the parachain. This variant can also be used to prevent upgrades by the governance
	/// should an emergency emerge.
	///
	/// The expected reaction on this variant is that the parachain will admit this message and
	/// remove all the data about the pending upgrade. Depending on the nature of the problem (to
	/// be examined offchain for now), it can try to send another validation code or just retry later.
	#[codec(index = 0)]
	Abort,
	/// Apply the pending code change. The parablock that is built on a relay-parent that is descendant
	/// of the relay-parent where the parachain observed this signal must use the upgraded validation
	/// code.
	#[codec(index = 1)]
	GoAhead,
}

1163
1164
1165
1166
1167
1168
1169
1170
/// Consensus engine id for polkadot v1 consensus engine.
pub const POLKADOT_ENGINE_ID: runtime_primitives::ConsensusEngineId = *b"POL1";

/// A consensus log item for polkadot validation. To be used with [`POLKADOT_ENGINE_ID`].
#[derive(Decode, Encode, Clone, PartialEq, Eq)]
pub enum ConsensusLog {
	/// A parachain or parathread upgraded its code.
	#[codec(index = 1)]
1171
	ParaUpgradeCode(Id, ValidationCodeHash),
Bernhard Schuster's avatar
Bernhard Schuster committed
1172
	/// A parachain or parathread scheduled a code upgrade.
1173
	#[codec(index = 2)]
1174
	ParaScheduleUpgradeCode(Id, ValidationCodeHash, BlockNumber),
1175
1176
1177
1178
	/// Governance requests to auto-approve every candidate included up to the given block
	/// number in the current chain, inclusive.
	#[codec(index = 3)]
	ForceApprove(BlockNumber),
1179
	/// A signal to revert the block number in the same chain as the
Denis_P's avatar
Denis_P committed
1180
	/// header this digest is part of and all of its descendants.
1181
1182
1183
1184
1185
1186
1187
	///
	/// It is a no-op for a block to contain a revert digest targeting
	/// its own number or a higher number.
	///
	/// In practice, these are issued when on-chain logic has detected an
	/// invalid parachain block within its own chain, due to a dispute.
	#[codec(index = 4)]
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1188
	Revert(BlockNumber),
1189
1190
1191
1192
}

impl ConsensusLog {
	/// Attempt to convert a reference to a generic digest item into a consensus log.
1193
1194
	pub fn from_digest_item(
		digest_item: &runtime_primitives::DigestItem,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1195
	) -> Result<Option<Self>, parity_scale_codec::Error> {
1196
1197
1198
1199
1200
1201
1202
1203
		match digest_item {
			runtime_primitives::DigestItem::Consensus(id, encoded) if id == &POLKADOT_ENGINE_ID =>
				Ok(Some(Self::decode(&mut &encoded[..])?)),
			_ => Ok(None),
		}
	}
}

1204
1205
impl From<ConsensusLog> for runtime_primitives::DigestItem {
	fn from(c: ConsensusLog) -> runtime_primitives::DigestItem {
1206
1207
1208
1209
		Self::Consensus(POLKADOT_ENGINE_ID, c.encode())
	}
}

1210
1211
1212
/// A statement about a candidate, to be used within the dispute resolution process.
///
/// Statements are either in favor of the candidate's validity or against it.
1213
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)]
1214
#[cfg_attr(feature = "std", derive(MallocSizeOf))]
1215
1216
1217
1218
1219
1220
1221
1222
1223
pub enum DisputeStatement {
	/// A valid statement, of the given kind.
	#[codec(index = 0)]
	Valid(ValidDisputeStatementKind),
	/// An invalid statement, of the given kind.
	#[codec(index = 1)]
	Invalid(InvalidDisputeStatementKind),
}

1224
1225
1226
impl DisputeStatement {
	/// Get the payload data for this type of dispute statement.
	pub fn payload_data(&self, candidate_hash: CandidateHash, session: SessionIndex) -> Vec<u8> {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
		match *self {
			DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) =>
				ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload(),
			DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded(
				inclusion_parent,
			)) => CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext {
				session_index: session,
				parent_hash: inclusion_parent,
			}),
			DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) =>
1237
1238
1239
				CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext {
					session_index: session,
					parent_hash: inclusion_parent,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1240
1241
1242
1243
1244
				}),
			DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) =>
				ApprovalVote(candidate_hash).signing_payload(session),
			DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) =>
				ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(),
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
		}
	}

	/// Check the signature on a dispute statement.
	pub fn check_signature(
		&self,
		validator_public: &ValidatorId,
		candidate_hash: CandidateHash,
		session: SessionIndex,
		validator_signature: &ValidatorSignature,
	) -> Result<(), ()> {
		let payload = self.payload_data(candidate_hash, session);

Shawn Tabrizi's avatar
Shawn Tabrizi committed
1258
		if validator_signature.verify(&payload[..], &validator_public) {
1259
1260
1261
1262
1263
			Ok(())
		} else {
			Err(())
		}
	}
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279

	/// Whether the statement indicates validity.
	pub fn indicates_validity(&self) -> bool {
		match *self {
			DisputeStatement::Valid(_) => true,
			DisputeStatement::Invalid(_) => false,
		}
	}

	/// Whether the statement indicates invalidity.
	pub fn indicates_invalidity(&self) -> bool {
		match *self {
			DisputeStatement::Valid(_) => false,
			DisputeStatement::Invalid(_) => true,
		}
	}
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290

	/// Statement is backing statement.
	pub fn is_backing(&self) -> bool {
		match *self {
			Self::Valid(ValidDisputeStatementKind::BackingSeconded(_)) |
			Self::Valid(ValidDisputeStatementKind::BackingValid(_)) => true,
			Self::Valid(ValidDisputeStatementKind::Explicit) |
			Self::Valid(ValidDisputeStatementKind::ApprovalChecking) |
			Self::Invalid(_) => false,
		}
	}
1291
1292
}

1293
/// Different kinds of statements of validity on  a candidate.
1294
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)]
1295
#[cfg_attr(feature = "std", derive(MallocSizeOf))]
1296
1297
1298
1299