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::{90 DispatchError, DispatchResult, Dispatchable, UnfilteredDispatchable, Parameter,91 GetDispatchInfo,92 },93 traits::{94 schedule::{self, DispatchTime, MaybeHashed},95 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,96 StorageVersion,97 },98 weights::{Weight},99};100101pub use weights::WeightInfo;102103104pub type TaskAddress<BlockNumber> = (BlockNumber, u32);105pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;106107pub type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];108pub type CallOrHashOf<T> =109 MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;110111112#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]113#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]114pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {115 116 maybe_id: Option<ScheduledId>,117 118 priority: schedule::Priority,119 120 call: Call,121 122 maybe_periodic: Option<schedule::Period<BlockNumber>>,123 124 origin: PalletsOrigin,125 _phantom: PhantomData<AccountId>,126}127128pub type ScheduledV3Of<T> = ScheduledV3<129 CallOrHashOf<T>,130 <T as frame_system::Config>::BlockNumber,131 <T as Config>::PalletsOrigin,132 <T as frame_system::Config>::AccountId,133>;134135pub type ScheduledOf<T> = ScheduledV3Of<T>;136137138pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =139 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;140141pub enum ScheduledEnsureOriginSuccess<AccountId> {142 Root,143 Signed(AccountId),144 Unsigned,145}146147#[cfg(feature = "runtime-benchmarks")]148mod preimage_provider {149 use frame_support::traits::PreimageRecipient;150 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}151 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}152}153154#[cfg(not(feature = "runtime-benchmarks"))]155mod preimage_provider {156 use frame_support::traits::PreimageProvider;157 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}158 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}159}160161pub use preimage_provider::PreimageProviderAndMaybeRecipient;162163pub(crate) trait MarginalWeightInfo: WeightInfo {164 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {165 match (periodic, named, resolved) {166 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),167 (_, true, None) => {168 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)169 }170 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),171 (false, true, Some(false)) => {172 Self::on_initialize_named(2) - Self::on_initialize_named(1)173 }174 (true, false, Some(false)) => {175 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)176 }177 (true, true, Some(false)) => {178 Self::on_initialize_periodic_named_resolved(2)179 - Self::on_initialize_periodic_named_resolved(1)180 }181 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),182 (false, true, Some(true)) => {183 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)184 }185 (true, false, Some(true)) => {186 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)187 }188 (true, true, Some(true)) => {189 Self::on_initialize_periodic_named_resolved(2)190 - Self::on_initialize_periodic_named_resolved(1)191 }192 }193 }194}195impl<T: WeightInfo> MarginalWeightInfo for T {}196197#[frame_support::pallet]198pub mod pallet {199 use super::*;200 use frame_support::{201 dispatch::PostDispatchInfo,202 pallet_prelude::*,203 traits::{204 schedule::{LookupError, LOWEST_PRIORITY},205 PreimageProvider,206 },207 };208 use frame_system::pallet_prelude::*;209210 211 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);212213 #[pallet::pallet]214 #[pallet::generate_store(pub(super) trait Store)]215 #[pallet::storage_version(STORAGE_VERSION)]216 #[pallet::without_storage_info]217 pub struct Pallet<T>(_);218219 220 #[pallet::config]221 pub trait Config: frame_system::Config {222 223 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;224225 226 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>227 + From<Self::PalletsOrigin>228 + IsType<<Self as system::Config>::RuntimeOrigin>;229230 231 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;232233 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;234235 236 type RuntimeCall: Parameter237 + Dispatchable<238 RuntimeOrigin = <Self as Config>::RuntimeOrigin,239 PostInfo = PostDispatchInfo,240 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>241 + GetDispatchInfo242 + From<system::Call<Self>>;243244 245 246 #[pallet::constant]247 type MaximumWeight: Get<Weight>;248249 250 type ScheduleOrigin: EnsureOrigin<251 <Self as system::Config>::RuntimeOrigin,252 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,253 >;254255 256 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;257258 259 260 261 262 263 264 265 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;266267 268 269 #[pallet::constant]270 type MaxScheduledPerBlock: Get<u32>;271272 273 type WeightInfo: WeightInfo;274275 276 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;277278 279 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;280281 282 283284 285 type CallExecutor: DispatchCall<Self, H160>;286 }287288 289 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {290 291 fn reserve_balance(292 id: ScheduledId,293 sponsor: <T as frame_system::Config>::AccountId,294 call: <T as Config>::RuntimeCall,295 count: u32,296 ) -> Result<(), DispatchError>;297298 299 fn pay_for_call(300 id: ScheduledId,301 sponsor: <T as frame_system::Config>::AccountId,302 call: <T as Config>::RuntimeCall,303 ) -> Result<u128, DispatchError>;304305 306 fn dispatch_call(307 signer: Option<T::AccountId>,308 function: <T as Config>::RuntimeCall,309 ) -> Result<310 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,311 TransactionValidityError,312 >;313314 315 fn cancel_reserve(316 id: ScheduledId,317 sponsor: <T as frame_system::Config>::AccountId,318 ) -> Result<u128, DispatchError>;319 }320321 322 #[pallet::storage]323 pub type Agenda<T: Config> =324 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;325326 327 #[pallet::storage]328 pub(crate) type Lookup<T: Config> =329 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;330331 332 #[pallet::event]333 #[pallet::generate_deposit(pub(super) fn deposit_event)]334 pub enum Event<T: Config> {335 336 Scheduled { when: T::BlockNumber, index: u32 },337 338 Canceled { when: T::BlockNumber, index: u32 },339 340 PriorityChanged {341 when: T::BlockNumber,342 index: u32,343 priority: schedule::Priority,344 },345 346 Dispatched {347 task: TaskAddress<T::BlockNumber>,348 id: Option<ScheduledId>,349 result: DispatchResult,350 },351 352 CallLookupFailed {353 task: TaskAddress<T::BlockNumber>,354 id: Option<ScheduledId>,355 error: LookupError,356 },357 }358359 #[pallet::error]360 pub enum Error<T> {361 362 FailedToSchedule,363 364 NotFound,365 366 TargetBlockNumberInPast,367 368 RescheduleNoChange,369 }370371 #[pallet::hooks]372 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {373 374 fn on_initialize(now: T::BlockNumber) -> Weight {375 let limit = T::MaximumWeight::get();376377 let mut queued = Agenda::<T>::take(now)378 .into_iter()379 .enumerate()380 .filter_map(|(index, s)| Some((index as u32, s?)))381 .collect::<Vec<_>>();382383 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {384 log::warn!(385 target: "runtime::scheduler",386 "Warning: This block has more items queued in Scheduler than \387 expected from the runtime configuration. An update might be needed."388 );389 }390391 queued.sort_by_key(|(_, s)| s.priority);392393 let next = now + One::one();394395 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);396 for (order, (index, mut s)) in queued.into_iter().enumerate() {397 let named = s.maybe_id.is_some();398399 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();400 s.call = call;401402 let resolved = if let Some(completed) = maybe_completed {403 T::PreimageProvider::unrequest_preimage(&completed);404 true405 } else {406 false407 };408 let call = match s.call.as_value().cloned() {409 Some(c) => c,410 None => {411 412 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));413 if let Some(delay) = T::NoPreimagePostponement::get() {414 let until = now.saturating_add(delay);415 if let Some(ref id) = s.maybe_id {416 let index = Agenda::<T>::decode_len(until).unwrap_or(0);417 Lookup::<T>::insert(id, (until, index as u32));418 }419 Agenda::<T>::append(until, Some(s));420 } else if let Some(ref id) = s.maybe_id {421 Lookup::<T>::remove(id);422 }423 continue;424 }425 };426427 let periodic = s.maybe_periodic.is_some();428 let call_weight = call.get_dispatch_info().weight;429 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));430 let origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(431 s.origin.clone(),432 )433 .into();434 if ensure_signed(origin).is_ok() {435 436 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));437 }438439 440 441 442 443 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;444 let test_weight = total_weight445 .saturating_add(call_weight)446 .saturating_add(item_weight);447 if !hard_deadline && order > 0 && test_weight.all_gt(limit) {448 449 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));450 if let Some(ref id) = s.maybe_id {451 452 453 454 455 let index = Agenda::<T>::decode_len(next).unwrap_or(0);456 Lookup::<T>::insert(id, (next, index as u32));457 }458 Agenda::<T>::append(next, Some(s));459 continue;460 }461462 let scheduled_origin =463 <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(464 s.origin.clone(),465 );466 let ensured_origin = T::ScheduleOrigin::ensure_origin(scheduled_origin.into());467468 let r = match ensured_origin {469 Ok(ScheduledEnsureOriginSuccess::Root) => {470 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))471 }472 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {473 474 475 T::CallExecutor::dispatch_call(Some(sender), call.clone())476 }477 Ok(ScheduledEnsureOriginSuccess::Unsigned) => {478 479 T::CallExecutor::dispatch_call(None, call.clone())480 }481 Err(e) => Ok(Err(e.into())),482 };483484 let mut actual_call_weight: Weight = item_weight;485 let result: Result<_, DispatchError> = match r {486 Ok(o) => match o {487 Ok(di) => {488 actual_call_weight = di.actual_weight.unwrap_or(item_weight);489 Ok(())490 }491 Err(err) => Err(err.error),492 },493 Err(_) => {494 log::error!(495 target: "runtime::scheduler",496 "Warning: Scheduler has failed to execute a post-dispatch transaction. \497 This block might have become invalid.");498 Err(DispatchError::CannotLookup)499 } 500 };501502 total_weight.saturating_accrue(item_weight);503 total_weight.saturating_accrue(actual_call_weight);504505 Self::deposit_event(Event::Dispatched {506 task: (now, index),507 id: s.maybe_id.clone(),508 result,509 });510511 if let &Some((period, count)) = &s.maybe_periodic {512 if count > 1 {513 s.maybe_periodic = Some((period, count - 1));514 } else {515 s.maybe_periodic = None;516 }517 let wake = now + period;518 let is_canceled;519520 521 if let Some(ref id) = s.maybe_id {522 is_canceled = Lookup::<T>::get(id).is_none();523 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);524525 if !is_canceled {526 Lookup::<T>::insert(id, (wake, wake_index as u32));527 }528 } else {529 is_canceled = false;530 }531532 if !is_canceled {533 Agenda::<T>::append(wake, Some(s));534 }535 } else if let Some(ref id) = s.maybe_id {536 Lookup::<T>::remove(id);537 }538 }539 total_weight540 }541 }542543 #[pallet::call]544 impl<T: Config> Pallet<T> {545 546 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]547 pub fn schedule_named(548 origin: OriginFor<T>,549 id: ScheduledId,550 when: T::BlockNumber,551 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,552 priority: Option<schedule::Priority>,553 call: Box<CallOrHashOf<T>>,554 ) -> DispatchResult {555 T::ScheduleOrigin::ensure_origin(origin.clone())?;556557 if priority.is_some() {558 T::PrioritySetOrigin::ensure_origin(origin.clone())?;559 }560561 let origin = <T as Config>::RuntimeOrigin::from(origin);562 Self::do_schedule_named(563 id,564 DispatchTime::At(when),565 maybe_periodic,566 priority.unwrap_or(LOWEST_PRIORITY),567 origin.caller().clone(),568 *call,569 )?;570 Ok(())571 }572573 574 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]575 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {576 T::ScheduleOrigin::ensure_origin(origin.clone())?;577 let origin = <T as Config>::RuntimeOrigin::from(origin);578 Self::do_cancel_named(Some(origin.caller().clone()), id)?;579 Ok(())580 }581582 583 584 585 586 587 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]588 pub fn schedule_named_after(589 origin: OriginFor<T>,590 id: ScheduledId,591 after: T::BlockNumber,592 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,593 priority: Option<schedule::Priority>,594 call: Box<CallOrHashOf<T>>,595 ) -> DispatchResult {596 T::ScheduleOrigin::ensure_origin(origin.clone())?;597598 if priority.is_some() {599 T::PrioritySetOrigin::ensure_origin(origin.clone())?;600 }601602 let origin = <T as Config>::RuntimeOrigin::from(origin);603 Self::do_schedule_named(604 id,605 DispatchTime::After(after),606 maybe_periodic,607 priority.unwrap_or(LOWEST_PRIORITY),608 origin.caller().clone(),609 *call,610 )?;611 Ok(())612 }613614 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]615 pub fn change_named_priority(616 origin: OriginFor<T>,617 id: ScheduledId,618 priority: schedule::Priority,619 ) -> DispatchResult {620 T::PrioritySetOrigin::ensure_origin(origin.clone())?;621 let origin = <T as Config>::RuntimeOrigin::from(origin);622 Self::do_change_named_priority(origin.caller().clone(), id, priority)623 }624 }625}626627impl<T: Config> Pallet<T> {628 #[cfg(feature = "try-runtime")]629 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {630 Ok(())631 }632633 #[cfg(feature = "try-runtime")]634 pub fn post_migrate_to_v3() -> Result<(), &'static str> {635 use frame_support::dispatch::GetStorageVersion;636637 assert!(Self::current_storage_version() == 3);638 for k in Agenda::<T>::iter_keys() {639 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;640 }641 Ok(())642 }643644 645 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {646 Agenda::<T>::translate::<647 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,648 _,649 >(|_, agenda| {650 Some(651 agenda652 .into_iter()653 .map(|schedule| {654 schedule.map(|schedule| Scheduled {655 maybe_id: schedule.maybe_id,656 priority: schedule.priority,657 call: schedule.call,658 maybe_periodic: schedule.maybe_periodic,659 origin: schedule.origin.into(),660 _phantom: Default::default(),661 })662 })663 .collect::<Vec<_>>(),664 )665 });666 }667668 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {669 let now = frame_system::Pallet::<T>::block_number();670671 let when = match when {672 DispatchTime::At(x) => x,673 674 675 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),676 };677678 if when <= now {679 return Err(Error::<T>::TargetBlockNumberInPast.into());680 }681682 Ok(when)683 }684685 fn do_schedule_named(686 id: ScheduledId,687 when: DispatchTime<T::BlockNumber>,688 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,689 priority: schedule::Priority,690 origin: T::PalletsOrigin,691 call: CallOrHashOf<T>,692 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {693 694 if Lookup::<T>::contains_key(&id) {695 return Err(Error::<T>::FailedToSchedule)?;696 }697698 let when = Self::resolve_time(when)?;699700 call.ensure_requested::<T::PreimageProvider>();701702 703 let maybe_periodic = maybe_periodic704 .filter(|p| p.1 > 1 && !p.0.is_zero())705 706 .map(|(p, c)| (p, c - 1));707708 let s = Scheduled {709 maybe_id: Some(id.clone()),710 priority,711 call: call.clone(),712 maybe_periodic,713 origin: origin.clone(),714 _phantom: Default::default(),715 };716717 718 719 720 721 722 723 724 725 726 727 728 729 730731 Agenda::<T>::append(when, Some(s));732 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;733 let address = (when, index);734 Lookup::<T>::insert(&id, &address);735 Self::deposit_event(Event::Scheduled { when, index });736737 Ok(address)738 }739740 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {741 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {742 if let Some((when, index)) = lookup.take() {743 let i = index as usize;744 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {745 if let Some(s) = agenda.get_mut(i) {746 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {747 if matches!(748 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),749 Some(Ordering::Less) | None750 ) {751 return Err(BadOrigin.into());752 }753 754 755 756 757 758 759 760 761762 s.call.ensure_unrequested::<T::PreimageProvider>();763 }764 *s = None;765 }766 Ok(())767 })?;768769 Self::deposit_event(Event::Canceled { when, index });770 Ok(())771 } else {772 Err(Error::<T>::NotFound)?773 }774 })775 }776777 fn do_change_named_priority(778 origin: T::PalletsOrigin,779 id: ScheduledId,780 priority: schedule::Priority,781 ) -> DispatchResult {782 match Lookup::<T>::get(id) {783 Some((when, index)) => {784 let i = index as usize;785 Agenda::<T>::try_mutate(when, |agenda| {786 if let Some(Some(s)) = agenda.get_mut(i) {787 if matches!(788 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),789 Some(Ordering::Less) | None790 ) {791 return Err(BadOrigin.into());792 }793794 s.priority = priority;795 Self::deposit_event(Event::PriorityChanged {796 when,797 index,798 priority,799 });800 }801 Ok(())802 })803 }804 None => Err(Error::<T>::NotFound.into()),805 }806 }807}