12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#![cfg_attr(not(feature = "std"), no_std)]8081#[cfg(feature = "runtime-benchmarks")]82mod benchmarking;8384pub mod weights;8586use sp_core::H160;87use codec::{Codec, Decode, Encode};88use frame_system::{self as system, ensure_signed};89pub use pallet::*;90use scale_info::TypeInfo;91use sp_runtime::{92 traits::{BadOrigin, One, Saturating, Zero},93 RuntimeDebug, DispatchErrorWithPostInfo,94};95use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};9697use frame_support::{98 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},99 traits::{100 schedule::{self, DispatchTime, MaybeHashed},101 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,102 StorageVersion,103 },104 weights::{GetDispatchInfo, Weight},105};106107pub use weights::WeightInfo;108109110pub type PeriodicIndex = u32;111112pub type TaskAddress<BlockNumber> = (BlockNumber, u32);113pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;114115type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];116pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;117118119#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]120#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]121pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {122 123 maybe_id: Option<ScheduledId>,124 125 priority: schedule::Priority,126 127 call: Call,128 129 maybe_periodic: Option<schedule::Period<BlockNumber>>,130 131 origin: PalletsOrigin,132 _phantom: PhantomData<AccountId>,133}134135pub type ScheduledV3Of<T> = ScheduledV3<136 CallOrHashOf<T>,137 <T as frame_system::Config>::BlockNumber,138 <T as Config>::PalletsOrigin,139 <T as frame_system::Config>::AccountId,140>;141142pub type ScheduledOf<T> = ScheduledV3Of<T>;143144145pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =146 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;147148#[cfg(feature = "runtime-benchmarks")]149mod preimage_provider {150 use frame_support::traits::PreimageRecipient;151 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}152 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}153}154155#[cfg(not(feature = "runtime-benchmarks"))]156mod preimage_provider {157 use frame_support::traits::PreimageProvider;158 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}159 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}160}161162pub use preimage_provider::PreimageProviderAndMaybeRecipient;163164165pub(crate) trait MarginalWeightInfo: WeightInfo {166 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {167 match (periodic, named, resolved) {168 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),169 (_, true, None) => {170 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)171 }172 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),173 (false, true, Some(false)) => {174 Self::on_initialize_named(2) - Self::on_initialize_named(1)175 }176 (true, false, Some(false)) => {177 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)178 }179 (true, true, Some(false)) => {180 Self::on_initialize_periodic_named_resolved(2)181 - Self::on_initialize_periodic_named_resolved(1)182 }183 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),184 (false, true, Some(true)) => {185 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)186 }187 (true, false, Some(true)) => {188 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)189 }190 (true, true, Some(true)) => {191 Self::on_initialize_periodic_named_resolved(2)192 - Self::on_initialize_periodic_named_resolved(1)193 }194 }195 }196}197impl<T: WeightInfo> MarginalWeightInfo for T {}198199#[frame_support::pallet]200pub mod pallet {201 use super::*;202 use frame_support::{203 dispatch::PostDispatchInfo,204 pallet_prelude::*,205 traits::{schedule::LookupError, PreimageProvider},206 };207 use frame_system::pallet_prelude::*;208209 210 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);211212 #[pallet::pallet]213 #[pallet::generate_store(pub(super) trait Store)]214 #[pallet::storage_version(STORAGE_VERSION)]215 #[pallet::without_storage_info]216 pub struct Pallet<T>(_);217218 219 #[pallet::config]220 pub trait Config: frame_system::Config {221 222 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;223224 225 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>226 + From<Self::PalletsOrigin>227 + IsType<<Self as system::Config>::Origin>;228229 230 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;231232 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;233234 235 type Call: Parameter236 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>237 + GetDispatchInfo238 + From<system::Call<Self>>;239240 241 242 #[pallet::constant]243 type MaximumWeight: Get<Weight>;244245 246 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;247248 249 250 251 252 253 254 255 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;256257 258 259 #[pallet::constant]260 type MaxScheduledPerBlock: Get<u32>;261262 263 type WeightInfo: WeightInfo;264265 266 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;267268 269 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;270271 272 273274 275 type CallExecutor: DispatchCall<Self, H160>;276 }277278 279 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {280 281 fn reserve_balance(282 id: ScheduledId,283 sponsor: <T as frame_system::Config>::AccountId,284 call: <T as Config>::Call,285 count: u32,286 ) -> Result<(), DispatchError>;287288 289 fn pay_for_call(290 id: ScheduledId,291 sponsor: <T as frame_system::Config>::AccountId,292 call: <T as Config>::Call,293 ) -> Result<u128, DispatchError>;294295 296 fn dispatch_call(297 signer: T::AccountId,298 function: <T as Config>::Call,299 ) -> Result<300 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,301 TransactionValidityError,302 >;303304 305 fn cancel_reserve(306 id: ScheduledId,307 sponsor: <T as frame_system::Config>::AccountId,308 ) -> Result<u128, DispatchError>;309 }310311 312 #[pallet::storage]313 pub type Agenda<T: Config> =314 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;315316 317 #[pallet::storage]318 pub(crate) type Lookup<T: Config> =319 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;320321 322 #[pallet::event]323 #[pallet::generate_deposit(pub(super) fn deposit_event)]324 pub enum Event<T: Config> {325 326 Scheduled { when: T::BlockNumber, index: u32 },327 328 Canceled { when: T::BlockNumber, index: u32 },329 330 Dispatched {331 task: TaskAddress<T::BlockNumber>,332 id: Option<ScheduledId>,333 result: DispatchResult,334 },335 336 CallLookupFailed {337 task: TaskAddress<T::BlockNumber>,338 id: Option<ScheduledId>,339 error: LookupError,340 },341 }342343 #[pallet::error]344 pub enum Error<T> {345 346 FailedToSchedule,347 348 NotFound,349 350 TargetBlockNumberInPast,351 352 RescheduleNoChange,353 }354355 #[pallet::hooks]356 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {357 358 fn on_initialize(now: T::BlockNumber) -> Weight {359 let limit = T::MaximumWeight::get();360361 let mut queued = Agenda::<T>::take(now)362 .into_iter()363 .enumerate()364 .filter_map(|(index, s)| Some((index as u32, s?)))365 .collect::<Vec<_>>();366367 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {368 log::warn!(369 target: "runtime::scheduler",370 "Warning: This block has more items queued in Scheduler than \371 expected from the runtime configuration. An update might be needed."372 );373 }374375 queued.sort_by_key(|(_, s)| s.priority);376377 let next = now + One::one();378379 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);380 for (order, (index, mut s)) in queued.into_iter().enumerate() {381 let named = if let Some(ref id) = s.maybe_id {382 Lookup::<T>::remove(id);383 true384 } else {385 false386 };387388 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();389 s.call = call;390391 let resolved = if let Some(completed) = maybe_completed {392 T::PreimageProvider::unrequest_preimage(&completed);393 true394 } else {395 false396 };397 let call = match s.call.as_value().cloned() {398 Some(c) => c,399 None => {400 401 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));402 if let Some(delay) = T::NoPreimagePostponement::get() {403 let until = now.saturating_add(delay);404 if let Some(ref id) = s.maybe_id {405 let index = Agenda::<T>::decode_len(until).unwrap_or(0);406 Lookup::<T>::insert(id, (until, index as u32));407 }408 Agenda::<T>::append(until, Some(s));409 }410 continue;411 }412 };413414 let periodic = s.maybe_periodic.is_some();415 let call_weight = call.get_dispatch_info().weight;416 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));417 let origin =418 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())419 .into();420 if ensure_signed(origin).is_ok() {421 422 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));423 }424425 426 427 428 429 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;430 let test_weight = total_weight431 .saturating_add(call_weight)432 .saturating_add(item_weight);433 if !hard_deadline && order > 0 && test_weight > limit {434 435 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));436 if let Some(ref id) = s.maybe_id {437 438 439 440 441 let index = Agenda::<T>::decode_len(next).unwrap_or(0);442 Lookup::<T>::insert(id, (next, index as u32));443 }444 Agenda::<T>::append(next, Some(s));445 continue;446 }447448 449 let sender = ensure_signed(450 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())451 .into(),452 )453 .unwrap();454455 456 457 458 459 460 461 462 463464 465 466 let r = T::CallExecutor::dispatch_call(sender, call.clone());467468 let mut actual_call_weight: Weight = item_weight;469 let result: Result<_, DispatchError> = match r {470 Ok(o) => match o {471 Ok(di) => {472 actual_call_weight = di.actual_weight.unwrap_or(item_weight);473 Ok(())474 }475 Err(err) => Err(err.error),476 },477 Err(_) => {478 log::error!(479 target: "runtime::scheduler",480 "Warning: Scheduler has failed to execute a post-dispatch transaction. \481 This block might have become invalid.");482 Err(DispatchError::CannotLookup)483 } 484 };485486 total_weight.saturating_accrue(item_weight);487 total_weight.saturating_accrue(actual_call_weight);488489 Self::deposit_event(Event::Dispatched {490 task: (now, index),491 id: s.maybe_id.clone(),492 result,493 });494495 if let &Some((period, count)) = &s.maybe_periodic {496 if count > 1 {497 s.maybe_periodic = Some((period, count - 1));498 } else {499 s.maybe_periodic = None;500 }501 let wake = now + period;502 503 if let Some(ref id) = s.maybe_id {504 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);505 Lookup::<T>::insert(id, (wake, wake_index as u32));506 }507 Agenda::<T>::append(wake, Some(s));508 }509 }510 511 0512 }513 }514515 #[pallet::call]516 impl<T: Config> Pallet<T> {517 518 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]519 pub fn schedule_named(520 origin: OriginFor<T>,521 id: ScheduledId,522 when: T::BlockNumber,523 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,524 priority: schedule::Priority,525 call: Box<CallOrHashOf<T>>,526 ) -> DispatchResult {527 T::ScheduleOrigin::ensure_origin(origin.clone())?;528 let origin = <T as Config>::Origin::from(origin);529 Self::do_schedule_named(530 id,531 DispatchTime::At(when),532 maybe_periodic,533 priority,534 origin.caller().clone(),535 *call,536 )?;537 Ok(())538 }539540 541 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]542 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {543 T::ScheduleOrigin::ensure_origin(origin.clone())?;544 let origin = <T as Config>::Origin::from(origin);545 Self::do_cancel_named(Some(origin.caller().clone()), id)?;546 Ok(())547 }548549 550 551 552 553 554 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]555 pub fn schedule_named_after(556 origin: OriginFor<T>,557 id: ScheduledId,558 after: T::BlockNumber,559 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,560 priority: schedule::Priority,561 call: Box<CallOrHashOf<T>>,562 ) -> DispatchResult {563 T::ScheduleOrigin::ensure_origin(origin.clone())?;564 let origin = <T as Config>::Origin::from(origin);565 Self::do_schedule_named(566 id,567 DispatchTime::After(after),568 maybe_periodic,569 priority,570 origin.caller().clone(),571 *call,572 )?;573 Ok(())574 }575 }576}577578impl<T: Config> Pallet<T> {579 #[cfg(feature = "try-runtime")]580 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {581 Ok(())582 }583584 #[cfg(feature = "try-runtime")]585 pub fn post_migrate_to_v3() -> Result<(), &'static str> {586 use frame_support::dispatch::GetStorageVersion;587588 assert!(Self::current_storage_version() == 3);589 for k in Agenda::<T>::iter_keys() {590 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;591 }592 Ok(())593 }594595 596 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {597 Agenda::<T>::translate::<598 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,599 _,600 >(|_, agenda| {601 Some(602 agenda603 .into_iter()604 .map(|schedule| {605 schedule.map(|schedule| Scheduled {606 maybe_id: schedule.maybe_id,607 priority: schedule.priority,608 call: schedule.call,609 maybe_periodic: schedule.maybe_periodic,610 origin: schedule.origin.into(),611 _phantom: Default::default(),612 })613 })614 .collect::<Vec<_>>(),615 )616 });617 }618619 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {620 let now = frame_system::Pallet::<T>::block_number();621622 let when = match when {623 DispatchTime::At(x) => x,624 625 626 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),627 };628629 if when <= now {630 return Err(Error::<T>::TargetBlockNumberInPast.into());631 }632633 Ok(when)634 }635636 fn do_schedule_named(637 id: ScheduledId,638 when: DispatchTime<T::BlockNumber>,639 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,640 priority: schedule::Priority,641 origin: T::PalletsOrigin,642 call: CallOrHashOf<T>,643 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {644 645 if Lookup::<T>::contains_key(&id) {646 return Err(Error::<T>::FailedToSchedule)?;647 }648649 let when = Self::resolve_time(when)?;650651 call.ensure_requested::<T::PreimageProvider>();652653 654 let maybe_periodic = maybe_periodic655 .filter(|p| p.1 > 1 && !p.0.is_zero())656 657 .map(|(p, c)| (p, c - 1));658659 let s = Scheduled {660 maybe_id: Some(id.clone()),661 priority,662 call: call.clone(),663 maybe_periodic,664 origin: origin.clone(),665 _phantom: Default::default(),666 };667668 669 670 671 672 673 674 675 676 677 678 679 680 681682 Agenda::<T>::append(when, Some(s));683 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;684 let address = (when, index);685 Lookup::<T>::insert(&id, &address);686 Self::deposit_event(Event::Scheduled { when, index });687688 Ok(address)689 }690691 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {692 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {693 if let Some((when, index)) = lookup.take() {694 let i = index as usize;695 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {696 if let Some(s) = agenda.get_mut(i) {697 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {698 if matches!(699 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),700 Some(Ordering::Less) | None701 ) {702 return Err(BadOrigin.into());703 }704 705 706 707 708 709 710 711 712713 s.call.ensure_unrequested::<T::PreimageProvider>();714 }715 *s = None;716 }717 Ok(())718 })?;719720 Self::deposit_event(Event::Canceled { when, index });721 Ok(())722 } else {723 Err(Error::<T>::NotFound)?724 }725 })726 }727}