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, Parameter},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{GetDispatchInfo, Weight},96};9798pub use weights::WeightInfo;99100101pub type PeriodicIndex = u32;102103pub type TaskAddress<BlockNumber> = (BlockNumber, u32);104pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;105106type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];107pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;108109110#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]111#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]112pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {113 114 maybe_id: Option<ScheduledId>,115 116 priority: schedule::Priority,117 118 call: Call,119 120 maybe_periodic: Option<schedule::Period<BlockNumber>>,121 122 origin: PalletsOrigin,123 _phantom: PhantomData<AccountId>,124}125126pub type ScheduledV3Of<T> = ScheduledV3<127 CallOrHashOf<T>,128 <T as frame_system::Config>::BlockNumber,129 <T as Config>::PalletsOrigin,130 <T as frame_system::Config>::AccountId,131>;132133pub type ScheduledOf<T> = ScheduledV3Of<T>;134135136pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =137 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;138139#[cfg(feature = "runtime-benchmarks")]140mod preimage_provider {141 use frame_support::traits::PreimageRecipient;142 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}143 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}144}145146#[cfg(not(feature = "runtime-benchmarks"))]147mod preimage_provider {148 use frame_support::traits::PreimageProvider;149 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}150 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}151}152153pub use preimage_provider::PreimageProviderAndMaybeRecipient;154155156pub(crate) trait MarginalWeightInfo: WeightInfo {157 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {158 match (periodic, named, resolved) {159 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),160 (_, true, None) => {161 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)162 }163 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),164 (false, true, Some(false)) => {165 Self::on_initialize_named(2) - Self::on_initialize_named(1)166 }167 (true, false, Some(false)) => {168 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)169 }170 (true, true, Some(false)) => {171 Self::on_initialize_periodic_named_resolved(2)172 - Self::on_initialize_periodic_named_resolved(1)173 }174 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),175 (false, true, Some(true)) => {176 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)177 }178 (true, false, Some(true)) => {179 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)180 }181 (true, true, Some(true)) => {182 Self::on_initialize_periodic_named_resolved(2)183 - Self::on_initialize_periodic_named_resolved(1)184 }185 }186 }187}188impl<T: WeightInfo> MarginalWeightInfo for T {}189190#[frame_support::pallet]191pub mod pallet {192 use super::*;193 use frame_support::{194 dispatch::PostDispatchInfo,195 pallet_prelude::*,196 traits::{schedule::LookupError, PreimageProvider},197 };198 use frame_system::pallet_prelude::*;199200 201 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);202203 #[pallet::pallet]204 #[pallet::generate_store(pub(super) trait Store)]205 #[pallet::storage_version(STORAGE_VERSION)]206 #[pallet::without_storage_info]207 pub struct Pallet<T>(_);208209 210 #[pallet::config]211 pub trait Config: frame_system::Config {212 213 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;214215 216 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>217 + From<Self::PalletsOrigin>218 + IsType<<Self as system::Config>::Origin>;219220 221 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;222223 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;224225 226 type Call: Parameter227 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>228 + GetDispatchInfo229 + From<system::Call<Self>>;230231 232 233 #[pallet::constant]234 type MaximumWeight: Get<Weight>;235236 237 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;238239 240 241 242 243 244 245 246 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;247248 249 250 #[pallet::constant]251 type MaxScheduledPerBlock: Get<u32>;252253 254 type WeightInfo: WeightInfo;255256 257 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;258259 260 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;261262 263 264265 266 type CallExecutor: DispatchCall<Self, H160>;267 }268269 270 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {271 272 fn reserve_balance(273 id: ScheduledId,274 sponsor: <T as frame_system::Config>::AccountId,275 call: <T as Config>::Call,276 count: u32,277 ) -> Result<(), DispatchError>;278279 280 fn pay_for_call(281 id: ScheduledId,282 sponsor: <T as frame_system::Config>::AccountId,283 call: <T as Config>::Call,284 ) -> Result<u128, DispatchError>;285286 287 fn dispatch_call(288 signer: T::AccountId,289 function: <T as Config>::Call,290 ) -> Result<291 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,292 TransactionValidityError,293 >;294295 296 fn cancel_reserve(297 id: ScheduledId,298 sponsor: <T as frame_system::Config>::AccountId,299 ) -> Result<u128, DispatchError>;300 }301302 303 #[pallet::storage]304 pub type Agenda<T: Config> =305 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;306307 308 #[pallet::storage]309 pub(crate) type Lookup<T: Config> =310 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;311312 313 #[pallet::event]314 #[pallet::generate_deposit(pub(super) fn deposit_event)]315 pub enum Event<T: Config> {316 317 Scheduled { when: T::BlockNumber, index: u32 },318 319 Canceled { when: T::BlockNumber, index: u32 },320 321 Dispatched {322 task: TaskAddress<T::BlockNumber>,323 id: Option<ScheduledId>,324 result: DispatchResult,325 },326 327 CallLookupFailed {328 task: TaskAddress<T::BlockNumber>,329 id: Option<ScheduledId>,330 error: LookupError,331 },332 }333334 #[pallet::error]335 pub enum Error<T> {336 337 FailedToSchedule,338 339 NotFound,340 341 TargetBlockNumberInPast,342 343 RescheduleNoChange,344 }345346 #[pallet::hooks]347 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {348 349 fn on_initialize(now: T::BlockNumber) -> Weight {350 let limit = T::MaximumWeight::get();351352 let mut queued = Agenda::<T>::take(now)353 .into_iter()354 .enumerate()355 .filter_map(|(index, s)| Some((index as u32, s?)))356 .collect::<Vec<_>>();357358 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {359 log::warn!(360 target: "runtime::scheduler",361 "Warning: This block has more items queued in Scheduler than \362 expected from the runtime configuration. An update might be needed."363 );364 }365366 queued.sort_by_key(|(_, s)| s.priority);367368 let next = now + One::one();369370 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);371 for (order, (index, mut s)) in queued.into_iter().enumerate() {372 let named = if let Some(ref id) = s.maybe_id {373 Lookup::<T>::remove(id);374 true375 } else {376 false377 };378379 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();380 s.call = call;381382 let resolved = if let Some(completed) = maybe_completed {383 T::PreimageProvider::unrequest_preimage(&completed);384 true385 } else {386 false387 };388 let call = match s.call.as_value().cloned() {389 Some(c) => c,390 None => {391 392 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));393 if let Some(delay) = T::NoPreimagePostponement::get() {394 let until = now.saturating_add(delay);395 if let Some(ref id) = s.maybe_id {396 let index = Agenda::<T>::decode_len(until).unwrap_or(0);397 Lookup::<T>::insert(id, (until, index as u32));398 }399 Agenda::<T>::append(until, Some(s));400 }401 continue;402 }403 };404405 let periodic = s.maybe_periodic.is_some();406 let call_weight = call.get_dispatch_info().weight;407 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));408 let origin =409 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())410 .into();411 if ensure_signed(origin).is_ok() {412 413 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));414 }415416 417 418 419 420 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;421 let test_weight = total_weight422 .saturating_add(call_weight)423 .saturating_add(item_weight);424 if !hard_deadline && order > 0 && test_weight > limit {425 426 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));427 if let Some(ref id) = s.maybe_id {428 429 430 431 432 let index = Agenda::<T>::decode_len(next).unwrap_or(0);433 Lookup::<T>::insert(id, (next, index as u32));434 }435 Agenda::<T>::append(next, Some(s));436 continue;437 }438439 440 let sender = ensure_signed(441 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())442 .into(),443 )444 .unwrap();445446 447 448 449 450 451 452 453 454455 456 457 let r = T::CallExecutor::dispatch_call(sender, call.clone());458459 let mut actual_call_weight: Weight = item_weight;460 let result: Result<_, DispatchError> = match r {461 Ok(o) => match o {462 Ok(di) => {463 actual_call_weight = di.actual_weight.unwrap_or(item_weight);464 Ok(())465 }466 Err(err) => Err(err.error),467 },468 Err(_) => {469 log::error!(470 target: "runtime::scheduler",471 "Warning: Scheduler has failed to execute a post-dispatch transaction. \472 This block might have become invalid.");473 Err(DispatchError::CannotLookup)474 } 475 };476477 total_weight.saturating_accrue(item_weight);478 total_weight.saturating_accrue(actual_call_weight);479480 Self::deposit_event(Event::Dispatched {481 task: (now, index),482 id: s.maybe_id.clone(),483 result,484 });485486 if let &Some((period, count)) = &s.maybe_periodic {487 if count > 1 {488 s.maybe_periodic = Some((period, count - 1));489 } else {490 s.maybe_periodic = None;491 }492 let wake = now + period;493 494 if let Some(ref id) = s.maybe_id {495 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);496 Lookup::<T>::insert(id, (wake, wake_index as u32));497 }498 Agenda::<T>::append(wake, Some(s));499 }500 }501 502 0503 }504 }505506 #[pallet::call]507 impl<T: Config> Pallet<T> {508 509 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]510 pub fn schedule_named(511 origin: OriginFor<T>,512 id: ScheduledId,513 when: T::BlockNumber,514 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,515 priority: schedule::Priority,516 call: Box<CallOrHashOf<T>>,517 ) -> DispatchResult {518 T::ScheduleOrigin::ensure_origin(origin.clone())?;519 let origin = <T as Config>::Origin::from(origin);520 Self::do_schedule_named(521 id,522 DispatchTime::At(when),523 maybe_periodic,524 priority,525 origin.caller().clone(),526 *call,527 )?;528 Ok(())529 }530531 532 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]533 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {534 T::ScheduleOrigin::ensure_origin(origin.clone())?;535 let origin = <T as Config>::Origin::from(origin);536 Self::do_cancel_named(Some(origin.caller().clone()), id)?;537 Ok(())538 }539540 541 542 543 544 545 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]546 pub fn schedule_named_after(547 origin: OriginFor<T>,548 id: ScheduledId,549 after: T::BlockNumber,550 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,551 priority: schedule::Priority,552 call: Box<CallOrHashOf<T>>,553 ) -> DispatchResult {554 T::ScheduleOrigin::ensure_origin(origin.clone())?;555 let origin = <T as Config>::Origin::from(origin);556 Self::do_schedule_named(557 id,558 DispatchTime::After(after),559 maybe_periodic,560 priority,561 origin.caller().clone(),562 *call,563 )?;564 Ok(())565 }566 }567}568569impl<T: Config> Pallet<T> {570 #[cfg(feature = "try-runtime")]571 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {572 Ok(())573 }574575 #[cfg(feature = "try-runtime")]576 pub fn post_migrate_to_v3() -> Result<(), &'static str> {577 use frame_support::dispatch::GetStorageVersion;578579 assert!(Self::current_storage_version() == 3);580 for k in Agenda::<T>::iter_keys() {581 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;582 }583 Ok(())584 }585586 587 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {588 Agenda::<T>::translate::<589 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,590 _,591 >(|_, agenda| {592 Some(593 agenda594 .into_iter()595 .map(|schedule| {596 schedule.map(|schedule| Scheduled {597 maybe_id: schedule.maybe_id,598 priority: schedule.priority,599 call: schedule.call,600 maybe_periodic: schedule.maybe_periodic,601 origin: schedule.origin.into(),602 _phantom: Default::default(),603 })604 })605 .collect::<Vec<_>>(),606 )607 });608 }609610 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {611 let now = frame_system::Pallet::<T>::block_number();612613 let when = match when {614 DispatchTime::At(x) => x,615 616 617 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),618 };619620 if when <= now {621 return Err(Error::<T>::TargetBlockNumberInPast.into());622 }623624 Ok(when)625 }626627 fn do_schedule_named(628 id: ScheduledId,629 when: DispatchTime<T::BlockNumber>,630 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,631 priority: schedule::Priority,632 origin: T::PalletsOrigin,633 call: CallOrHashOf<T>,634 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {635 636 if Lookup::<T>::contains_key(&id) {637 return Err(Error::<T>::FailedToSchedule)?;638 }639640 let when = Self::resolve_time(when)?;641642 call.ensure_requested::<T::PreimageProvider>();643644 645 let maybe_periodic = maybe_periodic646 .filter(|p| p.1 > 1 && !p.0.is_zero())647 648 .map(|(p, c)| (p, c - 1));649650 let s = Scheduled {651 maybe_id: Some(id.clone()),652 priority,653 call: call.clone(),654 maybe_periodic,655 origin: origin.clone(),656 _phantom: Default::default(),657 };658659 660 661 662 663 664 665 666 667 668 669 670 671 672673 Agenda::<T>::append(when, Some(s));674 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;675 let address = (when, index);676 Lookup::<T>::insert(&id, &address);677 Self::deposit_event(Event::Scheduled { when, index });678679 Ok(address)680 }681682 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {683 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {684 if let Some((when, index)) = lookup.take() {685 let i = index as usize;686 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {687 if let Some(s) = agenda.get_mut(i) {688 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {689 if matches!(690 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),691 Some(Ordering::Less) | None692 ) {693 return Err(BadOrigin.into());694 }695 696 697 698 699 700 701 702 703704 s.call.ensure_unrequested::<T::PreimageProvider>();705 }706 *s = None;707 }708 Ok(())709 })?;710711 Self::deposit_event(Event::Canceled { when, index });712 Ok(())713 } else {714 Err(Error::<T>::NotFound)?715 }716 })717 }718}