123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#![cfg_attr(not(feature = "std"), no_std)]70#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]7172mod benchmarking;73pub mod weights;7475use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};76use codec::{Encode, Decode, Codec};77use sp_runtime::{78 RuntimeDebug,79 traits::{Zero, One, BadOrigin, Saturating},80};81use frame_support::{82 decl_module, decl_storage, decl_event, decl_error,83 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},84 traits::{85 Get,86 schedule::{self, DispatchTime},87 OriginTrait, EnsureOrigin, IsType,88 },89 weights::{GetDispatchInfo, Weight},90};91use frame_system::{self as system, ensure_signed};92pub use weights::WeightInfo;93use up_sponsorship::SponsorshipHandler;94use scale_info::TypeInfo;9596979899100101102pub trait Config: system::Config {103 104 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;105106 107 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>108 + From<Self::PalletsOrigin>109 + IsType<<Self as system::Config>::Origin>;110111 112 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;113114 115 type Call: Parameter116 + Dispatchable<Origin = <Self as Config>::Origin>117 + GetDispatchInfo118 + From<system::Call<Self>>;119120 121 122 type MaximumWeight: Get<Weight>;123124 125 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;126127 128 129 type MaxScheduledPerBlock: Get<u32>;130131 132 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;133134 135 type WeightInfo: WeightInfo;136}137138139140141pub type PeriodicIndex = u32;142143pub type TaskAddress<BlockNumber> = (BlockNumber, u32);144145#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]146#[derive(Clone, RuntimeDebug, Encode, Decode)]147struct ScheduledV1<Call, BlockNumber> {148 maybe_id: Option<Vec<u8>>,149 priority: schedule::Priority,150 call: Call,151 maybe_periodic: Option<schedule::Period<BlockNumber>>,152}153154155#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]156#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]157pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {158 159 maybe_id: Option<Vec<u8>>,160 161 priority: schedule::Priority,162 163 call: Call,164 165 maybe_periodic: Option<schedule::Period<BlockNumber>>,166 167 origin: PalletsOrigin,168 _phantom: PhantomData<AccountId>,169}170171172pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =173 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;174175176177178#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]179enum Releases {180 V1,181 V2,182}183184impl Default for Releases {185 fn default() -> Self {186 Releases::V1187 }188}189190#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]191pub struct CallSpec {192 module: u32,193 method: u32,194}195196decl_storage! {197 trait Store for Module<T: Config> as Scheduler {198 199 pub Agenda: map hasher(twox_64_concat) T::BlockNumber200 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;201202 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber203 => Vec<Option<CallSpec>>;204205 206 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;207208 209 210 211 StorageVersion build(|_| Releases::V2): Releases;212 }213}214215decl_event!(216 pub enum Event<T> where <T as system::Config>::BlockNumber {217 218 Scheduled(BlockNumber, u32),219 220 Canceled(BlockNumber, u32),221 222 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),223 }224);225226decl_error! {227 pub enum Error for Module<T: Config> {228 229 FailedToSchedule,230 231 NotFound,232 233 TargetBlockNumberInPast,234 235 RescheduleNoChange,236 }237}238239decl_module! {240 241 pub struct Module<T: Config> for enum Call242 where243 origin: <T as system::Config>::Origin244 {245 type Error = Error<T>;246 fn deposit_event() = default;247248249 250 251 252 253 254 255 256 257 258 259 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]260 fn schedule(origin,261 when: T::BlockNumber,262 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,263 priority: schedule::Priority,264 call: Box<<T as Config>::Call>,265 )266 {267 let origin = <T as Config>::Origin::from(origin);268 Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;269 }270271 272 273 274 275 276 277 278 279 280 281 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]282 fn cancel(origin, when: T::BlockNumber, index: u32) {283 T::ScheduleOrigin::ensure_origin(origin.clone())?;284 let origin = <T as Config>::Origin::from(origin);285 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;286 }287288 289 290 291 292 293 294 295 296 297 298 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]299 fn schedule_named(origin,300 id: Vec<u8>,301 when: T::BlockNumber,302 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,303 priority: schedule::Priority,304 call: Box<<T as Config>::Call>,305 ) {306 T::ScheduleOrigin::ensure_origin(origin.clone())?;307 let origin = <T as Config>::Origin::from(origin);308 Self::do_schedule_named(309 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call310 )?;311 }312313 314 315 316 317 318 319 320 321 322 323 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]324 fn cancel_named(origin, id: Vec<u8>) {325 T::ScheduleOrigin::ensure_origin(origin.clone())?;326 let origin = <T as Config>::Origin::from(origin);327 Self::do_cancel_named(Some(origin.caller().clone()), id)?;328 }329330 331 332 333 334 335 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]336 fn schedule_after(origin,337 after: T::BlockNumber,338 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,339 priority: schedule::Priority,340 call: Box<<T as Config>::Call>,341 ) {342 T::ScheduleOrigin::ensure_origin(origin.clone())?;343 let origin = <T as Config>::Origin::from(origin);344 Self::do_schedule(345 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call346 )?;347 }348349 350 351 352 353 354 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]355 fn schedule_named_after(origin,356 id: Vec<u8>,357 after: T::BlockNumber,358 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,359 priority: schedule::Priority,360 call: Box<<T as Config>::Call>,361 ) {362 T::ScheduleOrigin::ensure_origin(origin.clone())?;363 let origin = <T as Config>::Origin::from(origin);364 Self::do_schedule_named(365 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call366 )?;367 }368369 370 371 372 373 374 375 376 377 378 379 380 fn on_initialize(now: T::BlockNumber) -> Weight {381 let limit = T::MaximumWeight::get();382 let mut queued = Agenda::<T>::take(now).into_iter()383 .enumerate()384 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))385 .collect::<Vec<_>>();386 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {387 log::warn!(388 target: "runtime::scheduler",389 "Warning: This block has more items queued in Scheduler than \390 expected from the runtime configuration. An update might be needed."391 );392 }393 queued.sort_by_key(|(_, s)| s.priority);394 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); 395 let mut total_weight: Weight = 0;396 queued.into_iter()397 .enumerate()398 .scan(base_weight, |cumulative_weight, (order, (index, s))| {399 *cumulative_weight = cumulative_weight400 .saturating_add(s.call.get_dispatch_info().weight);401402 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(403 s.origin.clone()404 ).into();405406 if ensure_signed(origin).is_ok() {407 408 *cumulative_weight = cumulative_weight409 .saturating_add(T::DbWeight::get().reads_writes(1, 1));410 }411412 if s.maybe_id.is_some() {413 414 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));415 }416 if s.maybe_periodic.is_some() {417 418 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));419 }420421 Some((order, index, *cumulative_weight, s))422 })423 .filter_map(|(order, index, cumulative_weight, mut s)| {424 425 426 427 428 if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {429430 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(431 s.origin.clone()432 ).into();433 let sender = match ensure_signed(origin) {434 Ok(v) => v,435 436 Err(_) => return Some(Some(s))437 };438 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);439 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));440 let r = s.call.clone().dispatch(sponsor.into());441 let maybe_id = s.maybe_id.clone();442 if let Some((period, count)) = s.maybe_periodic {443 if count > 1 {444 s.maybe_periodic = Some((period, count - 1));445 } else {446 s.maybe_periodic = None;447 }448 let next = now + period;449 450 if let Some(ref id) = s.maybe_id {451 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);452 Lookup::<T>::insert(id, (next, next_index as u32));453 }454 Agenda::<T>::append(next, Some(s));455 } else if let Some(ref id) = s.maybe_id {456 Lookup::<T>::remove(id);457 }458 Self::deposit_event(RawEvent::Dispatched(459 (now, index),460 maybe_id,461 r.map(|_| ()).map_err(|e| e.error)462 ));463 total_weight = cumulative_weight;464 None465 } else {466 Some(Some(s))467 }468 })469 .for_each(|unused| {470 let next = now + One::one();471 Agenda::<T>::append(next, unused);472 });473474 total_weight475 }476 }477}478479impl<T: Config> Module<T> {480 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {481 let now = frame_system::Pallet::<T>::block_number();482483 let when = match when {484 DispatchTime::At(x) => x,485 486 487 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),488 };489490 if when <= now {491 return Err(Error::<T>::TargetBlockNumberInPast.into());492 }493494 Ok(when)495 }496497 fn do_schedule(498 when: DispatchTime<T::BlockNumber>,499 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,500 priority: schedule::Priority,501 origin: T::PalletsOrigin,502 call: <T as Config>::Call,503 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {504 let when = Self::resolve_time(when)?;505506 507 let maybe_periodic = maybe_periodic508 .filter(|p| p.1 > 1 && !p.0.is_zero())509 510 .map(|(p, c)| (p, c - 1));511 let s = Some(Scheduled {512 maybe_id: None,513 priority,514 call,515 maybe_periodic,516 origin,517 _phantom: PhantomData::<T::AccountId>::default(),518 });519 Agenda::<T>::append(when, s);520 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;521 if index > T::MaxScheduledPerBlock::get() {522 log::warn!(523 target: "runtime::scheduler",524 "Warning: There are more items queued in the Scheduler than \525 expected from the runtime configuration. An update might be needed.",526 );527 }528 Self::deposit_event(RawEvent::Scheduled(when, index));529530 Ok((when, index))531 }532533 fn do_cancel(534 origin: Option<T::PalletsOrigin>,535 (when, index): TaskAddress<T::BlockNumber>,536 ) -> Result<(), DispatchError> {537 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {538 agenda.get_mut(index as usize).map_or(539 Ok(None),540 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {541 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {542 if *o != s.origin {543 return Err(BadOrigin.into());544 }545 };546 Ok(s.take())547 },548 )549 })?;550 if let Some(s) = scheduled {551 if let Some(id) = s.maybe_id {552 Lookup::<T>::remove(id);553 }554 Self::deposit_event(RawEvent::Canceled(when, index));555 Ok(())556 } else {557 Err(Error::<T>::NotFound.into())558 }559 }560561 fn do_reschedule(562 (when, index): TaskAddress<T::BlockNumber>,563 new_time: DispatchTime<T::BlockNumber>,564 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {565 let new_time = Self::resolve_time(new_time)?;566567 if new_time == when {568 return Err(Error::<T>::RescheduleNoChange.into());569 }570571 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {572 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;573 let task = task.take().ok_or(Error::<T>::NotFound)?;574 Agenda::<T>::append(new_time, Some(task));575 Ok(())576 })?;577578 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;579 Self::deposit_event(RawEvent::Canceled(when, index));580 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));581582 Ok((new_time, new_index))583 }584585 fn do_schedule_named(586 id: Vec<u8>,587 when: DispatchTime<T::BlockNumber>,588 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,589 priority: schedule::Priority,590 origin: T::PalletsOrigin,591 call: <T as Config>::Call,592 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {593 594 if Lookup::<T>::contains_key(&id) {595 return Err(Error::<T>::FailedToSchedule.into());596 }597598 let when = Self::resolve_time(when)?;599600 601 let maybe_periodic = maybe_periodic602 .filter(|p| p.1 > 1 && !p.0.is_zero())603 604 .map(|(p, c)| (p, c - 1));605606 let s = Scheduled {607 maybe_id: Some(id.clone()),608 priority,609 call,610 maybe_periodic,611 origin,612 _phantom: Default::default(),613 };614 Agenda::<T>::append(when, Some(s));615 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;616 if index > T::MaxScheduledPerBlock::get() {617 log::warn!(618 target: "runtime::scheduler",619 "Warning: There are more items queued in the Scheduler than \620 expected from the runtime configuration. An update might be needed.",621 );622 }623 let address = (when, index);624 Lookup::<T>::insert(&id, &address);625 Self::deposit_event(RawEvent::Scheduled(when, index));626627 Ok(address)628 }629630 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {631 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {632 if let Some((when, index)) = lookup.take() {633 let i = index as usize;634 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {635 if let Some(s) = agenda.get_mut(i) {636 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {637 if *o != s.origin {638 return Err(BadOrigin.into());639 }640 }641 *s = None;642 }643 Ok(())644 })?;645 Self::deposit_event(RawEvent::Canceled(when, index));646 Ok(())647 } else {648 Err(Error::<T>::NotFound.into())649 }650 })651 }652653 fn do_reschedule_named(654 id: Vec<u8>,655 new_time: DispatchTime<T::BlockNumber>,656 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {657 let new_time = Self::resolve_time(new_time)?;658659 Lookup::<T>::try_mutate_exists(660 id,661 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;663664 if new_time == when {665 return Err(Error::<T>::RescheduleNoChange.into());666 }667668 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {669 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;670 let task = task.take().ok_or(Error::<T>::NotFound)?;671 Agenda::<T>::append(new_time, Some(task));672673 Ok(())674 })?;675676 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;677 Self::deposit_event(RawEvent::Canceled(when, index));678 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));679680 *lookup = Some((new_time, new_index));681682 Ok((new_time, new_index))683 },684 )685 }686}687688#[cfg(test)]689#[allow(clippy::from_over_into)]690mod tests {691 use super::*;692693 use frame_support::{694 ord_parameter_types, parameter_types,695 traits::{Contains, ConstU32, EnsureOneOf},696 weights::constants::RocksDbWeight,697 };698 use sp_core::H256;699 use sp_runtime::{700 Perbill,701 testing::Header,702 traits::{BlakeTwo256, IdentityLookup},703 };704 use frame_system::{EnsureRoot, EnsureSignedBy};705 use crate as scheduler;706707 mod logger {708 use super::*;709 use std::cell::RefCell;710711 thread_local! {712 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());713 }714 pub trait Config: system::Config {715 type Event: From<Event> + Into<<Self as system::Config>::Event>;716 }717 decl_event! {718 pub enum Event {719 Logged(u32, Weight),720 }721 }722 decl_module! {723 pub struct Module<T: Config> for enum Call724 where725 origin: <T as system::Config>::Origin,726 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>727 {728 fn deposit_event() = default;729730 #[weight = *weight]731 fn log(origin, i: u32, weight: Weight) {732 Self::deposit_event(Event::Logged(i, weight));733 LOG.with(|log| {734 log.borrow_mut().push((origin.caller().clone(), i));735 })736 }737738 #[weight = *weight]739 fn log_without_filter(origin, i: u32, weight: Weight) {740 Self::deposit_event(Event::Logged(i, weight));741 LOG.with(|log| {742 log.borrow_mut().push((origin.caller().clone(), i));743 })744 }745 }746 }747 }748749 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;750 type Block = frame_system::mocking::MockBlock<Test>;751752 frame_support::construct_runtime!(753 pub enum Test where754 Block = Block,755 NodeBlock = Block,756 UncheckedExtrinsic = UncheckedExtrinsic,757 {758 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},759 Logger: logger::{Pallet, Call, Event},760 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},761 }762 );763764 765 pub struct BaseFilter;766 impl Contains<Call> for BaseFilter {767 fn contains(call: &Call) -> bool {768 !matches!(call, Call::Logger(logger::Call::log { .. }))769 }770 }771772 parameter_types! {773 pub const BlockHashCount: u64 = 250;774 pub BlockWeights: frame_system::limits::BlockWeights =775 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);776 }777 impl system::Config for Test {778 type BaseCallFilter = BaseFilter;779 type BlockWeights = ();780 type BlockLength = ();781 type DbWeight = RocksDbWeight;782 type Origin = Origin;783 type Call = Call;784 type Index = u64;785 type BlockNumber = u64;786 type Hash = H256;787 type Hashing = BlakeTwo256;788 type AccountId = u64;789 type Lookup = IdentityLookup<Self::AccountId>;790 type Header = Header;791 type Event = Event;792 type BlockHashCount = BlockHashCount;793 type Version = ();794 type PalletInfo = PalletInfo;795 type AccountData = ();796 type OnNewAccount = ();797 type OnKilledAccount = ();798 type SystemWeightInfo = ();799 type SS58Prefix = ();800 type OnSetCode = ();801 type MaxConsumers = ConstU32<16>;802 }803 impl logger::Config for Test {804 type Event = Event;805 }806 parameter_types! {807 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;808 pub const MaxScheduledPerBlock: u32 = 10;809 }810 ord_parameter_types! {811 pub const One: u64 = 1;812 }813814 impl Config for Test {815 type Event = Event;816 type Origin = Origin;817 type PalletsOrigin = OriginCaller;818 type Call = Call;819 type MaximumWeight = MaximumSchedulerWeight;820 type ScheduleOrigin = EnsureOneOf<EnsureRoot<u64>, EnsureSignedBy<One, u64>>;821 type MaxScheduledPerBlock = MaxScheduledPerBlock;822 type WeightInfo = ();823 type SponsorshipHandler = ();824 }825}