12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970#![cfg_attr(not(feature = "std"), no_std)]7172#[cfg(feature = "runtime-benchmarks")]73mod benchmarking;7475pub mod weights;7677use sp_core::H160;78use codec::{Codec, Decode, Encode};79use frame_system::{self as system, ensure_signed};80pub use pallet::*;81use scale_info::TypeInfo;82use sp_runtime::{83 traits::{BadOrigin, One, Saturating, Zero},84 RuntimeDebug, DispatchErrorWithPostInfo,85};86use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};8788use frame_support::{89 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{GetDispatchInfo, Weight},96};9798pub use weights::WeightInfo;99100101pub type PeriodicIndex = u32;102103pub type TaskAddress<BlockNumber> = (BlockNumber, u32);104pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;105106type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];107pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;108109110#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]111#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]112pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {113 114 maybe_id: Option<ScheduledId>,115 116 priority: schedule::Priority,117 118 call: Call,119 120 maybe_periodic: Option<schedule::Period<BlockNumber>>,121 122 origin: PalletsOrigin,123 _phantom: PhantomData<AccountId>,124}125126pub type ScheduledV3Of<T> = ScheduledV3<127 CallOrHashOf<T>,128 <T as frame_system::Config>::BlockNumber,129 <T as Config>::PalletsOrigin,130 <T as frame_system::Config>::AccountId,131>;132133pub type ScheduledOf<T> = ScheduledV3Of<T>;134135136pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =137 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;138139#[cfg(feature = "runtime-benchmarks")]140mod preimage_provider {141 use frame_support::traits::PreimageRecipient;142 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}143 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}144}145146#[cfg(not(feature = "runtime-benchmarks"))]147mod preimage_provider {148 use frame_support::traits::PreimageProvider;149 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}150 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}151}152153pub use preimage_provider::PreimageProviderAndMaybeRecipient;154155pub(crate) trait MarginalWeightInfo: WeightInfo {156 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {157 match (periodic, named, resolved) {158 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),159 (_, true, None) => {160 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)161 }162 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),163 (false, true, Some(false)) => {164 Self::on_initialize_named(2) - Self::on_initialize_named(1)165 }166 (true, false, Some(false)) => {167 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)168 }169 (true, true, Some(false)) => {170 Self::on_initialize_periodic_named_resolved(2)171 - Self::on_initialize_periodic_named_resolved(1)172 }173 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),174 (false, true, Some(true)) => {175 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)176 }177 (true, false, Some(true)) => {178 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)179 }180 (true, true, Some(true)) => {181 Self::on_initialize_periodic_named_resolved(2)182 - Self::on_initialize_periodic_named_resolved(1)183 }184 }185 }186}187impl<T: WeightInfo> MarginalWeightInfo for T {}188189#[frame_support::pallet]190pub mod pallet {191 use super::*;192 use frame_support::{193 dispatch::PostDispatchInfo,194 pallet_prelude::*,195 traits::{schedule::LookupError, PreimageProvider},196 };197 use frame_system::pallet_prelude::*;198199 200 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);201202 #[pallet::pallet]203 #[pallet::generate_store(pub(super) trait Store)]204 #[pallet::storage_version(STORAGE_VERSION)]205 #[pallet::without_storage_info]206 pub struct Pallet<T>(_);207208 209 #[pallet::config]210 pub trait Config: frame_system::Config {211 212 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;213214 215 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>216 + From<Self::PalletsOrigin>217 + IsType<<Self as system::Config>::Origin>;218219 220 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;221222 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;223224 225 type Call: Parameter226 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>227 + GetDispatchInfo228 + From<system::Call<Self>>;229230 231 232 #[pallet::constant]233 type MaximumWeight: Get<Weight>;234235 236 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;237238 239 240 241 242 243 244 245 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;246247 248 249 #[pallet::constant]250 type MaxScheduledPerBlock: Get<u32>;251252 253 type WeightInfo: WeightInfo;254255 256 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;257258 259 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;260261 262 263264 265 type CallExecutor: DispatchCall<Self, H160>;266 }267268 269 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {270 271 fn reserve_balance(272 id: ScheduledId,273 sponsor: <T as frame_system::Config>::AccountId,274 call: <T as Config>::Call,275 count: u32,276 ) -> Result<(), DispatchError>;277278 279 fn pay_for_call(280 id: ScheduledId,281 sponsor: <T as frame_system::Config>::AccountId,282 call: <T as Config>::Call,283 ) -> Result<u128, DispatchError>;284285 286 fn dispatch_call(287 signer: T::AccountId,288 function: <T as Config>::Call,289 ) -> Result<290 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,291 TransactionValidityError,292 >;293294 295 fn cancel_reserve(296 id: ScheduledId,297 sponsor: <T as frame_system::Config>::AccountId,298 ) -> Result<u128, DispatchError>;299 }300301 302 #[pallet::storage]303 pub type Agenda<T: Config> =304 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;305306 307 #[pallet::storage]308 pub(crate) type Lookup<T: Config> =309 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;310311 312 #[pallet::event]313 #[pallet::generate_deposit(pub(super) fn deposit_event)]314 pub enum Event<T: Config> {315 316 Scheduled { when: T::BlockNumber, index: u32 },317 318 Canceled { when: T::BlockNumber, index: u32 },319 320 Dispatched {321 task: TaskAddress<T::BlockNumber>,322 id: Option<ScheduledId>,323 result: DispatchResult,324 },325 326 CallLookupFailed {327 task: TaskAddress<T::BlockNumber>,328 id: Option<ScheduledId>,329 error: LookupError,330 },331 }332333 #[pallet::error]334 pub enum Error<T> {335 336 FailedToSchedule,337 338 NotFound,339 340 TargetBlockNumberInPast,341 342 RescheduleNoChange,343 }344345 #[pallet::hooks]346 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {347 348 fn on_initialize(now: T::BlockNumber) -> Weight {349 let limit = T::MaximumWeight::get();350351 let mut queued = Agenda::<T>::take(now)352 .into_iter()353 .enumerate()354 .filter_map(|(index, s)| Some((index as u32, s?)))355 .collect::<Vec<_>>();356357 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {358 log::warn!(359 target: "runtime::scheduler",360 "Warning: This block has more items queued in Scheduler than \361 expected from the runtime configuration. An update might be needed."362 );363 }364365 queued.sort_by_key(|(_, s)| s.priority);366367 let next = now + One::one();368369 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);370 for (order, (index, mut s)) in queued.into_iter().enumerate() {371 let named = if let Some(ref id) = s.maybe_id {372 Lookup::<T>::remove(id);373 true374 } else {375 false376 };377378 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();379 s.call = call;380381 let resolved = if let Some(completed) = maybe_completed {382 T::PreimageProvider::unrequest_preimage(&completed);383 true384 } else {385 false386 };387 let call = match s.call.as_value().cloned() {388 Some(c) => c,389 None => {390 391 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));392 if let Some(delay) = T::NoPreimagePostponement::get() {393 let until = now.saturating_add(delay);394 if let Some(ref id) = s.maybe_id {395 let index = Agenda::<T>::decode_len(until).unwrap_or(0);396 Lookup::<T>::insert(id, (until, index as u32));397 }398 Agenda::<T>::append(until, Some(s));399 }400 continue;401 }402 };403404 let periodic = s.maybe_periodic.is_some();405 let call_weight = call.get_dispatch_info().weight;406 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));407 let origin =408 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())409 .into();410 if ensure_signed(origin).is_ok() {411 412 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));413 }414415 416 417 418 419 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;420 let test_weight = total_weight421 .saturating_add(call_weight)422 .saturating_add(item_weight);423 if !hard_deadline && order > 0 && test_weight > limit {424 425 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));426 if let Some(ref id) = s.maybe_id {427 428 429 430 431 let index = Agenda::<T>::decode_len(next).unwrap_or(0);432 Lookup::<T>::insert(id, (next, index as u32));433 }434 Agenda::<T>::append(next, Some(s));435 continue;436 }437438 let sender = ensure_signed(439 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())440 .into(),441 )442 .unwrap();443444 445 446 447 448 449 450 451 452453 454 455 let r = T::CallExecutor::dispatch_call(sender, call.clone());456457 let mut actual_call_weight: Weight = item_weight;458 let result: Result<_, DispatchError> = match r {459 Ok(o) => match o {460 Ok(di) => {461 actual_call_weight = di.actual_weight.unwrap_or(item_weight);462 Ok(())463 }464 Err(err) => Err(err.error),465 },466 Err(_) => {467 log::error!(468 target: "runtime::scheduler",469 "Warning: Scheduler has failed to execute a post-dispatch transaction. \470 This block might have become invalid.");471 Err(DispatchError::CannotLookup)472 } 473 };474475 total_weight.saturating_accrue(item_weight);476 total_weight.saturating_accrue(actual_call_weight);477478 Self::deposit_event(Event::Dispatched {479 task: (now, index),480 id: s.maybe_id.clone(),481 result,482 });483484 if let &Some((period, count)) = &s.maybe_periodic {485 if count > 1 {486 s.maybe_periodic = Some((period, count - 1));487 } else {488 s.maybe_periodic = None;489 }490 let wake = now + period;491 492 if let Some(ref id) = s.maybe_id {493 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);494 Lookup::<T>::insert(id, (wake, wake_index as u32));495 }496 Agenda::<T>::append(wake, Some(s));497 }498 }499 500 Weight::zero()501 }502 }503504 #[pallet::call]505 impl<T: Config> Pallet<T> {506 507 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]508 pub fn schedule_named(509 origin: OriginFor<T>,510 id: ScheduledId,511 when: T::BlockNumber,512 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,513 priority: schedule::Priority,514 call: Box<CallOrHashOf<T>>,515 ) -> DispatchResult {516 T::ScheduleOrigin::ensure_origin(origin.clone())?;517 let origin = <T as Config>::Origin::from(origin);518 Self::do_schedule_named(519 id,520 DispatchTime::At(when),521 maybe_periodic,522 priority,523 origin.caller().clone(),524 *call,525 )?;526 Ok(())527 }528529 530 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]531 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {532 T::ScheduleOrigin::ensure_origin(origin.clone())?;533 let origin = <T as Config>::Origin::from(origin);534 Self::do_cancel_named(Some(origin.caller().clone()), id)?;535 Ok(())536 }537538 539 540 541 542 543 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]544 pub fn schedule_named_after(545 origin: OriginFor<T>,546 id: ScheduledId,547 after: T::BlockNumber,548 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,549 priority: schedule::Priority,550 call: Box<CallOrHashOf<T>>,551 ) -> DispatchResult {552 T::ScheduleOrigin::ensure_origin(origin.clone())?;553 let origin = <T as Config>::Origin::from(origin);554 Self::do_schedule_named(555 id,556 DispatchTime::After(after),557 maybe_periodic,558 priority,559 origin.caller().clone(),560 *call,561 )?;562 Ok(())563 }564 }565}566567impl<T: Config> Pallet<T> {568 #[cfg(feature = "try-runtime")]569 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {570 Ok(())571 }572573 #[cfg(feature = "try-runtime")]574 pub fn post_migrate_to_v3() -> Result<(), &'static str> {575 use frame_support::dispatch::GetStorageVersion;576577 assert!(Self::current_storage_version() == 3);578 for k in Agenda::<T>::iter_keys() {579 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;580 }581 Ok(())582 }583584 585 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {586 Agenda::<T>::translate::<587 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,588 _,589 >(|_, agenda| {590 Some(591 agenda592 .into_iter()593 .map(|schedule| {594 schedule.map(|schedule| Scheduled {595 maybe_id: schedule.maybe_id,596 priority: schedule.priority,597 call: schedule.call,598 maybe_periodic: schedule.maybe_periodic,599 origin: schedule.origin.into(),600 _phantom: Default::default(),601 })602 })603 .collect::<Vec<_>>(),604 )605 });606 }607608 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {609 let now = frame_system::Pallet::<T>::block_number();610611 let when = match when {612 DispatchTime::At(x) => x,613 614 615 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),616 };617618 if when <= now {619 return Err(Error::<T>::TargetBlockNumberInPast.into());620 }621622 Ok(when)623 }624625 fn do_schedule_named(626 id: ScheduledId,627 when: DispatchTime<T::BlockNumber>,628 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,629 priority: schedule::Priority,630 origin: T::PalletsOrigin,631 call: CallOrHashOf<T>,632 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {633 634 if Lookup::<T>::contains_key(&id) {635 return Err(Error::<T>::FailedToSchedule)?;636 }637638 let when = Self::resolve_time(when)?;639640 call.ensure_requested::<T::PreimageProvider>();641642 643 let maybe_periodic = maybe_periodic644 .filter(|p| p.1 > 1 && !p.0.is_zero())645 646 .map(|(p, c)| (p, c - 1));647648 let s = Scheduled {649 maybe_id: Some(id.clone()),650 priority,651 call: call.clone(),652 maybe_periodic,653 origin: origin.clone(),654 _phantom: Default::default(),655 };656657 658 659 660 661 662 663 664 665 666 667 668 669 670671 Agenda::<T>::append(when, Some(s));672 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;673 let address = (when, index);674 Lookup::<T>::insert(&id, &address);675 Self::deposit_event(Event::Scheduled { when, index });676677 Ok(address)678 }679680 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {681 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {682 if let Some((when, index)) = lookup.take() {683 let i = index as usize;684 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {685 if let Some(s) = agenda.get_mut(i) {686 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {687 if matches!(688 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),689 Some(Ordering::Less) | None690 ) {691 return Err(BadOrigin.into());692 }693 694 695 696 697 698 699 700 701702 s.call.ensure_unrequested::<T::PreimageProvider>();703 }704 *s = None;705 }706 Ok(())707 })?;708709 Self::deposit_event(Event::Canceled { when, index });710 Ok(())711 } else {712 Err(Error::<T>::NotFound)?713 }714 })715 }716}