registrar.rs 52.1 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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/>.

//! Module to handle which parachains/parathreads (collectively referred to as "paras") are
//! registered and which are scheduled. Doesn't manage any of the actual execution/validation logic
//! which is left to `parachains.rs`.

21
use sp_std::{prelude::*, result};
22
#[cfg(any(feature = "std", test))]
23
use sp_std::marker::PhantomData;
24
25
use codec::{Encode, Decode};

26
use sp_runtime::{
27
	transaction_validity::{TransactionValidityError, ValidTransaction, TransactionValidity},
28
	traits::{Hash as HashT, SignedExtension, DispatchInfoOf},
29
30
};

31
use frame_support::{
32
	decl_storage, decl_module, decl_event, decl_error, ensure,
33
	dispatch::{DispatchResult, IsSubType}, traits::{Get, Currency, ReservableCurrency},
34
	weights::{DispatchClass, Weight},
35
36
37
38
};
use system::{self, ensure_root, ensure_signed};
use primitives::parachain::{
	Id as ParaId, CollatorId, Scheduling, LOWEST_USER_ID, SwapAux, Info as ParaInfo, ActiveParas,
39
	Retriable, ValidationCode, HeadData,
40
41
};
use crate::parachains;
42
use sp_runtime::transaction_validity::InvalidTransaction;
43
44
45
46
47
48

/// Parachain registration API.
pub trait Registrar<AccountId> {
	/// Create a new unique parachain identity for later registration.
	fn new_id() -> ParaId;

49
50
51
52
53
54
	/// Checks whether the given initial head data size falls within the limit.
	fn head_data_size_allowed(head_data_size: u32) -> bool;

	/// Checks whether the given validation code falls within the limit.
	fn code_size_allowed(code_size: u32) -> bool;

55
56
57
	/// Fetches metadata for a para by ID, if any.
	fn para_info(id: ParaId) -> Option<ParaInfo>;

58
59
	/// Register a parachain with given `code` and `initial_head_data`. `id` must not yet be registered or it will
	/// result in a error.
60
61
62
63
64
	///
	/// This does not enforce any code size or initial head data limits, as these
	/// are governable and parameters for parachain initialization are often
	/// determined long ahead-of-time. Not checking these values ensures that changes to limits
	/// do not invalidate in-progress auction winners.
65
66
67
	fn register_para(
		id: ParaId,
		info: ParaInfo,
68
69
		code: ValidationCode,
		initial_head_data: HeadData,
70
	) -> DispatchResult;
71
72

	/// Deregister a parachain with given `id`. If `id` is not currently registered, an error is returned.
73
	fn deregister_para(id: ParaId) -> DispatchResult;
74
75
76
77
78
79
80
}

impl<T: Trait> Registrar<T::AccountId> for Module<T> {
	fn new_id() -> ParaId {
		<NextFreeId>::mutate(|n| { let r = *n; *n = ParaId::from(u32::from(*n) + 1); r })
	}

81
82
83
84
85
86
87
88
	fn head_data_size_allowed(head_data_size: u32) -> bool {
		head_data_size <= <T as parachains::Trait>::MaxHeadDataSize::get()
	}

	fn code_size_allowed(code_size: u32) -> bool {
		code_size <= <T as parachains::Trait>::MaxCodeSize::get()
	}

89
90
91
92
	fn para_info(id: ParaId) -> Option<ParaInfo> {
		Self::paras(&id)
	}

93
94
95
	fn register_para(
		id: ParaId,
		info: ParaInfo,
96
97
		code: ValidationCode,
		initial_head_data: HeadData,
98
	) -> DispatchResult {
99
		ensure!(!Paras::contains_key(id), Error::<T>::ParaAlreadyExists);
100
101
102
		if let Scheduling::Always = info.scheduling {
			Parachains::mutate(|parachains|
				match parachains.binary_search(&id) {
103
					Ok(_) => Err(Error::<T>::ParaAlreadyExists),
104
105
106
107
108
109
110
111
112
113
114
115
					Err(idx) => {
						parachains.insert(idx, id);
						Ok(())
					}
				}
			)?;
		}
		<parachains::Module<T>>::initialize_para(id, code, initial_head_data);
		Paras::insert(id, info);
		Ok(())
	}

116
	fn deregister_para(id: ParaId) -> DispatchResult {
117
		let info = Paras::take(id).ok_or(Error::<T>::InvalidChainId)?;
118
119
120
121
		if let Scheduling::Always = info.scheduling {
			Parachains::mutate(|parachains|
				parachains.binary_search(&id)
					.map(|index| parachains.remove(index))
122
					.map_err(|_| Error::<T>::InvalidChainId)
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
			)?;
		}
		<parachains::Module<T>>::cleanup_para(id);
		Paras::remove(id);
		Ok(())
	}
}

type BalanceOf<T> =
	<<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;

pub trait Trait: parachains::Trait {
	/// The overarching event type.
	type Event: From<Event> + Into<<Self as system::Trait>::Event>;

	/// The aggregated origin type must support the parachains origin. We require that we can
	/// infallibly convert between this origin and the system origin, but in reality, they're the
	/// same type, we just can't express that to the Rust type system without writing a `where`
	/// clause everywhere.
	type Origin: From<<Self as system::Trait>::Origin>
		+ Into<result::Result<parachains::Origin, <Self as Trait>::Origin>>;

	/// The system's currency for parathread payment.
	type Currency: ReservableCurrency<Self::AccountId>;

	/// The deposit to be paid to run a parathread.
	type ParathreadDeposit: Get<BalanceOf<Self>>;

	/// Handler for when two ParaIds are swapped.
	type SwapAux: SwapAux;

	/// The number of items in the parathread queue, aka the number of blocks in advance to schedule
	/// parachain execution.
	type QueueSize: Get<usize>;

	/// The number of rotations that you will have as grace if you miss a block.
	type MaxRetries: Get<u32>;
}

decl_storage! {
	trait Store for Module<T: Trait> as Registrar {
		// Vector of all parachain IDs, in ascending order.
		Parachains: Vec<ParaId>;

		/// The number of threads to schedule per block.
		ThreadCount: u32;

		/// An array of the queue of set of threads scheduled for the coming blocks; ordered by
		/// ascending para ID. There can be no duplicates of para ID in each list item.
		SelectedThreads: Vec<Vec<(ParaId, CollatorId)>>;

		/// Parathreads/chains scheduled for execution this block. If the collator ID is set, then
		/// a particular collator has already been chosen for the next block, and no other collator
		/// may provide the block. In this case we allow the possibility of the combination being
		/// retried in a later block, expressed by `Retriable`.
		///
		/// Ordered by ParaId.
		Active: Vec<(ParaId, Option<(CollatorId, Retriable)>)>;

		/// The next unused ParaId value. Start this high in order to keep low numbers for
		/// system-level chains.
		NextFreeId: ParaId = LOWEST_USER_ID;

		/// Pending swap operations.
187
		PendingSwap: map hasher(twox_64_concat) ParaId => Option<ParaId>;
188
189

		/// Map of all registered parathreads/chains.
190
		Paras get(fn paras): map hasher(twox_64_concat) ParaId => Option<ParaInfo>;
191
192

		/// The current queue for parathreads that should be retried.
193
		RetryQueue get(fn retry_queue): Vec<Vec<(ParaId, CollatorId)>>;
194
195

		/// Users who have paid a parathread's deposit
196
		Debtors: map hasher(twox_64_concat) ParaId => T::AccountId;
197
198
	}
	add_extra_genesis {
199
		config(parachains): Vec<(ParaId, ValidationCode, HeadData)>;
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
		config(_phdata): PhantomData<T>;
		build(build::<T>);
	}
}

#[cfg(feature = "std")]
fn build<T: Trait>(config: &GenesisConfig<T>) {
	let mut p = config.parachains.clone();
	p.sort_unstable_by_key(|&(ref id, _, _)| *id);
	p.dedup_by_key(|&mut (ref id, _, _)| *id);

	let only_ids: Vec<ParaId> = p.iter().map(|&(ref id, _, _)| id).cloned().collect();

	Parachains::put(&only_ids);

	for (id, code, genesis) in p {
		Paras::insert(id, &primitives::parachain::PARACHAIN_INFO);
		// no ingress -- a chain cannot be routed to until it is live.
		<parachains::Code>::insert(&id, &code);
		<parachains::Heads>::insert(&id, &genesis);
		// Save initial parachains in registrar
		Paras::insert(id, ParaInfo { scheduling: Scheduling::Always })
	}
}

/// Swap the existence of two items, provided by value, within an ordered list.
///
/// If neither item exists, or if both items exist this will do nothing. If exactly one of the
/// items exists, then it will be removed and the other inserted.
pub fn swap_ordered_existence<T: PartialOrd + Ord + Copy>(ids: &mut [T], one: T, other: T) {
	let maybe_one_pos = ids.binary_search(&one);
	let maybe_other_pos = ids.binary_search(&other);
	match (maybe_one_pos, maybe_other_pos) {
		(Ok(one_pos), Err(_)) => ids[one_pos] = other,
		(Err(_), Ok(other_pos)) => ids[other_pos] = one,
		_ => return,
	};
	ids.sort();
}

240
241
242
243
244
245
246
247
decl_error! {
	pub enum Error for Module<T: Trait> {
		/// Parachain already exists.
		ParaAlreadyExists,
		/// Invalid parachain ID.
		InvalidChainId,
		/// Invalid parathread ID.
		InvalidThreadId,
248
249
250
251
		/// Invalid para code size.
		CodeTooLarge,
		/// Invalid para head data size.
		HeadDataTooLarge,
252
253
254
	}
}

255
256
257
decl_module! {
	/// Parachains module.
	pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin {
258
259
		type Error = Error<T>;

260
261
		fn deposit_event() = default;

262
		/// Register a parachain with given code. Must be called by root.
263
		/// Fails if given ID is already used.
264
265
266
		///
		/// Unlike the `Registrar` trait function of the same name, this
		/// checks the code and head data against size limits.
267
		#[weight = (5_000_000_000, DispatchClass::Operational)]
268
269
270
		pub fn register_para(origin,
			#[compact] id: ParaId,
			info: ParaInfo,
271
272
			code: ValidationCode,
			initial_head_data: HeadData,
273
		) -> DispatchResult {
274
			ensure_root(origin)?;
275
276

			ensure!(
277
				<Self as Registrar<T::AccountId>>::code_size_allowed(code.0.len() as _),
278
279
280
281
282
				Error::<T>::CodeTooLarge,
			);

			ensure!(
				<Self as Registrar<T::AccountId>>::head_data_size_allowed(
283
					initial_head_data.0.len() as _
284
285
286
				),
				Error::<T>::HeadDataTooLarge,
			);
287
288
289
290
291
			<Self as Registrar<T::AccountId>>::
				register_para(id, info, code, initial_head_data)
		}

		/// Deregister a parachain with given id
292
		#[weight = (10_000_000, DispatchClass::Operational)]
293
		pub fn deregister_para(origin, #[compact] id: ParaId) -> DispatchResult {
294
295
296
297
298
299
300
301
302
			ensure_root(origin)?;
			<Self as Registrar<T::AccountId>>::deregister_para(id)
		}

		/// Reset the number of parathreads that can pay to be scheduled in a single block.
		///
		/// - `count`: The number of parathreads.
		///
		/// Must be called from Root origin.
303
		#[weight = 0]
304
305
306
307
308
309
310
311
312
		fn set_thread_count(origin, count: u32) {
			ensure_root(origin)?;
			ThreadCount::put(count);
		}

		/// Register a parathread for immediate use.
		///
		/// Must be sent from a Signed origin that is able to have ParathreadDeposit reserved.
		/// `code` and `initial_head_data` are used to initialize the parathread's state.
313
314
315
316
		///
		/// Unlike `register_para`, this function does check that the maximum code size
		/// and head data size are respected, as parathread registration is an atomic
		/// action.
317
		#[weight = 0]
318
		fn register_parathread(origin,
319
320
			code: ValidationCode,
			initial_head_data: HeadData,
321
322
323
		) {
			let who = ensure_signed(origin)?;

324
			<T as Trait>::Currency::reserve(&who, T::ParathreadDeposit::get())?;
325
326
327
328

			let info = ParaInfo {
				scheduling: Scheduling::Dynamic,
			};
329
330

			ensure!(
331
				<Self as Registrar<T::AccountId>>::code_size_allowed(code.0.len() as _),
332
333
334
335
336
				Error::<T>::CodeTooLarge,
			);

			ensure!(
				<Self as Registrar<T::AccountId>>::head_data_size_allowed(
337
					initial_head_data.0.len() as _
338
339
340
341
				),
				Error::<T>::HeadDataTooLarge,
			);

342
343
344
345
346
347
348
349
350
351
352
353
			let id = <Self as Registrar<T::AccountId>>::new_id();

			let _ = <Self as Registrar<T::AccountId>>::
				register_para(id, info, code, initial_head_data);

			<Debtors<T>>::insert(id, who);

			Self::deposit_event(Event::ParathreadRegistered(id));
		}

		/// Place a bid for a parathread to be progressed in the next block.
		///
Leo Arias's avatar
Leo Arias committed
354
		/// This is a kind of special transaction that should be heavily prioritized in the
355
356
		/// transaction pool according to the `value`; only `ThreadCount` of them may be presented
		/// in any single block.
357
		#[weight = 0]
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
		fn select_parathread(origin,
			#[compact] _id: ParaId,
			_collator: CollatorId,
			_head_hash: T::Hash,
		) {
			ensure_signed(origin)?;
			// Everything else is checked for in the transaction `SignedExtension`.
		}

		/// Deregister a parathread and retrieve the deposit.
		///
		/// Must be sent from a `Parachain` origin which is currently a parathread.
		///
		/// Ensure that before calling this that any funds you want emptied from the parathread's
		/// account is moved out; after this it will be impossible to retrieve them (without
		/// governance intervention).
374
		#[weight = 0]
375
376
377
		fn deregister_parathread(origin) {
			let id = parachains::ensure_parachain(<T as Trait>::Origin::from(origin))?;

378
379
			let info = Paras::get(id).ok_or(Error::<T>::InvalidChainId)?;
			if let Scheduling::Dynamic = info.scheduling {} else { Err(Error::<T>::InvalidThreadId)? }
380
381
382
383
384

			<Self as Registrar<T::AccountId>>::deregister_para(id)?;
			Self::force_unschedule(|i| i == id);

			let debtor = <Debtors<T>>::take(id);
385
			let _ = <T as Trait>::Currency::unreserve(&debtor, T::ParathreadDeposit::get());
386
387
388
389
390
391
392
393
394
395
396
397

			Self::deposit_event(Event::ParathreadRegistered(id));
		}

		/// Swap a parachain with another parachain or parathread. The origin must be a `Parachain`.
		/// The swap will happen only if there is already an opposite swap pending. If there is not,
		/// the swap will be stored in the pending swaps map, ready for a later confirmatory swap.
		///
		/// The `ParaId`s remain mapped to the same head data and code so external code can rely on
		/// `ParaId` to be a long-term identifier of a notional "parachain". However, their
		/// scheduling info (i.e. whether they're a parathread or parachain), auction information
		/// and the auction deposit are switched.
398
		#[weight = 0]
399
400
401
402
403
404
405
406
407
408
409
410
411
		fn swap(origin, #[compact] other: ParaId) {
			let id = parachains::ensure_parachain(<T as Trait>::Origin::from(origin))?;

			if PendingSwap::get(other) == Some(id) {
				// actually do the swap.
				T::SwapAux::ensure_can_swap(id, other)?;

				// Remove intention to swap.
				PendingSwap::remove(other);
				Self::force_unschedule(|i| i == id || i == other);
				Parachains::mutate(|ids| swap_ordered_existence(ids, id, other));
				Paras::mutate(id, |i|
					Paras::mutate(other, |j|
412
						sp_std::mem::swap(i, j)
413
414
415
416
417
					)
				);

				<Debtors<T>>::mutate(id, |i|
					<Debtors<T>>::mutate(other, |j|
418
						sp_std::mem::swap(i, j)
419
420
421
422
423
424
425
426
427
					)
				);
				let _ = T::SwapAux::on_swap(id, other);
			} else {
				PendingSwap::insert(id, other);
			}
		}

		/// Block initializer. Clears SelectedThreads and constructs/replaces Active.
428
		fn on_initialize() -> Weight {
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
			let next_up = SelectedThreads::mutate(|t| {
				let r = if t.len() >= T::QueueSize::get() {
					// Take the first set of parathreads in queue
					t.remove(0)
				} else {
					vec![]
				};
				while t.len() < T::QueueSize::get() {
					t.push(vec![]);
				}
				r
			});
			// mutable so that we can replace with `None` if parathread appears in new schedule.
			let mut retrying = Self::take_next_retry();
			if let Some(((para, _), _)) = retrying {
				// this isn't really ideal: better would be if there were an earlier pass that set
				// retrying to the first item in the Missed queue that isn't already scheduled, but
				// this is potentially O(m*n) in terms of missed queue size and parathread pool size.
				if next_up.iter().any(|x| x.0 == para) {
					retrying = None
				}
			}

			let mut paras = Parachains::get().into_iter()
				.map(|id| (id, None))
				.chain(next_up.into_iter()
					.map(|(para, collator)|
						(para, Some((collator, Retriable::WithRetries(0))))
					)
				).chain(retrying.into_iter()
					.map(|((para, collator), retries)|
						(para, Some((collator, Retriable::WithRetries(retries + 1))))
					)
				).collect::<Vec<_>>();
			// for Rust's timsort algorithm, sorting a concatenation of two sorted ranges is near
			// O(N).
			paras.sort_by_key(|&(ref id, _)| *id);

			Active::put(paras);
468

469
			0
470
471
472
473
474
475
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
		}

		fn on_finalize() {
			// a block without this will panic, but let's not panic here.
			if let Some(proceeded_vec) = parachains::DidUpdate::get() {
				// Active is sorted and DidUpdate is a sorted subset of its elements.
				//
				// We just go through the contents of active and find any items that don't appear in
				// DidUpdate *and* which are enabled for retry.
				let mut proceeded = proceeded_vec.into_iter();
				let mut i = proceeded.next();
				for sched in Active::get().into_iter() {
					match i {
						// Scheduled parachain proceeded properly. Move onto next item.
						Some(para) if para == sched.0 => i = proceeded.next(),
						// Scheduled `sched` missed their block.
						// Queue for retry if it's allowed.
						_ => if let (i, Some((c, Retriable::WithRetries(n)))) = sched {
							Self::retry_later((i, c), n)
						},
					}
				}
			}
		}
	}
}

decl_event!{
	pub enum Event {
		/// A parathread was registered; its new ID is supplied.
		ParathreadRegistered(ParaId),

		/// The parathread of the supplied ID was de-registered.
		ParathreadDeregistered(ParaId),
	}
}

impl<T: Trait> Module<T> {
508
	/// Ensures that the given `ParaId` corresponds to a registered parathread, and returns a descriptor if so.
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
	pub fn ensure_thread_id(id: ParaId) -> Option<ParaInfo> {
		Paras::get(id).and_then(|info| if let Scheduling::Dynamic = info.scheduling {
			Some(info)
		} else {
			None
		})
	}

	fn retry_later(sched: (ParaId, CollatorId), retries: u32) {
		if retries < T::MaxRetries::get() {
			RetryQueue::mutate(|q| {
				q.resize(T::MaxRetries::get() as usize, vec![]);
				q[retries as usize].push(sched);
			});
		}
	}

	fn take_next_retry() -> Option<((ParaId, CollatorId), u32)> {
		RetryQueue::mutate(|q| {
			for (i, q) in q.iter_mut().enumerate() {
				if !q.is_empty() {
					return Some((q.remove(0), i as u32));
				}
			}
			None
		})
	}

	/// Forcibly remove the threads matching `m` from all current and future scheduling.
	fn force_unschedule(m: impl Fn(ParaId) -> bool) {
		RetryQueue::mutate(|qs| for q in qs.iter_mut() {
			q.retain(|i| !m(i.0))
		});
		SelectedThreads::mutate(|qs| for q in qs.iter_mut() {
			q.retain(|i| !m(i.0))
		});
		Active::mutate(|a| for i in a.iter_mut() {
			if m(i.0) {
				if let Some((_, ref mut r)) = i.1 {
					*r = Retriable::Never;
				}
			}
		});
	}
}

impl<T: Trait> ActiveParas for Module<T> {
	fn active_paras() -> Vec<(ParaId, Option<(CollatorId, Retriable)>)> {
		Active::get()
	}
}

/// Ensure that parathread selections happen prioritized by fees.
#[derive(Encode, Decode, Clone, Eq, PartialEq)]
563
pub struct LimitParathreadCommits<T: Trait + Send + Sync>(sp_std::marker::PhantomData<T>) where
564
565
	<T as system::Trait>::Call: IsSubType<Module<T>, T>;

566
567
568
569
570
571
572
573
574
impl<T: Trait + Send + Sync> LimitParathreadCommits<T> where
	<T as system::Trait>::Call: IsSubType<Module<T>, T>
{
	/// Create a new `LimitParathreadCommits` struct.
	pub fn new() -> Self {
		LimitParathreadCommits(sp_std::marker::PhantomData)
	}
}

575
impl<T: Trait + Send + Sync> sp_std::fmt::Debug for LimitParathreadCommits<T> where
576
577
	<T as system::Trait>::Call: IsSubType<Module<T>, T>
{
578
	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
579
580
581
582
583
584
		write!(f, "LimitParathreadCommits<T>")
	}
}

/// Custom validity errors used in Polkadot while validating transactions.
#[repr(u8)]
585
pub enum ValidityError {
586
587
588
589
590
591
592
593
594
	/// Parathread ID has already been submitted for this block.
	Duplicate = 0,
	/// Parathread ID does not identify a parathread.
	InvalidId = 1,
}

impl<T: Trait + Send + Sync> SignedExtension for LimitParathreadCommits<T> where
	<T as system::Trait>::Call: IsSubType<Module<T>, T>
{
Gavin Wood's avatar
Gavin Wood committed
595
	const IDENTIFIER: &'static str = "LimitParathreadCommits";
596
597
598
599
600
601
	type AccountId = T::AccountId;
	type Call = <T as system::Trait>::Call;
	type AdditionalSigned = ();
	type Pre = ();

	fn additional_signed(&self)
602
		-> sp_std::result::Result<Self::AdditionalSigned, TransactionValidityError>
603
604
605
606
607
608
609
610
	{
		Ok(())
	}

	fn validate(
		&self,
		_who: &Self::AccountId,
		call: &Self::Call,
611
		_info: &DispatchInfoOf<Self::Call>,
612
613
614
615
616
617
		_len: usize,
	) -> TransactionValidity {
		let mut r = ValidTransaction::default();
		if let Some(local_call) = call.is_sub_type() {
			if let Call::select_parathread(id, collator, hash) = local_call {
				// ensure that the para ID is actually a parathread.
618
				let e = TransactionValidityError::from(InvalidTransaction::Custom(ValidityError::InvalidId as u8));
619
620
621
622
623
624
625
626
627
628
629
630
				<Module<T>>::ensure_thread_id(*id).ok_or(e)?;

				// ensure that we haven't already had a full complement of selected parathreads.
				let mut upcoming_selected_threads = SelectedThreads::get();
				if upcoming_selected_threads.is_empty() {
					upcoming_selected_threads.push(vec![]);
				}
				let i = upcoming_selected_threads.len() - 1;
				let selected_threads = &mut upcoming_selected_threads[i];
				let thread_count = ThreadCount::get() as usize;
				ensure!(
					selected_threads.len() < thread_count,
631
					InvalidTransaction::ExhaustsResources,
632
633
634
				);

				// ensure that this is not selecting a duplicate parathread ID
635
				let e = TransactionValidityError::from(InvalidTransaction::Custom(ValidityError::Duplicate as u8));
636
637
638
639
640
641
				let pos = selected_threads
					.binary_search_by(|&(ref other_id, _)| other_id.cmp(id))
					.err()
					.ok_or(e)?;

				// ensure that this is a live bid (i.e. that the thread's chain head matches)
642
				let e = TransactionValidityError::from(InvalidTransaction::Custom(ValidityError::InvalidId as u8));
643
				let head = <parachains::Module<T>>::parachain_head(id).ok_or(e)?;
644
				let actual = T::Hashing::hash(&head.0);
645
				ensure!(&actual == hash, InvalidTransaction::Stale);
646
647
648

				// updated the selected threads.
				selected_threads.insert(pos, (*id, collator.clone()));
649
				sp_std::mem::drop(selected_threads);
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
				SelectedThreads::put(upcoming_selected_threads);

				// provides the state-transition for this head-data-hash; this should cue the pool
				// to throw out competing transactions with lesser fees.
				r.provides = vec![hash.encode()];
			}
		}
		Ok(r)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use bitvec::vec::BitVec;
665
666
667
	use sp_io::TestExternalities;
	use sp_core::{H256, Pair};
	use sp_runtime::{
668
		traits::{
669
			BlakeTwo256, IdentityLookup, Dispatchable,
670
			AccountIdConversion, Extrinsic as ExtrinsicT,
671
		}, testing::{UintAuthorityId, TestXt}, KeyTypeId, Perbill, curve::PiecewiseLinear,
672
673
674
675
	};
	use primitives::{
		parachain::{
			ValidatorId, Info as ParaInfo, Scheduling, LOWEST_USER_ID, AttestedCandidate,
676
			CandidateReceipt, HeadData, ValidityAttestation, Statement, Chain,
677
			CollatorPair, CandidateCommitments,
678
		},
679
		Balance, BlockNumber, Header, Signature,
680
	};
681
	use frame_support::{
682
		traits::{KeyOwnerProofSystem, OnInitialize, OnFinalize},
683
		impl_outer_origin, impl_outer_dispatch, assert_ok, parameter_types, assert_noop,
684
		weights::DispatchInfo,
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
	};
	use keyring::Sr25519Keyring;

	use crate::parachains;
	use crate::slots;
	use crate::attestations;

	impl_outer_origin! {
		pub enum Origin for Test {
			parachains,
		}
	}

	impl_outer_dispatch! {
		pub enum Call for Test where origin: Origin {
			parachains::Parachains,
			registrar::Registrar,
702
			staking::Staking,
703
704
705
		}
	}

706
707
708
709
710
711
712
713
714
715
716
	pallet_staking_reward_curve::build! {
		const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
			min_inflation: 0_025_000,
			max_inflation: 0_100_000,
			ideal_stake: 0_500_000,
			falloff: 0_050_000,
			max_piece_count: 40,
			test_precision: 0_005_000,
		);
	}

717
718
719
720
721
722
723
724
725
726
727
728
	#[derive(Clone, Eq, PartialEq)]
	pub struct Test;
	parameter_types! {
		pub const BlockHashCount: u32 = 250;
		pub const MaximumBlockWeight: u32 = 4 * 1024 * 1024;
		pub const MaximumBlockLength: u32 = 4 * 1024 * 1024;
		pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
	}
	impl system::Trait for Test {
		type Origin = Origin;
		type Call = Call;
		type Index = u64;
729
		type BlockNumber = BlockNumber;
730
731
732
733
734
735
736
737
		type Hash = H256;
		type Hashing = BlakeTwo256;
		type AccountId = u64;
		type Lookup = IdentityLookup<u64>;
		type Header = Header;
		type Event = ();
		type BlockHashCount = BlockHashCount;
		type MaximumBlockWeight = MaximumBlockWeight;
738
		type DbWeight = ();
739
740
		type BlockExecutionWeight = ();
		type ExtrinsicBaseWeight = ();
Tomasz Drwięga's avatar
Tomasz Drwięga committed
741
		type MaximumExtrinsicWeight = MaximumBlockWeight;
742
743
744
		type MaximumBlockLength = MaximumBlockLength;
		type AvailableBlockRatio = AvailableBlockRatio;
		type Version = ();
745
		type ModuleToIndex = ();
746
		type AccountData = balances::AccountData<u128>;
Gavin Wood's avatar
Gavin Wood committed
747
		type OnNewAccount = ();
748
		type OnKilledAccount = Balances;
749
750
	}

751
752
753
754
755
756
757
	impl<C> system::offchain::SendTransactionTypes<C> for Test where
		Call: From<C>,
	{
		type OverarchingCall = Call;
		type Extrinsic = TestXt<Call, ()>;
	}

758
	parameter_types! {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
759
		pub const ExistentialDeposit: Balance = 1;
760
761
762
	}

	impl balances::Trait for Test {
763
		type Balance = u128;
764
		type DustRemoval = ();
765
		type Event = ();
766
		type ExistentialDeposit = ExistentialDeposit;
767
		type AccountStore = System;
768
769
770
	}

	parameter_types!{
771
772
		pub const LeasePeriod: BlockNumber = 10;
		pub const EndingPeriod: BlockNumber = 3;
773
774
775
776
777
778
779
780
	}

	impl slots::Trait for Test {
		type Event = ();
		type Currency = balances::Module<Test>;
		type Parachains = Registrar;
		type EndingPeriod = EndingPeriod;
		type LeasePeriod = LeasePeriod;
781
		type Randomness = RandomnessCollectiveFlip;
782
783
784
	}

	parameter_types!{
785
		pub const SlashDeferDuration: staking::EraIndex = 7;
786
		pub const AttestationPeriod: BlockNumber = 100;
787
788
789
790
		pub const MinimumPeriod: u64 = 3;
		pub const SessionsPerEra: sp_staking::SessionIndex = 6;
		pub const BondingDuration: staking::EraIndex = 28;
		pub const MaxNominatorRewardedPerValidator: u32 = 64;
791
792
793
794
795
796
797
798
799
800
801
802
	}

	impl attestations::Trait for Test {
		type AttestationPeriod = AttestationPeriod;
		type ValidatorIdentities = parachains::ValidatorIdentities<Test>;
		type RewardAttestation = ();
	}

	parameter_types! {
		pub const Period: BlockNumber = 1;
		pub const Offset: BlockNumber = 0;
		pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
803
		pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
804
805
806
	}

	impl session::Trait for Test {
807
		type SessionManager = ();
808
809
		type Keys = UintAuthorityId;
		type ShouldEndSession = session::PeriodicSessions<Period, Offset>;
810
		type NextSessionRotation = session::PeriodicSessions<Period, Offset>;
Gavin Wood's avatar
Gavin Wood committed
811
		type SessionHandler = session::TestSessionHandler;
812
813
814
815
816
817
		type Event = ();
		type ValidatorId = u64;
		type ValidatorIdOf = ();
		type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
	}

818
819
820
	parameter_types! {
		pub const MaxHeadDataSize: u32 = 100;
		pub const MaxCodeSize: u32 = 100;
821
822
823
824

		pub const ValidationUpgradeFrequency: BlockNumber = 10;
		pub const ValidationUpgradeDelay: BlockNumber = 2;
		pub const SlashPeriod: BlockNumber = 50;
825
		pub const ElectionLookahead: BlockNumber = 0;
826
		pub const StakingUnsignedPriority: u64 = u64::max_value() / 2;
827
828
	}

829
830
831
832
833
834
835
836
837
838
839
840
	impl staking::Trait for Test {
		type RewardRemainder = ();
		type CurrencyToVote = ();
		type Event = ();
		type Currency = balances::Module<Test>;
		type Slash = ();
		type Reward = ();
		type SessionsPerEra = SessionsPerEra;
		type BondingDuration = BondingDuration;
		type SlashDeferDuration = SlashDeferDuration;
		type SlashCancelOrigin = system::EnsureRoot<Self::AccountId>;
		type SessionInterface = Self;
841
		type UnixTime = timestamp::Module<Test>;
842
843
		type RewardCurve = RewardCurve;
		type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
844
845
846
		type NextNewSession = Session;
		type ElectionLookahead = ElectionLookahead;
		type Call = Call;
847
		type UnsignedPriority = StakingUnsignedPriority;
848
		type MaxIterations = ();
849
		type MinSolutionScoreBump = ();
850
851
852
853
854
855
856
857
858
859
860
861
862
	}

	impl timestamp::Trait for Test {
		type Moment = u64;
		type OnTimestampSet = ();
		type MinimumPeriod = MinimumPeriod;
	}

	impl session::historical::Trait for Test {
		type FullIdentification = staking::Exposure<u64, Balance>;
		type FullIdentificationOf = staking::ExposureOf<Self>;
	}

863
864
	// This is needed for a custom `AccountId` type which is `u64` in testing here.
	pub mod test_keys {
865
866
		use sp_core::{crypto::KeyTypeId, sr25519};
		use primitives::Signature;
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886

		pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"test");

		mod app {
			use super::super::Parachains;
			use sp_application_crypto::{app_crypto, sr25519};

			app_crypto!(sr25519, super::KEY_TYPE);

			impl sp_runtime::traits::IdentifyAccount for Public {
				type AccountId = u64;

				fn into_account(self) -> Self::AccountId {
					let id = self.0.clone().into();
					Parachains::authorities().iter().position(|b| *b == id).unwrap() as u64
				}
			}
		}

		pub type ReporterId = app::Public;
887
888
889
890
891
892
		pub struct ReporterAuthorityId;
		impl system::offchain::AppCrypto<ReporterId, Signature> for ReporterAuthorityId {
			type RuntimeAppPublic = ReporterId;
			type GenericSignature = sr25519::Signature;
			type GenericPublic = sr25519::Public;
		}
893
894
	}

895
	impl parachains::Trait for Test {
896
		type AuthorityId = test_keys::ReporterAuthorityId;
897
898
899
		type Origin = Origin;
		type Call = Call;
		type ParachainCurrency = balances::Module<Test>;
900
		type BlockNumberConversion = sp_runtime::traits::Identity;
901
902
		type ActiveParachains = Registrar;
		type Registrar = Registrar;
903
		type Randomness = RandomnessCollectiveFlip;
904
905
		type MaxCodeSize = MaxCodeSize;
		type MaxHeadDataSize = MaxHeadDataSize;
906
907
908
		type ValidationUpgradeFrequency = ValidationUpgradeFrequency;
		type ValidationUpgradeDelay = ValidationUpgradeDelay;
		type SlashPeriod = SlashPeriod;
909
		type Proof = sp_session::MembershipProof;
910
		type KeyOwnerProofSystem = session::historical::Module<Test>;
911
912
913
914
		type IdentificationTuple = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
			KeyTypeId,
			Vec<u8>,
		)>>::IdentificationTuple;
915
		type ReportOffence = ();
916
		type BlockHashConversion = sp_runtime::traits::Identity;
917
918
919
920
	}

	type Extrinsic = TestXt<Call, ()>;

921
922
923
924
925
926
	impl<LocalCall> system::offchain::CreateSignedTransaction<LocalCall> for Test where
		Call: From<LocalCall>,
	{
		fn create_transaction<C: system::offchain::AppCrypto<Self::Public, Self::Signature>>(
			call: Call,
			_public: test_keys::ReporterId,
927
928
			_account: <Test as system::Trait>::AccountId,
			nonce: <Test as system::Trait>::Index,
929
		) -> Option<(Call, <Extrinsic as ExtrinsicT>::SignaturePayload)> {
930
931
			Some((call, (nonce, ())))
		}
932
933
	}

934
935
936
937
938
	impl system::offchain::SigningTypes for Test {
		type Public = test_keys::ReporterId;
		type Signature = Signature;
	}

939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
	parameter_types! {
		pub const ParathreadDeposit: Balance = 10;
		pub const QueueSize: usize = 2;
		pub const MaxRetries: u32 = 3;
	}

	impl Trait for Test {
		type Event = ();
		type Origin = Origin;
		type Currency = balances::Module<Test>;
		type ParathreadDeposit = ParathreadDeposit;
		type SwapAux = slots::Module<Test>;
		type QueueSize = QueueSize;
		type MaxRetries = MaxRetries;
	}

	type Balances = balances::Module<Test>;
	type Parachains = parachains::Module<Test>;
	type System = system::Module<Test>;
	type Slots = slots::Module<Test>;
	type Registrar = Module<Test>;
960
	type RandomnessCollectiveFlip = randomness_collective_flip::Module<Test>;
961
962
	type Session = session::Module<Test>;
	type Staking = staking::Module<Test>;
963
964
965
966
967
968
969
970
971
972
973
974

	const AUTHORITY_KEYS: [Sr25519Keyring; 8] = [
		Sr25519Keyring::Alice,
		Sr25519Keyring::Bob,
		Sr25519Keyring::Charlie,
		Sr25519Keyring::Dave,
		Sr25519Keyring::Eve,
		Sr25519Keyring::Ferdie,
		Sr25519Keyring::One,
		Sr25519Keyring::Two,
	];

975
	fn new_test_ext(parachains: Vec<(ParaId, ValidationCode, HeadData)>) -> TestExternalities {
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
		let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();

		let authority_keys = [
			Sr25519Keyring::Alice,
			Sr25519Keyring::Bob,
			Sr25519Keyring::Charlie,
			Sr25519Keyring::Dave,
			Sr25519Keyring::Eve,
			Sr25519Keyring::Ferdie,
			Sr25519Keyring::One,
			Sr25519Keyring::Two,
		];

		// stashes are the index.
		let session_keys: Vec<_> = authority_keys.iter().enumerate()
991
			.map(|(i, _k)| (i as u64, i as u64, UintAuthorityId(i as u64)))
992
993
994
995
996
997
998
999
			.collect();

		let authorities: Vec<_> = authority_keys.iter().map(|k| ValidatorId::from(k.public())).collect();

		let balances: Vec<_> = (0..authority_keys.len()).map(|i| (i as u64, 10_000_000)).collect();

		parachains::GenesisConfig {
			authorities: authorities.clone(),
1000
		}.assimilate_storage::<Test>(&mut t).unwrap();
For faster browsing, not all history is shown. View entire blame