polkadot_runtime_parachains/coretime/
mod.rs1use 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
55pub 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
73pub type BalanceOf<T> = <<T as on_demand::Config>::Currency as Currency<
75 <T as frame_system::Config>::AccountId,
76>>::Balance;
77
78#[derive(Encode, Decode)]
83enum BrokerRuntimePallets {
84 #[codec(index = 50)]
85 Broker(CoretimeCalls),
86}
87
88#[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 #[pallet::constant]
124 type BrokerId: Get<u32>;
125 #[pallet::constant]
127 type BrokerPotLocation: Get<InteriorLocation>;
128 type WeightInfo: WeightInfo;
130 type SendXcm: SendXcm;
132 type AssetTransactor: TransactAsset;
134 type AccountToLocation: for<'a> TryConvert<&'a Self::AccountId, Location>;
136
137 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 RevenueInfoRequested { when: BlockNumberFor<T> },
148 CoreAssigned { core: CoreIndex },
150 }
151
152 #[pallet::error]
153 pub enum Error<T> {
154 NotBroker,
156 RequestedFutureRevenue,
159 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 #[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 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 #[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 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 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 #[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 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 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 ensure!(caller_id == id, Error::<T>::NotBroker);
251 } else {
252 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 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 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 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}