v0.rs 34.6 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

20
use sp_std::prelude::*;
21
22
#[cfg(feature = "std")]
use sp_std::convert::TryInto;
23
use sp_std::cmp::Ordering;
24

25
use parity_scale_codec::{Encode, Decode};
26
use bitvec::vec::BitVec;
27
28
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
29
30
#[cfg(feature = "std")]
use parity_util_mem::{MallocSizeOf, MallocSizeOfOps};
31

Gav's avatar
Gav committed
32
#[cfg(feature = "std")]
33
use sp_keystore::{CryptoStore, SyncCryptoStorePtr, Error as KeystoreError};
34
use primitives::RuntimeDebug;
35
use runtime_primitives::traits::{AppVerify, Block as BlockT};
36
use inherents::InherentIdentifier;
37
38
#[cfg(feature = "std")]
use application_crypto::AppKey;
39
use application_crypto::KeyTypeId;
asynchronous rob's avatar
asynchronous rob committed
40
41
42
43

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

45
pub use polkadot_parachain::primitives::{
46
	Id, LOWEST_USER_ID, UpwardMessage, HeadData, BlockData,
47
	ValidationCode,
48
};
49

50
51
52
/// The key type ID for a collator key.
pub const COLLATOR_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"coll");

53
54
55
56
/// An identifier for inherent data that provides new minimally-attested
/// parachain heads.
pub const NEW_HEADS_IDENTIFIER: InherentIdentifier = *b"newheads";

57
58
59
60
61
mod collator_app {
	use application_crypto::{app_crypto, sr25519};
	app_crypto!(sr25519, super::COLLATOR_KEY_TYPE_ID);
}

Gav Wood's avatar
Gav Wood committed
62
/// Identity that collators use.
63
64
pub type CollatorId = collator_app::Public;

65
66
67
68
69
70
71
72
73
74
#[cfg(feature = "std")]
impl MallocSizeOf for CollatorId {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

75
76
77
/// A Parachain collator keypair.
#[cfg(feature = "std")]
pub type CollatorPair = collator_app::Pair;
Gav Wood's avatar
Gav Wood committed
78

79
/// Signature on candidate's block data by a collator.
80
81
pub type CollatorSignature = collator_app::Signature;

82
83
84
85
86
87
88
89
90
91
#[cfg(feature = "std")]
impl MallocSizeOf for CollatorSignature {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

92
93
94
95
96
97
98
/// 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
99
100
101

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

106
107
108
109
110
111
112
113
114
115
#[cfg(feature = "std")]
impl MallocSizeOf for ValidatorId {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

116
/// Index of the validator is used as a lightweight replacement of the `ValidatorId` when appropriate.
117
118
119
120
121
122
123
124
125
126
#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone, Encode, Decode)]
#[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)
	}
}
127

128
129
130
131
application_crypto::with_pair! {
	/// A Parachain validator keypair.
	pub type ValidatorPair = validator_app::Pair;
}
132

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

139
140
141
142
143
144
145
146
147
148
#[cfg(feature = "std")]
impl MallocSizeOf for ValidatorSignature {
	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
		0
	}
	fn constant_size() -> Option<usize> {
		Some(0)
	}
}

149
150
151
152
/// Retriability for a given active para.
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum Retriable {
joe petrowski's avatar
joe petrowski committed
153
	/// Ineligible for retry. This means it's either a parachain that is always scheduled anyway or
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
	/// 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.
173
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
174
175
176
177
178
179
180
181
pub enum Scheduling {
	/// Scheduled every block.
	Always,
	/// Scheduled dynamically (i.e. a parathread).
	Dynamic,
}

/// Information regarding a deployed parachain/thread.
182
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
183
184
185
186
187
188
189
190
191
192
pub struct Info {
	/// Scheduling info.
	pub scheduling: Scheduling,
}

/// An `Info` value for a standard leased parachain.
pub const PARACHAIN_INFO: Info = Info {
	scheduling: Scheduling::Always,
};

joe petrowski's avatar
joe petrowski committed
193
/// Auxilliary for when there's an attempt to swap two parachains/parathreads.
194
195
196
197
198
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
199
	/// code and `head_data` remain equivalent for all parachains/threads, however other properties
200
201
202
203
204
205
206
207
	/// 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
208
209
210
211
212
impl SwapAux for () {
	fn ensure_can_swap(_: Id, _: Id) -> Result<(), &'static str> { Err("Swapping disabled") }
	fn on_swap(_: Id, _: Id) -> Result<(), &'static str> { Err("Swapping disabled") }
}

213
/// Identifier for a chain, either one of a number of parachains or the relay chain.
214
#[derive(Copy, Clone, PartialEq, Encode, Decode)]
215
216
217
218
219
220
221
222
223
#[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.
224
#[derive(Clone, PartialEq, Encode, Decode)]
225
226
227
228
229
230
#[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
231
/// Extra data that is needed along with the other fields in a `CandidateReceipt`
232
233
234
235
236
/// to fully validate the candidate.
///
/// These are global parameters that apply to all parachain candidates in a block.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Default))]
237
pub struct GlobalValidationData<N = BlockNumber> {
238
239
240
241
	/// 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,
242
	/// The relay-chain block number this is in the context of.
asynchronous rob's avatar
asynchronous rob committed
243
	pub block_number: N,
244
245
}

joe petrowski's avatar
joe petrowski committed
246
/// Extra data that is needed along with the other fields in a `CandidateReceipt`
247
/// to fully validate the candidate. These fields are parachain-specific.
248
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
249
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
250
pub struct LocalValidationData<N = BlockNumber> {
251
252
253
254
	/// The parent head-data.
	pub parent_head: HeadData,
	/// The balance of the parachain at the moment of validation.
	pub balance: Balance,
255
256
257
258
259
260
261
262
263
264
265
	/// 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
266
	pub code_upgrade_allowed: Option<N>,
267
268
269
270
271
}

/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
272
pub struct CandidateCommitments<H = Hash> {
joe petrowski's avatar
joe petrowski committed
273
	/// Fees paid from the chain to the relay chain validators.
274
275
276
277
	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
278
	pub erasure_root: H,
279
	/// New validation code.
280
	pub new_validation_code: Option<ValidationCode>,
281
282
283
284
	/// 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,
285
286
287
}

/// Get a collator signature payload on a relay-parent, block-data combo.
asynchronous rob's avatar
asynchronous rob committed
288
289
pub fn collator_signature_payload<H: AsRef<[u8]>>(
	relay_parent: &H,
290
	parachain_index: &Id,
asynchronous rob's avatar
asynchronous rob committed
291
	pov_block_hash: &H,
292
293
294
295
296
297
298
299
300
301
302
) -> [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
303
304
fn check_collator_signature<H: AsRef<[u8]>>(
	relay_parent: &H,
305
	parachain_index: &Id,
asynchronous rob's avatar
asynchronous rob committed
306
	pov_block_hash: &H,
307
308
309
310
311
312
313
314
315
316
317
318
319
320
	collator: &CollatorId,
	signature: &CollatorSignature,
) -> Result<(),()> {
	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.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
321
pub struct CandidateReceipt<H = Hash, N = BlockNumber> {
322
323
	/// The ID of the parachain this is a candidate for.
	pub parachain_index: Id,
324
325
	/// The hash of the relay-chain block this should be executed in
	/// the context of.
asynchronous rob's avatar
asynchronous rob committed
326
	pub relay_parent: H,
327
328
	/// The head-data
	pub head_data: HeadData,
329
330
331
332
	/// The collator's relay-chain account ID
	pub collator: CollatorId,
	/// Signature on blake2-256 of the block data by collator.
	pub signature: CollatorSignature,
333
	/// The hash of the PoV-block.
asynchronous rob's avatar
asynchronous rob committed
334
	pub pov_block_hash: H,
335
	/// The global validation schedule.
336
	pub global_validation: GlobalValidationData<N>,
337
	/// The local validation data.
asynchronous rob's avatar
asynchronous rob committed
338
	pub local_validation: LocalValidationData<N>,
339
	/// Commitments made as a result of validation.
asynchronous rob's avatar
asynchronous rob committed
340
	pub commitments: CandidateCommitments<H>,
341
342
}

asynchronous rob's avatar
asynchronous rob committed
343
impl<H: AsRef<[u8]>, N> CandidateReceipt<H, N> {
344
345
346
347
348
349
350
351
352
353
354
355
356
	/// 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
357
	pub fn abridge(self) -> (AbridgedCandidateReceipt<H>, OmittedValidationData<N>) {
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
		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,
		};

		let omitted = OmittedValidationData {
			global_validation,
			local_validation,
		};

		(abridged, omitted)
386
387
388
	}
}

389
390
391
392
393
impl PartialOrd for CandidateReceipt {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}
394

395
396
397
398
399
400
impl Ord for CandidateReceipt {
	fn cmp(&self, other: &Self) -> Ordering {
		// TODO: compare signatures or something more sane
		// https://github.com/paritytech/polkadot/issues/222
		self.parachain_index.cmp(&other.parachain_index)
			.then_with(|| self.head_data.cmp(&other.head_data))
401
402
403
	}
}

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

/// 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.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Default))]
asynchronous rob's avatar
asynchronous rob committed
422
pub struct AbridgedCandidateReceipt<H = Hash> {
Gav's avatar
Gav committed
423
424
	/// The ID of the parachain this is a candidate for.
	pub parachain_index: Id,
425
426
427
428
	/// 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
429
	pub relay_parent: H,
430
431
	/// The head-data
	pub head_data: HeadData,
432
	/// The collator's relay-chain account ID
Gav Wood's avatar
Gav Wood committed
433
	pub collator: CollatorId,
434
	/// Signature on blake2-256 of the block data by collator.
Gav Wood's avatar
Gav Wood committed
435
	pub signature: CollatorSignature,
436
	/// The hash of the pov-block.
asynchronous rob's avatar
asynchronous rob committed
437
	pub pov_block_hash: H,
438
	/// Commitments made as a result of validation.
asynchronous rob's avatar
asynchronous rob committed
439
	pub commitments: CandidateCommitments<H>,
Gav's avatar
Gav committed
440
441
}

442
443
444
445
446
447
448
449
450
/// A candidate-receipt with commitments directly included.
pub struct CommitedCandidateReceipt<H = Hash> {
	/// The descriptor of the candidae.
	pub descriptor: CandidateDescriptor,

	/// The commitments of the candidate receipt.
	pub commitments: CandidateCommitments<H>
}

asynchronous rob's avatar
asynchronous rob committed
451
452
453
454
455
456
457
458
459
460
461
462
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,
		)
	}

463
464
465
466
	/// 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
467
	/// receipt is committed to in the abridged receipt; this receipt references
468
469
	/// the relay-chain block in which context it should be executed, which implies
	/// any blockchain state that must be referenced.
470
	pub fn hash(&self) -> Hash {
Gav Wood's avatar
Gav Wood committed
471
		BlakeTwo256::hash_of(self)
472
	}
asynchronous rob's avatar
asynchronous rob committed
473
}
474

asynchronous rob's avatar
asynchronous rob committed
475
impl AbridgedCandidateReceipt {
476
477
478
479
480
481
482
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
508
509
510
511
512
513
514
515
516
517
	/// 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;

		let OmittedValidationData {
			global_validation,
			local_validation,
		} = omitted;

		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;
518

519
520
521
522
523
524
525
		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,
526
527
		}
	}
528
529
530
531
532
533
534
535
536
537
538

	/// 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(),
		}
	}
539
540
}

541
impl PartialOrd for AbridgedCandidateReceipt {
542
543
544
545
546
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

547
impl Ord for AbridgedCandidateReceipt {
548
549
	fn cmp(&self, other: &Self) -> Ordering {
		// TODO: compare signatures or something more sane
550
		// https://github.com/paritytech/polkadot/issues/222
551
552
553
554
555
		self.parachain_index.cmp(&other.parachain_index)
			.then_with(|| self.head_data.cmp(&other.head_data))
	}
}

556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/// A unique descriptor of the candidate receipt, in a lightweight format.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[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:
	/// The para ID, the relay parent, and the pov_hash.
	pub signature: CollatorSignature,
	/// The hash of the pov-block.
	pub pov_hash: H,
}

576
577
578
579
580
581
582
583
584
585
586
587
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
621
622
623
624
625
626
627
628
629
/// A collation sent by a collator.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[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,
	/// blake2-256 Hash of the pov-block
	pub pov_block_hash: Hash,
}

impl CollationInfo {
	/// Check integrity vs. a pov-block.
	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,
		}
	}
}

630
/// A full collation.
631
632
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Debug, Encode, Decode))]
633
634
pub struct Collation {
	/// Candidate receipt itself.
635
	pub info: CollationInfo,
636
637
	/// A proof-of-validation for the receipt.
	pub pov: PoVBlock,
638
639
}

640
/// A Proof-of-Validation block.
Gav's avatar
Gav committed
641
#[derive(PartialEq, Eq, Clone)]
642
643
644
645
646
647
#[cfg_attr(feature = "std", derive(Debug, Encode, Decode))]
pub struct PoVBlock {
	/// Block data.
	pub block_data: BlockData,
}

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

668
/// A chunk of erasure-encoded block data.
669
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
670
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, Hash))]
671
672
673
674
pub struct ErasureChunk {
	/// The erasure-encoded chunk of data belonging to the candidate block.
	pub chunk: Vec<u8>,
	/// The index of this erasure-encoded chunk of data.
675
	pub index: ValidatorIndex,
676
677
678
679
	/// Proof for this chunk's branch in the Merkle tree.
	pub proof: Vec<Vec<u8>>,
}

680
681
const BACKING_STATEMENT_MAGIC: [u8; 4] = *b"BKNG";

joe petrowski's avatar
joe petrowski committed
682
683
/// Statements that can be made about parachain candidates. These are the
/// actual values that are signed.
684
#[derive(Clone, PartialEq, Eq)]
685
#[cfg_attr(feature = "std", derive(Debug, Hash))]
686
pub enum CompactStatement {
687
	/// Proposal of a parachain candidate.
688
	Seconded(CandidateHash),
689
	/// State that a parachain candidate is valid.
690
	Valid(CandidateHash),
691
692
693
694
695
696
697
698
699
}

// Inner helper for codec on `CompactStatement`.
#[derive(Encode, Decode)]
enum CompactStatementInner {
	#[codec(index = 1)]
	Seconded(CandidateHash),
	#[codec(index = 2)]
	Valid(CandidateHash),
700
}
701

702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
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 {
	fn decode<I: parity_scale_codec::Input>(input: &mut I) -> Result<Self, parity_scale_codec::Error> {
		let maybe_magic = <[u8; 4]>::decode(input)?;
		if maybe_magic != BACKING_STATEMENT_MAGIC {
			return Err(parity_scale_codec::Error::from("invalid magic string"));
		}

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

737
738
impl CompactStatement {
	/// Get the underlying candidate hash this references.
739
	pub fn candidate_hash(&self) -> &CandidateHash {
740
		match *self {
741
			CompactStatement::Seconded(ref h) | CompactStatement::Valid(ref h) => h,
742
743
744
745
		}
	}
}

746
747
/// A signed compact statement, suitable to be sent to the chain.
pub type SignedStatement = Signed<CompactStatement>;
748

749
750
/// An either implicit or explicit attestation to the validity of a parachain
/// candidate.
751
#[derive(Clone, Eq, PartialEq, Decode, Encode, RuntimeDebug)]
752
pub enum ValidityAttestation {
joe petrowski's avatar
joe petrowski committed
753
	/// Implicit validity attestation by issuing.
754
	/// This corresponds to issuance of a `Candidate` statement.
755
	#[codec(index = 1)]
756
	Implicit(ValidatorSignature),
757
758
	/// An explicit attestation. This corresponds to issuance of a
	/// `Valid` statement.
759
	#[codec(index = 2)]
760
	Explicit(ValidatorSignature),
761
762
}

asynchronous rob's avatar
asynchronous rob committed
763
764
765
766
767
768
769
770
771
772
773
774
775
impl ValidityAttestation {
	/// 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,
776
		candidate_hash: CandidateHash,
asynchronous rob's avatar
asynchronous rob committed
777
778
779
780
		signing_context: &SigningContext<H>,
	) -> Vec<u8> {
		match *self {
			ValidityAttestation::Implicit(_) => (
781
				CompactStatement::Seconded(candidate_hash),
asynchronous rob's avatar
asynchronous rob committed
782
783
784
				signing_context,
			).encode(),
			ValidityAttestation::Explicit(_) => (
785
				CompactStatement::Valid(candidate_hash),
asynchronous rob's avatar
asynchronous rob committed
786
787
788
789
790
791
				signing_context,
			).encode(),
		}
	}
}

792
793
/// 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
794
pub struct SigningContext<H = Hash> {
795
796
797
	/// Current session index.
	pub session_index: sp_staking::SessionIndex,
	/// Hash of the parent.
asynchronous rob's avatar
asynchronous rob committed
798
	pub parent_hash: H,
799
800
}

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

impl AttestedCandidate {
	/// Get the candidate.
815
	pub fn candidate(&self) -> &AbridgedCandidateReceipt {
816
817
818
819
820
821
822
823
824
		&self.candidate
	}

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

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

impl FeeSchedule {
	/// Compute the fee for a message of given size.
837
	pub fn compute_message_fee(&self, n_bytes: usize) -> Balance {
838
		use sp_std::mem;
839
840
841
842
843
844
845
		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))
	}
}

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

/// Runtime ID module.
pub mod id {
875
	use sp_version::ApiId;
876
877
878
879

	/// Parachain host runtime API id.
	pub const PARACHAIN_HOST: ApiId = *b"parahost";
}
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
/// This helper trait ensures that we can encode Statement as CompactStatement,
/// and anything as itself.
///
/// This resembles `parity_scale_codec::EncodeLike`, but it's distinct:
/// EncodeLike is a marker trait which asserts at the typesystem level that
/// one type's encoding is a valid encoding for another type. It doesn't
/// perform any type conversion when encoding.
///
/// This trait, on the other hand, provides a method which can be used to
/// simultaneously convert and encode one type as another.
pub trait EncodeAs<T> {
	/// Convert Self into T, then encode T.
	///
	/// This is useful when T is a subset of Self, reducing encoding costs;
	/// its signature also means that we do not need to clone Self in order
	/// to retain ownership, as we would if we were to do
	/// `self.clone().into().encode()`.
	fn encode_as(&self) -> Vec<u8>;
}

impl<T: Encode> EncodeAs<T> for T {
	fn encode_as(&self) -> Vec<u8> {
		self.encode()
	}
}

/// A signed type which encapsulates the common desire to sign some data and validate a signature.
///
/// Note that the internal fields are not public; they are all accessable by immutable getters.
/// This reduces the chance that they are accidentally mutated, invalidating the signature.
Fedor Sakharov's avatar
Fedor Sakharov committed
911
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
pub struct Signed<Payload, RealPayload = Payload> {
	/// The payload is part of the signed data. The rest is the signing context,
	/// which is known both at signing and at validation.
	payload: Payload,
	/// The index of the validator signing this statement.
	validator_index: ValidatorIndex,
	/// The signature by the validator of the signed payload.
	signature: ValidatorSignature,
	/// This ensures the real payload is tracked at the typesystem level.
	real_payload: sp_std::marker::PhantomData<RealPayload>,
}

// We can't bound this on `Payload: Into<RealPayload>` beacuse that conversion consumes
// the payload, and we don't want that. We can't bound it on `Payload: AsRef<RealPayload>`
// because there's no blanket impl of `AsRef<T> for T`. In the end, we just invent our
// own trait which does what we need: EncodeAs.
impl<Payload: EncodeAs<RealPayload>, RealPayload: Encode> Signed<Payload, RealPayload> {
	fn payload_data<H: Encode>(payload: &Payload, context: &SigningContext<H>) -> Vec<u8> {
		// equivalent to (real_payload, context).encode()
		let mut out = payload.encode_as();
		out.extend(context.encode());
		out
	}

936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
	/// Used to create a `Signed` from already existing parts.
	#[cfg(feature = "std")]
	pub fn new<H: Encode>(
		payload: Payload,
		validator_index: ValidatorIndex,
		signature: ValidatorSignature,
		context: &SigningContext<H>,
		key: &ValidatorId,
	) -> Option<Self> {
		let s = Self {
			payload,
			validator_index,
			signature,
			real_payload: std::marker::PhantomData,
		};

		s.check_signature(context, key).ok()?;

		Some(s)
	}

957
958
	/// Sign this payload with the given context and key, storing the validator index.
	#[cfg(feature = "std")]
959
960
	pub async fn sign<H: Encode>(
		keystore: &SyncCryptoStorePtr,
961
962
963
		payload: Payload,
		context: &SigningContext<H>,
		validator_index: ValidatorIndex,
964
		key: &ValidatorId,
965
	) -> Result<Option<Self>, KeystoreError> {
966
		let data = Self::payload_data(&payload, context);
967
		let signature = CryptoStore::sign_with(
968
969
970
971
			&**keystore,
			ValidatorId::ID,
			&key.into(),
			&data,
972
973
974
975
976
977
978
979
		).await?;

		let signature = match signature {
			Some(sig) => sig.try_into().map_err(|_| KeystoreError::KeyNotSupported(ValidatorId::ID))?,
			None => return Ok(None),
		};

		Ok(Some(Self {
980
981
982
983
			payload,
			validator_index,
			signature,
			real_payload: std::marker::PhantomData,
984
		}))
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
	}

	/// Validate the payload given the context and public key.
	pub fn check_signature<H: Encode>(&self, context: &SigningContext<H>, key: &ValidatorId) -> Result<(), ()> {
		let data = Self::payload_data(&self.payload, context);
		if self.signature.verify(data.as_slice(), key) { Ok(()) } else { Err(()) }
	}

	/// Immutably access the payload.
	#[inline]
	pub fn payload(&self) -> &Payload {
		&self.payload
	}

	/// Immutably access the validator index.
	#[inline]
For faster browsing, not all history is shown. View entire blame