1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768#![cfg_attr(not(feature = "std"), no_std)]69#![deny(missing_docs)]7071#[cfg(feature = "runtime-benchmarks")]72mod benchmarking;73#[cfg(test)]74mod mock;75#[cfg(test)]76mod tests;77pub mod weights;7879use codec::{Codec, Decode, Encode, MaxEncodedLen};80use frame_support::{81 dispatch::{82 DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,83 },84 traits::{85 schedule::{self, DispatchTime, LOWEST_PRIORITY},86 EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,87 ConstU32, UnfilteredDispatchable,88 },89 weights::Weight,90 unsigned::TransactionValidityError,91};9293use frame_system::{self as system};94use scale_info::TypeInfo;95use sp_runtime::{96 traits::{BadOrigin, One, Saturating, Zero, Hash},97 BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,98};99use sp_core::H160;100use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};101pub use weights::WeightInfo;102103pub use pallet::*;104105106pub type PeriodicIndex = u32;107108pub type TaskAddress<BlockNumber> = (BlockNumber, u32);109110111pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;112113#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]114#[scale_info(skip_type_params(T))]115116117pub enum ScheduledCall<T: Config> {118 119 Inline(EncodedCall),120121 122 PreimageLookup {123 124 hash: T::Hash,125126 127 unbounded_len: u32,128 },129}130131impl<T: Config> ScheduledCall<T> {132 133 134 135 pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {136 let encoded = call.encode();137 let len = encoded.len();138139 match EncodedCall::try_from(encoded.clone()) {140 Ok(bounded) => Ok(Self::Inline(bounded)),141 Err(_) => {142 let hash = <T as system::Config>::Hashing::hash_of(&encoded);143 <T as Config>::Preimages::note_preimage(144 encoded145 .try_into()146 .map_err(|_| <Error<T>>::TooBigScheduledCall)?,147 );148149 Ok(Self::PreimageLookup {150 hash,151 unbounded_len: len as u32,152 })153 }154 }155 }156157 158 pub fn lookup_len(&self) -> Option<u32> {159 match self {160 Self::Inline(..) => None,161 Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),162 }163 }164165 166 pub fn lookup_needed(&self) -> bool {167 match self {168 Self::Inline(_) => false,169 Self::PreimageLookup { .. } => true,170 }171 }172173 174 fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {175 <T as Config>::RuntimeCall::decode(&mut data)176 .map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())177 }178}179180181pub trait SchedulerPreimagesWeightInfo<W: WeightInfo> {182 183 fn service_task_fetched(call_length: u32) -> Weight;184}185186impl<W: WeightInfo> SchedulerPreimagesWeightInfo<W> for () {187 fn service_task_fetched(_call_length: u32) -> Weight {188 W::service_task_base()189 }190}191192193194pub trait SchedulerPreimages<T: Config>:195 PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>196{197 198 fn drop(call: &ScheduledCall<T>);199200 201 202 203 204 205 fn peek(206 call: &ScheduledCall<T>,207 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;208209 210 211 212 fn realize(213 call: &ScheduledCall<T>,214 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;215}216217impl<T: Config, PP: PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>>218 SchedulerPreimages<T> for PP219{220 fn drop(call: &ScheduledCall<T>) {221 match call {222 ScheduledCall::Inline(_) => {}223 ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),224 }225 }226227 fn peek(228 call: &ScheduledCall<T>,229 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {230 match call {231 ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),232 ScheduledCall::PreimageLookup {233 hash,234 unbounded_len,235 } => {236 let (preimage, len) = Self::get_preimage(hash)237 .ok_or(<Error<T>>::PreimageNotFound)238 .map(|preimage| (preimage, *unbounded_len))?;239240 Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))241 }242 }243 }244245 fn realize(246 call: &ScheduledCall<T>,247 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {248 let r = Self::peek(call)?;249 Self::drop(call);250 Ok(r)251 }252}253254255pub enum ScheduledEnsureOriginSuccess<AccountId> {256 257 Root,258259 260 Signed(AccountId),261}262263264pub type TaskName = [u8; 32];265266267#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]268#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]269pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {270 271 maybe_id: Option<Name>,272273 274 priority: schedule::Priority,275276 277 call: Call,278279 280 maybe_periodic: Option<schedule::Period<BlockNumber>>,281282 283 origin: PalletsOrigin,284 _phantom: PhantomData<AccountId>,285}286287288pub type ScheduledOf<T> = Scheduled<289 TaskName,290 ScheduledCall<T>,291 <T as frame_system::Config>::BlockNumber,292 <T as Config>::PalletsOrigin,293 <T as frame_system::Config>::AccountId,294>;295296#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]297#[scale_info(skip_type_params(T))]298299300301302pub struct BlockAgenda<T: Config> {303 agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,304 free_places: u32,305}306307impl<T: Config> BlockAgenda<T> {308 309 310 311 312 313 314 315 316 fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {317 if self.free_places == 0 {318 return Err(scheduled);319 }320321 self.free_places = self.free_places.saturating_sub(1);322323 if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {324 325 let _ = self.agenda.try_push(Some(scheduled));326 Ok((self.agenda.len() - 1) as u32)327 } else {328 match self.agenda.iter().position(|i| i.is_none()) {329 Some(hole_index) => {330 self.agenda[hole_index] = Some(scheduled);331 Ok(hole_index as u32)332 }333 None => unreachable!("free_places was greater than 0; qed"),334 }335 }336 }337338 339 340 341 342 fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {343 self.agenda[index as usize] = slot;344 }345346 347 fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {348 self.agenda.iter()349 }350351 352 353 354 355 356 fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {357 match self.agenda.get(index as usize) {358 Some(Some(scheduled)) => Some(scheduled),359 _ => None,360 }361 }362363 364 365 366 367 368 fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {369 match self.agenda.get_mut(index as usize) {370 Some(Some(scheduled)) => Some(scheduled),371 _ => None,372 }373 }374375 376 377 378 379 380 381 382 383 fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {384 let removed = self.agenda.get_mut(index as usize)?.take();385386 if removed.is_some() {387 self.free_places = self.free_places.saturating_add(1);388 }389390 removed391 }392}393394impl<T: Config> Default for BlockAgenda<T> {395 fn default() -> Self {396 let agenda = Default::default();397 let free_places = T::MaxScheduledPerBlock::get();398399 Self {400 agenda,401 free_places,402 }403 }404}405406407struct WeightCounter {408 used: Weight,409 limit: Weight,410}411412impl WeightCounter {413 414 415 416 417 fn check_accrue(&mut self, w: Weight) -> bool {418 let test = self.used.saturating_add(w);419 if test.any_gt(self.limit) {420 false421 } else {422 self.used = test;423 true424 }425 }426427 428 fn can_accrue(&mut self, w: Weight) -> bool {429 self.used.saturating_add(w).all_lte(self.limit)430 }431}432433pub(crate) struct MarginalWeightInfo<T: Config>(sp_std::marker::PhantomData<T>);434435impl<T: Config> MarginalWeightInfo<T> {436 437 fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {438 let base = T::WeightInfo::service_task_base();439 let mut total = match maybe_lookup_len {440 None => base,441 Some(l) => T::Preimages::service_task_fetched(l as u32),442 };443 if named {444 total.saturating_accrue(T::WeightInfo::service_task_named().saturating_sub(base));445 }446 if periodic {447 total.saturating_accrue(T::WeightInfo::service_task_periodic().saturating_sub(base));448 }449 total450 }451}452453#[frame_support::pallet]454pub mod pallet {455 use super::*;456 use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};457 use system::pallet_prelude::*;458459 460 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);461462 #[pallet::pallet]463 #[pallet::generate_store(pub(super) trait Store)]464 #[pallet::storage_version(STORAGE_VERSION)]465 pub struct Pallet<T>(_);466467 #[pallet::config]468 pub trait Config: frame_system::Config {469 470 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;471472 473 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>474 + From<Self::PalletsOrigin>475 + IsType<<Self as system::Config>::RuntimeOrigin>476 + Clone;477478 479 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>480 + Codec481 + Clone482 + Eq483 + TypeInfo484 + MaxEncodedLen;485486 487 type RuntimeCall: Parameter488 + Dispatchable<489 RuntimeOrigin = <Self as Config>::RuntimeOrigin,490 PostInfo = PostDispatchInfo,491 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>492 + GetDispatchInfo493 + From<system::Call<Self>>;494495 496 #[pallet::constant]497 type MaximumWeight: Get<Weight>;498499 500 type ScheduleOrigin: EnsureOrigin<501 <Self as system::Config>::RuntimeOrigin,502 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,503 >;504505 506 507 508 509 510 511 512 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;513514 515 #[pallet::constant]516 type MaxScheduledPerBlock: Get<u32>;517518 519 type WeightInfo: WeightInfo;520521 522 type Preimages: SchedulerPreimages<Self>;523524 525 type CallExecutor: DispatchCall<Self, H160>;526527 528 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;529 }530531 532 533 #[pallet::storage]534 pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;535536 537 #[pallet::storage]538 pub type Agenda<T: Config> =539 StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;540541 542 #[pallet::storage]543 pub(crate) type Lookup<T: Config> =544 StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;545546 547 #[pallet::event]548 #[pallet::generate_deposit(pub(super) fn deposit_event)]549 pub enum Event<T: Config> {550 551 Scheduled {552 553 when: T::BlockNumber,554555 556 index: u32,557 },558 559 Canceled {560 561 when: T::BlockNumber,562563 564 index: u32,565 },566 567 Dispatched {568 569 task: TaskAddress<T::BlockNumber>,570571 572 id: Option<[u8; 32]>,573574 575 result: DispatchResult,576 },577 578 PriorityChanged {579 580 task: TaskAddress<T::BlockNumber>,581582 583 priority: schedule::Priority,584 },585 586 CallUnavailable {587 588 task: TaskAddress<T::BlockNumber>,589590 591 id: Option<[u8; 32]>,592 },593 594 PermanentlyOverweight {595 596 task: TaskAddress<T::BlockNumber>,597598 599 id: Option<[u8; 32]>,600 },601 }602603 #[pallet::error]604 pub enum Error<T> {605 606 FailedToSchedule,607 608 AgendaIsExhausted,609 610 ScheduledCallCorrupted,611 612 PreimageNotFound,613 614 TooBigScheduledCall,615 616 NotFound,617 618 TargetBlockNumberInPast,619 620 Named,621 }622623 #[pallet::hooks]624 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {625 626 fn on_initialize(now: T::BlockNumber) -> Weight {627 let mut weight_counter = WeightCounter {628 used: Weight::zero(),629 limit: T::MaximumWeight::get(),630 };631 Self::service_agendas(&mut weight_counter, now, u32::max_value());632 weight_counter.used633 }634 }635636 #[pallet::call]637 impl<T: Config> Pallet<T> {638 639 640 641 642 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]643 pub fn schedule(644 origin: OriginFor<T>,645 when: T::BlockNumber,646 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,647 priority: Option<schedule::Priority>,648 call: Box<<T as Config>::RuntimeCall>,649 ) -> DispatchResult {650 T::ScheduleOrigin::ensure_origin(origin.clone())?;651652 if priority.is_some() {653 T::PrioritySetOrigin::ensure_origin(origin.clone())?;654 }655656 let origin = <T as Config>::RuntimeOrigin::from(origin);657 Self::do_schedule(658 DispatchTime::At(when),659 maybe_periodic,660 priority.unwrap_or(LOWEST_PRIORITY),661 origin.caller().clone(),662 <ScheduledCall<T>>::new(*call)?,663 )?;664 Ok(())665 }666667 668 669 670 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]671 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {672 T::ScheduleOrigin::ensure_origin(origin.clone())?;673 let origin = <T as Config>::RuntimeOrigin::from(origin);674 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;675 Ok(())676 }677678 679 680 681 682 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]683 pub fn schedule_named(684 origin: OriginFor<T>,685 id: TaskName,686 when: T::BlockNumber,687 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,688 priority: Option<schedule::Priority>,689 call: Box<<T as Config>::RuntimeCall>,690 ) -> DispatchResult {691 T::ScheduleOrigin::ensure_origin(origin.clone())?;692693 if priority.is_some() {694 T::PrioritySetOrigin::ensure_origin(origin.clone())?;695 }696697 let origin = <T as Config>::RuntimeOrigin::from(origin);698 Self::do_schedule_named(699 id,700 DispatchTime::At(when),701 maybe_periodic,702 priority.unwrap_or(LOWEST_PRIORITY),703 origin.caller().clone(),704 <ScheduledCall<T>>::new(*call)?,705 )?;706 Ok(())707 }708709 710 711 712 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]713 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {714 T::ScheduleOrigin::ensure_origin(origin.clone())?;715 let origin = <T as Config>::RuntimeOrigin::from(origin);716 Self::do_cancel_named(Some(origin.caller().clone()), id)?;717 Ok(())718 }719720 721 722 723 724 725 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]726 pub fn schedule_after(727 origin: OriginFor<T>,728 after: T::BlockNumber,729 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,730 priority: Option<schedule::Priority>,731 call: Box<<T as Config>::RuntimeCall>,732 ) -> DispatchResult {733 T::ScheduleOrigin::ensure_origin(origin.clone())?;734735 if priority.is_some() {736 T::PrioritySetOrigin::ensure_origin(origin.clone())?;737 }738739 let origin = <T as Config>::RuntimeOrigin::from(origin);740 Self::do_schedule(741 DispatchTime::After(after),742 maybe_periodic,743 priority.unwrap_or(LOWEST_PRIORITY),744 origin.caller().clone(),745 <ScheduledCall<T>>::new(*call)?,746 )?;747 Ok(())748 }749750 751 752 753 754 755 756 757 758 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]759 pub fn schedule_named_after(760 origin: OriginFor<T>,761 id: TaskName,762 after: T::BlockNumber,763 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,764 priority: Option<schedule::Priority>,765 call: Box<<T as Config>::RuntimeCall>,766 ) -> DispatchResult {767 T::ScheduleOrigin::ensure_origin(origin.clone())?;768769 if priority.is_some() {770 T::PrioritySetOrigin::ensure_origin(origin.clone())?;771 }772773 let origin = <T as Config>::RuntimeOrigin::from(origin);774 Self::do_schedule_named(775 id,776 DispatchTime::After(after),777 maybe_periodic,778 priority.unwrap_or(LOWEST_PRIORITY),779 origin.caller().clone(),780 <ScheduledCall<T>>::new(*call)?,781 )?;782 Ok(())783 }784785 786 787 788 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]789 pub fn change_named_priority(790 origin: OriginFor<T>,791 id: TaskName,792 priority: schedule::Priority,793 ) -> DispatchResult {794 T::PrioritySetOrigin::ensure_origin(origin.clone())?;795 let origin = <T as Config>::RuntimeOrigin::from(origin);796 Self::do_change_named_priority(origin.caller().clone(), id, priority)797 }798 }799}800801impl<T: Config> Pallet<T> {802 803 804 805 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {806 let now = frame_system::Pallet::<T>::block_number();807808 let when = match when {809 DispatchTime::At(x) => x,810 811 812 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),813 };814815 if when <= now {816 return Err(Error::<T>::TargetBlockNumberInPast.into());817 }818819 Ok(when)820 }821822 823 824 825 826 827 828 fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {829 Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");830 }831832 833 834 835 fn try_place_task(836 when: T::BlockNumber,837 what: ScheduledOf<T>,838 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {839 Self::place_task(when, what, false)840 }841842 843 844 845 846 fn place_task(847 mut when: T::BlockNumber,848 what: ScheduledOf<T>,849 is_mandatory: bool,850 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {851 let maybe_name = what.maybe_id;852 let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;853 let address = (when, index);854 if let Some(name) = maybe_name {855 Lookup::<T>::insert(name, address)856 }857 Self::deposit_event(Event::Scheduled {858 when: address.0,859 index: address.1,860 });861 Ok(address)862 }863864 865 866 867 868 869 fn push_to_agenda(870 when: &mut T::BlockNumber,871 mut what: ScheduledOf<T>,872 is_mandatory: bool,873 ) -> Result<u32, DispatchError> {874 let mut agenda;875876 let index = loop {877 agenda = Agenda::<T>::get(*when);878879 match agenda.try_push(what) {880 Ok(index) => break index,881 Err(returned_what) if is_mandatory => {882 what = returned_what;883 when.saturating_inc();884 }885 Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),886 }887 };888889 Agenda::<T>::insert(when, agenda);890 Ok(index)891 }892893 fn do_schedule(894 when: DispatchTime<T::BlockNumber>,895 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,896 priority: schedule::Priority,897 origin: T::PalletsOrigin,898 call: ScheduledCall<T>,899 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {900 let when = Self::resolve_time(when)?;901902 903 let maybe_periodic = maybe_periodic904 .filter(|p| p.1 > 1 && !p.0.is_zero())905 906 .map(|(p, c)| (p, c - 1));907 let task = Scheduled {908 maybe_id: None,909 priority,910 call,911 maybe_periodic,912 origin,913 _phantom: PhantomData,914 };915 Self::try_place_task(when, task)916 }917918 fn do_cancel(919 origin: Option<T::PalletsOrigin>,920 (when, index): TaskAddress<T::BlockNumber>,921 ) -> Result<(), DispatchError> {922 let scheduled = Agenda::<T>::try_mutate(923 when,924 |agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {925 let scheduled = match agenda.get(index) {926 Some(scheduled) => scheduled,927 None => return Ok(None),928 };929930 if let Some(ref o) = origin {931 if matches!(932 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),933 Some(Ordering::Less) | None934 ) {935 return Err(BadOrigin.into());936 }937 }938939 Ok(agenda.take(index))940 },941 )?;942 if let Some(s) = scheduled {943 T::Preimages::drop(&s.call);944945 if let Some(id) = s.maybe_id {946 Lookup::<T>::remove(id);947 }948 Self::deposit_event(Event::Canceled { when, index });949 Ok(())950 } else {951 Err(Error::<T>::NotFound.into())952 }953 }954955 fn do_schedule_named(956 id: TaskName,957 when: DispatchTime<T::BlockNumber>,958 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,959 priority: schedule::Priority,960 origin: T::PalletsOrigin,961 call: ScheduledCall<T>,962 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {963 964 if Lookup::<T>::contains_key(&id) {965 return Err(Error::<T>::FailedToSchedule.into());966 }967968 let when = Self::resolve_time(when)?;969970 971 let maybe_periodic = maybe_periodic972 .filter(|p| p.1 > 1 && !p.0.is_zero())973 974 .map(|(p, c)| (p, c - 1));975976 let task = Scheduled {977 maybe_id: Some(id),978 priority,979 call,980 maybe_periodic,981 origin,982 _phantom: Default::default(),983 };984 Self::try_place_task(when, task)985 }986987 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {988 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {989 if let Some((when, index)) = lookup.take() {990 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {991 let scheduled = match agenda.get(index) {992 Some(scheduled) => scheduled,993 None => return Ok(()),994 };995996 if let Some(ref o) = origin {997 if matches!(998 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),999 Some(Ordering::Less) | None1000 ) {1001 return Err(BadOrigin.into());1002 }1003 T::Preimages::drop(&scheduled.call);1004 }10051006 agenda.take(index);10071008 Ok(())1009 })?;1010 Self::deposit_event(Event::Canceled { when, index });1011 Ok(())1012 } else {1013 Err(Error::<T>::NotFound.into())1014 }1015 })1016 }10171018 fn do_change_named_priority(1019 origin: T::PalletsOrigin,1020 id: TaskName,1021 priority: schedule::Priority,1022 ) -> DispatchResult {1023 match Lookup::<T>::get(id) {1024 Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {1025 let scheduled = match agenda.get_mut(index) {1026 Some(scheduled) => scheduled,1027 None => return Ok(()),1028 };10291030 if matches!(1031 T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),1032 Some(Ordering::Less) | None1033 ) {1034 return Err(BadOrigin.into());1035 }10361037 scheduled.priority = priority;1038 Self::deposit_event(Event::PriorityChanged {1039 task: (when, index),1040 priority,1041 });10421043 Ok(())1044 }),1045 None => Err(Error::<T>::NotFound.into()),1046 }1047 }1048}10491050enum ServiceTaskError {1051 1052 Unavailable,1053 1054 Overweight,1055}1056use ServiceTaskError::*;105710581059pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {1060 1061 fn dispatch_call(1062 signer: Option<T::AccountId>,1063 function: <T as Config>::RuntimeCall,1064 ) -> Result<1065 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,1066 TransactionValidityError,1067 >;1068}10691070impl<T: Config> Pallet<T> {1071 1072 fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {1073 if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {1074 return;1075 }10761077 let mut incomplete_since = now + One::one();1078 let mut when = IncompleteSince::<T>::take().unwrap_or(now);1079 let mut executed = 0;10801081 let max_items = T::MaxScheduledPerBlock::get();1082 let mut count_down = max;1083 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);1084 while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {1085 if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {1086 incomplete_since = incomplete_since.min(when);1087 }1088 when.saturating_inc();1089 count_down.saturating_dec();1090 }1091 incomplete_since = incomplete_since.min(when);1092 if incomplete_since <= now {1093 IncompleteSince::<T>::put(incomplete_since);1094 }1095 }10961097 1098 1099 fn service_agenda(1100 weight: &mut WeightCounter,1101 executed: &mut u32,1102 now: T::BlockNumber,1103 when: T::BlockNumber,1104 max: u32,1105 ) -> bool {1106 let mut agenda = Agenda::<T>::get(when);1107 let mut ordered = agenda1108 .iter()1109 .enumerate()1110 .filter_map(|(index, maybe_item)| {1111 maybe_item1112 .as_ref()1113 .map(|item| (index as u32, item.priority))1114 })1115 .collect::<Vec<_>>();1116 ordered.sort_by_key(|k| k.1);1117 let within_limit =1118 weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));1119 debug_assert!(1120 within_limit,1121 "weight limit should have been checked in advance"1122 );11231124 1125 let mut postponed = (ordered.len() as u32).saturating_sub(max);1126 1127 let mut dropped = 0;11281129 for (agenda_index, _) in ordered.into_iter().take(max as usize) {1130 let task = match agenda.take(agenda_index).take() {1131 None => continue,1132 Some(t) => t,1133 };1134 let base_weight = MarginalWeightInfo::<T>::service_task(1135 task.call.lookup_len().map(|x| x as usize),1136 task.maybe_id.is_some(),1137 task.maybe_periodic.is_some(),1138 );1139 if !weight.can_accrue(base_weight) {1140 postponed += 1;1141 break;1142 }1143 let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);1144 match result {1145 Err((Unavailable, slot)) => {1146 dropped += 1;1147 agenda.set_slot(agenda_index, slot);1148 }1149 Err((Overweight, slot)) => {1150 postponed += 1;1151 agenda.set_slot(agenda_index, slot);1152 }1153 Ok(()) => {1154 *executed += 1;1155 }1156 };1157 }1158 if postponed > 0 || dropped > 0 {1159 Agenda::<T>::insert(when, agenda);1160 } else {1161 Agenda::<T>::remove(when);1162 }1163 postponed == 01164 }11651166 1167 1168 1169 1170 1171 1172 fn service_task(1173 weight: &mut WeightCounter,1174 now: T::BlockNumber,1175 when: T::BlockNumber,1176 agenda_index: u32,1177 is_first: bool,1178 mut task: ScheduledOf<T>,1179 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1180 let (call, lookup_len) = match T::Preimages::peek(&task.call) {1181 Ok(c) => c,1182 Err(_) => {1183 if let Some(ref id) = task.maybe_id {1184 Lookup::<T>::remove(id);1185 }11861187 return Err((Unavailable, Some(task)));1188 }1189 };11901191 weight.check_accrue(MarginalWeightInfo::<T>::service_task(1192 lookup_len.map(|x| x as usize),1193 task.maybe_id.is_some(),1194 task.maybe_periodic.is_some(),1195 ));11961197 match Self::execute_dispatch(weight, task.origin.clone(), call) {1198 Err(Unavailable) => {1199 debug_assert!(false, "Checked to exist with `peek`");12001201 if let Some(ref id) = task.maybe_id {1202 Lookup::<T>::remove(id);1203 }12041205 Self::deposit_event(Event::CallUnavailable {1206 task: (when, agenda_index),1207 id: task.maybe_id,1208 });1209 Err((Unavailable, Some(task)))1210 }1211 Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1212 T::Preimages::drop(&task.call);12131214 if let Some(ref id) = task.maybe_id {1215 Lookup::<T>::remove(id);1216 }12171218 Self::deposit_event(Event::PermanentlyOverweight {1219 task: (when, agenda_index),1220 id: task.maybe_id,1221 });1222 Err((Unavailable, Some(task)))1223 }1224 Err(Overweight) => {1225 1226 Err((Overweight, Some(task)))1227 }1228 Ok(result) => {1229 Self::deposit_event(Event::Dispatched {1230 task: (when, agenda_index),1231 id: task.maybe_id,1232 result,1233 });12341235 let is_canceled = task1236 .maybe_id1237 .as_ref()1238 .map(|id| !Lookup::<T>::contains_key(id))1239 .unwrap_or(false);12401241 match &task.maybe_periodic {1242 &Some((period, count)) if !is_canceled => {1243 if count > 1 {1244 task.maybe_periodic = Some((period, count - 1));1245 } else {1246 task.maybe_periodic = None;1247 }1248 let wake = now.saturating_add(period);1249 Self::mandatory_place_task(wake, task);1250 }1251 _ => {1252 if let Some(ref id) = task.maybe_id {1253 Lookup::<T>::remove(id);1254 }12551256 T::Preimages::drop(&task.call)1257 }1258 }1259 Ok(())1260 }1261 }1262 }12631264 fn is_runtime_upgraded() -> bool {1265 let last = system::LastRuntimeUpgrade::<T>::get();1266 let current = T::Version::get();12671268 last.map(|v| v.was_upgraded(¤t)).unwrap_or(true)1269 }12701271 1272 1273 1274 1275 1276 1277 fn execute_dispatch(1278 weight: &mut WeightCounter,1279 origin: T::PalletsOrigin,1280 call: <T as Config>::RuntimeCall,1281 ) -> Result<DispatchResult, ServiceTaskError> {1282 let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1283 let base_weight = match dispatch_origin.clone().as_signed() {1284 Some(_) => T::WeightInfo::execute_dispatch_signed(),1285 _ => T::WeightInfo::execute_dispatch_unsigned(),1286 };1287 let call_weight = call.get_dispatch_info().weight;1288 1289 let max_weight = base_weight.saturating_add(call_weight);12901291 if !weight.can_accrue(max_weight) {1292 return Err(Overweight);1293 }12941295 let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());12961297 let r = match ensured_origin {1298 Ok(ScheduledEnsureOriginSuccess::Root) => {1299 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1300 }1301 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1302 1303 1304 T::CallExecutor::dispatch_call(Some(sender), call)1305 }1306 Err(e) => Ok(Err(e.into())),1307 };13081309 let (maybe_actual_call_weight, result) = match r {1310 Ok(result) => match result {1311 Ok(post_info) => (post_info.actual_weight, Ok(())),1312 Err(error_and_info) => (1313 error_and_info.post_info.actual_weight,1314 Err(error_and_info.error),1315 ),1316 },1317 Err(_) => {1318 log::error!(1319 target: "runtime::scheduler",1320 "Warning: Scheduler has failed to execute a post-dispatch transaction. \1321 This block might have become invalid.");1322 (None, Err(DispatchError::CannotLookup))1323 }1324 };1325 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1326 weight.check_accrue(base_weight);1327 weight.check_accrue(call_weight);1328 Ok(result)1329 }1330}