12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#![cfg_attr(not(feature = "std"), no_std)]6263#[cfg(feature = "runtime-benchmarks")]64mod benchmarking;6566pub mod weights;6768use sp_core::H160;69use codec::{Codec, Decode, Encode};70use frame_system::{self as system, ensure_signed};71pub use pallet::*;72use scale_info::TypeInfo;73use sp_runtime::{74 traits::{BadOrigin, One, Saturating, Zero},75 RuntimeDebug, DispatchErrorWithPostInfo,76};77use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};7879use frame_support::{80 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},81 traits::{82 schedule::{self, DispatchTime, MaybeHashed},83 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,84 StorageVersion,85 },86 weights::{GetDispatchInfo, Weight},87};8889pub use weights::WeightInfo;909192pub type PeriodicIndex = u32;9394pub type TaskAddress<BlockNumber> = (BlockNumber, u32);95pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;9697type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];98pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;99100101#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]102#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]103pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {104 105 maybe_id: Option<ScheduledId>,106 107 priority: schedule::Priority,108 109 call: Call,110 111 maybe_periodic: Option<schedule::Period<BlockNumber>>,112 113 origin: PalletsOrigin,114 _phantom: PhantomData<AccountId>,115}116117pub type ScheduledV3Of<T> = ScheduledV3<118 CallOrHashOf<T>,119 <T as frame_system::Config>::BlockNumber,120 <T as Config>::PalletsOrigin,121 <T as frame_system::Config>::AccountId,122>;123124pub type ScheduledOf<T> = ScheduledV3Of<T>;125126127pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =128 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;129130#[cfg(feature = "runtime-benchmarks")]131mod preimage_provider {132 use frame_support::traits::PreimageRecipient;133 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}134 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}135}136137#[cfg(not(feature = "runtime-benchmarks"))]138mod preimage_provider {139 use frame_support::traits::PreimageProvider;140 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}141 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}142}143144pub use preimage_provider::PreimageProviderAndMaybeRecipient;145146pub(crate) trait MarginalWeightInfo: WeightInfo {147 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {148 match (periodic, named, resolved) {149 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),150 (_, true, None) => {151 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)152 }153 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),154 (false, true, Some(false)) => {155 Self::on_initialize_named(2) - Self::on_initialize_named(1)156 }157 (true, false, Some(false)) => {158 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)159 }160 (true, true, Some(false)) => {161 Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)162 }163 (false, false, Some(true)) => {164 Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)165 }166 (false, true, Some(true)) => {167 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)168 }169 (true, false, Some(true)) => {170 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)171 }172 (true, true, Some(true)) => {173 Self::on_initialize_periodic_named_resolved(2)174 - Self::on_initialize_periodic_named_resolved(1)175 }176 }177 }178}179impl<T: WeightInfo> MarginalWeightInfo for T {}180181#[frame_support::pallet]182pub mod pallet {183 use super::*;184 use frame_support::{185 dispatch::PostDispatchInfo,186 pallet_prelude::*,187 traits::{schedule::LookupError, PreimageProvider},188 };189 use frame_system::pallet_prelude::*;190191 192 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);193194 #[pallet::pallet]195 #[pallet::generate_store(pub(super) trait Store)]196 #[pallet::storage_version(STORAGE_VERSION)]197 #[pallet::without_storage_info]198 pub struct Pallet<T>(_);199200 201 #[pallet::config]202 pub trait Config: frame_system::Config {203 204 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;205206 207 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>208 + From<Self::PalletsOrigin>209 + IsType<<Self as system::Config>::Origin>;210211 212 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;213214 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;215216 217 type Call: Parameter218 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>219 + GetDispatchInfo220 + From<system::Call<Self>>;221222 223 224 #[pallet::constant]225 type MaximumWeight: Get<Weight>;226227 228 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;229230 231 232 233 234 235 236 237 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;238239 240 241 #[pallet::constant]242 type MaxScheduledPerBlock: Get<u32>;243244 245 type WeightInfo: WeightInfo;246247 248 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;249250 251 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;252253 254 255256 257 type CallExecutor: DispatchCall<Self, H160>;258 }259260 261 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {262 fn reserve_balance(263 id: ScheduledId,264 sponsor: <T as frame_system::Config>::AccountId,265 call: <T as Config>::Call,266 count: u32,267 ) -> Result<(), DispatchError>;268269 fn pay_for_call(270 id: ScheduledId,271 sponsor: <T as frame_system::Config>::AccountId,272 call: <T as Config>::Call,273 ) -> Result<u128, DispatchError>;274275 276 fn dispatch_call(277 signer: T::AccountId,278 function: <T as Config>::Call,279 ) -> Result<280 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,281 TransactionValidityError,282 >;283284 fn cancel_reserve(285 id: ScheduledId,286 sponsor: <T as frame_system::Config>::AccountId,287 ) -> Result<u128, DispatchError>;288 }289290 291 #[pallet::storage]292 pub type Agenda<T: Config> =293 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;294295 296 #[pallet::storage]297 pub(crate) type Lookup<T: Config> =298 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;299300 301 #[pallet::event]302 #[pallet::generate_deposit(pub(super) fn deposit_event)]303 pub enum Event<T: Config> {304 305 Scheduled { when: T::BlockNumber, index: u32 },306 307 Canceled { when: T::BlockNumber, index: u32 },308 309 Dispatched {310 task: TaskAddress<T::BlockNumber>,311 id: Option<ScheduledId>,312 result: DispatchResult,313 },314 315 CallLookupFailed {316 task: TaskAddress<T::BlockNumber>,317 id: Option<ScheduledId>,318 error: LookupError,319 },320 }321322 #[pallet::error]323 pub enum Error<T> {324 325 FailedToSchedule,326 327 NotFound,328 329 TargetBlockNumberInPast,330 331 RescheduleNoChange,332 }333334 #[pallet::hooks]335 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {336 337 fn on_initialize(now: T::BlockNumber) -> Weight {338 let limit = T::MaximumWeight::get();339340 let mut queued = Agenda::<T>::take(now)341 .into_iter()342 .enumerate()343 .filter_map(|(index, s)| Some((index as u32, s?)))344 .collect::<Vec<_>>();345346 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {347 log::warn!(348 target: "runtime::scheduler",349 "Warning: This block has more items queued in Scheduler than \350 expected from the runtime configuration. An update might be needed."351 );352 }353354 queued.sort_by_key(|(_, s)| s.priority);355356 let next = now + One::one();357358 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);359 for (order, (index, mut s)) in queued.into_iter().enumerate() {360 let named = if let Some(ref id) = s.maybe_id {361 Lookup::<T>::remove(id);362 true363 } else {364 false365 };366367 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();368 s.call = call;369370 let resolved = if let Some(completed) = maybe_completed {371 T::PreimageProvider::unrequest_preimage(&completed);372 true373 } else {374 false375 };376 let call = match s.call.as_value().cloned() {377 Some(c) => c,378 None => {379 380 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));381 if let Some(delay) = T::NoPreimagePostponement::get() {382 let until = now.saturating_add(delay);383 if let Some(ref id) = s.maybe_id {384 let index = Agenda::<T>::decode_len(until).unwrap_or(0);385 Lookup::<T>::insert(id, (until, index as u32));386 }387 Agenda::<T>::append(until, Some(s));388 }389 continue;390 }391 };392393 let periodic = s.maybe_periodic.is_some();394 let call_weight = call.get_dispatch_info().weight;395 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));396 let origin =397 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())398 .into();399 if ensure_signed(origin).is_ok() {400 401 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));402 }403404 405 406 407 408 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;409 let test_weight = total_weight410 .saturating_add(call_weight)411 .saturating_add(item_weight);412 if !hard_deadline && order > 0 && test_weight > limit {413 414 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));415 if let Some(ref id) = s.maybe_id {416 417 418 419 420 let index = Agenda::<T>::decode_len(next).unwrap_or(0);421 Lookup::<T>::insert(id, (next, index as u32));422 }423 Agenda::<T>::append(next, Some(s));424 continue;425 }426427 let sender = ensure_signed(428 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())429 .into(),430 )431 .unwrap();432433 434 435 436 437 438 439 440 441442 let r = T::CallExecutor::dispatch_call(sender, call.clone());443444 let mut actual_call_weight: Weight = item_weight;445 let result: Result<_, DispatchError> = match r {446 Ok(o) => match o {447 Ok(di) => {448 actual_call_weight = di.actual_weight.unwrap_or(item_weight);449 Ok(())450 }451 Err(err) => Err(err.error),452 },453 Err(_) => {454 log::error!(455 target: "runtime::scheduler",456 "Warning: Scheduler has failed to execute a post-dispatch transaction. \457 This block might have become invalid.");458 Err(DispatchError::CannotLookup)459 } 460 };461462 total_weight.saturating_accrue(item_weight);463 total_weight.saturating_accrue(actual_call_weight);464465 Self::deposit_event(Event::Dispatched {466 task: (now, index),467 id: s.maybe_id.clone(),468 result,469 });470471 if let &Some((period, count)) = &s.maybe_periodic {472 if count > 1 {473 s.maybe_periodic = Some((period, count - 1));474 } else {475 s.maybe_periodic = None;476 }477 let wake = now + period;478 479 if let Some(ref id) = s.maybe_id {480 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);481 Lookup::<T>::insert(id, (wake, wake_index as u32));482 }483 Agenda::<T>::append(wake, Some(s));484 }485 }486 0487 488 }489 }490491 #[pallet::call]492 impl<T: Config> Pallet<T> {493 494 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]495 pub fn schedule_named(496 origin: OriginFor<T>,497 id: ScheduledId,498 when: T::BlockNumber,499 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,500 priority: schedule::Priority,501 call: Box<CallOrHashOf<T>>,502 ) -> DispatchResult {503 T::ScheduleOrigin::ensure_origin(origin.clone())?;504 let origin = <T as Config>::Origin::from(origin);505 Self::do_schedule_named(506 id,507 DispatchTime::At(when),508 maybe_periodic,509 priority,510 origin.caller().clone(),511 *call,512 )?;513 Ok(())514 }515516 517 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]518 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {519 T::ScheduleOrigin::ensure_origin(origin.clone())?;520 let origin = <T as Config>::Origin::from(origin);521 Self::do_cancel_named(Some(origin.caller().clone()), id)?;522 Ok(())523 }524525 526 527 528 529 530 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]531 pub fn schedule_named_after(532 origin: OriginFor<T>,533 id: ScheduledId,534 after: T::BlockNumber,535 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,536 priority: schedule::Priority,537 call: Box<CallOrHashOf<T>>,538 ) -> DispatchResult {539 T::ScheduleOrigin::ensure_origin(origin.clone())?;540 let origin = <T as Config>::Origin::from(origin);541 Self::do_schedule_named(542 id,543 DispatchTime::After(after),544 maybe_periodic,545 priority,546 origin.caller().clone(),547 *call,548 )?;549 Ok(())550 }551 }552}553554impl<T: Config> Pallet<T> {555 #[cfg(feature = "try-runtime")]556 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {557 Ok(())558 }559560 #[cfg(feature = "try-runtime")]561 pub fn post_migrate_to_v3() -> Result<(), &'static str> {562 use frame_support::dispatch::GetStorageVersion;563564 assert!(Self::current_storage_version() == 3);565 for k in Agenda::<T>::iter_keys() {566 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;567 }568 Ok(())569 }570571 572 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {573 Agenda::<T>::translate::<574 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,575 _,576 >(|_, agenda| {577 Some(578 agenda579 .into_iter()580 .map(|schedule| {581 schedule.map(|schedule| Scheduled {582 maybe_id: schedule.maybe_id,583 priority: schedule.priority,584 call: schedule.call,585 maybe_periodic: schedule.maybe_periodic,586 origin: schedule.origin.into(),587 _phantom: Default::default(),588 })589 })590 .collect::<Vec<_>>(),591 )592 });593 }594595 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {596 let now = frame_system::Pallet::<T>::block_number();597598 let when = match when {599 DispatchTime::At(x) => x,600 601 602 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),603 };604605 if when <= now {606 return Err(Error::<T>::TargetBlockNumberInPast.into());607 }608609 Ok(when)610 }611612 fn do_schedule(613 when: DispatchTime<T::BlockNumber>,614 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,615 priority: schedule::Priority,616 origin: T::PalletsOrigin,617 call: CallOrHashOf<T>,618 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {619 let when = Self::resolve_time(when)?;620 call.ensure_requested::<T::PreimageProvider>();621622 623 let maybe_periodic = maybe_periodic624 .filter(|p| p.1 > 1 && !p.0.is_zero())625 626 .map(|(p, c)| (p, c - 1));627 let s = Some(Scheduled {628 maybe_id: None,629 priority,630 call,631 maybe_periodic,632 origin,633 _phantom: PhantomData::<T::AccountId>::default(),634 });635 Agenda::<T>::append(when, s);636 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;637 Self::deposit_event(Event::Scheduled { when, index });638639 Ok((when, index))640 }641642 fn do_schedule_named(643 id: ScheduledId,644 when: DispatchTime<T::BlockNumber>,645 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,646 priority: schedule::Priority,647 origin: T::PalletsOrigin,648 call: CallOrHashOf<T>,649 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {650 651 if Lookup::<T>::contains_key(&id) {652 return Err(Error::<T>::FailedToSchedule)?;653 }654655 let when = Self::resolve_time(when)?;656657 call.ensure_requested::<T::PreimageProvider>();658659 660 let maybe_periodic = maybe_periodic661 .filter(|p| p.1 > 1 && !p.0.is_zero())662 663 .map(|(p, c)| (p, c - 1));664665 let s = Scheduled {666 maybe_id: Some(id.clone()),667 priority,668 call: call.clone(),669 maybe_periodic,670 origin: origin.clone(),671 _phantom: Default::default(),672 };673674 675 676 677 678 679 680 681 682 683 684 685 686 687688 Agenda::<T>::append(when, Some(s));689 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;690 let address = (when, index);691 Lookup::<T>::insert(&id, &address);692 Self::deposit_event(Event::Scheduled { when, index });693694 Ok(address)695 }696697 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {698 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {699 if let Some((when, index)) = lookup.take() {700 let i = index as usize;701 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {702 if let Some(s) = agenda.get_mut(i) {703 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {704 if matches!(705 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),706 Some(Ordering::Less) | None707 ) {708 return Err(BadOrigin.into());709 }710 711 712 713 714 715 716 717 718719 s.call.ensure_unrequested::<T::PreimageProvider>();720 }721 *s = None;722 }723 Ok(())724 })?;725726 Self::deposit_event(Event::Canceled { when, index });727 Ok(())728 } else {729 Err(Error::<T>::NotFound)?730 }731 })732 }733}