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;154155pub(crate) trait MarginalWeightInfo: WeightInfo {156 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {157 match (periodic, named, resolved) {158 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),159 (_, true, None) => {160 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)161 }162 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),163 (false, true, Some(false)) => {164 Self::on_initialize_named(2) - Self::on_initialize_named(1)165 }166 (true, false, Some(false)) => {167 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)168 }169 (true, true, Some(false)) => {170 Self::on_initialize_periodic_named_resolved(2)171 - Self::on_initialize_periodic_named_resolved(1)172 }173 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),174 (false, true, Some(true)) => {175 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)176 }177 (true, false, Some(true)) => {178 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)179 }180 (true, true, Some(true)) => {181 Self::on_initialize_periodic_named_resolved(2)182 - Self::on_initialize_periodic_named_resolved(1)183 }184 }185 }186}187impl<T: WeightInfo> MarginalWeightInfo for T {}188189#[frame_support::pallet]190pub mod pallet {191 use super::*;192 use frame_support::{193 dispatch::PostDispatchInfo,194 pallet_prelude::*,195 traits::{schedule::LookupError, PreimageProvider},196 };197 use frame_system::pallet_prelude::*;198199 200 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);201202 #[pallet::pallet]203 #[pallet::generate_store(pub(super) trait Store)]204 #[pallet::storage_version(STORAGE_VERSION)]205 #[pallet::without_storage_info]206 pub struct Pallet<T>(_);207208 209 #[pallet::config]210 pub trait Config: frame_system::Config {211 212 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;213214 215 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>216 + From<Self::PalletsOrigin>217 + IsType<<Self as system::Config>::Origin>;218219 220 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;221222 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;223224 225 type Call: Parameter226 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>227 + GetDispatchInfo228 + From<system::Call<Self>>;229230 231 232 #[pallet::constant]233 type MaximumWeight: Get<Weight>;234235 236 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;237238 239 240 241 242 243 244 245 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;246247 248 249 #[pallet::constant]250 type MaxScheduledPerBlock: Get<u32>;251252 253 type WeightInfo: WeightInfo;254255 256 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;257258 259 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;260261 262 263264 265 type CallExecutor: DispatchCall<Self, H160>;266 }267268 269 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {270 fn reserve_balance(271 id: ScheduledId,272 sponsor: <T as frame_system::Config>::AccountId,273 call: <T as Config>::Call,274 count: u32,275 ) -> Result<(), DispatchError>;276277 278 fn pay_for_call(279 id: ScheduledId,280 sponsor: <T as frame_system::Config>::AccountId,281 call: <T as Config>::Call,282 ) -> Result<u128, DispatchError>;283284 285 fn dispatch_call(286 signer: T::AccountId,287 function: <T as Config>::Call,288 ) -> Result<289 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,290 TransactionValidityError,291 >;292293 fn cancel_reserve(294 id: ScheduledId,295 sponsor: <T as frame_system::Config>::AccountId,296 ) -> Result<u128, DispatchError>;297 }298299 300 #[pallet::storage]301 pub type Agenda<T: Config> =302 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;303304 305 #[pallet::storage]306 pub(crate) type Lookup<T: Config> =307 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;308309 310 #[pallet::event]311 #[pallet::generate_deposit(pub(super) fn deposit_event)]312 pub enum Event<T: Config> {313 314 Scheduled { when: T::BlockNumber, index: u32 },315 316 Canceled { when: T::BlockNumber, index: u32 },317 318 Dispatched {319 task: TaskAddress<T::BlockNumber>,320 id: Option<ScheduledId>,321 result: DispatchResult,322 },323 324 CallLookupFailed {325 task: TaskAddress<T::BlockNumber>,326 id: Option<ScheduledId>,327 error: LookupError,328 },329 }330331 #[pallet::error]332 pub enum Error<T> {333 334 FailedToSchedule,335 336 NotFound,337 338 TargetBlockNumberInPast,339 340 RescheduleNoChange,341 }342343 #[pallet::hooks]344 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {345 346 fn on_initialize(now: T::BlockNumber) -> Weight {347 let limit = T::MaximumWeight::get();348349 let mut queued = Agenda::<T>::take(now)350 .into_iter()351 .enumerate()352 .filter_map(|(index, s)| Some((index as u32, s?)))353 .collect::<Vec<_>>();354355 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {356 log::warn!(357 target: "runtime::scheduler",358 "Warning: This block has more items queued in Scheduler than \359 expected from the runtime configuration. An update might be needed."360 );361 }362363 queued.sort_by_key(|(_, s)| s.priority);364365 let next = now + One::one();366367 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);368 for (order, (index, mut s)) in queued.into_iter().enumerate() {369 let named = if let Some(ref id) = s.maybe_id {370 Lookup::<T>::remove(id);371 true372 } else {373 false374 };375376 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();377 s.call = call;378379 let resolved = if let Some(completed) = maybe_completed {380 T::PreimageProvider::unrequest_preimage(&completed);381 true382 } else {383 false384 };385 let call = match s.call.as_value().cloned() {386 Some(c) => c,387 None => {388 389 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));390 if let Some(delay) = T::NoPreimagePostponement::get() {391 let until = now.saturating_add(delay);392 if let Some(ref id) = s.maybe_id {393 let index = Agenda::<T>::decode_len(until).unwrap_or(0);394 Lookup::<T>::insert(id, (until, index as u32));395 }396 Agenda::<T>::append(until, Some(s));397 }398 continue;399 }400 };401402 let periodic = s.maybe_periodic.is_some();403 let call_weight = call.get_dispatch_info().weight;404 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));405 let origin =406 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())407 .into();408 if ensure_signed(origin).is_ok() {409 410 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));411 }412413 414 415 416 417 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;418 let test_weight = total_weight419 .saturating_add(call_weight)420 .saturating_add(item_weight);421 if !hard_deadline && order > 0 && test_weight > limit {422 423 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));424 if let Some(ref id) = s.maybe_id {425 426 427 428 429 let index = Agenda::<T>::decode_len(next).unwrap_or(0);430 Lookup::<T>::insert(id, (next, index as u32));431 }432 Agenda::<T>::append(next, Some(s));433 continue;434 }435436 let sender = ensure_signed(437 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())438 .into(),439 )440 .unwrap();441442 443 444 445 446 447 448 449 450451 452 453 let r = T::CallExecutor::dispatch_call(sender, call.clone());454455 let mut actual_call_weight: Weight = item_weight;456 let result: Result<_, DispatchError> = match r {457 Ok(o) => match o {458 Ok(di) => {459 actual_call_weight = di.actual_weight.unwrap_or(item_weight);460 Ok(())461 }462 Err(err) => Err(err.error),463 },464 Err(_) => {465 log::error!(466 target: "runtime::scheduler",467 "Warning: Scheduler has failed to execute a post-dispatch transaction. \468 This block might have become invalid.");469 Err(DispatchError::CannotLookup)470 } 471 };472473 total_weight.saturating_accrue(item_weight);474 total_weight.saturating_accrue(actual_call_weight);475476 Self::deposit_event(Event::Dispatched {477 task: (now, index),478 id: s.maybe_id.clone(),479 result,480 });481482 if let &Some((period, count)) = &s.maybe_periodic {483 if count > 1 {484 s.maybe_periodic = Some((period, count - 1));485 } else {486 s.maybe_periodic = None;487 }488 let wake = now + period;489 490 if let Some(ref id) = s.maybe_id {491 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);492 Lookup::<T>::insert(id, (wake, wake_index as u32));493 }494 Agenda::<T>::append(wake, Some(s));495 }496 }497 498 0499 500 }501 }502503 #[pallet::call]504 impl<T: Config> Pallet<T> {505 506 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]507 pub fn schedule_named(508 origin: OriginFor<T>,509 id: ScheduledId,510 when: T::BlockNumber,511 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,512 priority: schedule::Priority,513 call: Box<CallOrHashOf<T>>,514 ) -> DispatchResult {515 T::ScheduleOrigin::ensure_origin(origin.clone())?;516 let origin = <T as Config>::Origin::from(origin);517 Self::do_schedule_named(518 id,519 DispatchTime::At(when),520 maybe_periodic,521 priority,522 origin.caller().clone(),523 *call,524 )?;525 Ok(())526 }527528 529 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]530 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {531 T::ScheduleOrigin::ensure_origin(origin.clone())?;532 let origin = <T as Config>::Origin::from(origin);533 Self::do_cancel_named(Some(origin.caller().clone()), id)?;534 Ok(())535 }536537 538 539 540 541 542 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]543 pub fn schedule_named_after(544 origin: OriginFor<T>,545 id: ScheduledId,546 after: T::BlockNumber,547 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,548 priority: schedule::Priority,549 call: Box<CallOrHashOf<T>>,550 ) -> DispatchResult {551 T::ScheduleOrigin::ensure_origin(origin.clone())?;552 let origin = <T as Config>::Origin::from(origin);553 Self::do_schedule_named(554 id,555 DispatchTime::After(after),556 maybe_periodic,557 priority,558 origin.caller().clone(),559 *call,560 )?;561 Ok(())562 }563 }564}565566impl<T: Config> Pallet<T> {567 #[cfg(feature = "try-runtime")]568 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {569 Ok(())570 }571572 #[cfg(feature = "try-runtime")]573 pub fn post_migrate_to_v3() -> Result<(), &'static str> {574 use frame_support::dispatch::GetStorageVersion;575576 assert!(Self::current_storage_version() == 3);577 for k in Agenda::<T>::iter_keys() {578 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;579 }580 Ok(())581 }582583 584 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {585 Agenda::<T>::translate::<586 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,587 _,588 >(|_, agenda| {589 Some(590 agenda591 .into_iter()592 .map(|schedule| {593 schedule.map(|schedule| Scheduled {594 maybe_id: schedule.maybe_id,595 priority: schedule.priority,596 call: schedule.call,597 maybe_periodic: schedule.maybe_periodic,598 origin: schedule.origin.into(),599 _phantom: Default::default(),600 })601 })602 .collect::<Vec<_>>(),603 )604 });605 }606607 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {608 let now = frame_system::Pallet::<T>::block_number();609610 let when = match when {611 DispatchTime::At(x) => x,612 613 614 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),615 };616617 if when <= now {618 return Err(Error::<T>::TargetBlockNumberInPast.into());619 }620621 Ok(when)622 }623624 fn do_schedule_named(625 id: ScheduledId,626 when: DispatchTime<T::BlockNumber>,627 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,628 priority: schedule::Priority,629 origin: T::PalletsOrigin,630 call: CallOrHashOf<T>,631 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {632 633 if Lookup::<T>::contains_key(&id) {634 return Err(Error::<T>::FailedToSchedule)?;635 }636637 let when = Self::resolve_time(when)?;638639 call.ensure_requested::<T::PreimageProvider>();640641 642 let maybe_periodic = maybe_periodic643 .filter(|p| p.1 > 1 && !p.0.is_zero())644 645 .map(|(p, c)| (p, c - 1));646647 let s = Scheduled {648 maybe_id: Some(id.clone()),649 priority,650 call: call.clone(),651 maybe_periodic,652 origin: origin.clone(),653 _phantom: Default::default(),654 };655656 657 658 659 660 661 662 663 664 665 666 667 668 669670 Agenda::<T>::append(when, Some(s));671 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;672 let address = (when, index);673 Lookup::<T>::insert(&id, &address);674 Self::deposit_event(Event::Scheduled { when, index });675676 Ok(address)677 }678679 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {680 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {681 if let Some((when, index)) = lookup.take() {682 let i = index as usize;683 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {684 if let Some(s) = agenda.get_mut(i) {685 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {686 if matches!(687 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),688 Some(Ordering::Less) | None689 ) {690 return Err(BadOrigin.into());691 }692 693 694 695 696 697 698 699 700701 s.call.ensure_unrequested::<T::PreimageProvider>();702 }703 *s = None;704 }705 Ok(())706 })?;707708 Self::deposit_event(Event::Canceled { when, index });709 Ok(())710 } else {711 Err(Error::<T>::NotFound)?712 }713 })714 }715}