polkadot_runtime_parachains/coretime/
mod.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Extrinsics implementing the relay chain side of the Coretime interface.
18//!
19//! <https://github.com/polkadot-fellows/RFCs/blob/main/text/0005-coretime-interface.md>
20
21use alloc::{vec, vec::Vec};
22use core::result;
23use frame_support::{
24	pallet_prelude::*,
25	traits::{defensive_prelude::*, Currency},
26};
27use frame_system::pallet_prelude::*;
28pub use pallet::*;
29use pallet_broker::{CoreAssignment, CoreIndex as BrokerCoreIndex};
30use polkadot_primitives::{Balance, BlockNumber, CoreIndex, Id as ParaId};
31use sp_arithmetic::traits::SaturatedConversion;
32use sp_runtime::traits::TryConvert;
33use xcm::prelude::*;
34use xcm_executor::traits::TransactAsset;
35
36use crate::{
37	assigner_coretime::{self, PartsOf57600},
38	initializer::{OnNewSession, SessionChangeNotification},
39	on_demand,
40	origin::{ensure_parachain, Origin},
41};
42
43mod benchmarking;
44pub mod migration;
45
46const LOG_TARGET: &str = "runtime::parachains::coretime";
47
48pub trait WeightInfo {
49	fn request_core_count() -> Weight;
50	fn request_revenue_at() -> Weight;
51	//fn credit_account() -> Weight;
52	fn assign_core(s: u32) -> Weight;
53}
54
55/// A weight info that is only suitable for testing.
56pub struct TestWeightInfo;
57
58impl WeightInfo for TestWeightInfo {
59	fn request_core_count() -> Weight {
60		Weight::MAX
61	}
62	fn request_revenue_at() -> Weight {
63		Weight::MAX
64	}
65	// TODO: Add real benchmarking functionality for each of these to
66	// benchmarking.rs, then uncomment here and in trait definition.
67	//fn credit_account() -> Weight {
68	//	Weight::MAX
69	//}
70	fn assign_core(_s: u32) -> Weight {
71		Weight::MAX
72	}
73}
74
75/// Shorthand for the Balance type the runtime is using.
76pub type BalanceOf<T> =
77	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
78
79/// Broker pallet index on the coretime chain. Used to
80///
81/// construct remote calls. The codec index must correspond to the index of `Broker` in the
82/// `construct_runtime` of the coretime chain.
83#[derive(Encode, Decode)]
84enum BrokerRuntimePallets {
85	#[codec(index = 50)]
86	Broker(CoretimeCalls),
87}
88
89/// Call encoding for the calls needed from the Broker pallet.
90#[derive(Encode, Decode)]
91enum CoretimeCalls {
92	#[codec(index = 1)]
93	Reserve(pallet_broker::Schedule),
94	#[codec(index = 3)]
95	SetLease(pallet_broker::TaskId, pallet_broker::Timeslice),
96	#[codec(index = 19)]
97	NotifyCoreCount(u16),
98	#[codec(index = 20)]
99	NotifyRevenue((BlockNumber, Balance)),
100	#[codec(index = 99)]
101	SwapLeases(ParaId, ParaId),
102}
103
104#[frame_support::pallet]
105pub mod pallet {
106
107	use crate::configuration;
108	use sp_runtime::traits::TryConvert;
109	use xcm::latest::InteriorLocation;
110	use xcm_executor::traits::TransactAsset;
111
112	use super::*;
113
114	#[pallet::pallet]
115	#[pallet::without_storage_info]
116	pub struct Pallet<T>(_);
117
118	#[pallet::config]
119	pub trait Config: frame_system::Config + assigner_coretime::Config + on_demand::Config {
120		type RuntimeOrigin: From<<Self as frame_system::Config>::RuntimeOrigin>
121			+ Into<result::Result<Origin, <Self as Config>::RuntimeOrigin>>;
122		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
123		/// The runtime's definition of a Currency.
124		type Currency: Currency<Self::AccountId>;
125		/// The ParaId of the coretime chain.
126		#[pallet::constant]
127		type BrokerId: Get<u32>;
128		/// The coretime chain pot location.
129		#[pallet::constant]
130		type BrokerPotLocation: Get<InteriorLocation>;
131		/// Something that provides the weight of this pallet.
132		type WeightInfo: WeightInfo;
133		/// The XCM sender.
134		type SendXcm: SendXcm;
135		/// The asset transactor.
136		type AssetTransactor: TransactAsset;
137		/// AccountId to Location converter
138		type AccountToLocation: for<'a> TryConvert<&'a Self::AccountId, Location>;
139
140		/// Maximum weight for any XCM transact call that should be executed on the coretime chain.
141		///
142		/// Basically should be `max_weight(set_leases, reserve, notify_core_count)`.
143		type MaxXcmTransactWeight: Get<Weight>;
144	}
145
146	#[pallet::event]
147	#[pallet::generate_deposit(pub(super) fn deposit_event)]
148	pub enum Event<T: Config> {
149		/// The broker chain has asked for revenue information for a specific block.
150		RevenueInfoRequested { when: BlockNumberFor<T> },
151		/// A core has received a new assignment from the broker chain.
152		CoreAssigned { core: CoreIndex },
153	}
154
155	#[pallet::error]
156	pub enum Error<T> {
157		/// The paraid making the call is not the coretime brokerage system parachain.
158		NotBroker,
159		/// Requested revenue information `when` parameter was in the future from the current
160		/// block height.
161		RequestedFutureRevenue,
162		/// Failed to transfer assets to the coretime chain
163		AssetTransferFailed,
164	}
165
166	#[pallet::hooks]
167	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
168
169	#[pallet::call]
170	impl<T: Config> Pallet<T> {
171		/// Request the configuration to be updated with the specified number of cores. Warning:
172		/// Since this only schedules a configuration update, it takes two sessions to come into
173		/// effect.
174		///
175		/// - `origin`: Root or the Coretime Chain
176		/// - `count`: total number of cores
177		#[pallet::weight(<T as Config>::WeightInfo::request_core_count())]
178		#[pallet::call_index(1)]
179		pub fn request_core_count(origin: OriginFor<T>, count: u16) -> DispatchResult {
180			// Ignore requests not coming from the coretime chain or root.
181			Self::ensure_root_or_para(origin, <T as Config>::BrokerId::get().into())?;
182
183			configuration::Pallet::<T>::set_coretime_cores_unchecked(u32::from(count))
184		}
185
186		/// Request to claim the instantaneous coretime sales revenue starting from the block it was
187		/// last claimed until and up to the block specified. The claimed amount value is sent back
188		/// to the Coretime chain in a `notify_revenue` message. At the same time, the amount is
189		/// teleported to the Coretime chain.
190		#[pallet::weight(<T as Config>::WeightInfo::request_revenue_at())]
191		#[pallet::call_index(2)]
192		pub fn request_revenue_at(origin: OriginFor<T>, when: BlockNumber) -> DispatchResult {
193			// Ignore requests not coming from the Coretime Chain or Root.
194			Self::ensure_root_or_para(origin, <T as Config>::BrokerId::get().into())?;
195			Self::notify_revenue(when)
196		}
197
198		//// TODO Impl me!
199		////#[pallet::weight(<T as Config>::WeightInfo::credit_account())]
200		//#[pallet::call_index(3)]
201		//pub fn credit_account(
202		//	origin: OriginFor<T>,
203		//	_who: T::AccountId,
204		//	_amount: BalanceOf<T>,
205		//) -> DispatchResult {
206		//	// Ignore requests not coming from the coretime chain or root.
207		//	Self::ensure_root_or_para(origin, <T as Config>::BrokerId::get().into())?;
208		//	Ok(())
209		//}
210
211		/// Receive instructions from the `ExternalBrokerOrigin`, detailing how a specific core is
212		/// to be used.
213		///
214		/// Parameters:
215		/// -`origin`: The `ExternalBrokerOrigin`, assumed to be the coretime chain.
216		/// -`core`: The core that should be scheduled.
217		/// -`begin`: The starting blockheight of the instruction.
218		/// -`assignment`: How the blockspace should be utilised.
219		/// -`end_hint`: An optional hint as to when this particular set of instructions will end.
220		// The broker pallet's `CoreIndex` definition is `u16` but on the relay chain it's `struct
221		// CoreIndex(u32)`
222		#[pallet::call_index(4)]
223		#[pallet::weight(<T as Config>::WeightInfo::assign_core(assignment.len() as u32))]
224		pub fn assign_core(
225			origin: OriginFor<T>,
226			core: BrokerCoreIndex,
227			begin: BlockNumberFor<T>,
228			assignment: Vec<(CoreAssignment, PartsOf57600)>,
229			end_hint: Option<BlockNumberFor<T>>,
230		) -> DispatchResult {
231			// Ignore requests not coming from the coretime chain or root.
232			Self::ensure_root_or_para(origin, T::BrokerId::get().into())?;
233
234			let core = u32::from(core).into();
235
236			<assigner_coretime::Pallet<T>>::assign_core(core, begin, assignment, end_hint)?;
237			Self::deposit_event(Event::<T>::CoreAssigned { core });
238			Ok(())
239		}
240	}
241}
242
243impl<T: Config> Pallet<T> {
244	/// Ensure the origin is one of Root or the `para` itself.
245	fn ensure_root_or_para(
246		origin: <T as frame_system::Config>::RuntimeOrigin,
247		id: ParaId,
248	) -> DispatchResult {
249		if let Ok(caller_id) = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin.clone()))
250		{
251			// Check if matching para id...
252			ensure!(caller_id == id, Error::<T>::NotBroker);
253		} else {
254			// Check if root...
255			ensure_root(origin.clone())?;
256		}
257		Ok(())
258	}
259
260	pub fn initializer_on_new_session(notification: &SessionChangeNotification<BlockNumberFor<T>>) {
261		let old_core_count = notification.prev_config.scheduler_params.num_cores;
262		let new_core_count = notification.new_config.scheduler_params.num_cores;
263		if new_core_count != old_core_count {
264			let core_count: u16 = new_core_count.saturated_into();
265			let message = Xcm(vec![
266				Instruction::UnpaidExecution {
267					weight_limit: WeightLimit::Unlimited,
268					check_origin: None,
269				},
270				mk_coretime_call::<T>(crate::coretime::CoretimeCalls::NotifyCoreCount(core_count)),
271			]);
272			if let Err(err) = send_xcm::<T::SendXcm>(
273				Location::new(0, [Junction::Parachain(T::BrokerId::get())]),
274				message,
275			) {
276				log::error!(target: LOG_TARGET, "Sending `NotifyCoreCount` to coretime chain failed: {:?}", err);
277			}
278		}
279	}
280
281	/// Provide the amount of revenue accumulated from Instantaneous Coretime Sales from Relay-chain
282	/// block number last_until to until, not including until itself. last_until is defined as being
283	/// the until argument of the last notify_revenue message sent, or zero for the first call. If
284	/// revenue is None, this indicates that the information is no longer available. This explicitly
285	/// disregards the possibility of multiple parachains requesting and being notified of revenue
286	/// information.
287	///
288	/// The Relay-chain must be configured to ensure that only a single revenue information
289	/// destination exists.
290	pub fn notify_revenue(until: BlockNumber) -> DispatchResult {
291		let now = <frame_system::Pallet<T>>::block_number();
292		let until_bnf: BlockNumberFor<T> = until.into();
293
294		// When cannot be in the future.
295		ensure!(until_bnf <= now, Error::<T>::RequestedFutureRevenue);
296
297		let amount = <on_demand::Pallet<T>>::claim_revenue_until(until_bnf);
298		log::debug!(target: LOG_TARGET, "Revenue info requested: {:?}", amount);
299
300		let raw_revenue: Balance = amount.try_into().map_err(|_| {
301			log::error!(target: LOG_TARGET, "Converting on demand revenue for `NotifyRevenue` failed");
302			Error::<T>::AssetTransferFailed
303		})?;
304
305		do_notify_revenue::<T>(until, raw_revenue).map_err(|err| {
306			log::error!(target: LOG_TARGET, "notify_revenue failed: {err:?}");
307			Error::<T>::AssetTransferFailed
308		})?;
309
310		Ok(())
311	}
312
313	// Handle legacy swaps in coretime. Notifies coretime chain that a lease swap has occurred via
314	// XCM message. This function is meant to be used in an implementation of `OnSwap` trait.
315	pub fn on_legacy_lease_swap(one: ParaId, other: ParaId) {
316		let message = Xcm(vec![
317			Instruction::UnpaidExecution {
318				weight_limit: WeightLimit::Unlimited,
319				check_origin: None,
320			},
321			mk_coretime_call::<T>(crate::coretime::CoretimeCalls::SwapLeases(one, other)),
322		]);
323		if let Err(err) = send_xcm::<T::SendXcm>(
324			Location::new(0, [Junction::Parachain(T::BrokerId::get())]),
325			message,
326		) {
327			log::error!(target: LOG_TARGET, "Sending `SwapLeases` to coretime chain failed: {:?}", err);
328		}
329	}
330}
331
332impl<T: Config> OnNewSession<BlockNumberFor<T>> for Pallet<T> {
333	fn on_new_session(notification: &SessionChangeNotification<BlockNumberFor<T>>) {
334		Self::initializer_on_new_session(notification);
335	}
336}
337
338fn mk_coretime_call<T: Config>(call: crate::coretime::CoretimeCalls) -> Instruction<()> {
339	Instruction::Transact {
340		origin_kind: OriginKind::Superuser,
341		fallback_max_weight: Some(T::MaxXcmTransactWeight::get()),
342		call: BrokerRuntimePallets::Broker(call).encode().into(),
343	}
344}
345
346fn do_notify_revenue<T: Config>(when: BlockNumber, raw_revenue: Balance) -> Result<(), XcmError> {
347	let dest = Junction::Parachain(T::BrokerId::get()).into_location();
348	let mut message = vec![Instruction::UnpaidExecution {
349		weight_limit: WeightLimit::Unlimited,
350		check_origin: None,
351	}];
352	let asset = Asset { id: Location::here().into(), fun: Fungible(raw_revenue) };
353	let dummy_xcm_context = XcmContext { origin: None, message_id: [0; 32], topic: None };
354
355	if raw_revenue > 0 {
356		let on_demand_pot =
357			T::AccountToLocation::try_convert(&<on_demand::Pallet<T>>::account_id()).map_err(
358				|err| {
359					log::error!(
360						target: LOG_TARGET,
361						"Failed to convert on-demand pot account to XCM location: {err:?}",
362					);
363					XcmError::InvalidLocation
364				},
365			)?;
366
367		let withdrawn = T::AssetTransactor::withdraw_asset(&asset, &on_demand_pot, None)?;
368
369		T::AssetTransactor::can_check_out(&dest, &asset, &dummy_xcm_context)?;
370
371		let assets_reanchored = Into::<Assets>::into(withdrawn)
372			.reanchored(&dest, &Here.into())
373			.defensive_map_err(|_| XcmError::ReanchorFailed)?;
374
375		message.extend(
376			[
377				ReceiveTeleportedAsset(assets_reanchored),
378				DepositAsset {
379					assets: Wild(AllCounted(1)),
380					beneficiary: T::BrokerPotLocation::get().into_location(),
381				},
382			]
383			.into_iter(),
384		);
385	}
386
387	message.push(mk_coretime_call::<T>(CoretimeCalls::NotifyRevenue((when, raw_revenue))));
388
389	send_xcm::<T::SendXcm>(dest.clone(), Xcm(message))?;
390
391	if raw_revenue > 0 {
392		T::AssetTransactor::check_out(&dest, &asset, &dummy_xcm_context);
393	}
394
395	Ok(())
396}