slots.rs 61.5 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
Gavin Wood's avatar
Gavin Wood committed
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/>.

//! Auctioning system to determine the set of Parachains in operation. This includes logic for the
//! auctioning mechanism, for locking balance as part of the "payment", and to provide the requisite
//! information for commissioning and decommissioning them.

21
use sp_std::{prelude::*, mem::swap, convert::TryInto};
22
use sp_runtime::traits::{
23
24
	CheckedSub, StaticLookup, Zero, One, CheckedConversion, Hash, AccountIdConversion,
};
25
use parity_scale_codec::{Encode, Decode, Codec};
26
use frame_support::{
27
	decl_module, decl_storage, decl_event, decl_error, ensure, dispatch::DispatchResult,
28
	traits::{Currency, ReservableCurrency, WithdrawReasons, ExistenceRequirement, Get, Randomness},
29
	weights::{DispatchClass, Weight},
30
};
31
32
use primitives::v1::{
	Id as ParaId, ValidationCode, HeadData,
33
};
34
use frame_system::{ensure_signed, ensure_root};
Gavin Wood's avatar
Gavin Wood committed
35
36
use crate::slot_range::{SlotRange, SLOT_RANGE_COUNT};

37
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
Gavin Wood's avatar
Gavin Wood committed
38
39

/// The module's configuration trait.
40
pub trait Config: frame_system::Config {
Gavin Wood's avatar
Gavin Wood committed
41
	/// The overarching event type.
42
	type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;
Gavin Wood's avatar
Gavin Wood committed
43
44
45
46
47

	/// The currency type used for bidding.
	type Currency: ReservableCurrency<Self::AccountId>;

	/// The parachain registrar type.
48
	type Parachains: Registrar<Self::AccountId>;
Gavin Wood's avatar
Gavin Wood committed
49
50
51
52
53
54

	/// The number of blocks over which an auction may be retroactively ended.
	type EndingPeriod: Get<Self::BlockNumber>;

	/// The number of blocks over which a single period lasts.
	type LeasePeriod: Get<Self::BlockNumber>;
55
56

	/// Something that provides randomness in the runtime.
57
	type Randomness: Randomness<Self::Hash, Self::BlockNumber>;
Gavin Wood's avatar
Gavin Wood committed
58
59
}

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/// Parachain registration API.
pub trait Registrar<AccountId> {
	/// Create a new unique parachain identity for later registration.
	fn new_id() -> ParaId;

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

	/// Register a parachain with given `code` and `initial_head_data`. `id` must not yet be registered or it will
	/// result in a error.
	///
	/// 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.
	fn register_para(
		id: ParaId,
		_parachain: bool,
		code: ValidationCode,
		initial_head_data: HeadData,
	) -> DispatchResult;

	/// Deregister a parachain with given `id`. If `id` is not currently registered, an error is returned.
	fn deregister_para(id: ParaId) -> DispatchResult;
}

/// Auxilliary for when there's an attempt to swap two parachains/parathreads.
pub trait SwapAux {
	/// Result describing whether it is possible to swap two parachains. Doesn't mutate state.
	fn ensure_can_swap(one: ParaId, other: ParaId) -> Result<(), &'static str>;

	/// Updates any needed state/references to enact a logical swap of two parachains. Identity,
	/// code and `head_data` remain equivalent for all parachains/threads, however other properties
	/// 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: ParaId, other: ParaId) -> Result<(), &'static str>;
}

Gavin Wood's avatar
Gavin Wood committed
104
105
106
107
108
109
110
111
112
113
114
115
116
/// A sub-bidder identifier. Used to distinguish between different logical bidders coming from the
/// same account ID.
pub type SubId = u32;
/// An auction index. We count auctions in this type.
pub type AuctionIndex = u32;

/// A bidder identifier, which is just the combination of an account ID and a sub-bidder ID.
/// This is called `NewBidder` in order to distinguish between bidders that would deploy a *new*
/// parachain and pre-existing parachains bidding to renew themselves.
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct NewBidder<AccountId> {
	/// The bidder's account ID; this is the account that funds the bid.
117
	pub who: AccountId,
Gavin Wood's avatar
Gavin Wood committed
118
119
	/// An additional ID to allow the same account ID (and funding source) to have multiple
	/// logical bidders.
120
	pub sub: SubId,
Gavin Wood's avatar
Gavin Wood committed
121
122
123
124
125
}

/// The desired target of a bidder in an auction.
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
126
pub enum Bidder<AccountId> {
Gavin Wood's avatar
Gavin Wood committed
127
128
129
130
131
132
133
134
	/// An account ID, funds coming from that account.
	New(NewBidder<AccountId>),

	/// An existing parachain, funds coming from the amount locked as part of a previous bid topped
	/// up with funds administered by the parachain.
	Existing(ParaId),
}

135
impl<AccountId: Clone + Default + Codec> Bidder<AccountId> {
Gavin Wood's avatar
Gavin Wood committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
	/// Get the account that will fund this bid.
	fn funding_account(&self) -> AccountId {
		match self {
			Bidder::New(new_bidder) => new_bidder.who.clone(),
			Bidder::Existing(para_id) => para_id.into_account(),
		}
	}
}

/// Information regarding a parachain that will be deployed.
///
/// We store either the bidder that will be able to set the final deployment information or the
/// information itself.
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum IncomingParachain<AccountId, Hash> {
	/// Deploy information not yet set; just the bidder identity.
	Unset(NewBidder<AccountId>),
154
155
156
157
158
	/// Deploy information set only by code hash; so we store the code hash, code size, and head data.
	///
	/// The code size must be included so that checks against a maximum code size
	/// can be done. If the size of the preimage of the code hash does not match
	/// the given code size, it will not be possible to register the parachain.
159
	Fixed { code_hash: Hash, code_size: u32, initial_head_data: HeadData },
Gavin Wood's avatar
Gavin Wood committed
160
	/// Deploy information fully set; so we store the code and head data.
161
	Deploy { code: ValidationCode, initial_head_data: HeadData },
Gavin Wood's avatar
Gavin Wood committed
162
163
}

164
type LeasePeriodOf<T> = <T as frame_system::Config>::BlockNumber;
Gavin Wood's avatar
Gavin Wood committed
165
// Winning data type. This encodes the top bidders of each range together with their bid.
166
type WinningData<T> =
167
	[Option<(Bidder<<T as frame_system::Config>::AccountId>, BalanceOf<T>)>; SLOT_RANGE_COUNT];
Gavin Wood's avatar
Gavin Wood committed
168
169
// Winners data type. This encodes each of the final winners of a parachain auction, the parachain
// index assigned to them, their winning bid and the range that they won.
170
type WinnersData<T> =
171
	Vec<(Option<NewBidder<<T as frame_system::Config>::AccountId>>, ParaId, BalanceOf<T>, SlotRange)>;
Gavin Wood's avatar
Gavin Wood committed
172

173
// This module's storage items.
Gavin Wood's avatar
Gavin Wood committed
174
decl_storage! {
175
	trait Store for Module<T: Config> as Slots {
Leo Arias's avatar
Leo Arias committed
176
		/// The number of auctions that have been started so far.
177
		pub AuctionCounter get(fn auction_counter): AuctionIndex;
Gavin Wood's avatar
Gavin Wood committed
178

179
180
		/// Ordered list of all `ParaId` values that are managed by this module. This includes
		/// chains that are not yet deployed (but have won an auction in the future).
181
		pub ManagedIds get(fn managed_ids): Vec<ParaId>;
Gavin Wood's avatar
Gavin Wood committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195

		/// Various amounts on deposit for each parachain. An entry in `ManagedIds` implies a non-
		/// default entry here.
		///
		/// The actual amount locked on its behalf at any time is the maximum item in this list. The
		/// first item in the list is the amount locked for the current Lease Period. Following
		/// items are for the subsequent lease periods.
		///
		/// The default value (an empty list) implies that the parachain no longer exists (or never
		/// existed) as far as this module is concerned.
		///
		/// If a parachain doesn't exist *yet* but is scheduled to exist in the future, then it
		/// will be left-padded with one or more zeroes to denote the fact that nothing is held on
		/// deposit for the non-existent chain currently, but is held at some point in the future.
196
		pub Deposits get(fn deposits): map hasher(twox_64_concat) ParaId => Vec<BalanceOf<T>>;
Gavin Wood's avatar
Gavin Wood committed
197
198
199
200
201
202

		/// Information relating to the current auction, if there is one.
		///
		/// The first item in the tuple is the lease period index that the first of the four
		/// contiguous lease periods on auction is for. The second is the block number when the
		/// auction will "begin to end", i.e. the first block of the Ending Period of the auction.
203
		pub AuctionInfo get(fn auction_info): Option<(LeasePeriodOf<T>, T::BlockNumber)>;
Gavin Wood's avatar
Gavin Wood committed
204
205
206
207

		/// The winning bids for each of the 10 ranges at each block in the final Ending Period of
		/// the current auction. The map's key is the 0-based index into the Ending Period. The
		/// first block of the ending period is 0; the last is `EndingPeriod - 1`.
208
		pub Winning get(fn winning): map hasher(twox_64_concat) T::BlockNumber => Option<WinningData<T>>;
Gavin Wood's avatar
Gavin Wood committed
209
210
211

		/// Amounts currently reserved in the accounts of the bidders currently winning
		/// (sub-)ranges.
212
		pub ReservedAmounts get(fn reserved_amounts):
213
			map hasher(twox_64_concat) Bidder<T::AccountId> => Option<BalanceOf<T>>;
Gavin Wood's avatar
Gavin Wood committed
214
215
216

		/// The set of Para IDs that have won and need to be on-boarded at an upcoming lease-period.
		/// This is cleared out on the first block of the lease period.
217
		pub OnboardQueue get(fn onboard_queue): map hasher(twox_64_concat) LeasePeriodOf<T> => Vec<ParaId>;
Gavin Wood's avatar
Gavin Wood committed
218
219
220
221
222

		/// The actual on-boarding information. Only exists when one of the following is true:
		/// - It is before the lease period that the parachain should be on-boarded.
		/// - The full on-boarding information has not yet been provided and the parachain is not
		/// yet due to be off-boarded.
223
		pub Onboarding get(fn onboarding):
224
			map hasher(twox_64_concat) ParaId =>
Gavin Wood's avatar
Gavin Wood committed
225
226
227
228
			Option<(LeasePeriodOf<T>, IncomingParachain<T::AccountId, T::Hash>)>;

		/// Off-boarding account; currency held on deposit for the parachain gets placed here if the
		/// parachain gets off-boarded; i.e. its lease period is up and it isn't renewed.
229
		pub Offboarding get(fn offboarding): map hasher(twox_64_concat) ParaId => T::AccountId;
230
231
232
	}
}

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/// 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.
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();
}

248
impl<T: Config> SwapAux for Module<T> {
249
	fn ensure_can_swap(one: ParaId, other: ParaId) -> Result<(), &'static str> {
250
		if <Onboarding<T>>::contains_key(one) || <Onboarding<T>>::contains_key(other) {
251
252
253
254
255
256
257
258
259
			Err("can't swap an undeployed parachain")?
		}
		Ok(())
	}
	fn on_swap(one: ParaId, other: ParaId) -> Result<(), &'static str> {
		<Offboarding<T>>::swap(one, other);
		<Deposits<T>>::swap(one, other);
		ManagedIds::mutate(|ids| swap_ordered_existence(ids, one, other));
		Ok(())
Gavin Wood's avatar
Gavin Wood committed
260
261
262
263
264
	}
}

decl_event!(
	pub enum Event<T> where
265
266
		AccountId = <T as frame_system::Config>::AccountId,
		BlockNumber = <T as frame_system::Config>::BlockNumber,
Gavin Wood's avatar
Gavin Wood committed
267
		LeasePeriod = LeasePeriodOf<T>,
268
		ParaId = ParaId,
Gavin Wood's avatar
Gavin Wood committed
269
270
		Balance = BalanceOf<T>,
	{
271
		/// A new [lease_period] is beginning.
Gavin Wood's avatar
Gavin Wood committed
272
273
274
		NewLeasePeriod(LeasePeriod),
		/// An auction started. Provides its index and the block number where it will begin to
		/// close and the first lease period of the quadruplet that is auctioned.
275
		/// [auction_index, lease_period, ending]
Gavin Wood's avatar
Gavin Wood committed
276
		AuctionStarted(AuctionIndex, LeasePeriod, BlockNumber),
277
		/// An auction ended. All funds become unreserved. [auction_index]
Gavin Wood's avatar
Gavin Wood committed
278
279
		AuctionClosed(AuctionIndex),
		/// Someone won the right to deploy a parachain. Balance amount is deducted for deposit.
280
		/// [bidder, range, parachain_id, amount]
Gavin Wood's avatar
Gavin Wood committed
281
282
		WonDeploy(NewBidder<AccountId>, SlotRange, ParaId, Balance),
		/// An existing parachain won the right to continue.
283
		/// First balance is the extra amount reseved. Second is the total amount reserved.
284
		/// [parachain_id, range, extra_reseved, total_amount]
Gavin Wood's avatar
Gavin Wood committed
285
286
		WonRenewal(ParaId, SlotRange, Balance, Balance),
		/// Funds were reserved for a winning bid. First balance is the extra amount reserved.
287
		/// Second is the total. [bidder, extra_reserved, total_amount]
Gavin Wood's avatar
Gavin Wood committed
288
		Reserved(AccountId, Balance, Balance),
289
		/// Funds were unreserved since bidder is no longer active. [bidder, amount]
Gavin Wood's avatar
Gavin Wood committed
290
291
292
293
		Unreserved(AccountId, Balance),
	}
);

294
decl_error! {
295
	pub enum Error for Module<T: Config> {
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
		/// This auction is already in progress.
		AuctionInProgress,
		/// The lease period is in the past.
		LeasePeriodInPast,
		/// The origin for this call must be a parachain.
		NotParaOrigin,
		/// The parachain ID is not onboarding.
		ParaNotOnboarding,
		/// The origin for this call must be the origin who registered the parachain.
		InvalidOrigin,
		/// Parachain is already registered.
		AlreadyRegistered,
		/// The code must correspond to the hash.
		InvalidCode,
		/// Deployment data has not been set for this parachain.
		UnsetDeployData,
		/// The bid must overlap all intersecting ranges.
		NonIntersectingRange,
		/// Not a current auction.
		NotCurrentAuction,
		/// Not an auction.
		NotAuction,
318
319
320
321
		/// Given code size is too large.
		CodeTooLarge,
		/// Given initial head data is too large.
		HeadDataTooLarge,
322
323
324
	}
}

Gavin Wood's avatar
Gavin Wood committed
325
decl_module! {
326
	pub struct Module<T: Config> for enum Call where origin: T::Origin {
327
328
		type Error = Error<T>;

thiolliere's avatar
thiolliere committed
329
		fn deposit_event() = default;
Gavin Wood's avatar
Gavin Wood committed
330

331
		fn on_initialize(n: T::BlockNumber) -> Weight {
Gavin Wood's avatar
Gavin Wood committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
			let lease_period = T::LeasePeriod::get();
			let lease_period_index: LeasePeriodOf<T> = (n / lease_period).into();

			// Check to see if an auction just ended.
			if let Some((winning_ranges, auction_lease_period_index)) = Self::check_auction_end(n) {
				// Auction is ended now. We have the winning ranges and the lease period index which
				// acts as the offset. Handle it.
				Self::manage_auction_end(
					lease_period_index,
					auction_lease_period_index,
					winning_ranges,
				);
			}
			// If we're beginning a new lease period then handle that, too.
			if (n % lease_period).is_zero() {
				Self::manage_lease_period_start(lease_period_index);
			}
349

350
			0
Gavin Wood's avatar
Gavin Wood committed
351
352
353
354
355
356
357
		}

		fn on_finalize(now: T::BlockNumber) {
			// If the current auction is in it ending period, then ensure that the (sub-)range
			// winner information is duplicated from the previous block in case no bids happened
			// in this block.
			if let Some(offset) = Self::is_ending(now) {
358
				if !<Winning<T>>::contains_key(&offset) {
Gavin Wood's avatar
Gavin Wood committed
359
360
361
362
363
364
365
366
367
368
369
370
371
372
					<Winning<T>>::insert(offset,
						offset.checked_sub(&One::one())
							.and_then(<Winning<T>>::get)
							.unwrap_or_default()
					);
				}
			}
		}

		/// Create a new auction.
		///
		/// This can only happen when there isn't already an auction in progress and may only be
		/// called by the root origin. Accepts the `duration` of this auction and the
		/// `lease_period_index` of the initial lease period of the four that are to be auctioned.
373
		#[weight = (100_000_000, DispatchClass::Operational)]
374
		pub fn new_auction(origin,
Gavin Wood's avatar
Gavin Wood committed
375
376
377
			#[compact] duration: T::BlockNumber,
			#[compact] lease_period_index: LeasePeriodOf<T>
		) {
378
			ensure_root(origin)?;
379
380
			ensure!(!Self::is_in_progress(), Error::<T>::AuctionInProgress);
			ensure!(lease_period_index >= Self::lease_period_index(), Error::<T>::LeasePeriodInPast);
Gavin Wood's avatar
Gavin Wood committed
381
382

			// Bump the counter.
Gavin Wood's avatar
Gavin Wood committed
383
			let n = <AuctionCounter>::mutate(|n| { *n += 1; *n });
Gavin Wood's avatar
Gavin Wood committed
384
385

			// Set the information.
386
			let ending = <frame_system::Module<T>>::block_number() + duration;
Gavin Wood's avatar
Gavin Wood committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
			<AuctionInfo<T>>::put((lease_period_index, ending));

			Self::deposit_event(RawEvent::AuctionStarted(n, lease_period_index, ending))
		}

		/// Make a new bid from an account (including a parachain account) for deploying a new
		/// parachain.
		///
		/// Multiple simultaneous bids from the same bidder are allowed only as long as all active
		/// bids overlap each other (i.e. are mutually exclusive). Bids cannot be redacted.
		///
		/// - `sub` is the sub-bidder ID, allowing for multiple competing bids to be made by (and
		/// funded by) the same account.
		/// - `auction_index` is the index of the auction to bid on. Should just be the present
		/// value of `AuctionCounter`.
		/// - `first_slot` is the first lease period index of the range to bid on. This is the
		/// absolute lease period index value, not an auction-specific offset.
		/// - `last_slot` is the last lease period index of the range to bid on. This is the
		/// absolute lease period index value, not an auction-specific offset.
		/// - `amount` is the amount to bid to be held as deposit for the parachain should the
		/// bid win. This amount is held throughout the range.
408
		#[weight = 500_000_000]
409
		pub fn bid(origin,
Gavin Wood's avatar
Gavin Wood committed
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
			#[compact] sub: SubId,
			#[compact] auction_index: AuctionIndex,
			#[compact] first_slot: LeasePeriodOf<T>,
			#[compact] last_slot: LeasePeriodOf<T>,
			#[compact] amount: BalanceOf<T>
		) {
			let who = ensure_signed(origin)?;
			let bidder = Bidder::New(NewBidder{who: who.clone(), sub});
			Self::handle_bid(bidder, auction_index, first_slot, last_slot, amount)?;
		}

		/// Make a new bid from a parachain account for renewing that (pre-existing) parachain.
		///
		/// The origin *must* be a parachain account.
		///
		/// Multiple simultaneous bids from the same bidder are allowed only as long as all active
		/// bids overlap each other (i.e. are mutually exclusive). Bids cannot be redacted.
		///
		/// - `auction_index` is the index of the auction to bid on. Should just be the present
		/// value of `AuctionCounter`.
		/// - `first_slot` is the first lease period index of the range to bid on. This is the
		/// absolute lease period index value, not an auction-specific offset.
		/// - `last_slot` is the last lease period index of the range to bid on. This is the
		/// absolute lease period index value, not an auction-specific offset.
		/// - `amount` is the amount to bid to be held as deposit for the parachain should the
		/// bid win. This amount is held throughout the range.
436
		#[weight = 500_000_000]
437
		fn bid_renew(origin,
Gavin Wood's avatar
Gavin Wood committed
438
439
440
441
442
443
			#[compact] auction_index: AuctionIndex,
			#[compact] first_slot: LeasePeriodOf<T>,
			#[compact] last_slot: LeasePeriodOf<T>,
			#[compact] amount: BalanceOf<T>
		) {
			let who = ensure_signed(origin)?;
444
			let para_id = <ParaId>::try_from_account(&who)
445
				.ok_or(Error::<T>::NotParaOrigin)?;
Gavin Wood's avatar
Gavin Wood committed
446
447
448
449
450
451
452
453
454
			let bidder = Bidder::Existing(para_id);
			Self::handle_bid(bidder, auction_index, first_slot, last_slot, amount)?;
		}

		/// Set the off-boarding information for a parachain.
		///
		/// The origin *must* be a parachain account.
		///
		/// - `dest` is the destination account to receive the parachain's deposit.
455
		#[weight = 1_000_000_000]
456
		pub fn set_offboarding(origin, dest: <T::Lookup as StaticLookup>::Source) {
Gavin Wood's avatar
Gavin Wood committed
457
458
			let who = ensure_signed(origin)?;
			let dest = T::Lookup::lookup(dest)?;
459
			let para_id = <ParaId>::try_from_account(&who)
460
				.ok_or(Error::<T>::NotParaOrigin)?;
Gavin Wood's avatar
Gavin Wood committed
461
462
463
464
465
466
467
468
469
470
			<Offboarding<T>>::insert(para_id, dest);
		}

		/// Set the deploy information for a successful bid to deploy a new parachain.
		///
		/// - `origin` must be the successful bidder account.
		/// - `sub` is the sub-bidder ID of the bidder.
		/// - `para_id` is the parachain ID allotted to the winning bidder.
		/// - `code_hash` is the hash of the parachain's Wasm validation function.
		/// - `initial_head_data` is the parachain's initial head data.
471
		#[weight = 500_000_000]
472
		pub fn fix_deploy_data(origin,
Gavin Wood's avatar
Gavin Wood committed
473
			#[compact] sub: SubId,
474
			#[compact] para_id: ParaId,
Gavin Wood's avatar
Gavin Wood committed
475
			code_hash: T::Hash,
476
			code_size: u32,
477
			initial_head_data: HeadData,
Gavin Wood's avatar
Gavin Wood committed
478
479
480
		) {
			let who = ensure_signed(origin)?;
			let (starts, details) = <Onboarding<T>>::get(&para_id)
481
				.ok_or(Error::<T>::ParaNotOnboarding)?;
Gavin Wood's avatar
Gavin Wood committed
482
			if let IncomingParachain::Unset(ref nb) = details {
483
				ensure!(nb.who == who && nb.sub == sub, Error::<T>::InvalidOrigin);
Gavin Wood's avatar
Gavin Wood committed
484
			} else {
485
				Err(Error::<T>::AlreadyRegistered)?
Gavin Wood's avatar
Gavin Wood committed
486
			}
487
488

			ensure!(
489
				T::Parachains::head_data_size_allowed(initial_head_data.0.len() as _),
490
491
492
493
494
495
496
497
				Error::<T>::HeadDataTooLarge,
			);
			ensure!(
				T::Parachains::code_size_allowed(code_size),
				Error::<T>::CodeTooLarge,
			);

			let item = (starts, IncomingParachain::Fixed{code_hash, code_size, initial_head_data});
Gavin Wood's avatar
Gavin Wood committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
			<Onboarding<T>>::insert(&para_id, item);
		}

		/// Note a new parachain's code.
		///
		/// This must be called after `fix_deploy_data` and `code` must be the preimage of the
		/// `code_hash` passed there for the same `para_id`.
		///
		/// This may be called before or after the beginning of the parachain's first lease period.
		/// If called before then the parachain will become active at the first block of its
		/// starting lease period. If after, then it will become active immediately after this call.
		///
		/// - `_origin` is irrelevant.
		/// - `para_id` is the parachain ID whose code will be elaborated.
		/// - `code` is the preimage of the registered `code_hash` of `para_id`.
513
		#[weight = 5_000_000_000]
514
515
516
517
518
		pub fn elaborate_deploy_data(
			_origin,
			#[compact] para_id: ParaId,
			code: ValidationCode,
		) -> DispatchResult {
Gavin Wood's avatar
Gavin Wood committed
519
			let (starts, details) = <Onboarding<T>>::get(&para_id)
520
				.ok_or(Error::<T>::ParaNotOnboarding)?;
521
			if let IncomingParachain::Fixed{code_hash, code_size, initial_head_data} = details {
522
				ensure!(code.0.len() as u32 == code_size, Error::<T>::InvalidCode);
523
				ensure!(<T as frame_system::Config>::Hashing::hash(&code.0) == code_hash, Error::<T>::InvalidCode);
524

Gavin Wood's avatar
Gavin Wood committed
525
526
527
528
529
530
531
532
				if starts > Self::lease_period_index() {
					// Hasn't yet begun. Replace the on-boarding entry with the new information.
					let item = (starts, IncomingParachain::Deploy{code, initial_head_data});
					<Onboarding<T>>::insert(&para_id, item);
				} else {
					// Should have already begun. Remove the on-boarding entry and register the
					// parachain for its immediate start.
					<Onboarding<T>>::remove(&para_id);
533
					let _ = T::Parachains::
534
						register_para(para_id, true, code, initial_head_data);
Gavin Wood's avatar
Gavin Wood committed
535
				}
536
537

				Ok(())
Gavin Wood's avatar
Gavin Wood committed
538
			} else {
539
				Err(Error::<T>::UnsetDeployData)?
Gavin Wood's avatar
Gavin Wood committed
540
541
542
543
544
			}
		}
	}
}

545
impl<T: Config> Module<T> {
Gavin Wood's avatar
Gavin Wood committed
546
	/// Deposit currently held for a particular parachain that we administer.
547
	fn deposit_held(para_id: &ParaId) -> BalanceOf<T> {
Gavin Wood's avatar
Gavin Wood committed
548
549
550
551
		<Deposits<T>>::get(para_id).into_iter().max().unwrap_or_else(Zero::zero)
	}

	/// True if an auction is in progress.
552
	pub fn is_in_progress() -> bool {
Gavin Wood's avatar
Gavin Wood committed
553
554
555
556
557
		<AuctionInfo<T>>::exists()
	}

	/// Returns `Some(n)` if the now block is part of the ending period of an auction, where `n`
	/// represents how far into the ending period this block is. Otherwise, returns `None`.
558
	pub fn is_ending(now: T::BlockNumber) -> Option<T::BlockNumber> {
Gavin Wood's avatar
Gavin Wood committed
559
560
561
562
563
564
565
566
567
568
569
570
		if let Some((_, early_end)) = <AuctionInfo<T>>::get() {
			if let Some(after_early_end) = now.checked_sub(&early_end) {
				if after_early_end < T::EndingPeriod::get() {
					return Some(after_early_end)
				}
			}
		}
		None
	}

	/// Returns the current lease period.
	fn lease_period_index() -> LeasePeriodOf<T> {
571
		(<frame_system::Module<T>>::block_number() / T::LeasePeriod::get()).into()
Gavin Wood's avatar
Gavin Wood committed
572
573
574
575
576
577
578
579
580
581
	}

	/// Some when the auction's end is known (with the end block number). None if it is unknown.
	/// If `Some` then the block number must be at most the previous block and at least the
	/// previous block minus `T::EndingPeriod::get()`.
	///
	/// This mutates the state, cleaning up `AuctionInfo` and `Winning` in the case of an auction
	/// ending. An immediately subsequent call with the same argument will always return `None`.
	fn check_auction_end(now: T::BlockNumber) -> Option<(WinningData<T>, LeasePeriodOf<T>)> {
		if let Some((lease_period_index, early_end)) = <AuctionInfo<T>>::get() {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
582
583
			let ending_period = T::EndingPeriod::get();
			if early_end + ending_period == now {
Gavin Wood's avatar
Gavin Wood committed
584
				// Just ended!
585
586
				let (seed, _) = T::Randomness::random_seed();
				let offset = T::BlockNumber::decode(&mut seed.as_ref())
Gavin Wood's avatar
Gavin Wood committed
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
630
631
632
633
					.expect("secure hashes always bigger than block numbers; qed") % ending_period;
				let res = <Winning<T>>::get(offset).unwrap_or_default();
				let mut i = T::BlockNumber::zero();
				while i < ending_period {
					<Winning<T>>::remove(i);
					i += One::one();
				}
				<AuctionInfo<T>>::kill();
				return Some((res, lease_period_index))
			}
		}
		None
	}

	/// Auction just ended. We have the current lease period, the auction's lease period (which
	/// is guaranteed to be at least the current period) and the bidders that were winning each
	/// range at the time of the auction's close.
	fn manage_auction_end(
		lease_period_index: LeasePeriodOf<T>,
		auction_lease_period_index: LeasePeriodOf<T>,
		winning_ranges: WinningData<T>,
	) {
		// First, unreserve all amounts that were reserved for the bids. We will later deduct the
		// amounts from the bidders that ended up being assigned the slot so there's no need to
		// special-case them here.
		for (bidder, _) in winning_ranges.iter().filter_map(|x| x.as_ref()) {
			if let Some(amount) = <ReservedAmounts<T>>::take(bidder) {
				T::Currency::unreserve(&bidder.funding_account(), amount);
			}
		}

		// Next, calculate the winning combination of slots and thus the final winners of the
		// auction.
		let winners = Self::calculate_winners(winning_ranges, T::Parachains::new_id);

		Self::deposit_event(RawEvent::AuctionClosed(Self::auction_counter()));

		// Go through those winners and deduct their bid, updating our table of deposits
		// accordingly.
		for (maybe_new_deploy, para_id, amount, range) in winners.into_iter() {
			match maybe_new_deploy {
				Some(bidder) => {
					// For new deployments we ensure the full amount is deducted. This should always
					// succeed as we just unreserved the same amount above.
					if T::Currency::withdraw(
						&bidder.who,
						amount,
634
						WithdrawReasons::FEE,
Gavin Wood's avatar
Gavin Wood committed
635
636
637
638
639
640
						ExistenceRequirement::AllowDeath
					).is_err() {
						continue;
					}

					// Add para IDs of any chains that will be newly deployed to our set of managed
641
					// IDs.
642
643
644
645
646
647
648
649
					ManagedIds::mutate(|ids|
						if let Err(pos) = ids.binary_search(&para_id) {
							ids.insert(pos, para_id)
						} else {
							// This can't happen as it's a winner being newly
							// deployed and thus the para_id shouldn't already be being managed.
						}
					);
Gavin Wood's avatar
Gavin Wood committed
650
651
652
653
654
655
656
					Self::deposit_event(RawEvent::WonDeploy(bidder.clone(), range, para_id, amount));

					// Add a deployment record so we know to on-board them at the appropriate
					// juncture.
					let begin_offset = <LeasePeriodOf<T>>::from(range.as_pair().0 as u32);
					let begin_lease_period = auction_lease_period_index + begin_offset;
					<OnboardQueue<T>>::mutate(begin_lease_period, |starts| starts.push(para_id));
657
658
					// Add a default off-boarding account which matches the original bidder
					<Offboarding<T>>::insert(&para_id, &bidder.who);
Gavin Wood's avatar
Gavin Wood committed
659
660
661
662
663
664
665
666
667
668
669
670
					let entry = (begin_lease_period, IncomingParachain::Unset(bidder));
					<Onboarding<T>>::insert(&para_id, entry);
				}
				None => {
					// For renewals, reserve any extra on top of what we already have held
					// on deposit for their chain.
					let extra = if let Some(additional) =
						amount.checked_sub(&Self::deposit_held(&para_id))
					{
						if T::Currency::withdraw(
							&para_id.into_account(),
							additional,
671
							WithdrawReasons::FEE,
Gavin Wood's avatar
Gavin Wood committed
672
673
674
675
676
677
678
679
							ExistenceRequirement::AllowDeath
						).is_err() {
							continue;
						}
						additional
					} else {
						Default::default()
					};
680
					Self::deposit_event(RawEvent::WonRenewal(para_id, range, extra, amount));
Gavin Wood's avatar
Gavin Wood committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
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
				}
			}

			// Finally, we update the deposit held so it is `amount` for the new lease period
			// indices that were won in the auction.
			let maybe_offset = auction_lease_period_index
				.checked_sub(&lease_period_index)
				.and_then(|x| x.checked_into::<usize>());
			if let Some(offset) = maybe_offset {
				// Should always succeed; for it to fail it would mean we auctioned a lease period
				// that already ended.

				// The lease period index range (begin, end) that newly belongs to this parachain
				// ID. We need to ensure that it features in `Deposits` to prevent it from being
				// reaped too early (any managed parachain whose `Deposits` set runs low will be
				// removed).
				let pair = range.as_pair();
				let pair = (pair.0 as usize + offset, pair.1 as usize + offset);
				<Deposits<T>>::mutate(para_id, |d| {
					// Left-pad with zeroes as necessary.
					if d.len() < pair.0 {
						d.resize_with(pair.0, Default::default);
					}
					// Then place the deposit values for as long as the chain should exist.
					for i in pair.0 ..= pair.1 {
						if d.len() > i {
							// The chain bought the same lease period twice. Just take the maximum.
							d[i] = d[i].max(amount);
						} else if d.len() == i {
							d.push(amount);
						} else {
							unreachable!("earlier resize means it must be >= i; qed")
						}
					}
				});
			}
		}
	}

	/// A new lease period is beginning. We're at the start of the first block of it.
	///
	/// We need to on-board and off-board parachains as needed. We should also handle reducing/
	/// returning deposits.
	fn manage_lease_period_start(lease_period_index: LeasePeriodOf<T>) {
		Self::deposit_event(RawEvent::NewLeasePeriod(lease_period_index));
		// First, bump off old deposits and decommission any managed chains that are coming
		// to a close.
728
		ManagedIds::mutate(|ids| {
Gavin Wood's avatar
Gavin Wood committed
729
730
731
732
733
734
735
736
737
738
739
740
			let new = ids.drain(..).filter(|id| {
				let mut d = <Deposits<T>>::get(id);
				if !d.is_empty() {
					// ^^ should always be true, since we would have deleted the entry otherwise.

					if d.len() == 1 {
						// Just one entry, which corresponds to the now-ended lease period. Time
						// to decommission this chain.
						if <Onboarding<T>>::take(id).is_none() {
							// Only unregister it if it was actually registered in the first place.
							// If the on-boarding entry still existed, then it was never actually
							// commissioned.
741
							let _ = T::Parachains::deregister_para(id.clone());
Gavin Wood's avatar
Gavin Wood committed
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
						}
						// Return the full deposit to the off-boarding account.
						T::Currency::deposit_creating(&<Offboarding<T>>::take(id), d[0]);
						// Remove the now-empty deposits set and don't keep the ID around.
						<Deposits<T>>::remove(id);
						false
					} else {
						// The parachain entry is continuing into the next lease period.
						// We need to pop the first deposit entry, which corresponds to the now-
						// ended lease period.
						let outgoing = d[0];
						d.remove(0);
						<Deposits<T>>::insert(id, &d);
						// Then we need to get the new amount that should continue to be held on
						// deposit for the parachain.
						let new_held = d.into_iter().max().unwrap_or_default();
						// If this is less than what we were holding previously, then return it
						// to the parachain itself.
						if let Some(rebate) = outgoing.checked_sub(&new_held) {
							T::Currency::deposit_creating(
								&id.into_account(),
								rebate
							);
						}
						// We keep this entry around until the next lease period.
						true
					}
				} else {
					false
				}
			}).collect::<Vec<_>>();
			*ids = new;
		});

		// Deploy any new chains that are due to be commissioned.
		for para_id in <OnboardQueue<T>>::take(lease_period_index) {
			if let Some((_, IncomingParachain::Deploy{code, initial_head_data}))
				= <Onboarding<T>>::get(&para_id)
			{
				// The chain's deployment data is set; go ahead and register it, and remove the
				// now-redundant on-boarding entry.
783
				let _ = T::Parachains::
784
					register_para(para_id.clone(), true, code, initial_head_data);
Gavin Wood's avatar
Gavin Wood committed
785
786
787
788
789
790
791
792
793
794
795
796
797
798
				// ^^ not much we can do if it fails for some reason.
				<Onboarding<T>>::remove(para_id)
			}
		}
	}

	/// Actually place a bid in the current auction.
	///
	/// - `bidder`: The account that will be funding this bid.
	/// - `auction_index`: The auction index of the bid. For this to succeed, must equal
	/// the current value of `AuctionCounter`.
	/// - `first_slot`: The first lease period index of the range to be bid on.
	/// - `last_slot`: The last lease period index of the range to be bid on (inclusive).
	/// - `amount`: The total amount to be the bid for deposit over the range.
799
	pub fn handle_bid(
800
		bidder: Bidder<T::AccountId>,
Gavin Wood's avatar
Gavin Wood committed
801
802
803
804
		auction_index: u32,
		first_slot: LeasePeriodOf<T>,
		last_slot: LeasePeriodOf<T>,
		amount: BalanceOf<T>
805
	) -> DispatchResult {
Gavin Wood's avatar
Gavin Wood committed
806
		// Bidding on latest auction.
807
		ensure!(auction_index == <AuctionCounter>::get(), Error::<T>::NotCurrentAuction);
Gavin Wood's avatar
Gavin Wood committed
808
		// Assume it's actually an auction (this should never fail because of above).
809
		let (first_lease_period, _) = <AuctionInfo<T>>::get().ok_or(Error::<T>::NotAuction)?;
Gavin Wood's avatar
Gavin Wood committed
810
811
812
813
814
815

		// Our range.
		let range = SlotRange::new_bounded(first_lease_period, first_slot, last_slot)?;
		// Range as an array index.
		let range_index = range as u8 as usize;
		// The offset into the auction ending set.
816
		let offset = Self::is_ending(<frame_system::Module<T>>::block_number()).unwrap_or_default();
Gavin Wood's avatar
Gavin Wood committed
817
818
819
820
821
822
823
824
825
826
827
828
829
830
		// The current winning ranges.
		let mut current_winning = <Winning<T>>::get(offset)
			.or_else(|| offset.checked_sub(&One::one()).and_then(<Winning<T>>::get))
			.unwrap_or_default();
		// If this bid beat the previous winner of our range.
		if current_winning[range_index].as_ref().map_or(true, |last| amount > last.1) {
			// This must overlap with all existing ranges that we're winning on or it's invalid.
			ensure!(current_winning.iter()
				.enumerate()
				.all(|(i, x)| x.as_ref().map_or(true, |(w, _)|
					w != &bidder || range.intersects(i.try_into()
						.expect("array has SLOT_RANGE_COUNT items; index never reaches that value; qed")
					)
				)),
831
				Error::<T>::NonIntersectingRange,
Gavin Wood's avatar
Gavin Wood committed
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
			);

			// Ok; we are the new winner of this range - reserve the additional amount and record.

			// Get the amount already held on deposit on our behalf if this is a renewal bid from
			// an existing parachain.
			let deposit_held = if let Bidder::Existing(ref bidder_para_id) = bidder {
				Self::deposit_held(bidder_para_id)
			} else {
				Zero::zero()
			};
			// Get the amount already reserved in any prior and still active bids by us.
			let already_reserved =
				<ReservedAmounts<T>>::get(&bidder).unwrap_or_default() + deposit_held;
			// If these don't already cover the bid...
			if let Some(additional) = amount.checked_sub(&already_reserved) {
				// ...then reserve some more funds from their account, failing if there's not
				// enough funds.
				T::Currency::reserve(&bidder.funding_account(), additional)?;
				// ...and record the amount reserved.
				<ReservedAmounts<T>>::insert(&bidder, amount);

				Self::deposit_event(RawEvent::Reserved(
					bidder.funding_account(),
					additional,
					amount
				));
			}

			// Return any funds reserved for the previous winner if they no longer have any active
			// bids.
			let mut outgoing_winner = Some((bidder, amount));
			swap(&mut current_winning[range_index], &mut outgoing_winner);
			if let Some((who, _)) = outgoing_winner {
				if current_winning.iter()
					.filter_map(Option::as_ref)
					.all(|&(ref other, _)| other != &who)
				{
					// Previous bidder is no longer winning any ranges: unreserve their funds.
					if let Some(amount) = <ReservedAmounts<T>>::take(&who) {
						// It really should be reserved; there's not much we can do here on fail.
						let _ = T::Currency::unreserve(&who.funding_account(), amount);

						Self::deposit_event(RawEvent::Unreserved(who.funding_account(), amount));
					}
				}
			}
			// Update the range winner.
			<Winning<T>>::insert(offset, &current_winning);
		}
		Ok(())
	}

	/// Calculate the final winners from the winning slots.
	///
	/// This is a simple dynamic programming algorithm designed by Al, the original code is at:
	/// https://github.com/w3f/consensus/blob/master/NPoS/auctiondynamicthing.py
	fn calculate_winners(
		mut winning: WinningData<T>,
891
		new_id: impl Fn() -> ParaId
Gavin Wood's avatar
Gavin Wood committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
	) -> WinnersData<T> {
		let winning_ranges = {
			let mut best_winners_ending_at:
				[(Vec<SlotRange>, BalanceOf<T>); 4] = Default::default();
			let best_bid = |range: SlotRange| {
				winning[range as u8 as usize].as_ref()
					.map(|(_, amount)| *amount * (range.len() as u32).into())
			};
			for i in 0..4 {
				let r = SlotRange::new_bounded(0, 0, i as u32).expect("`i < 4`; qed");
				if let Some(bid) = best_bid(r) {
					best_winners_ending_at[i] = (vec![r], bid);
				}
				for j in 0..i {
					let r = SlotRange::new_bounded(0, j as u32 + 1, i as u32)
						.expect("`i < 4`; `j < i`; `j + 1 < 4`; qed");
					if let Some(mut bid) = best_bid(r) {
						bid += best_winners_ending_at[j].1;
						if bid > best_winners_ending_at[i].1 {
							let mut new_winners = best_winners_ending_at[j].0.clone();
							new_winners.push(r);
							best_winners_ending_at[i] = (new_winners, bid);
						}
					} else {
						if best_winners_ending_at[j].1 > best_winners_ending_at[i].1 {
							best_winners_ending_at[i] = best_winners_ending_at[j].clone();
						}
					}
				}
			}
			let [_, _, _, (winning_ranges, _)] = best_winners_ending_at;
			winning_ranges
		};

		winning_ranges.into_iter().map(|r| {
			let mut final_winner = (Bidder::Existing(Default::default()), Default::default());
			swap(&mut final_winner, winning[r as u8 as usize].as_mut()
				.expect("none values are filtered out in previous logic; qed"));
			let (slot_winner, bid) = final_winner;
			match slot_winner {
				Bidder::New(new_bidder) => (Some(new_bidder), new_id(), bid, r),
				Bidder::Existing(para_id) => (None, para_id, bid, r),
			}
		}).collect::<Vec<_>>()
	}
}

/// tests for this module
#[cfg(test)]
mod tests {
	use super::*;
943
	use std::{collections::HashMap, cell::RefCell};
Gavin Wood's avatar
Gavin Wood committed
944

945
	use sp_core::H256;
946
	use sp_runtime::traits::{BlakeTwo256, Hash, IdentityLookup};
947
	use frame_support::{
948
		parameter_types, assert_ok, assert_noop,
949
		traits::{OnInitialize, OnFinalize}
Gavin Wood's avatar
Gavin Wood committed
950
	};
951
	use pallet_balances;
952
	use primitives::v1::{BlockNumber, Header, Id as ParaId};
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
	use crate::slots;

	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
	type Block = frame_system::mocking::MockBlock<Test>;

	frame_support::construct_runtime!(
		pub enum Test where
			Block = Block,
			NodeBlock = Block,
			UncheckedExtrinsic = UncheckedExtrinsic,
		{
			System: frame_system::{Module, Call, Config, Storage, Event<T>},
			Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},
			Slots: slots::{Module, Call, Storage, Event<T>},
	 		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},
		}
	);
Gavin Wood's avatar
Gavin Wood committed
970

971
	parameter_types! {
972
		pub const BlockHashCount: u32 = 250;
973
	}
974
	impl frame_system::Config for Test {
975
		type BaseCallFilter = ();
976
977
978
		type BlockWeights = ();
		type BlockLength = ();
		type DbWeight = ();
Gavin Wood's avatar
Gavin Wood committed
979
		type Origin = Origin;
980
		type Call = Call;
Gavin Wood's avatar
Gavin Wood committed
981
		type Index = u64;
982
		type BlockNumber = BlockNumber;
Gavin Wood's avatar
Gavin Wood committed
983
984
985
986
987
		type Hash = H256;
		type Hashing = BlakeTwo256;
		type AccountId = u64;
		type Lookup = IdentityLookup<Self::AccountId>;
		type Header = Header;
988
		type Event = Event;
989
		type BlockHashCount = BlockHashCount;
990
		type Version = ();
991
		type PalletInfo = PalletInfo;
992
		type AccountData = pallet_balances::AccountData<u64>;
Gavin Wood's avatar
Gavin Wood committed
993
		type OnNewAccount = ();
994
		type OnKilledAccount = ();
995
		type SystemWeightInfo = ();
996
		type SS58Prefix = ();
Gavin Wood's avatar
Gavin Wood committed
997
998
	}

Gavin Wood's avatar
Gavin Wood committed
999
	parameter_types! {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1000
		pub const ExistentialDeposit: u64 = 1;
Gavin Wood's avatar
Gavin Wood committed
1001
1002
	}

1003
	impl pallet_balances::Config for Test {
Gavin Wood's avatar
Gavin Wood committed
1004
		type Balance = u64;
1005
		type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
1006
		type DustRemoval = ();
Gavin Wood's avatar
Gavin Wood committed
1007
		type ExistentialDeposit = ExistentialDeposit;
1008
		type AccountStore = System;
1009
		type MaxLocks = ();
1010
		type WeightInfo = ();
Gavin Wood's avatar
Gavin Wood committed
1011
1012
1013
1014
1015
	}

	thread_local! {
		pub static PARACHAIN_COUNT: RefCell<u32> = RefCell::new(0);
		pub static PARACHAINS:
1016
			RefCell<HashMap<u32, (ValidationCode, HeadData)>> = RefCell::new(HashMap::new());
Gavin Wood's avatar
Gavin Wood committed
1017
1018
	}

1019
1020
1021
	const MAX_CODE_SIZE: u32 = 100;
	const MAX_HEAD_DATA_SIZE: u32 = 10;

Gavin Wood's avatar
Gavin Wood committed
1022
	pub struct TestParachains;
1023
1024
	impl Registrar<u64> for TestParachains {
		fn new_id() -> ParaId {
Gavin Wood's avatar
Gavin Wood committed
1025
1026
1027
1028
1029
			PARACHAIN_COUNT.with(|p| {
				*p.borrow_mut() += 1;
				(*p.borrow() - 1).into()
			})
		}
1030
1031
1032
1033
1034
1035
1036
1037
1038

		fn head_data_size_allowed(head_data_size: u32) -> bool {
			head_data_size <= MAX_HEAD_DATA_SIZE
		}

		fn code_size_allowed(code_size: u32) -> bool {
			code_size <= MAX_CODE_SIZE
		}

1039
1040
		fn register_para(
			id: ParaId,
1041
			_parachain: bool,
1042
1043
			code: ValidationCode,
			initial_head_data: HeadData,
1044
		) -> DispatchResult {
Gavin Wood's avatar
Gavin Wood committed
1045
			PARACHAINS.with(|p| {
1046
				if p.borrow().contains_key(&id.into()) {
Gavin Wood's avatar
Gavin Wood committed
1047
1048
					panic!("ID already exists")
				}
1049
				p.borrow_mut().insert(id.into(), (code, initial_head_data));
Gavin Wood's avatar
Gavin Wood committed
1050
1051
1052
				Ok(())
			})
		}
1053
		fn deregister_para(id: ParaId) -> DispatchResult {
Gavin Wood's avatar
Gavin Wood committed
1054
			PARACHAINS.with(|p| {
1055
				if !p.borrow().contains_key(&id.into()) {
Gavin Wood's avatar
Gavin Wood committed
1056
1057
					panic!("ID doesn't exist")
				}
1058
				p.borrow_mut().remove(&id.into());
Gavin Wood's avatar
Gavin Wood committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
				Ok(())
			})
		}
	}

	fn reset_count() {
		PARACHAIN_COUNT.with(|p| *p.borrow_mut() = 0);
	}

1068
	fn with_parachains<T>(f: impl FnOnce(&HashMap<u32, (ValidationCode, HeadData)>) -> T) -> T {
Gavin Wood's avatar
Gavin Wood committed
1069
1070
1071
1072
		PARACHAINS.with(|p| f(&*p.borrow()))
	}

	parameter_types!{
1073
1074
		pub const LeasePeriod: BlockNumber = 10;
		pub const EndingPeriod: BlockNumber = 3;
Gavin Wood's avatar
Gavin Wood committed
1075
1076
	}

1077
	impl Config for Test {
1078
		type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
1079
1080
1081
1082
		type Currency = Balances;
		type Parachains = TestParachains;
		type LeasePeriod = LeasePeriod;
		type EndingPeriod = EndingPeriod;
1083
		type Randomness = RandomnessCollectiveFlip;
Gavin Wood's avatar
Gavin Wood committed
1084
1085
1086
1087
	}

	// This function basically just builds a genesis storage key/value store according to
	// our desired mock up.
1088
	fn new_test_ext() -> sp_io::TestExternalities {
1089
1090
		let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
		pallet_balances::GenesisConfig::<Test>{
Gavin Wood's avatar
Gavin Wood committed
1091
			balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)],
1092
		}.assimilate_storage(&mut t).unwrap();
Gavin Wood's avatar
Gavin Wood committed
1093
1094
1095
		t.into()
	}

1096
	fn run_to_block(n: BlockNumber) {
Gavin Wood's avatar
Gavin Wood committed
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
		while System::block_number() < n {
			Slots::on_finalize(System::block_number());
			Balances::on_finalize(System::block_number());
			System::on_finalize(System::block_number());
			System::set_block_number(System::block_number() + 1);
			System::on_initialize(System::block_number());
			Balances::on_initialize(System::block_number());
			Slots::on_initialize(System::block_number());
		}
	}

	#[test]
	fn basic_setup_works() {
1110
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
			assert_eq!(Slots::auction_counter(), 0);
			assert_eq!(Slots::deposit_held(&0u32.into()), 0);
			assert_eq!(Slots::is_in_progress(), false);
			assert_eq!(Slots::is_ending(System::block_number()), None);

			run_to_block(10);

			assert_eq!(Slots::auction_counter(), 0);
			assert_eq!(Slots::deposit_held(&0u32.into()), 0);
			assert_eq!(Slots::is_in_progress(), false);
			assert_eq!(Slots::is_ending(System::block_number()), None);
		});
	}

	#[test]
	fn can_start_auction() {
1127
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1128
1129
			run_to_block(1);

1130
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
Gavin Wood's avatar
Gavin Wood committed
1131
1132
1133
1134
1135
1136
1137
1138
1139

			assert_eq!(Slots::auction_counter(), 1);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), None);
		});
	}

	#[test]
	fn auction_proceeds_correctly() {
1140
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1141
1142
			run_to_block(1);

1143
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
Gavin Wood's avatar
Gavin Wood committed
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184

			assert_eq!(Slots::auction_counter(), 1);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), None);

			run_to_block(2);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), None);

			run_to_block(3);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), None);

			run_to_block(4);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), None);

			run_to_block(5);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), None);

			run_to_block(6);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), Some(0));

			run_to_block(7);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), Some(1));

			run_to_block(8);
			assert_eq!(Slots::is_in_progress(), true);
			assert_eq!(Slots::is_ending(System::block_number()), Some(2));

			run_to_block(9);
			assert_eq!(Slots::is_in_progress(), false);
			assert_eq!(Slots::is_ending(System::block_number()), None);
		});
	}

	#[test]
	fn can_win_auction() {
1185
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1186
1187
			run_to_block(1);

1188
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
Gavin Wood's avatar
Gavin Wood committed
1189
			assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 1));
Gavin Wood's avatar
Gavin Wood committed
1190
1191
			assert_eq!(Balances::reserved_balance(1), 1);
			assert_eq!(Balances::free_balance(1), 9);
Gavin Wood's avatar
Gavin Wood committed
1192
1193
1194

			run_to_block(9);
			assert_eq!(Slots::onboard_queue(1), vec![0.into()]);
thiolliere's avatar
thiolliere committed
1195
			assert_eq!(Slots::onboarding(ParaId::from(0)),
Gavin Wood's avatar
Gavin Wood committed
1196
1197
1198
				Some((1, IncomingParachain::Unset(NewBidder { who: 1, sub: 0 })))
			);
			assert_eq!(Slots::deposit_held(&0.into()), 1);
Gavin Wood's avatar
Gavin Wood committed
1199
1200
			assert_eq!(Balances::reserved_balance(1), 0);
			assert_eq!(Balances::free_balance(1), 9);
Gavin Wood's avatar
Gavin Wood committed
1201
1202
1203
1204
1205
		});
	}

	#[test]
	fn offboarding_works() {
1206
		new_test_ext().execute_with(|| {
1207
			run_to_block(1);
1208
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
1209
			assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 1));
Gavin Wood's avatar
Gavin Wood committed
1210
			assert_eq!(Balances::free_balance(1), 9);
1211
1212
1213

			run_to_block(9);
			assert_eq!(Slots::deposit_held(&0.into()), 1);
thiolliere's avatar
thiolliere committed
1214
			assert_eq!(Slots::deposits(ParaId::from(0))[0], 0);
1215
1216
1217

			run_to_block(50);
			assert_eq!(Slots::deposit_held(&0.into()), 0);
Gavin Wood's avatar
Gavin Wood committed
1218
			assert_eq!(Balances::free_balance(1), 10);
1219
1220
1221
1222
1223
		});
	}

	#[test]
	fn set_offboarding_works() {
1224
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1225
			run_to_block(1);
1226
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
Gavin Wood's avatar
Gavin Wood committed
1227
1228
1229
1230
			assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 1));

			run_to_block(9);
			assert_eq!(Slots::deposit_held(&0.into()), 1);
thiolliere's avatar
thiolliere committed
1231
			assert_eq!(Slots::deposits(ParaId::from(0))[0], 0);
Gavin Wood's avatar
Gavin Wood committed
1232
1233
1234
1235
1236
1237
1238

			run_to_block(49);
			assert_eq!(Slots::deposit_held(&0.into()), 1);
			assert_ok!(Slots::set_offboarding(Origin::signed(ParaId::from(0).into_account()), 10));

			run_to_block(50);
			assert_eq!(Slots::deposit_held(&0.into()), 0);
Gavin Wood's avatar
Gavin Wood committed
1239
			assert_eq!(Balances::free_balance(10), 1);
Gavin Wood's avatar
Gavin Wood committed
1240
1241
1242
1243
1244
		});
	}

	#[test]
	fn onboarding_works() {
1245
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1246
			run_to_block(1);
1247
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
Gavin Wood's avatar
Gavin Wood committed
1248
1249
1250
1251
			assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 1));

			run_to_block(9);
			let h = BlakeTwo256::hash(&[42u8][..]);
1252
1253
			assert_ok!(Slots::fix_deploy_data(Origin::signed(1), 0, 0.into(), h, 1, vec![69].into()));
			assert_ok!(Slots::elaborate_deploy_data(Origin::signed(0), 0.into(), vec![42].into()));
Gavin Wood's avatar
Gavin Wood committed
1254
1255
1256
1257

			run_to_block(10);
			with_parachains(|p| {
				assert_eq!(p.len(), 1);
1258
				assert_eq!(p[&0], (vec![42].into(), vec![69].into()));
Gavin Wood's avatar
Gavin Wood committed
1259
1260
1261
1262
1263
1264
			});
		});
	}

	#[test]
	fn late_onboarding_works() {
1265
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1266
			run_to_block(1);
1267
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
Gavin Wood's avatar
Gavin Wood committed
1268
1269
1270
1271
1272
1273
1274
1275
1276
			assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 1));

			run_to_block(10);
			with_parachains(|p| {
				assert_eq!(p.len(), 0);
			});

			run_to_block(11);
			let h = BlakeTwo256::hash(&[42u8][..]);
1277
1278
			assert_ok!(Slots::fix_deploy_data(Origin::signed(1), 0, 0.into(), h, 1, vec![69].into()));
			assert_ok!(Slots::elaborate_deploy_data(Origin::signed(0), 0.into(), vec![42].into()));
Gavin Wood's avatar
Gavin Wood committed
1279
1280
			with_parachains(|p| {
				assert_eq!(p.len(), 1);
1281
				assert_eq!(p[&0], (vec![42].into(), vec![69].into()));
Gavin Wood's avatar
Gavin Wood committed
1282
1283
1284
1285
1286
1287
			});
		});
	}

	#[test]
	fn under_bidding_works() {
1288
		new_test_ext().execute_with(|| {
Gavin Wood's avatar
Gavin Wood committed
1289
			run_to_block(1);
1290
			assert_ok!(Slots::new_auction(Origin::root(), 5, 1));
Gavin Wood's avatar
Gavin Wood committed
1291
1292
			assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 5));
			assert_ok!(Slots::bid(Origin::signed(2), 0, 1, 1, 4, 1));
Gavin Wood's avatar
Gavin Wood committed
1293
1294
			assert_eq!(Balances::reserved_balance(2), 0);
			assert_eq!(Balances::free_balance(2), 20);
Gavin Wood's avatar
Gavin Wood committed
1295
1296
1297
1298
1299