difftreelog
style(pallet-scheduler) ignore deprecation warnings
in: master
1 file changed
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//! with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter64//! that can be used for identification.65//! * `cancel_named` - the named complement to the cancel function.6667// Ensure we're `no_std` when compiling for Wasm.68#![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::*;104105/// Just a simple index for naming period tasks.106pub type PeriodicIndex = u32;107/// The location of a scheduled task that can be used to remove it.108pub type TaskAddress<BlockNumber> = (BlockNumber, u32);109110/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.111pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;112113#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]114#[scale_info(skip_type_params(T))]115/// A scheduled call is stored as is or as a preimage hash to lookup.116/// This enum represents both variants.117pub enum ScheduledCall<T: Config> {118 /// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.119 Inline(EncodedCall),120121 /// A Blake2-256 hash of the call together with an upper limit for its size.122 PreimageLookup {123 /// A call hash to lookup124 hash: T::Hash,125126 /// The length of the decoded call127 unbounded_len: u32,128 },129}130131impl<T: Config> ScheduledCall<T> {132 /// Convert an otherwise unbounded or large value into a type ready for placing in storage.133 ///134 /// NOTE: Once this API is used, you should use either `drop` or `realize`.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 /// The maximum length of the lookup that is needed to peek `Self`.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 /// Returns whether the image will require a lookup to be peeked.166 pub fn lookup_needed(&self) -> bool {167 match self {168 Self::Inline(_) => false,169 Self::PreimageLookup { .. } => true,170 }171 }172173 // Decodes a runtime call174 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}179180/// Weight Info for the Preimages fetches.181pub trait SchedulerPreimagesWeightInfo<W: WeightInfo> {182 /// Get the weight of a task fetches with a given decoded length.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}191192/// A scheduler's interface for managing preimages to hashes193/// and looking up preimages from their hash on-chain.194pub trait SchedulerPreimages<T: Config>:195 PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>196{197 /// No longer request that the data for decoding the given `call` is available.198 fn drop(call: &ScheduledCall<T>);199200 /// Convert the given `call` instance back into its original instance, also returning the201 /// exact size of its encoded form if it needed to be looked-up from a stored preimage.202 ///203 /// NOTE: This does not remove any data needed for realization. If you will no longer use the204 /// `call`, use `realize` instead or use `drop` afterwards.205 fn peek(206 call: &ScheduledCall<T>,207 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;208209 /// Convert the given scheduled `call` value back into its original instance. If successful,210 /// `drop` any data backing it. This will not break the realisability of independently211 /// created instances of `ScheduledCall` which happen to have identical data.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}253254/// Scheduler's supported origins.255pub enum ScheduledEnsureOriginSuccess<AccountId> {256 /// A scheduled transaction has the Root origin.257 Root,258259 /// A specific account has signed a scheduled transaction.260 Signed(AccountId),261}262263/// An identifier of a scheduled task.264pub type TaskName = [u8; 32];265266/// Information regarding an item to be executed in the future.267#[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 /// The unique identity for this task, if there is one.271 maybe_id: Option<Name>,272273 /// This task's priority.274 priority: schedule::Priority,275276 /// The call to be dispatched.277 call: Call,278279 /// If the call is periodic, then this points to the information concerning that.280 maybe_periodic: Option<schedule::Period<BlockNumber>>,281282 /// The origin with which to dispatch the call.283 origin: PalletsOrigin,284 _phantom: PhantomData<AccountId>,285}286287/// Information regarding an item to be executed in the future.288pub 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))]298/// A structure for storing scheduled tasks in a block.299/// The `BlockAgenda` tracks the available free space for a new task in a block.4300///301/// The agenda's maximum amount of tasks is `T::MaxScheduledPerBlock`.302pub struct BlockAgenda<T: Config> {303 agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,304 free_places: u32,305}306307impl<T: Config> BlockAgenda<T> {308 /// Tries to push a new scheduled task into the block's agenda.309 /// If there is a free place, the new task will take it,310 /// and the `BlockAgenda` will record that the number of free places has decreased.311 ///312 /// An error containing the scheduled task will be returned if there are no free places.313 ///314 /// The complexity of the check for the *existence* of a free place is O(1).315 /// The complexity of *finding* the free slot is O(n).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 // will always succeed due to the above check.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 /// Sets a slot by the given index and the slot value.339 ///340 /// ### Panics341 /// If the index is out of range, the function will panic.342 fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {343 self.agenda[index as usize] = slot;344 }345346 /// Returns an iterator containing references to the agenda's slots.347 fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {348 self.agenda.iter()349 }350351 /// Returns an immutable reference to a scheduled task if there is one under the given index.352 ///353 /// The function returns `None` if:354 /// * The `index` is out of range355 /// * No scheduled task occupies the agenda slot under the given index.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 /// Returns a mutable reference to a scheduled task if there is one under the given index.364 ///365 /// The function returns `None` if:366 /// * The `index` is out of range367 /// * No scheduled task occupies the agenda slot under the given index.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 /// Take a scheduled task by the given index.376 ///377 /// If there is a task under the index, the function will:378 /// * Free the corresponding agenda slot.379 /// * Decrease the number of free places.380 /// * Return the scheduled task.381 ///382 /// The function returns `None` if there is no task under the index.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}405/// A structure for tracking the used weight406/// and checking if it does not exceed the weight limit.407struct WeightCounter {408 used: Weight,409 limit: Weight,410}411412impl WeightCounter {413 /// Checks if the weight `w` can be accommodated by the counter.414 ///415 /// If there is room for the additional weight `w`,416 /// the function will update the used weight and return true.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 /// Checks if the weight `w` can be accommodated by the counter.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 /// Return the weight of servicing a single task.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 /// The current storage version.460 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);461462 #[pallet::pallet]463 #[pallet::storage_version(STORAGE_VERSION)]464 pub struct Pallet<T>(_);465466 #[pallet::config]467 pub trait Config: frame_system::Config {468 /// The overarching event type.469 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;470471 /// The aggregated origin which the dispatch will take.472 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>473 + From<Self::PalletsOrigin>474 + IsType<<Self as system::Config>::RuntimeOrigin>475 + Clone;476477 /// The caller origin, overarching type of all pallets origins.478 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>479 + Codec480 + Clone481 + Eq482 + TypeInfo483 + MaxEncodedLen;484485 /// The aggregated call type.486 type RuntimeCall: Parameter487 + Dispatchable<488 RuntimeOrigin = <Self as Config>::RuntimeOrigin,489 PostInfo = PostDispatchInfo,490 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>491 + GetDispatchInfo492 + From<system::Call<Self>>;493494 /// The maximum weight that may be scheduled per block for any dispatchables.495 #[pallet::constant]496 type MaximumWeight: Get<Weight>;497498 /// Required origin to schedule or cancel calls.499 type ScheduleOrigin: EnsureOrigin<500 <Self as system::Config>::RuntimeOrigin,501 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,502 >;503504 /// Compare the privileges of origins.505 ///506 /// This will be used when canceling a task, to ensure that the origin that tries507 /// to cancel has greater or equal privileges as the origin that created the scheduled task.508 ///509 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can510 /// be used. This will only check if two given origins are equal.511 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;512513 /// The maximum number of scheduled calls in the queue for a single block.514 #[pallet::constant]515 type MaxScheduledPerBlock: Get<u32>;516517 /// Weight information for extrinsics in this pallet.518 type WeightInfo: WeightInfo;519520 /// The preimage provider with which we look up call hashes to get the call.521 type Preimages: SchedulerPreimages<Self>;522523 /// The helper type used for custom transaction fee logic.524 type CallExecutor: DispatchCall<Self, H160>;525526 /// Required origin to set/change calls' priority.527 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;528 }529530 /// It contains the block number from which we should service tasks.531 /// It's used for delaying the servicing of future blocks' agendas if we had overweight tasks.532 #[pallet::storage]533 pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;534535 /// Items to be executed, indexed by the block number that they should be executed on.536 #[pallet::storage]537 pub type Agenda<T: Config> =538 StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;539540 /// Lookup from a name to the block number and index of the task.541 #[pallet::storage]542 pub(crate) type Lookup<T: Config> =543 StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;544545 /// Events type.546 #[pallet::event]547 #[pallet::generate_deposit(pub(super) fn deposit_event)]548 pub enum Event<T: Config> {549 /// Scheduled some task.550 Scheduled {551 /// The block number in which the scheduled task should be executed.552 when: T::BlockNumber,553554 /// The index of the block's agenda slot.555 index: u32,556 },557 /// Canceled some task.558 Canceled {559 /// The block number in which the canceled task has been.560 when: T::BlockNumber,561562 /// The index of the block's agenda slot that had become available.563 index: u32,564 },565 /// Dispatched some task.566 Dispatched {567 /// The task's address - the block number and the block's agenda index.568 task: TaskAddress<T::BlockNumber>,569570 /// The task's name if it is not anonymous.571 id: Option<[u8; 32]>,572573 /// The task's execution result.574 result: DispatchResult,575 },576 /// Scheduled task's priority has changed577 PriorityChanged {578 /// The task's address - the block number and the block's agenda index.579 task: TaskAddress<T::BlockNumber>,580581 /// The new priority of the task.582 priority: schedule::Priority,583 },584 /// The call for the provided hash was not found so the task has been aborted.585 CallUnavailable {586 /// The task's address - the block number and the block's agenda index.587 task: TaskAddress<T::BlockNumber>,588589 /// The task's name if it is not anonymous.590 id: Option<[u8; 32]>,591 },592 /// The given task can never be executed since it is overweight.593 PermanentlyOverweight {594 /// The task's address - the block number and the block's agenda index.595 task: TaskAddress<T::BlockNumber>,596597 /// The task's name if it is not anonymous.598 id: Option<[u8; 32]>,599 },600 }601602 #[pallet::error]603 pub enum Error<T> {604 /// Failed to schedule a call605 FailedToSchedule,606 /// There is no place for a new task in the agenda607 AgendaIsExhausted,608 /// Scheduled call is corrupted609 ScheduledCallCorrupted,610 /// Scheduled call preimage is not found611 PreimageNotFound,612 /// Scheduled call is too big613 TooBigScheduledCall,614 /// Cannot find the scheduled call.615 NotFound,616 /// Given target block number is in the past.617 TargetBlockNumberInPast,618 /// Attempt to use a non-named function on a named task.619 Named,620 }621622 #[pallet::hooks]623 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {624 /// Execute the scheduled calls625 fn on_initialize(now: T::BlockNumber) -> Weight {626 let mut weight_counter = WeightCounter {627 used: Weight::zero(),628 limit: T::MaximumWeight::get(),629 };630 Self::service_agendas(&mut weight_counter, now, u32::max_value());631 weight_counter.used632 }633 }634635 #[pallet::call]636 impl<T: Config> Pallet<T> {637 /// Anonymously schedule a task.638 ///639 /// Only `T::ScheduleOrigin` is allowed to schedule a task.640 /// Only `T::PrioritySetOrigin` is allowed to set the task's priority.641 #[pallet::call_index(0)]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 /// Cancel an anonymously scheduled task.668 ///669 /// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.670 #[pallet::call_index(1)]671 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]672 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {673 T::ScheduleOrigin::ensure_origin(origin.clone())?;674 let origin = <T as Config>::RuntimeOrigin::from(origin);675 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;676 Ok(())677 }678679 /// Schedule a named task.680 ///681 /// Only `T::ScheduleOrigin` is allowed to schedule a task.682 /// Only `T::PrioritySetOrigin` is allowed to set the task's priority.683 #[pallet::call_index(2)]684 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]685 pub fn schedule_named(686 origin: OriginFor<T>,687 id: TaskName,688 when: T::BlockNumber,689 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,690 priority: Option<schedule::Priority>,691 call: Box<<T as Config>::RuntimeCall>,692 ) -> DispatchResult {693 T::ScheduleOrigin::ensure_origin(origin.clone())?;694695 if priority.is_some() {696 T::PrioritySetOrigin::ensure_origin(origin.clone())?;697 }698699 let origin = <T as Config>::RuntimeOrigin::from(origin);700 Self::do_schedule_named(701 id,702 DispatchTime::At(when),703 maybe_periodic,704 priority.unwrap_or(LOWEST_PRIORITY),705 origin.caller().clone(),706 <ScheduledCall<T>>::new(*call)?,707 )?;708 Ok(())709 }710711 /// Cancel a named scheduled task.712 ///713 /// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.714 #[pallet::call_index(3)]715 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]716 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {717 T::ScheduleOrigin::ensure_origin(origin.clone())?;718 let origin = <T as Config>::RuntimeOrigin::from(origin);719 Self::do_cancel_named(Some(origin.caller().clone()), id)?;720 Ok(())721 }722723 /// Anonymously schedule a task after a delay.724 ///725 /// # <weight>726 /// Same as [`schedule`].727 /// # </weight>728 #[pallet::call_index(4)]729 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]730 pub fn schedule_after(731 origin: OriginFor<T>,732 after: T::BlockNumber,733 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,734 priority: Option<schedule::Priority>,735 call: Box<<T as Config>::RuntimeCall>,736 ) -> DispatchResult {737 T::ScheduleOrigin::ensure_origin(origin.clone())?;738739 if priority.is_some() {740 T::PrioritySetOrigin::ensure_origin(origin.clone())?;741 }742743 let origin = <T as Config>::RuntimeOrigin::from(origin);744 Self::do_schedule(745 DispatchTime::After(after),746 maybe_periodic,747 priority.unwrap_or(LOWEST_PRIORITY),748 origin.caller().clone(),749 <ScheduledCall<T>>::new(*call)?,750 )?;751 Ok(())752 }753754 /// Schedule a named task after a delay.755 ///756 /// Only `T::ScheduleOrigin` is allowed to schedule a task.757 /// Only `T::PrioritySetOrigin` is allowed to set the task's priority.758 ///759 /// # <weight>760 /// Same as [`schedule_named`](Self::schedule_named).761 /// # </weight>762 #[pallet::call_index(5)]763 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]764 pub fn schedule_named_after(765 origin: OriginFor<T>,766 id: TaskName,767 after: T::BlockNumber,768 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,769 priority: Option<schedule::Priority>,770 call: Box<<T as Config>::RuntimeCall>,771 ) -> DispatchResult {772 T::ScheduleOrigin::ensure_origin(origin.clone())?;773774 if priority.is_some() {775 T::PrioritySetOrigin::ensure_origin(origin.clone())?;776 }777778 let origin = <T as Config>::RuntimeOrigin::from(origin);779 Self::do_schedule_named(780 id,781 DispatchTime::After(after),782 maybe_periodic,783 priority.unwrap_or(LOWEST_PRIORITY),784 origin.caller().clone(),785 <ScheduledCall<T>>::new(*call)?,786 )?;787 Ok(())788 }789790 /// Change a named task's priority.791 ///792 /// Only the `T::PrioritySetOrigin` is allowed to change the task's priority.793 #[pallet::call_index(6)]794 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]795 pub fn change_named_priority(796 origin: OriginFor<T>,797 id: TaskName,798 priority: schedule::Priority,799 ) -> DispatchResult {800 T::PrioritySetOrigin::ensure_origin(origin.clone())?;801 let origin = <T as Config>::RuntimeOrigin::from(origin);802 Self::do_change_named_priority(origin.caller().clone(), id, priority)803 }804 }805}806807impl<T: Config> Pallet<T> {808 /// Converts the `DispatchTime` to the `BlockNumber`.809 ///810 /// Returns an error if the block number is in the past.811 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {812 let now = frame_system::Pallet::<T>::block_number();813814 let when = match when {815 DispatchTime::At(x) => x,816 // The current block has already completed it's scheduled tasks, so817 // Schedule the task at lest one block after this current block.818 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),819 };820821 if when <= now {822 return Err(Error::<T>::TargetBlockNumberInPast.into());823 }824825 Ok(when)826 }827828 /// Places the mandatory task.829 ///830 /// It will try to place the task into the block pointed by the `when` parameter.831 ///832 /// If the block has no room for a task,833 /// the function will search for a future block that can accommodate the task.834 fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {835 Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");836 }837838 /// Tries to place a task `what` into the given block `when`.839 ///840 /// Returns an error if the block has no room for the task.841 fn try_place_task(842 when: T::BlockNumber,843 what: ScheduledOf<T>,844 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {845 Self::place_task(when, what, false)846 }847848 /// If `is_mandatory` is true, the function behaves like [`mandatory_place_task`](Self::mandatory_place_task);849 /// otherwise it acts like [`try_place_task`](Self::try_place_task).850 ///851 /// The function also updates the `Lookup` storage.852 fn place_task(853 mut when: T::BlockNumber,854 what: ScheduledOf<T>,855 is_mandatory: bool,856 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {857 let maybe_name = what.maybe_id;858 let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;859 let address = (when, index);860 if let Some(name) = maybe_name {861 Lookup::<T>::insert(name, address)862 }863 Self::deposit_event(Event::Scheduled {864 when: address.0,865 index: address.1,866 });867 Ok(address)868 }869870 /// Pushes the scheduled task into the block's agenda.871 ///872 /// If `is_mandatory` is true, it searches for a block with a free slot for the given task.873 ///874 /// If `is_mandatory` is false and there is no free slot, the function returns an error.875 fn push_to_agenda(876 when: &mut T::BlockNumber,877 mut what: ScheduledOf<T>,878 is_mandatory: bool,879 ) -> Result<u32, DispatchError> {880 let mut agenda;881882 let index = loop {883 agenda = Agenda::<T>::get(*when);884885 match agenda.try_push(what) {886 Ok(index) => break index,887 Err(returned_what) if is_mandatory => {888 what = returned_what;889 when.saturating_inc();890 }891 Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),892 }893 };894895 Agenda::<T>::insert(when, agenda);896 Ok(index)897 }898899 fn do_schedule(900 when: DispatchTime<T::BlockNumber>,901 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,902 priority: schedule::Priority,903 origin: T::PalletsOrigin,904 call: ScheduledCall<T>,905 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {906 let when = Self::resolve_time(when)?;907908 // sanitize maybe_periodic909 let maybe_periodic = maybe_periodic910 .filter(|p| p.1 > 1 && !p.0.is_zero())911 // Remove one from the number of repetitions since we will schedule one now.912 .map(|(p, c)| (p, c - 1));913 let task = Scheduled {914 maybe_id: None,915 priority,916 call,917 maybe_periodic,918 origin,919 _phantom: PhantomData,920 };921 Self::try_place_task(when, task)922 }923924 fn do_cancel(925 origin: Option<T::PalletsOrigin>,926 (when, index): TaskAddress<T::BlockNumber>,927 ) -> Result<(), DispatchError> {928 let scheduled = Agenda::<T>::try_mutate(929 when,930 |agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {931 let scheduled = match agenda.get(index) {932 Some(scheduled) => scheduled,933 None => return Ok(None),934 };935936 if let Some(ref o) = origin {937 if matches!(938 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),939 Some(Ordering::Less) | None940 ) {941 return Err(BadOrigin.into());942 }943 }944945 Ok(agenda.take(index))946 },947 )?;948 if let Some(s) = scheduled {949 T::Preimages::drop(&s.call);950951 if let Some(id) = s.maybe_id {952 Lookup::<T>::remove(id);953 }954 Self::deposit_event(Event::Canceled { when, index });955 Ok(())956 } else {957 Err(Error::<T>::NotFound.into())958 }959 }960961 fn do_schedule_named(962 id: TaskName,963 when: DispatchTime<T::BlockNumber>,964 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,965 priority: schedule::Priority,966 origin: T::PalletsOrigin,967 call: ScheduledCall<T>,968 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {969 // ensure id it is unique970 if Lookup::<T>::contains_key(&id) {971 return Err(Error::<T>::FailedToSchedule.into());972 }973974 let when = Self::resolve_time(when)?;975976 // sanitize maybe_periodic977 let maybe_periodic = maybe_periodic978 .filter(|p| p.1 > 1 && !p.0.is_zero())979 // Remove one from the number of repetitions since we will schedule one now.980 .map(|(p, c)| (p, c - 1));981982 let task = Scheduled {983 maybe_id: Some(id),984 priority,985 call,986 maybe_periodic,987 origin,988 _phantom: Default::default(),989 };990 Self::try_place_task(when, task)991 }992993 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {994 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {995 if let Some((when, index)) = lookup.take() {996 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {997 let scheduled = match agenda.get(index) {998 Some(scheduled) => scheduled,999 None => return Ok(()),1000 };10011002 if let Some(ref o) = origin {1003 if matches!(1004 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),1005 Some(Ordering::Less) | None1006 ) {1007 return Err(BadOrigin.into());1008 }1009 T::Preimages::drop(&scheduled.call);1010 }10111012 agenda.take(index);10131014 Ok(())1015 })?;1016 Self::deposit_event(Event::Canceled { when, index });1017 Ok(())1018 } else {1019 Err(Error::<T>::NotFound.into())1020 }1021 })1022 }10231024 fn do_change_named_priority(1025 origin: T::PalletsOrigin,1026 id: TaskName,1027 priority: schedule::Priority,1028 ) -> DispatchResult {1029 match Lookup::<T>::get(id) {1030 Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {1031 let scheduled = match agenda.get_mut(index) {1032 Some(scheduled) => scheduled,1033 None => return Ok(()),1034 };10351036 if matches!(1037 T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),1038 Some(Ordering::Less) | None1039 ) {1040 return Err(BadOrigin.into());1041 }10421043 scheduled.priority = priority;1044 Self::deposit_event(Event::PriorityChanged {1045 task: (when, index),1046 priority,1047 });10481049 Ok(())1050 }),1051 None => Err(Error::<T>::NotFound.into()),1052 }1053 }1054}10551056enum ServiceTaskError {1057 /// Could not be executed due to missing preimage.1058 Unavailable,1059 /// Could not be executed due to weight limitations.1060 Overweight,1061}1062use ServiceTaskError::*;10631064/// A Scheduler-Runtime interface for finer payment handling.1065pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {1066 /// Resolve the call dispatch, including any post-dispatch operations.1067 fn dispatch_call(1068 signer: Option<T::AccountId>,1069 function: <T as Config>::RuntimeCall,1070 ) -> Result<1071 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,1072 TransactionValidityError,1073 >;1074}10751076impl<T: Config> Pallet<T> {1077 /// Service up to `max` agendas queue starting from earliest incompletely executed agenda.1078 fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {1079 if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {1080 return;1081 }10821083 let mut incomplete_since = now + One::one();1084 let mut when = IncompleteSince::<T>::take().unwrap_or(now);1085 let mut executed = 0;10861087 let max_items = T::MaxScheduledPerBlock::get();1088 let mut count_down = max;1089 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);1090 while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {1091 if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {1092 incomplete_since = incomplete_since.min(when);1093 }1094 when.saturating_inc();1095 count_down.saturating_dec();1096 }1097 incomplete_since = incomplete_since.min(when);1098 if incomplete_since <= now {1099 IncompleteSince::<T>::put(incomplete_since);1100 }1101 }11021103 /// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a1104 /// later block.1105 fn service_agenda(1106 weight: &mut WeightCounter,1107 executed: &mut u32,1108 now: T::BlockNumber,1109 when: T::BlockNumber,1110 max: u32,1111 ) -> bool {1112 let mut agenda = Agenda::<T>::get(when);1113 let mut ordered = agenda1114 .iter()1115 .enumerate()1116 .filter_map(|(index, maybe_item)| {1117 maybe_item1118 .as_ref()1119 .map(|item| (index as u32, item.priority))1120 })1121 .collect::<Vec<_>>();1122 ordered.sort_by_key(|k| k.1);1123 let within_limit =1124 weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));1125 debug_assert!(1126 within_limit,1127 "weight limit should have been checked in advance"1128 );11291130 // Items which we know can be executed and have postponed for execution in a later block.1131 let mut postponed = (ordered.len() as u32).saturating_sub(max);1132 // Items which we don't know can ever be executed.1133 let mut dropped = 0;11341135 for (agenda_index, _) in ordered.into_iter().take(max as usize) {1136 let task = match agenda.take(agenda_index).take() {1137 None => continue,1138 Some(t) => t,1139 };1140 let base_weight = MarginalWeightInfo::<T>::service_task(1141 task.call.lookup_len().map(|x| x as usize),1142 task.maybe_id.is_some(),1143 task.maybe_periodic.is_some(),1144 );1145 if !weight.can_accrue(base_weight) {1146 postponed += 1;1147 break;1148 }1149 let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);1150 match result {1151 Err((Unavailable, slot)) => {1152 dropped += 1;1153 agenda.set_slot(agenda_index, slot);1154 }1155 Err((Overweight, slot)) => {1156 postponed += 1;1157 agenda.set_slot(agenda_index, slot);1158 }1159 Ok(()) => {1160 *executed += 1;1161 }1162 };1163 }1164 if postponed > 0 || dropped > 0 {1165 Agenda::<T>::insert(when, agenda);1166 } else {1167 Agenda::<T>::remove(when);1168 }1169 postponed == 01170 }11711172 /// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.1173 ///1174 /// This involves:1175 /// - removing and potentially replacing the `Lookup` entry for the task.1176 /// - realizing the task's call which can include a preimage lookup.1177 /// - Rescheduling the task for execution in a later agenda if periodic.1178 fn service_task(1179 weight: &mut WeightCounter,1180 now: T::BlockNumber,1181 when: T::BlockNumber,1182 agenda_index: u32,1183 is_first: bool,1184 mut task: ScheduledOf<T>,1185 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1186 let (call, lookup_len) = match T::Preimages::peek(&task.call) {1187 Ok(c) => c,1188 Err(_) => {1189 if let Some(ref id) = task.maybe_id {1190 Lookup::<T>::remove(id);1191 }11921193 return Err((Unavailable, Some(task)));1194 }1195 };11961197 weight.check_accrue(MarginalWeightInfo::<T>::service_task(1198 lookup_len.map(|x| x as usize),1199 task.maybe_id.is_some(),1200 task.maybe_periodic.is_some(),1201 ));12021203 match Self::execute_dispatch(weight, task.origin.clone(), call) {1204 Err(Unavailable) => {1205 debug_assert!(false, "Checked to exist with `peek`");12061207 if let Some(ref id) = task.maybe_id {1208 Lookup::<T>::remove(id);1209 }12101211 Self::deposit_event(Event::CallUnavailable {1212 task: (when, agenda_index),1213 id: task.maybe_id,1214 });1215 Err((Unavailable, Some(task)))1216 }1217 Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1218 T::Preimages::drop(&task.call);12191220 if let Some(ref id) = task.maybe_id {1221 Lookup::<T>::remove(id);1222 }12231224 Self::deposit_event(Event::PermanentlyOverweight {1225 task: (when, agenda_index),1226 id: task.maybe_id,1227 });1228 Err((Unavailable, Some(task)))1229 }1230 Err(Overweight) => {1231 // Preserve Lookup -- the task will be postponed.1232 Err((Overweight, Some(task)))1233 }1234 Ok(result) => {1235 Self::deposit_event(Event::Dispatched {1236 task: (when, agenda_index),1237 id: task.maybe_id,1238 result,1239 });12401241 let is_canceled = task1242 .maybe_id1243 .as_ref()1244 .map(|id| !Lookup::<T>::contains_key(id))1245 .unwrap_or(false);12461247 match &task.maybe_periodic {1248 &Some((period, count)) if !is_canceled => {1249 if count > 1 {1250 task.maybe_periodic = Some((period, count - 1));1251 } else {1252 task.maybe_periodic = None;1253 }1254 let wake = now.saturating_add(period);1255 Self::mandatory_place_task(wake, task);1256 }1257 _ => {1258 if let Some(ref id) = task.maybe_id {1259 Lookup::<T>::remove(id);1260 }12611262 T::Preimages::drop(&task.call)1263 }1264 }1265 Ok(())1266 }1267 }1268 }12691270 fn is_runtime_upgraded() -> bool {1271 let last = system::LastRuntimeUpgrade::<T>::get();1272 let current = T::Version::get();12731274 last.map(|v| v.was_upgraded(¤t)).unwrap_or(true)1275 }12761277 /// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1278 /// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1279 /// post info if available).1280 ///1281 /// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1282 /// call itself).1283 fn execute_dispatch(1284 weight: &mut WeightCounter,1285 origin: T::PalletsOrigin,1286 call: <T as Config>::RuntimeCall,1287 ) -> Result<DispatchResult, ServiceTaskError> {1288 let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1289 let base_weight = match dispatch_origin.clone().as_signed() {1290 Some(_) => T::WeightInfo::execute_dispatch_signed(),1291 _ => T::WeightInfo::execute_dispatch_unsigned(),1292 };1293 let call_weight = call.get_dispatch_info().weight;1294 // We only allow a scheduled call if it cannot push the weight past the limit.1295 let max_weight = base_weight.saturating_add(call_weight);12961297 if !weight.can_accrue(max_weight) {1298 return Err(Overweight);1299 }13001301 let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());13021303 let r = match ensured_origin {1304 Ok(ScheduledEnsureOriginSuccess::Root) => {1305 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1306 }1307 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1308 // Execute transaction via chain default pipeline1309 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1310 T::CallExecutor::dispatch_call(Some(sender), call)1311 }1312 Err(e) => Ok(Err(e.into())),1313 };13141315 let (maybe_actual_call_weight, result) = match r {1316 Ok(result) => match result {1317 Ok(post_info) => (post_info.actual_weight, Ok(())),1318 Err(error_and_info) => (1319 error_and_info.post_info.actual_weight,1320 Err(error_and_info.error),1321 ),1322 },1323 Err(_) => {1324 log::error!(1325 target: "runtime::scheduler",1326 "Warning: Scheduler has failed to execute a post-dispatch transaction. \1327 This block might have become invalid.");1328 (None, Err(DispatchError::CannotLookup))1329 }1330 };1331 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1332 weight.check_accrue(base_weight);1333 weight.check_accrue(call_weight);1334 Ok(result)1335 }1336}