12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970#![cfg_attr(not(feature = "std"), no_std)]7172#[cfg(feature = "runtime-benchmarks")]73mod benchmarking;7475pub mod weights;7677use sp_core::H160;78use codec::{Codec, Decode, Encode};79use frame_system::{self as system, ensure_signed};80pub use pallet::*;81use scale_info::TypeInfo;82use sp_runtime::{83 traits::{BadOrigin, One, Saturating, Zero},84 RuntimeDebug, DispatchErrorWithPostInfo,85};86use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};8788use frame_support::{89 dispatch::{DispatchError, DispatchResult, Dispatchable, UnfilteredDispatchable, Parameter},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{Weight},96};9798pub use weights::WeightInfo;99100101pub type TaskAddress<BlockNumber> = (BlockNumber, u32);102pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;103104type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];105pub type CallOrHashOf<T> =106 MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;107108109#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]110#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]111pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {112 113 maybe_id: Option<ScheduledId>,114 115 priority: schedule::Priority,116 117 call: Call,118 119 maybe_periodic: Option<schedule::Period<BlockNumber>>,120 121 origin: PalletsOrigin,122 _phantom: PhantomData<AccountId>,123}124125pub type ScheduledV3Of<T> = ScheduledV3<126 CallOrHashOf<T>,127 <T as frame_system::Config>::BlockNumber,128 <T as Config>::PalletsOrigin,129 <T as frame_system::Config>::AccountId,130>;131132pub type ScheduledOf<T> = ScheduledV3Of<T>;133134135pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =136 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;137138pub enum ScheduledEnsureOriginSuccess<AccountId> {139 Root,140 Signed(AccountId),141 Unsigned,142}143144#[cfg(feature = "runtime-benchmarks")]145mod preimage_provider {146 use frame_support::traits::PreimageRecipient;147 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}148 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}149}150151#[cfg(not(feature = "runtime-benchmarks"))]152mod preimage_provider {153 use frame_support::traits::PreimageProvider;154 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}155 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}156}157158pub use preimage_provider::PreimageProviderAndMaybeRecipient;159160pub(crate) trait MarginalWeightInfo: WeightInfo {161 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {162 match (periodic, named, resolved) {163 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),164 (_, true, None) => {165 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)166 }167 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),168 (false, true, Some(false)) => {169 Self::on_initialize_named(2) - Self::on_initialize_named(1)170 }171 (true, false, Some(false)) => {172 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)173 }174 (true, true, Some(false)) => {175 Self::on_initialize_periodic_named_resolved(2)176 - Self::on_initialize_periodic_named_resolved(1)177 }178 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),179 (false, true, Some(true)) => {180 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)181 }182 (true, false, Some(true)) => {183 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)184 }185 (true, true, Some(true)) => {186 Self::on_initialize_periodic_named_resolved(2)187 - Self::on_initialize_periodic_named_resolved(1)188 }189 }190 }191}192impl<T: WeightInfo> MarginalWeightInfo for T {}193194#[frame_support::pallet]195pub mod pallet {196 use super::*;197 use frame_support::{198 dispatch::PostDispatchInfo,199 pallet_prelude::*,200 traits::{201 schedule::{LookupError, LOWEST_PRIORITY},202 PreimageProvider,203 },204 };205 use frame_system::pallet_prelude::*;206207 208 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);209210 #[pallet::pallet]211 #[pallet::generate_store(pub(super) trait Store)]212 #[pallet::storage_version(STORAGE_VERSION)]213 #[pallet::without_storage_info]214 pub struct Pallet<T>(_);215216 217 #[pallet::config]218 pub trait Config: frame_system::Config {219 220 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;221222 223 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>224 + From<Self::PalletsOrigin>225 + IsType<<Self as system::Config>::RuntimeOrigin>;226227 228 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;229230 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;231232 233 type RuntimeCall: Parameter234 + Dispatchable<Origin = <Self as Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>235 + UnfilteredDispatchable<Origin = <Self as system::Config>::RuntimeOrigin>236 + GetDispatchInfo237 + From<system::RuntimeCall<Self>>;238239 240 241 #[pallet::constant]242 type MaximumWeight: Get<Weight>;243244 245 type ScheduleOrigin: EnsureOrigin<246 <Self as system::Config>::RuntimeOrigin,247 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,248 >;249250 251 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;252253 254 255 256 257 258 259 260 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;261262 263 264 #[pallet::constant]265 type MaxScheduledPerBlock: Get<u32>;266267 268 type WeightInfo: WeightInfo;269270 271 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;272273 274 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;275276 277 278279 280 type CallExecutor: DispatchCall<Self, H160>;281 }282283 284 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {285 286 fn reserve_balance(287 id: ScheduledId,288 sponsor: <T as frame_system::Config>::AccountId,289 call: <T as Config>::RuntimeCall,290 count: u32,291 ) -> Result<(), DispatchError>;292293 294 fn pay_for_call(295 id: ScheduledId,296 sponsor: <T as frame_system::Config>::AccountId,297 call: <T as Config>::RuntimeCall,298 ) -> Result<u128, DispatchError>;299300 301 fn dispatch_call(302 signer: Option<T::AccountId>,303 function: <T as Config>::RuntimeCall,304 ) -> Result<305 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,306 TransactionValidityError,307 >;308309 310 fn cancel_reserve(311 id: ScheduledId,312 sponsor: <T as frame_system::Config>::AccountId,313 ) -> Result<u128, DispatchError>;314 }315316 317 #[pallet::storage]318 pub type Agenda<T: Config> =319 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;320321 322 #[pallet::storage]323 pub(crate) type Lookup<T: Config> =324 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;325326 327 #[pallet::event]328 #[pallet::generate_deposit(pub(super) fn deposit_event)]329 pub enum Event<T: Config> {330 331 Scheduled { when: T::BlockNumber, index: u32 },332 333 Canceled { when: T::BlockNumber, index: u32 },334 335 PriorityChanged {336 when: T::BlockNumber,337 index: u32,338 priority: schedule::Priority,339 },340 341 Dispatched {342 task: TaskAddress<T::BlockNumber>,343 id: Option<ScheduledId>,344 result: DispatchResult,345 },346 347 CallLookupFailed {348 task: TaskAddress<T::BlockNumber>,349 id: Option<ScheduledId>,350 error: LookupError,351 },352 }353354 #[pallet::error]355 pub enum Error<T> {356 357 FailedToSchedule,358 359 NotFound,360 361 TargetBlockNumberInPast,362 363 RescheduleNoChange,364 }365366 #[pallet::hooks]367 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {368 369 fn on_initialize(now: T::BlockNumber) -> Weight {370 let limit = T::MaximumWeight::get();371372 let mut queued = Agenda::<T>::take(now)373 .into_iter()374 .enumerate()375 .filter_map(|(index, s)| Some((index as u32, s?)))376 .collect::<Vec<_>>();377378 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {379 log::warn!(380 target: "runtime::scheduler",381 "Warning: This block has more items queued in Scheduler than \382 expected from the runtime configuration. An update might be needed."383 );384 }385386 queued.sort_by_key(|(_, s)| s.priority);387388 let next = now + One::one();389390 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);391 for (order, (index, mut s)) in queued.into_iter().enumerate() {392 let named = s.maybe_id.is_some();393394 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();395 s.call = call;396397 let resolved = if let Some(completed) = maybe_completed {398 T::PreimageProvider::unrequest_preimage(&completed);399 true400 } else {401 false402 };403 let call = match s.call.as_value().cloned() {404 Some(c) => c,405 None => {406 407 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));408 if let Some(delay) = T::NoPreimagePostponement::get() {409 let until = now.saturating_add(delay);410 if let Some(ref id) = s.maybe_id {411 let index = Agenda::<T>::decode_len(until).unwrap_or(0);412 Lookup::<T>::insert(id, (until, index as u32));413 }414 Agenda::<T>::append(until, Some(s));415 } else if let Some(ref id) = s.maybe_id {416 Lookup::<T>::remove(id);417 }418 continue;419 }420 };421422 let periodic = s.maybe_periodic.is_some();423 let call_weight = call.get_dispatch_info().weight;424 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));425 let origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(426 s.origin.clone(),427 )428 .into();429 if ensure_signed(origin).is_ok() {430 431 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));432 }433434 435 436 437 438 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;439 let test_weight = total_weight440 .saturating_add(call_weight)441 .saturating_add(item_weight);442 if !hard_deadline && order > 0 && test_weight.all_gt(limit) {443 444 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));445 if let Some(ref id) = s.maybe_id {446 447 448 449 450 let index = Agenda::<T>::decode_len(next).unwrap_or(0);451 Lookup::<T>::insert(id, (next, index as u32));452 }453 Agenda::<T>::append(next, Some(s));454 continue;455 }456457 let scheduled_origin =458 <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(s.origin.clone());459 let ensured_origin =460 T::ScheduleOrigin::ensure_origin(scheduled_origin.into()).unwrap();461462 let r;463 let r = match ensured_origin {464 ...465 ScheduledEnsureOriginSuccess::Root => {466 r = Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()));467 }468 ScheduledEnsureOriginSuccess::Signed(sender) => {469 470 471 r = T::CallExecutor::dispatch_call(Some(sender), call.clone());472 }473 ScheduledEnsureOriginSuccess::Unsigned => {474 475 r = T::CallExecutor::dispatch_call(None, call.clone());476 }477 }478479 let mut actual_call_weight: Weight = item_weight;480 let result: Result<_, DispatchError> = match r {481 Ok(o) => match o {482 Ok(di) => {483 actual_call_weight = di.actual_weight.unwrap_or(item_weight);484 Ok(())485 }486 Err(err) => Err(err.error),487 },488 Err(_) => {489 log::error!(490 target: "runtime::scheduler",491 "Warning: Scheduler has failed to execute a post-dispatch transaction. \492 This block might have become invalid.");493 Err(DispatchError::CannotLookup)494 } 495 };496497 total_weight.saturating_accrue(item_weight);498 total_weight.saturating_accrue(actual_call_weight);499500 Self::deposit_event(Event::Dispatched {501 task: (now, index),502 id: s.maybe_id.clone(),503 result,504 });505506 if let &Some((period, count)) = &s.maybe_periodic {507 if count > 1 {508 s.maybe_periodic = Some((period, count - 1));509 } else {510 s.maybe_periodic = None;511 }512 let wake = now + period;513 let is_canceled;514515 516 if let Some(ref id) = s.maybe_id {517 is_canceled = Lookup::<T>::get(id).is_none();518 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);519520 if !is_canceled {521 Lookup::<T>::insert(id, (wake, wake_index as u32));522 }523 } else {524 is_canceled = false;525 }526527 if !is_canceled {528 Agenda::<T>::append(wake, Some(s));529 }530 } else if let Some(ref id) = s.maybe_id {531 Lookup::<T>::remove(id);532 }533 }534 total_weight535 }536 }537538 #[pallet::call]539 impl<T: Config> Pallet<T> {540 541 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]542 pub fn schedule_named(543 origin: OriginFor<T>,544 id: ScheduledId,545 when: T::BlockNumber,546 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,547 priority: Option<schedule::Priority>,548 call: Box<CallOrHashOf<T>>,549 ) -> DispatchResult {550 T::ScheduleOrigin::ensure_origin(origin.clone())?;551552 if priority.is_some() {553 T::PrioritySetOrigin::ensure_origin(origin.clone())?;554 }555556 let origin = <T as Config>::RuntimeOrigin::from(origin);557 Self::do_schedule_named(558 id,559 DispatchTime::At(when),560 maybe_periodic,561 priority.unwrap_or(LOWEST_PRIORITY),562 origin.caller().clone(),563 *call,564 )?;565 Ok(())566 }567568 569 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]570 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {571 T::ScheduleOrigin::ensure_origin(origin.clone())?;572 let origin = <T as Config>::RuntimeOrigin::from(origin);573 Self::do_cancel_named(Some(origin.caller().clone()), id)?;574 Ok(())575 }576577 578 579 580 581 582 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]583 pub fn schedule_named_after(584 origin: OriginFor<T>,585 id: ScheduledId,586 after: T::BlockNumber,587 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,588 priority: Option<schedule::Priority>,589 call: Box<CallOrHashOf<T>>,590 ) -> DispatchResult {591 T::ScheduleOrigin::ensure_origin(origin.clone())?;592593 if priority.is_some() {594 T::PrioritySetOrigin::ensure_origin(origin.clone())?;595 }596597 let origin = <T as Config>::RuntimeOrigin::from(origin);598 Self::do_schedule_named(599 id,600 DispatchTime::After(after),601 maybe_periodic,602 priority.unwrap_or(LOWEST_PRIORITY),603 origin.caller().clone(),604 *call,605 )?;606 Ok(())607 }608609 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]610 pub fn change_named_priority(611 origin: OriginFor<T>,612 id: ScheduledId,613 priority: schedule::Priority,614 ) -> DispatchResult {615 T::PrioritySetOrigin::ensure_origin(origin.clone())?;616 let origin = <T as Config>::Origin::from(origin);617 Self::do_change_named_priority(origin.caller().clone(), id, priority)618 }619 }620}621622impl<T: Config> Pallet<T> {623 #[cfg(feature = "try-runtime")]624 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {625 Ok(())626 }627628 #[cfg(feature = "try-runtime")]629 pub fn post_migrate_to_v3() -> Result<(), &'static str> {630 use frame_support::dispatch::GetStorageVersion;631632 assert!(Self::current_storage_version() == 3);633 for k in Agenda::<T>::iter_keys() {634 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;635 }636 Ok(())637 }638639 640 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {641 Agenda::<T>::translate::<642 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,643 _,644 >(|_, agenda| {645 Some(646 agenda647 .into_iter()648 .map(|schedule| {649 schedule.map(|schedule| Scheduled {650 maybe_id: schedule.maybe_id,651 priority: schedule.priority,652 call: schedule.call,653 maybe_periodic: schedule.maybe_periodic,654 origin: schedule.origin.into(),655 _phantom: Default::default(),656 })657 })658 .collect::<Vec<_>>(),659 )660 });661 }662663 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {664 let now = frame_system::Pallet::<T>::block_number();665666 let when = match when {667 DispatchTime::At(x) => x,668 669 670 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),671 };672673 if when <= now {674 return Err(Error::<T>::TargetBlockNumberInPast.into());675 }676677 Ok(when)678 }679680 fn do_schedule_named(681 id: ScheduledId,682 when: DispatchTime<T::BlockNumber>,683 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,684 priority: schedule::Priority,685 origin: T::PalletsOrigin,686 call: CallOrHashOf<T>,687 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {688 689 if Lookup::<T>::contains_key(&id) {690 return Err(Error::<T>::FailedToSchedule)?;691 }692693 let when = Self::resolve_time(when)?;694695 call.ensure_requested::<T::PreimageProvider>();696697 698 let maybe_periodic = maybe_periodic699 .filter(|p| p.1 > 1 && !p.0.is_zero())700 701 .map(|(p, c)| (p, c - 1));702703 let s = Scheduled {704 maybe_id: Some(id.clone()),705 priority,706 call: call.clone(),707 maybe_periodic,708 origin: origin.clone(),709 _phantom: Default::default(),710 };711712 713 714 715 716 717 718 719 720 721 722 723 724 725726 Agenda::<T>::append(when, Some(s));727 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;728 let address = (when, index);729 Lookup::<T>::insert(&id, &address);730 Self::deposit_event(Event::Scheduled { when, index });731732 Ok(address)733 }734735 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {736 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {737 if let Some((when, index)) = lookup.take() {738 let i = index as usize;739 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {740 if let Some(s) = agenda.get_mut(i) {741 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {742 if matches!(743 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),744 Some(Ordering::Less) | None745 ) {746 return Err(BadOrigin.into());747 }748 749 750 751 752 753 754 755 756757 s.call.ensure_unrequested::<T::PreimageProvider>();758 }759 *s = None;760 }761 Ok(())762 })?;763764 Self::deposit_event(Event::Canceled { when, index });765 Ok(())766 } else {767 Err(Error::<T>::NotFound)?768 }769 })770 }771772 fn do_change_named_priority(773 origin: T::PalletsOrigin,774 id: ScheduledId,775 priority: schedule::Priority,776 ) -> DispatchResult {777 match Lookup::<T>::get(id) {778 Some((when, index)) => {779 let i = index as usize;780 Agenda::<T>::try_mutate(when, |agenda| {781 if let Some(Some(s)) = agenda.get_mut(i) {782 if matches!(783 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),784 Some(Ordering::Less) | None785 ) {786 return Err(BadOrigin.into());787 }788789 s.priority = priority;790 Self::deposit_event(Event::PriorityChanged {791 when,792 index,793 priority,794 });795 }796 Ok(())797 })798 }799 None => Err(Error::<T>::NotFound.into()),800 }801 }802}