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}179180181182pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {183 184 fn drop(call: &ScheduledCall<T>);185186 187 188 189 190 191 fn peek(192 call: &ScheduledCall<T>,193 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;194195 196 197 198 fn realize(199 call: &ScheduledCall<T>,200 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;201}202203impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {204 fn drop(call: &ScheduledCall<T>) {205 match call {206 ScheduledCall::Inline(_) => {}207 ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),208 }209 }210211 fn peek(212 call: &ScheduledCall<T>,213 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {214 match call {215 ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),216 ScheduledCall::PreimageLookup {217 hash,218 unbounded_len,219 } => {220 let (preimage, len) = Self::get_preimage(hash)221 .ok_or(<Error<T>>::PreimageNotFound)222 .map(|preimage| (preimage, *unbounded_len))?;223224 Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))225 }226 }227 }228229 fn realize(230 call: &ScheduledCall<T>,231 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {232 let r = Self::peek(call)?;233 Self::drop(call);234 Ok(r)235 }236}237238239pub enum ScheduledEnsureOriginSuccess<AccountId> {240 241 Root,242243 244 Signed(AccountId),245}246247248pub type TaskName = [u8; 32];249250251#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]252#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]253pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {254 255 maybe_id: Option<Name>,256257 258 priority: schedule::Priority,259260 261 call: Call,262263 264 maybe_periodic: Option<schedule::Period<BlockNumber>>,265266 267 origin: PalletsOrigin,268 _phantom: PhantomData<AccountId>,269}270271272pub type ScheduledOf<T> = Scheduled<273 TaskName,274 ScheduledCall<T>,275 <T as frame_system::Config>::BlockNumber,276 <T as Config>::PalletsOrigin,277 <T as frame_system::Config>::AccountId,278>;279280#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]281#[scale_info(skip_type_params(T))]282283284285286pub struct BlockAgenda<T: Config> {287 agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,288 free_places: u32,289}290291impl<T: Config> BlockAgenda<T> {292 293 294 295 296 297 298 299 300 fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {301 if self.free_places == 0 {302 return Err(scheduled);303 }304305 self.free_places = self.free_places.saturating_sub(1);306307 if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {308 309 let _ = self.agenda.try_push(Some(scheduled));310 Ok((self.agenda.len() - 1) as u32)311 } else {312 match self.agenda.iter().position(|i| i.is_none()) {313 Some(hole_index) => {314 self.agenda[hole_index] = Some(scheduled);315 Ok(hole_index as u32)316 }317 None => unreachable!("free_places was greater than 0; qed"),318 }319 }320 }321322 323 324 325 326 fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {327 self.agenda[index as usize] = slot;328 }329330 331 fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {332 self.agenda.iter()333 }334335 336 337 338 339 340 fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {341 match self.agenda.get(index as usize) {342 Some(Some(scheduled)) => Some(scheduled),343 _ => None,344 }345 }346347 348 349 350 351 352 fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {353 match self.agenda.get_mut(index as usize) {354 Some(Some(scheduled)) => Some(scheduled),355 _ => None,356 }357 }358359 360 361 362 363 364 365 366 367 fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {368 let removed = self.agenda.get_mut(index as usize)?.take();369370 if removed.is_some() {371 self.free_places = self.free_places.saturating_add(1);372 }373374 removed375 }376}377378impl<T: Config> Default for BlockAgenda<T> {379 fn default() -> Self {380 let agenda = Default::default();381 let free_places = T::MaxScheduledPerBlock::get();382383 Self {384 agenda,385 free_places,386 }387 }388}389390391struct WeightCounter {392 used: Weight,393 limit: Weight,394}395396impl WeightCounter {397 398 399 400 401 fn check_accrue(&mut self, w: Weight) -> bool {402 let test = self.used.saturating_add(w);403 if test.any_gt(self.limit) {404 false405 } else {406 self.used = test;407 true408 }409 }410411 412 fn can_accrue(&mut self, w: Weight) -> bool {413 self.used.saturating_add(w).all_lte(self.limit)414 }415}416417pub(crate) trait MarginalWeightInfo: WeightInfo {418 419 fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {420 let base = Self::service_task_base();421 let mut total = match maybe_lookup_len {422 None => base,423 Some(_l) => {424 425 426 base427 }428 };429 if named {430 total.saturating_accrue(Self::service_task_named().saturating_sub(base));431 }432 if periodic {433 total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));434 }435 total436 }437}438439impl<T: WeightInfo> MarginalWeightInfo for T {}440441#[frame_support::pallet]442pub mod pallet {443 use super::*;444 use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};445 use system::pallet_prelude::*;446447 448 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);449450 #[pallet::pallet]451 #[pallet::generate_store(pub(super) trait Store)]452 #[pallet::storage_version(STORAGE_VERSION)]453 pub struct Pallet<T>(_);454455 #[pallet::config]456 pub trait Config: frame_system::Config {457 458 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;459460 461 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>462 + From<Self::PalletsOrigin>463 + IsType<<Self as system::Config>::RuntimeOrigin>464 + Clone;465466 467 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>468 + Codec469 + Clone470 + Eq471 + TypeInfo472 + MaxEncodedLen;473474 475 type RuntimeCall: Parameter476 + Dispatchable<477 RuntimeOrigin = <Self as Config>::RuntimeOrigin,478 PostInfo = PostDispatchInfo,479 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>480 + GetDispatchInfo481 + From<system::Call<Self>>;482483 484 #[pallet::constant]485 type MaximumWeight: Get<Weight>;486487 488 type ScheduleOrigin: EnsureOrigin<489 <Self as system::Config>::RuntimeOrigin,490 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,491 >;492493 494 495 496 497 498 499 500 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;501502 503 #[pallet::constant]504 type MaxScheduledPerBlock: Get<u32>;505506 507 type WeightInfo: WeightInfo;508509 510 type Preimages: SchedulerPreimages<Self>;511512 513 type CallExecutor: DispatchCall<Self, H160>;514515 516 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;517 }518519 520 521 #[pallet::storage]522 pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;523524 525 #[pallet::storage]526 pub type Agenda<T: Config> =527 StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;528529 530 #[pallet::storage]531 pub(crate) type Lookup<T: Config> =532 StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;533534 535 #[pallet::event]536 #[pallet::generate_deposit(pub(super) fn deposit_event)]537 pub enum Event<T: Config> {538 539 Scheduled {540 541 when: T::BlockNumber,542543 544 index: u32,545 },546 547 Canceled {548 549 when: T::BlockNumber,550551 552 index: u32,553 },554 555 Dispatched {556 557 task: TaskAddress<T::BlockNumber>,558559 560 id: Option<[u8; 32]>,561562 563 result: DispatchResult,564 },565 566 PriorityChanged {567 568 task: TaskAddress<T::BlockNumber>,569570 571 priority: schedule::Priority,572 },573 574 CallUnavailable {575 576 task: TaskAddress<T::BlockNumber>,577578 579 id: Option<[u8; 32]>,580 },581 582 PermanentlyOverweight {583 584 task: TaskAddress<T::BlockNumber>,585586 587 id: Option<[u8; 32]>,588 },589 }590591 #[pallet::error]592 pub enum Error<T> {593 594 FailedToSchedule,595 596 AgendaIsExhausted,597 598 ScheduledCallCorrupted,599 600 PreimageNotFound,601 602 TooBigScheduledCall,603 604 NotFound,605 606 TargetBlockNumberInPast,607 608 Named,609 }610611 #[pallet::hooks]612 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {613 614 fn on_initialize(now: T::BlockNumber) -> Weight {615 let mut weight_counter = WeightCounter {616 used: Weight::zero(),617 limit: T::MaximumWeight::get(),618 };619 Self::service_agendas(&mut weight_counter, now, u32::max_value());620 weight_counter.used621 }622 }623624 #[pallet::call]625 impl<T: Config> Pallet<T> {626 627 628 629 630 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]631 pub fn schedule(632 origin: OriginFor<T>,633 when: T::BlockNumber,634 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,635 priority: Option<schedule::Priority>,636 call: Box<<T as Config>::RuntimeCall>,637 ) -> DispatchResult {638 T::ScheduleOrigin::ensure_origin(origin.clone())?;639640 if priority.is_some() {641 T::PrioritySetOrigin::ensure_origin(origin.clone())?;642 }643644 let origin = <T as Config>::RuntimeOrigin::from(origin);645 Self::do_schedule(646 DispatchTime::At(when),647 maybe_periodic,648 priority.unwrap_or(LOWEST_PRIORITY),649 origin.caller().clone(),650 <ScheduledCall<T>>::new(*call)?,651 )?;652 Ok(())653 }654655 656 657 658 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]659 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {660 T::ScheduleOrigin::ensure_origin(origin.clone())?;661 let origin = <T as Config>::RuntimeOrigin::from(origin);662 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;663 Ok(())664 }665666 667 668 669 670 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]671 pub fn schedule_named(672 origin: OriginFor<T>,673 id: TaskName,674 when: T::BlockNumber,675 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,676 priority: Option<schedule::Priority>,677 call: Box<<T as Config>::RuntimeCall>,678 ) -> DispatchResult {679 T::ScheduleOrigin::ensure_origin(origin.clone())?;680681 if priority.is_some() {682 T::PrioritySetOrigin::ensure_origin(origin.clone())?;683 }684685 let origin = <T as Config>::RuntimeOrigin::from(origin);686 Self::do_schedule_named(687 id,688 DispatchTime::At(when),689 maybe_periodic,690 priority.unwrap_or(LOWEST_PRIORITY),691 origin.caller().clone(),692 <ScheduledCall<T>>::new(*call)?,693 )?;694 Ok(())695 }696697 698 699 700 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]701 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {702 T::ScheduleOrigin::ensure_origin(origin.clone())?;703 let origin = <T as Config>::RuntimeOrigin::from(origin);704 Self::do_cancel_named(Some(origin.caller().clone()), id)?;705 Ok(())706 }707708 709 710 711 712 713 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]714 pub fn schedule_after(715 origin: OriginFor<T>,716 after: T::BlockNumber,717 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,718 priority: Option<schedule::Priority>,719 call: Box<<T as Config>::RuntimeCall>,720 ) -> DispatchResult {721 T::ScheduleOrigin::ensure_origin(origin.clone())?;722723 if priority.is_some() {724 T::PrioritySetOrigin::ensure_origin(origin.clone())?;725 }726727 let origin = <T as Config>::RuntimeOrigin::from(origin);728 Self::do_schedule(729 DispatchTime::After(after),730 maybe_periodic,731 priority.unwrap_or(LOWEST_PRIORITY),732 origin.caller().clone(),733 <ScheduledCall<T>>::new(*call)?,734 )?;735 Ok(())736 }737738 739 740 741 742 743 744 745 746 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]747 pub fn schedule_named_after(748 origin: OriginFor<T>,749 id: TaskName,750 after: T::BlockNumber,751 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,752 priority: Option<schedule::Priority>,753 call: Box<<T as Config>::RuntimeCall>,754 ) -> DispatchResult {755 T::ScheduleOrigin::ensure_origin(origin.clone())?;756757 if priority.is_some() {758 T::PrioritySetOrigin::ensure_origin(origin.clone())?;759 }760761 let origin = <T as Config>::RuntimeOrigin::from(origin);762 Self::do_schedule_named(763 id,764 DispatchTime::After(after),765 maybe_periodic,766 priority.unwrap_or(LOWEST_PRIORITY),767 origin.caller().clone(),768 <ScheduledCall<T>>::new(*call)?,769 )?;770 Ok(())771 }772773 774 775 776 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]777 pub fn change_named_priority(778 origin: OriginFor<T>,779 id: TaskName,780 priority: schedule::Priority,781 ) -> DispatchResult {782 T::PrioritySetOrigin::ensure_origin(origin.clone())?;783 let origin = <T as Config>::RuntimeOrigin::from(origin);784 Self::do_change_named_priority(origin.caller().clone(), id, priority)785 }786 }787}788789impl<T: Config> Pallet<T> {790 791 792 793 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {794 let now = frame_system::Pallet::<T>::block_number();795796 let when = match when {797 DispatchTime::At(x) => x,798 799 800 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),801 };802803 if when <= now {804 return Err(Error::<T>::TargetBlockNumberInPast.into());805 }806807 Ok(when)808 }809810 811 812 813 814 815 816 fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {817 Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");818 }819820 821 822 823 fn try_place_task(824 when: T::BlockNumber,825 what: ScheduledOf<T>,826 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {827 Self::place_task(when, what, false)828 }829830 831 832 833 834 fn place_task(835 mut when: T::BlockNumber,836 what: ScheduledOf<T>,837 is_mandatory: bool,838 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {839 let maybe_name = what.maybe_id;840 let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;841 let address = (when, index);842 if let Some(name) = maybe_name {843 Lookup::<T>::insert(name, address)844 }845 Self::deposit_event(Event::Scheduled {846 when: address.0,847 index: address.1,848 });849 Ok(address)850 }851852 853 854 855 856 857 fn push_to_agenda(858 when: &mut T::BlockNumber,859 mut what: ScheduledOf<T>,860 is_mandatory: bool,861 ) -> Result<u32, DispatchError> {862 let mut agenda;863864 let index = loop {865 agenda = Agenda::<T>::get(*when);866867 match agenda.try_push(what) {868 Ok(index) => break index,869 Err(returned_what) if is_mandatory => {870 what = returned_what;871 when.saturating_inc();872 }873 Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),874 }875 };876877 Agenda::<T>::insert(when, agenda);878 Ok(index)879 }880881 fn do_schedule(882 when: DispatchTime<T::BlockNumber>,883 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,884 priority: schedule::Priority,885 origin: T::PalletsOrigin,886 call: ScheduledCall<T>,887 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {888 let when = Self::resolve_time(when)?;889890 891 let maybe_periodic = maybe_periodic892 .filter(|p| p.1 > 1 && !p.0.is_zero())893 894 .map(|(p, c)| (p, c - 1));895 let task = Scheduled {896 maybe_id: None,897 priority,898 call,899 maybe_periodic,900 origin,901 _phantom: PhantomData,902 };903 Self::try_place_task(when, task)904 }905906 fn do_cancel(907 origin: Option<T::PalletsOrigin>,908 (when, index): TaskAddress<T::BlockNumber>,909 ) -> Result<(), DispatchError> {910 let scheduled = Agenda::<T>::try_mutate(911 when,912 |agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {913 let scheduled = match agenda.get(index) {914 Some(scheduled) => scheduled,915 None => return Ok(None),916 };917918 if let Some(ref o) = origin {919 if matches!(920 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),921 Some(Ordering::Less) | None922 ) {923 return Err(BadOrigin.into());924 }925 }926927 Ok(agenda.take(index))928 },929 )?;930 if let Some(s) = scheduled {931 T::Preimages::drop(&s.call);932933 if let Some(id) = s.maybe_id {934 Lookup::<T>::remove(id);935 }936 Self::deposit_event(Event::Canceled { when, index });937 Ok(())938 } else {939 Err(Error::<T>::NotFound.into())940 }941 }942943 fn do_schedule_named(944 id: TaskName,945 when: DispatchTime<T::BlockNumber>,946 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,947 priority: schedule::Priority,948 origin: T::PalletsOrigin,949 call: ScheduledCall<T>,950 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {951 952 if Lookup::<T>::contains_key(&id) {953 return Err(Error::<T>::FailedToSchedule.into());954 }955956 let when = Self::resolve_time(when)?;957958 959 let maybe_periodic = maybe_periodic960 .filter(|p| p.1 > 1 && !p.0.is_zero())961 962 .map(|(p, c)| (p, c - 1));963964 let task = Scheduled {965 maybe_id: Some(id),966 priority,967 call,968 maybe_periodic,969 origin,970 _phantom: Default::default(),971 };972 Self::try_place_task(when, task)973 }974975 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {976 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {977 if let Some((when, index)) = lookup.take() {978 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {979 let scheduled = match agenda.get(index) {980 Some(scheduled) => scheduled,981 None => return Ok(()),982 };983984 if let Some(ref o) = origin {985 if matches!(986 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),987 Some(Ordering::Less) | None988 ) {989 return Err(BadOrigin.into());990 }991 T::Preimages::drop(&scheduled.call);992 }993994 agenda.take(index);995996 Ok(())997 })?;998 Self::deposit_event(Event::Canceled { when, index });999 Ok(())1000 } else {1001 Err(Error::<T>::NotFound.into())1002 }1003 })1004 }10051006 fn do_change_named_priority(1007 origin: T::PalletsOrigin,1008 id: TaskName,1009 priority: schedule::Priority,1010 ) -> DispatchResult {1011 match Lookup::<T>::get(id) {1012 Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {1013 let scheduled = match agenda.get_mut(index) {1014 Some(scheduled) => scheduled,1015 None => return Ok(()),1016 };10171018 if matches!(1019 T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),1020 Some(Ordering::Less) | None1021 ) {1022 return Err(BadOrigin.into());1023 }10241025 scheduled.priority = priority;1026 Self::deposit_event(Event::PriorityChanged {1027 task: (when, index),1028 priority,1029 });10301031 Ok(())1032 }),1033 None => Err(Error::<T>::NotFound.into()),1034 }1035 }1036}10371038enum ServiceTaskError {1039 1040 Unavailable,1041 1042 Overweight,1043}1044use ServiceTaskError::*;104510461047pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {1048 1049 fn dispatch_call(1050 signer: Option<T::AccountId>,1051 function: <T as Config>::RuntimeCall,1052 ) -> Result<1053 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,1054 TransactionValidityError,1055 >;1056}10571058impl<T: Config> Pallet<T> {1059 1060 fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {1061 if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {1062 return;1063 }10641065 let mut incomplete_since = now + One::one();1066 let mut when = IncompleteSince::<T>::take().unwrap_or(now);1067 let mut executed = 0;10681069 let max_items = T::MaxScheduledPerBlock::get();1070 let mut count_down = max;1071 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);1072 while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {1073 if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {1074 incomplete_since = incomplete_since.min(when);1075 }1076 when.saturating_inc();1077 count_down.saturating_dec();1078 }1079 incomplete_since = incomplete_since.min(when);1080 if incomplete_since <= now {1081 IncompleteSince::<T>::put(incomplete_since);1082 }1083 }10841085 1086 1087 fn service_agenda(1088 weight: &mut WeightCounter,1089 executed: &mut u32,1090 now: T::BlockNumber,1091 when: T::BlockNumber,1092 max: u32,1093 ) -> bool {1094 let mut agenda = Agenda::<T>::get(when);1095 let mut ordered = agenda1096 .iter()1097 .enumerate()1098 .filter_map(|(index, maybe_item)| {1099 maybe_item1100 .as_ref()1101 .map(|item| (index as u32, item.priority))1102 })1103 .collect::<Vec<_>>();1104 ordered.sort_by_key(|k| k.1);1105 let within_limit =1106 weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));1107 debug_assert!(1108 within_limit,1109 "weight limit should have been checked in advance"1110 );11111112 1113 let mut postponed = (ordered.len() as u32).saturating_sub(max);1114 1115 let mut dropped = 0;11161117 for (agenda_index, _) in ordered.into_iter().take(max as usize) {1118 let task = match agenda.take(agenda_index).take() {1119 None => continue,1120 Some(t) => t,1121 };1122 let base_weight = T::WeightInfo::service_task(1123 task.call.lookup_len().map(|x| x as usize),1124 task.maybe_id.is_some(),1125 task.maybe_periodic.is_some(),1126 );1127 if !weight.can_accrue(base_weight) {1128 postponed += 1;1129 break;1130 }1131 let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);1132 match result {1133 Err((Unavailable, slot)) => {1134 dropped += 1;1135 agenda.set_slot(agenda_index, slot);1136 }1137 Err((Overweight, slot)) => {1138 postponed += 1;1139 agenda.set_slot(agenda_index, slot);1140 }1141 Ok(()) => {1142 *executed += 1;1143 }1144 };1145 }1146 if postponed > 0 || dropped > 0 {1147 Agenda::<T>::insert(when, agenda);1148 } else {1149 Agenda::<T>::remove(when);1150 }1151 postponed == 01152 }11531154 1155 1156 1157 1158 1159 1160 fn service_task(1161 weight: &mut WeightCounter,1162 now: T::BlockNumber,1163 when: T::BlockNumber,1164 agenda_index: u32,1165 is_first: bool,1166 mut task: ScheduledOf<T>,1167 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1168 let (call, lookup_len) = match T::Preimages::peek(&task.call) {1169 Ok(c) => c,1170 Err(_) => {1171 if let Some(ref id) = task.maybe_id {1172 Lookup::<T>::remove(id);1173 }11741175 return Err((Unavailable, Some(task)));1176 }1177 };11781179 weight.check_accrue(T::WeightInfo::service_task(1180 lookup_len.map(|x| x as usize),1181 task.maybe_id.is_some(),1182 task.maybe_periodic.is_some(),1183 ));11841185 match Self::execute_dispatch(weight, task.origin.clone(), call) {1186 Err(Unavailable) => {1187 debug_assert!(false, "Checked to exist with `peek`");11881189 if let Some(ref id) = task.maybe_id {1190 Lookup::<T>::remove(id);1191 }11921193 Self::deposit_event(Event::CallUnavailable {1194 task: (when, agenda_index),1195 id: task.maybe_id,1196 });1197 Err((Unavailable, Some(task)))1198 }1199 Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1200 T::Preimages::drop(&task.call);12011202 if let Some(ref id) = task.maybe_id {1203 Lookup::<T>::remove(id);1204 }12051206 Self::deposit_event(Event::PermanentlyOverweight {1207 task: (when, agenda_index),1208 id: task.maybe_id,1209 });1210 Err((Unavailable, Some(task)))1211 }1212 Err(Overweight) => {1213 1214 Err((Overweight, Some(task)))1215 }1216 Ok(result) => {1217 Self::deposit_event(Event::Dispatched {1218 task: (when, agenda_index),1219 id: task.maybe_id,1220 result,1221 });12221223 let is_canceled = task1224 .maybe_id1225 .as_ref()1226 .map(|id| !Lookup::<T>::contains_key(id))1227 .unwrap_or(false);12281229 match &task.maybe_periodic {1230 &Some((period, count)) if !is_canceled => {1231 if count > 1 {1232 task.maybe_periodic = Some((period, count - 1));1233 } else {1234 task.maybe_periodic = None;1235 }1236 let wake = now.saturating_add(period);1237 Self::mandatory_place_task(wake, task);1238 }1239 _ => {1240 if let Some(ref id) = task.maybe_id {1241 Lookup::<T>::remove(id);1242 }12431244 T::Preimages::drop(&task.call)1245 }1246 }1247 Ok(())1248 }1249 }1250 }12511252 fn is_runtime_upgraded() -> bool {1253 let last = system::LastRuntimeUpgrade::<T>::get();1254 let current = T::Version::get();12551256 last.map(|v| v.was_upgraded(¤t)).unwrap_or(true)1257 }12581259 1260 1261 1262 1263 1264 1265 fn execute_dispatch(1266 weight: &mut WeightCounter,1267 origin: T::PalletsOrigin,1268 call: <T as Config>::RuntimeCall,1269 ) -> Result<DispatchResult, ServiceTaskError> {1270 let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1271 let base_weight = match dispatch_origin.clone().as_signed() {1272 Some(_) => T::WeightInfo::execute_dispatch_signed(),1273 _ => T::WeightInfo::execute_dispatch_unsigned(),1274 };1275 let call_weight = call.get_dispatch_info().weight;1276 1277 let max_weight = base_weight.saturating_add(call_weight);12781279 if !weight.can_accrue(max_weight) {1280 return Err(Overweight);1281 }12821283 let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());12841285 let r = match ensured_origin {1286 Ok(ScheduledEnsureOriginSuccess::Root) => {1287 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1288 }1289 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1290 1291 1292 T::CallExecutor::dispatch_call(Some(sender), call)1293 }1294 Err(e) => Ok(Err(e.into())),1295 };12961297 let (maybe_actual_call_weight, result) = match r {1298 Ok(result) => match result {1299 Ok(post_info) => (post_info.actual_weight, Ok(())),1300 Err(error_and_info) => (1301 error_and_info.post_info.actual_weight,1302 Err(error_and_info.error),1303 ),1304 },1305 Err(_) => {1306 log::error!(1307 target: "runtime::scheduler",1308 "Warning: Scheduler has failed to execute a post-dispatch transaction. \1309 This block might have become invalid.");1310 (None, Err(DispatchError::CannotLookup))1311 }1312 };1313 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1314 weight.check_accrue(base_weight);1315 weight.check_accrue(call_weight);1316 Ok(result)1317 }1318}