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