Allow specify schedule dispatch origin (#6387)

* allow specify schedule dispatch origin

* fix tests

* use caller origin for scheduled

* fix tests

* line width

* check origin for cancel

* line width

* fix some issues for benchmarking

* fix doc test

* another way to constraint origin

* fix build issues

* fix cancel

* line width

* fix benchmarks

* bump version

* enable runtime upgrade

* add migration code and test

* Update frame/scheduler/src/lib.rs

Co-authored-by: Gavin Wood <github@gavwood.com>

* expose migration method

* add notes

* bump version

* remove on_runtime_upgrade

* fix test

Co-authored-by: Gavin Wood <github@gavwood.com>
This commit is contained in:
Xiliang Chen
2020-07-03 01:05:15 +12:00
committed by GitHub
parent 540ae1c161
commit e1d0f84c67
16 changed files with 510 additions and 139 deletions
+1
View File
@@ -4502,6 +4502,7 @@ dependencies = [
"sp-io", "sp-io",
"sp-runtime", "sp-runtime",
"sp-std", "sp-std",
"substrate-test-utils",
] ]
[[package]] [[package]]
+3
View File
@@ -255,8 +255,10 @@ parameter_types! {
impl pallet_scheduler::Trait for Runtime { impl pallet_scheduler::Trait for Runtime {
type Event = Event; type Event = Event;
type Origin = Origin; type Origin = Origin;
type PalletsOrigin = OriginCaller;
type Call = Call; type Call = Call;
type MaximumWeight = MaximumSchedulerWeight; type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureRoot<AccountId>;
} }
parameter_types! { parameter_types! {
@@ -455,6 +457,7 @@ impl pallet_democracy::Trait for Runtime {
type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>; type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>;
type Slash = Treasury; type Slash = Treasury;
type Scheduler = Scheduler; type Scheduler = Scheduler;
type PalletsOrigin = OriginCaller;
type MaxVotes = MaxVotes; type MaxVotes = MaxVotes;
} }
+1 -1
View File
@@ -97,7 +97,7 @@ pub trait Trait<I: Instance=DefaultInstance>: frame_system::Trait {
} }
/// Origin for the collective module. /// Origin for the collective module.
#[derive(PartialEq, Eq, Clone, RuntimeDebug)] #[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)]
pub enum RawOrigin<AccountId, I> { pub enum RawOrigin<AccountId, I> {
/// It has been condoned by a given number of members of the collective from a given total. /// It has been condoned by a given number of members of the collective from a given total.
Members(MemberCount, MemberCount), Members(MemberCount, MemberCount),
@@ -79,6 +79,7 @@ fn add_referendum<T: Trait>(n: u32) -> Result<ReferendumIndex, &'static str> {
1.into(), 1.into(),
None, None,
63, 63,
system::RawOrigin::Root.into(),
Call::enact_proposal(proposal_hash, referendum_index).into(), Call::enact_proposal(proposal_hash, referendum_index).into(),
).map_err(|_| "failed to schedule named")?; ).map_err(|_| "failed to schedule named")?;
Ok(referendum_index) Ok(referendum_index)
+5 -1
View File
@@ -279,7 +279,10 @@ pub trait Trait: frame_system::Trait + Sized {
type Slash: OnUnbalanced<NegativeImbalanceOf<Self>>; type Slash: OnUnbalanced<NegativeImbalanceOf<Self>>;
/// The Scheduler. /// The Scheduler.
type Scheduler: ScheduleNamed<Self::BlockNumber, Self::Proposal>; type Scheduler: ScheduleNamed<Self::BlockNumber, Self::Proposal, Self::PalletsOrigin>;
/// Overarching type of all pallets origins.
type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>;
/// The maximum number of votes for an account. /// The maximum number of votes for an account.
/// ///
@@ -1625,6 +1628,7 @@ impl<T: Trait> Module<T> {
when, when,
None, None,
63, 63,
system::RawOrigin::Root.into(),
Call::enact_proposal(status.proposal_hash, index).into(), Call::enact_proposal(status.proposal_hash, index).into(),
).is_err() { ).is_err() {
frame_support::print("LOGIC ERROR: bake_referendum/schedule_named failed"); frame_support::print("LOGIC ERROR: bake_referendum/schedule_named failed");
+4 -1
View File
@@ -31,7 +31,7 @@ use sp_runtime::{
testing::Header, Perbill, testing::Header, Perbill,
}; };
use pallet_balances::{BalanceLock, Error as BalancesError}; use pallet_balances::{BalanceLock, Error as BalancesError};
use frame_system::EnsureSignedBy; use frame_system::{EnsureSignedBy, EnsureRoot};
mod cancellation; mod cancellation;
mod delegation; mod delegation;
@@ -123,8 +123,10 @@ parameter_types! {
impl pallet_scheduler::Trait for Test { impl pallet_scheduler::Trait for Test {
type Event = Event; type Event = Event;
type Origin = Origin; type Origin = Origin;
type PalletsOrigin = OriginCaller;
type Call = Call; type Call = Call;
type MaximumWeight = MaximumSchedulerWeight; type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureRoot<u64>;
} }
parameter_types! { parameter_types! {
pub const ExistentialDeposit: u64 = 1; pub const ExistentialDeposit: u64 = 1;
@@ -196,6 +198,7 @@ impl super::Trait for Test {
type Scheduler = Scheduler; type Scheduler = Scheduler;
type MaxVotes = MaxVotes; type MaxVotes = MaxVotes;
type OperationalPreimageOrigin = EnsureSignedBy<Six, u64>; type OperationalPreimageOrigin = EnsureSignedBy<Six, u64>;
type PalletsOrigin = OriginCaller;
} }
pub fn new_test_ext() -> sp_io::TestExternalities { pub fn new_test_ext() -> sp_io::TestExternalities {
+6 -1
View File
@@ -21,6 +21,7 @@ frame-benchmarking = { version = "2.0.0-rc4", default-features = false, path = "
[dev-dependencies] [dev-dependencies]
sp-core = { version = "2.0.0-rc4", path = "../../primitives/core", default-features = false } sp-core = { version = "2.0.0-rc4", path = "../../primitives/core", default-features = false }
substrate-test-utils = { version = "2.0.0-rc4", path = "../../test-utils" }
[features] [features]
default = ["std"] default = ["std"]
@@ -34,4 +35,8 @@ std = [
"sp-io/std", "sp-io/std",
"sp-std/std" "sp-std/std"
] ]
runtime-benchmarks = ["frame-benchmarking"] runtime-benchmarks = [
"frame-benchmarking",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
]
@@ -44,6 +44,7 @@ fn fill_schedule<T: Trait> (when: T::BlockNumber, n: u32) -> Result<(), &'static
Some((T::BlockNumber::one(), 100)), Some((T::BlockNumber::one(), 100)),
// HARD_DEADLINE priority means it gets executed no matter what // HARD_DEADLINE priority means it gets executed no matter what
0, 0,
frame_system::RawOrigin::Root.into(),
call.clone().into(), call.clone().into(),
)?; )?;
} }
+432 -114
View File
@@ -28,6 +28,14 @@
//! specified block number or at a specified period. These scheduled dispatches //! specified block number or at a specified period. These scheduled dispatches
//! may be named or anonymous and may be canceled. //! may be named or anonymous and may be canceled.
//! //!
//! **NOTE:** The scheduled calls will be dispatched with the default filter
//! for the origin: namely `frame_system::Trait::BaseCallFilter` for all origin
//! except root which will get no filter. And not the filter contained in origin
//! use to call `fn schedule`.
//!
//! If a call is scheduled using proxy or whatever mecanism which adds filter,
//! then those filter will not be used when dispatching the schedule call.
//!
//! ## Interface //! ## Interface
//! //!
//! ### Dispatchable Functions //! ### Dispatchable Functions
@@ -45,16 +53,16 @@
mod benchmarking; mod benchmarking;
use sp_std::prelude::*; use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};
use codec::{Encode, Decode}; use codec::{Encode, Decode, Codec};
use sp_runtime::{RuntimeDebug, traits::{Zero, One}}; use sp_runtime::{RuntimeDebug, traits::{Zero, One, BadOrigin}};
use frame_support::{ use frame_support::{
decl_module, decl_storage, decl_event, decl_error, decl_module, decl_storage, decl_event, decl_error, IterableStorageMap,
dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter}, dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},
traits::{Get, schedule}, traits::{Get, schedule, OriginTrait, EnsureOrigin, IsType},
weights::{GetDispatchInfo, Weight}, weights::{GetDispatchInfo, Weight},
}; };
use frame_system::{self as system, ensure_root}; use frame_system::{self as system};
/// Our pallet's configuration trait. All our types and constants go in here. If the /// Our pallet's configuration trait. All our types and constants go in here. If the
/// pallet is dependent on specific other pallets, then their configuration traits /// pallet is dependent on specific other pallets, then their configuration traits
@@ -66,7 +74,11 @@ pub trait Trait: system::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
/// The aggregated origin which the dispatch will take. /// The aggregated origin which the dispatch will take.
type Origin: From<system::RawOrigin<Self::AccountId>>; type Origin: OriginTrait<PalletsOrigin =
Self::PalletsOrigin> + From<Self::PalletsOrigin> + IsType<<Self as system::Trait>::Origin>;
/// The caller origin, overarching type of all pallets origins.
type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq;
/// The aggregated call type. /// The aggregated call type.
type Call: Parameter + Dispatchable<Origin=<Self as Trait>::Origin> + GetDispatchInfo + From<system::Call<Self>>; type Call: Parameter + Dispatchable<Origin=<Self as Trait>::Origin> + GetDispatchInfo + From<system::Call<Self>>;
@@ -74,6 +86,9 @@ pub trait Trait: system::Trait {
/// The maximum weight that may be scheduled per block for any dispatchables of less priority /// The maximum weight that may be scheduled per block for any dispatchables of less priority
/// than `schedule::HARD_DEADLINE`. /// than `schedule::HARD_DEADLINE`.
type MaximumWeight: Get<Weight>; type MaximumWeight: Get<Weight>;
/// Required origin to schedule or cancel calls.
type ScheduleOrigin: EnsureOrigin<<Self as system::Trait>::Origin>;
} }
/// Just a simple index for naming period tasks. /// Just a simple index for naming period tasks.
@@ -81,9 +96,19 @@ pub type PeriodicIndex = u32;
/// The location of a scheduled task that can be used to remove it. /// The location of a scheduled task that can be used to remove it.
pub type TaskAddress<BlockNumber> = (BlockNumber, u32); pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
/// Information regarding an item to be executed in the future. #[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
#[derive(Clone, RuntimeDebug, Encode, Decode)] #[derive(Clone, RuntimeDebug, Encode, Decode)]
pub struct Scheduled<Call, BlockNumber> { struct ScheduledV1<Call, BlockNumber> {
maybe_id: Option<Vec<u8>>,
priority: schedule::Priority,
call: Call,
maybe_periodic: Option<schedule::Period<BlockNumber>>,
}
/// Information regarding an item to be executed in the future.
#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
#[derive(Clone, RuntimeDebug, Encode, Decode)]
pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {
/// The unique identity for this task, if there is one. /// The unique identity for this task, if there is one.
maybe_id: Option<Vec<u8>>, maybe_id: Option<Vec<u8>>,
/// This task's priority. /// This task's priority.
@@ -92,16 +117,42 @@ pub struct Scheduled<Call, BlockNumber> {
call: Call, call: Call,
/// If the call is periodic, then this points to the information concerning that. /// If the call is periodic, then this points to the information concerning that.
maybe_periodic: Option<schedule::Period<BlockNumber>>, maybe_periodic: Option<schedule::Period<BlockNumber>>,
/// The origin to dispatch the call.
origin: PalletsOrigin,
_phantom: PhantomData<AccountId>,
}
/// The current version of Scheduled struct.
pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> = ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;
// A value placed in storage that represents the current version of the Scheduler storage.
// This value is used by the `on_runtime_upgrade` logic to determine whether we run
// storage migration logic.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)]
enum Releases {
V1,
V2,
}
impl Default for Releases {
fn default() -> Self {
Releases::V1
}
} }
decl_storage! { decl_storage! {
trait Store for Module<T: Trait> as Scheduler { trait Store for Module<T: Trait> as Scheduler {
/// Items to be executed, indexed by the block number that they should be executed on. /// Items to be executed, indexed by the block number that they should be executed on.
pub Agenda: map hasher(twox_64_concat) T::BlockNumber pub Agenda: map hasher(twox_64_concat) T::BlockNumber
=> Vec<Option<Scheduled<<T as Trait>::Call, T::BlockNumber>>>; => Vec<Option<Scheduled<<T as Trait>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;
/// Lookup from identity to the block number and index of the task. /// Lookup from identity to the block number and index of the task.
Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>; Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;
/// Storage version of the pallet.
///
/// New networks start with last version.
StorageVersion build(|_| Releases::V2): Releases;
} }
} }
@@ -127,6 +178,7 @@ decl_error! {
decl_module! { decl_module! {
/// Scheduler module declaration. /// Scheduler module declaration.
pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin { pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin {
type Error = Error<T>;
fn deposit_event() = default; fn deposit_event() = default;
/// Anonymously schedule a task. /// Anonymously schedule a task.
@@ -146,8 +198,9 @@ decl_module! {
priority: schedule::Priority, priority: schedule::Priority,
call: Box<<T as Trait>::Call>, call: Box<<T as Trait>::Call>,
) { ) {
ensure_root(origin)?; T::ScheduleOrigin::ensure_origin(origin.clone())?;
Self::do_schedule(when, maybe_periodic, priority, *call)?; let origin = <T as Trait>::Origin::from(origin);
Self::do_schedule(when, maybe_periodic, priority, origin.caller().clone(), *call)?;
} }
/// Cancel an anonymously scheduled task. /// Cancel an anonymously scheduled task.
@@ -162,8 +215,9 @@ decl_module! {
/// # </weight> /// # </weight>
#[weight = 100_000_000 + T::DbWeight::get().reads_writes(1, 2)] #[weight = 100_000_000 + T::DbWeight::get().reads_writes(1, 2)]
fn cancel(origin, when: T::BlockNumber, index: u32) { fn cancel(origin, when: T::BlockNumber, index: u32) {
ensure_root(origin)?; T::ScheduleOrigin::ensure_origin(origin.clone())?;
Self::do_cancel((when, index))?; let origin = <T as Trait>::Origin::from(origin);
Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
} }
/// Schedule a named task. /// Schedule a named task.
@@ -184,8 +238,9 @@ decl_module! {
priority: schedule::Priority, priority: schedule::Priority,
call: Box<<T as Trait>::Call>, call: Box<<T as Trait>::Call>,
) { ) {
ensure_root(origin)?; T::ScheduleOrigin::ensure_origin(origin.clone())?;
Self::do_schedule_named(id, when, maybe_periodic, priority, *call)?; let origin = <T as Trait>::Origin::from(origin);
Self::do_schedule_named(id, when, maybe_periodic, priority, origin.caller().clone(), *call)?;
} }
/// Cancel a named scheduled task. /// Cancel a named scheduled task.
@@ -200,8 +255,9 @@ decl_module! {
/// # </weight> /// # </weight>
#[weight = 100_000_000 + T::DbWeight::get().reads_writes(2, 2)] #[weight = 100_000_000 + T::DbWeight::get().reads_writes(2, 2)]
fn cancel_named(origin, id: Vec<u8>) { fn cancel_named(origin, id: Vec<u8>) {
ensure_root(origin)?; T::ScheduleOrigin::ensure_origin(origin.clone())?;
Self::do_cancel_named(id)?; let origin = <T as Trait>::Origin::from(origin);
Self::do_cancel_named(Some(origin.caller().clone()), id)?;
} }
/// Execute the scheduled calls /// Execute the scheduled calls
@@ -249,7 +305,7 @@ decl_module! {
// - It does not push the weight past the limit. // - It does not push the weight past the limit.
// - It is the first item in the schedule // - It is the first item in the schedule
if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 { if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {
let r = s.call.clone().dispatch(system::RawOrigin::Root.into()); let r = s.call.clone().dispatch(s.origin.clone().into());
let maybe_id = s.maybe_id.clone(); let maybe_id = s.maybe_id.clone();
if let &Some((period, count)) = &s.maybe_periodic { if let &Some((period, count)) = &s.maybe_periodic {
if count > 1 { if count > 1 {
@@ -291,10 +347,39 @@ decl_module! {
} }
impl<T: Trait> Module<T> { impl<T: Trait> Module<T> {
/// Migrate storage format from V1 to V2.
/// Return true if migration is performed.
pub fn migrate_v1_to_t2() -> bool {
if StorageVersion::get() == Releases::V1 {
StorageVersion::put(Releases::V2);
Agenda::<T>::translate::<
Vec<Option<ScheduledV1<<T as Trait>::Call, T::BlockNumber>>>, _
>(|_, agenda| Some(
agenda
.into_iter()
.map(|schedule| schedule.map(|schedule| ScheduledV2 {
maybe_id: schedule.maybe_id,
priority: schedule.priority,
call: schedule.call,
maybe_periodic: schedule.maybe_periodic,
origin: system::RawOrigin::Root.into(),
_phantom: Default::default(),
}))
.collect::<Vec<_>>()
));
true
} else {
false
}
}
fn do_schedule( fn do_schedule(
when: T::BlockNumber, when: T::BlockNumber,
maybe_periodic: Option<schedule::Period<T::BlockNumber>>, maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority, priority: schedule::Priority,
origin: T::PalletsOrigin,
call: <T as Trait>::Call call: <T as Trait>::Call
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> { ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
if when <= frame_system::Module::<T>::block_number() { if when <= frame_system::Module::<T>::block_number() {
@@ -306,7 +391,9 @@ impl<T: Trait> Module<T> {
.filter(|p| p.1 > 1 && !p.0.is_zero()) .filter(|p| p.1 > 1 && !p.0.is_zero())
// Remove one from the number of repetitions since we will schedule one now. // Remove one from the number of repetitions since we will schedule one now.
.map(|(p, c)| (p, c - 1)); .map(|(p, c)| (p, c - 1));
let s = Some(Scheduled { maybe_id: None, priority, call, maybe_periodic }); let s = Some(Scheduled {
maybe_id: None, priority, call, maybe_periodic, origin, _phantom: PhantomData::<T::AccountId>::default(),
});
Agenda::<T>::append(when, s); Agenda::<T>::append(when, s);
let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1; let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
Self::deposit_event(RawEvent::Scheduled(when, index)); Self::deposit_event(RawEvent::Scheduled(when, index));
@@ -314,8 +401,25 @@ impl<T: Trait> Module<T> {
Ok((when, index)) Ok((when, index))
} }
fn do_cancel((when, index): TaskAddress<T::BlockNumber>) -> Result<(), DispatchError> { fn do_cancel(
if let Some(s) = Agenda::<T>::mutate(when, |agenda| agenda.get_mut(index as usize).and_then(Option::take)) { origin: Option<T::PalletsOrigin>,
(when, index): TaskAddress<T::BlockNumber>
) -> Result<(), DispatchError> {
let scheduled = Agenda::<T>::try_mutate(
when,
|agenda| {
agenda.get_mut(index as usize)
.map_or(Ok(None), |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {
if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
if *o != s.origin {
return Err(BadOrigin.into());
}
};
Ok(s.take())
})
},
)?;
if let Some(s) = scheduled {
if let Some(id) = s.maybe_id { if let Some(id) = s.maybe_id {
Lookup::<T>::remove(id); Lookup::<T>::remove(id);
} }
@@ -331,6 +435,7 @@ impl<T: Trait> Module<T> {
when: T::BlockNumber, when: T::BlockNumber,
maybe_periodic: Option<schedule::Period<T::BlockNumber>>, maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority, priority: schedule::Priority,
origin: T::PalletsOrigin,
call: <T as Trait>::Call, call: <T as Trait>::Call,
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> { ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
// ensure id it is unique // ensure id it is unique
@@ -348,7 +453,9 @@ impl<T: Trait> Module<T> {
// Remove one from the number of repetitions since we will schedule one now. // Remove one from the number of repetitions since we will schedule one now.
.map(|(p, c)| (p, c - 1)); .map(|(p, c)| (p, c - 1));
let s = Scheduled { maybe_id: Some(id.clone()), priority, call, maybe_periodic }; let s = Scheduled {
maybe_id: Some(id.clone()), priority, call, maybe_periodic, origin, _phantom: Default::default()
};
Agenda::<T>::append(when, Some(s)); Agenda::<T>::append(when, Some(s));
let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1; let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
let address = (when, index); let address = (when, index);
@@ -358,36 +465,49 @@ impl<T: Trait> Module<T> {
Ok(address) Ok(address)
} }
fn do_cancel_named(id: Vec<u8>) -> Result<(), DispatchError> { fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {
if let Some((when, index)) = Lookup::<T>::take(id) { Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
let i = index as usize; if let Some((when, index)) = lookup.take() {
Agenda::<T>::mutate(when, |agenda| if let Some(s) = agenda.get_mut(i) { *s = None }); let i = index as usize;
Self::deposit_event(RawEvent::Canceled(when, index)); Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
Ok(()) if let Some(s) = agenda.get_mut(i) {
} else { if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
Err(Error::<T>::FailedToCancel)? if *o != s.origin {
} return Err(BadOrigin.into());
}
}
*s = None;
}
Ok(())
})?;
Self::deposit_event(RawEvent::Canceled(when, index));
Ok(())
} else {
Err(Error::<T>::FailedToCancel)?
}
})
} }
} }
impl<T: Trait> schedule::Anon<T::BlockNumber, <T as Trait>::Call> for Module<T> { impl<T: Trait> schedule::Anon<T::BlockNumber, <T as Trait>::Call, T::PalletsOrigin> for Module<T> {
type Address = TaskAddress<T::BlockNumber>; type Address = TaskAddress<T::BlockNumber>;
fn schedule( fn schedule(
when: T::BlockNumber, when: T::BlockNumber,
maybe_periodic: Option<schedule::Period<T::BlockNumber>>, maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority, priority: schedule::Priority,
origin: T::PalletsOrigin,
call: <T as Trait>::Call call: <T as Trait>::Call
) -> Result<Self::Address, DispatchError> { ) -> Result<Self::Address, DispatchError> {
Self::do_schedule(when, maybe_periodic, priority, call) Self::do_schedule(when, maybe_periodic, priority, origin, call)
} }
fn cancel((when, index): Self::Address) -> Result<(), ()> { fn cancel((when, index): Self::Address) -> Result<(), ()> {
Self::do_cancel((when, index)).map_err(|_| ()) Self::do_cancel(None, (when, index)).map_err(|_| ())
} }
} }
impl<T: Trait> schedule::Named<T::BlockNumber, <T as Trait>::Call> for Module<T> { impl<T: Trait> schedule::Named<T::BlockNumber, <T as Trait>::Call, T::PalletsOrigin> for Module<T> {
type Address = TaskAddress<T::BlockNumber>; type Address = TaskAddress<T::BlockNumber>;
fn schedule_named( fn schedule_named(
@@ -395,13 +515,14 @@ impl<T: Trait> schedule::Named<T::BlockNumber, <T as Trait>::Call> for Module<T>
when: T::BlockNumber, when: T::BlockNumber,
maybe_periodic: Option<schedule::Period<T::BlockNumber>>, maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority, priority: schedule::Priority,
origin: T::PalletsOrigin,
call: <T as Trait>::Call, call: <T as Trait>::Call,
) -> Result<Self::Address, ()> { ) -> Result<Self::Address, ()> {
Self::do_schedule_named(id, when, maybe_periodic, priority, call).map_err(|_| ()) Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())
} }
fn cancel_named(id: Vec<u8>) -> Result<(), ()> { fn cancel_named(id: Vec<u8>) -> Result<(), ()> {
Self::do_cancel_named(id).map_err(|_| ()) Self::do_cancel_named(None, id).map_err(|_| ())
} }
} }
@@ -410,8 +531,10 @@ mod tests {
use super::*; use super::*;
use frame_support::{ use frame_support::{
impl_outer_event, impl_outer_origin, impl_outer_dispatch, parameter_types, assert_ok, impl_outer_event, impl_outer_origin, impl_outer_dispatch, parameter_types, assert_ok, ord_parameter_types,
assert_err, traits::{OnInitialize, OnFinalize, Filter}, weights::constants::RocksDbWeight, assert_noop, assert_err, Hashable,
traits::{OnInitialize, OnFinalize, Filter},
weights::constants::RocksDbWeight,
}; };
use sp_core::H256; use sp_core::H256;
// The testing primitives are very useful for avoiding having to work with signatures // The testing primitives are very useful for avoiding having to work with signatures
@@ -421,41 +544,48 @@ mod tests {
testing::Header, testing::Header,
traits::{BlakeTwo256, IdentityLookup}, traits::{BlakeTwo256, IdentityLookup},
}; };
use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};
use crate as scheduler; use crate as scheduler;
mod logger { mod logger {
use super::*; use super::*;
use std::cell::RefCell; use std::cell::RefCell;
use frame_system::ensure_root;
thread_local! { thread_local! {
static LOG: RefCell<Vec<u32>> = RefCell::new(Vec::new()); static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());
} }
pub fn log() -> Vec<u32> { pub fn log() -> Vec<(OriginCaller, u32)> {
LOG.with(|log| log.borrow().clone()) LOG.with(|log| log.borrow().clone())
} }
pub trait Trait: system::Trait { pub trait Trait: system::Trait {
type Event: From<Event> + Into<<Self as system::Trait>::Event>; type Event: From<Event> + Into<<Self as system::Trait>::Event>;
} }
decl_storage! {
trait Store for Module<T: Trait> as Logger {
}
}
decl_event! { decl_event! {
pub enum Event { pub enum Event {
Logged(u32, Weight), Logged(u32, Weight),
} }
} }
decl_module! { decl_module! {
pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin { pub struct Module<T: Trait> for enum Call
where
origin: <T as system::Trait>::Origin,
<T as system::Trait>::Origin: OriginTrait<PalletsOrigin = OriginCaller>
{
fn deposit_event() = default; fn deposit_event() = default;
#[weight = *weight] #[weight = *weight]
fn log(origin, i: u32, weight: Weight) { fn log(origin, i: u32, weight: Weight) {
ensure_root(origin)?;
Self::deposit_event(Event::Logged(i, weight)); Self::deposit_event(Event::Logged(i, weight));
LOG.with(|log| { LOG.with(|log| {
log.borrow_mut().push(i); log.borrow_mut().push((origin.caller().clone(), i));
})
}
#[weight = *weight]
fn log_without_filter(origin, i: u32, weight: Weight) {
Self::deposit_event(Event::Logged(i, weight));
LOG.with(|log| {
log.borrow_mut().push((origin.caller().clone(), i));
}) })
} }
} }
@@ -485,7 +615,7 @@ mod tests {
pub struct BaseFilter; pub struct BaseFilter;
impl Filter<Call> for BaseFilter { impl Filter<Call> for BaseFilter {
fn filter(call: &Call) -> bool { fn filter(call: &Call) -> bool {
!matches!(call, Call::Logger(_)) !matches!(call, Call::Logger(logger::Call::log(_, _)))
} }
} }
@@ -532,11 +662,17 @@ mod tests {
parameter_types! { parameter_types! {
pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * MaximumBlockWeight::get(); pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * MaximumBlockWeight::get();
} }
ord_parameter_types! {
pub const One: u64 = 1;
}
impl Trait for Test { impl Trait for Test {
type Event = (); type Event = ();
type Origin = Origin; type Origin = Origin;
type PalletsOrigin = OriginCaller;
type Call = Call; type Call = Call;
type MaximumWeight = MaximumSchedulerWeight; type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;
} }
type System = system::Module<Test>; type System = system::Module<Test>;
type Logger = logger::Module<Test>; type Logger = logger::Module<Test>;
@@ -557,18 +693,22 @@ mod tests {
} }
} }
fn root() -> OriginCaller {
system::RawOrigin::Root.into()
}
#[test] #[test]
fn basic_scheduling_works() { fn basic_scheduling_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let call = Call::Logger(logger::Call::log(42, 1000)); let call = Call::Logger(logger::Call::log(42, 1000));
assert!(!<Test as frame_system::Trait>::BaseCallFilter::filter(&call)); assert!(!<Test as frame_system::Trait>::BaseCallFilter::filter(&call));
let _ = Scheduler::do_schedule(4, None, 127, call); let _ = Scheduler::do_schedule(4, None, 127, root(), call);
run_to_block(3); run_to_block(3);
assert!(logger::log().is_empty()); assert!(logger::log().is_empty());
run_to_block(4); run_to_block(4);
assert_eq!(logger::log(), vec![42u32]); assert_eq!(logger::log(), vec![(root(), 42u32)]);
run_to_block(100); run_to_block(100);
assert_eq!(logger::log(), vec![42u32]); assert_eq!(logger::log(), vec![(root(), 42u32)]);
}); });
} }
@@ -576,21 +716,23 @@ mod tests {
fn periodic_scheduling_works() { fn periodic_scheduling_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// at #4, every 3 blocks, 3 times. // at #4, every 3 blocks, 3 times.
let _ = Scheduler::do_schedule(4, Some((3, 3)), 127, Call::Logger(logger::Call::log(42, 1000))); let _ = Scheduler::do_schedule(
4, Some((3, 3)), 127, root(), Call::Logger(logger::Call::log(42, 1000))
);
run_to_block(3); run_to_block(3);
assert!(logger::log().is_empty()); assert!(logger::log().is_empty());
run_to_block(4); run_to_block(4);
assert_eq!(logger::log(), vec![42u32]); assert_eq!(logger::log(), vec![(root(), 42u32)]);
run_to_block(6); run_to_block(6);
assert_eq!(logger::log(), vec![42u32]); assert_eq!(logger::log(), vec![(root(), 42u32)]);
run_to_block(7); run_to_block(7);
assert_eq!(logger::log(), vec![42u32, 42u32]); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
run_to_block(9); run_to_block(9);
assert_eq!(logger::log(), vec![42u32, 42u32]); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
run_to_block(10); run_to_block(10);
assert_eq!(logger::log(), vec![42u32, 42u32, 42u32]); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);
run_to_block(100); run_to_block(100);
assert_eq!(logger::log(), vec![42u32, 42u32, 42u32]); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);
}); });
} }
@@ -598,12 +740,16 @@ mod tests {
fn cancel_named_scheduling_works_with_normal_cancel() { fn cancel_named_scheduling_works_with_normal_cancel() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// at #4. // at #4.
Scheduler::do_schedule_named(1u32.encode(), 4, None, 127, Call::Logger(logger::Call::log(69, 1000))).unwrap(); Scheduler::do_schedule_named(
let i = Scheduler::do_schedule(4, None, 127, Call::Logger(logger::Call::log(42, 1000))).unwrap(); 1u32.encode(), 4, None, 127, root(), Call::Logger(logger::Call::log(69, 1000))
).unwrap();
let i = Scheduler::do_schedule(
4, None, 127, root(), Call::Logger(logger::Call::log(42, 1000))
).unwrap();
run_to_block(3); run_to_block(3);
assert!(logger::log().is_empty()); assert!(logger::log().is_empty());
assert_ok!(Scheduler::do_cancel_named(1u32.encode())); assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
assert_ok!(Scheduler::do_cancel(i)); assert_ok!(Scheduler::do_cancel(None, i));
run_to_block(100); run_to_block(100);
assert!(logger::log().is_empty()); assert!(logger::log().is_empty());
}); });
@@ -613,53 +759,71 @@ mod tests {
fn cancel_named_periodic_scheduling_works() { fn cancel_named_periodic_scheduling_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// at #4, every 3 blocks, 3 times. // at #4, every 3 blocks, 3 times.
Scheduler::do_schedule_named(1u32.encode(), 4, Some((3, 3)), 127, Call::Logger(logger::Call::log(42, 1000))).unwrap(); Scheduler::do_schedule_named(
1u32.encode(), 4, Some((3, 3)), 127, root(), Call::Logger(logger::Call::log(42, 1000))
).unwrap();
// same id results in error. // same id results in error.
assert!(Scheduler::do_schedule_named(1u32.encode(), 4, None, 127, Call::Logger(logger::Call::log(69, 1000))).is_err()); assert!(Scheduler::do_schedule_named(
1u32.encode(), 4, None, 127, root(), Call::Logger(logger::Call::log(69, 1000))
).is_err());
// different id is ok. // different id is ok.
Scheduler::do_schedule_named(2u32.encode(), 8, None, 127, Call::Logger(logger::Call::log(69, 1000))).unwrap(); Scheduler::do_schedule_named(
2u32.encode(), 8, None, 127, root(), Call::Logger(logger::Call::log(69, 1000))
).unwrap();
run_to_block(3); run_to_block(3);
assert!(logger::log().is_empty()); assert!(logger::log().is_empty());
run_to_block(4); run_to_block(4);
assert_eq!(logger::log(), vec![42u32]); assert_eq!(logger::log(), vec![(root(), 42u32)]);
run_to_block(6); run_to_block(6);
assert_ok!(Scheduler::do_cancel_named(1u32.encode())); assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
run_to_block(100); run_to_block(100);
assert_eq!(logger::log(), vec![42u32, 69u32]); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
}); });
} }
#[test] #[test]
fn scheduler_respects_weight_limits() { fn scheduler_respects_weight_limits() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let _ = Scheduler::do_schedule(4, None, 127, Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))); let _ = Scheduler::do_schedule(
let _ = Scheduler::do_schedule(4, None, 127, Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))); 4, None, 127, root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
);
let _ = Scheduler::do_schedule(
4, None, 127, root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
);
// 69 and 42 do not fit together // 69 and 42 do not fit together
run_to_block(4); run_to_block(4);
assert_eq!(logger::log(), vec![42u32]); assert_eq!(logger::log(), vec![(root(), 42u32)]);
run_to_block(5); run_to_block(5);
assert_eq!(logger::log(), vec![42u32, 69u32]); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
}); });
} }
#[test] #[test]
fn scheduler_respects_hard_deadlines_more() { fn scheduler_respects_hard_deadlines_more() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let _ = Scheduler::do_schedule(4, None, 0, Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))); let _ = Scheduler::do_schedule(
let _ = Scheduler::do_schedule(4, None, 0, Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))); 4, None, 0, root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
);
let _ = Scheduler::do_schedule(
4, None, 0, root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
);
// With base weights, 69 and 42 should not fit together, but do because of hard deadlines // With base weights, 69 and 42 should not fit together, but do because of hard deadlines
run_to_block(4); run_to_block(4);
assert_eq!(logger::log(), vec![42u32, 69u32]); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
}); });
} }
#[test] #[test]
fn scheduler_respects_priority_ordering() { fn scheduler_respects_priority_ordering() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let _ = Scheduler::do_schedule(4, None, 1, Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))); let _ = Scheduler::do_schedule(
let _ = Scheduler::do_schedule(4, None, 0, Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))); 4, None, 1, root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
);
let _ = Scheduler::do_schedule(
4, None, 0, root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
);
run_to_block(4); run_to_block(4);
assert_eq!(logger::log(), vec![69u32, 42u32]); assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);
}); });
} }
@@ -667,30 +831,21 @@ mod tests {
fn scheduler_respects_priority_ordering_with_soft_deadlines() { fn scheduler_respects_priority_ordering_with_soft_deadlines() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let _ = Scheduler::do_schedule( let _ = Scheduler::do_schedule(
4, 4, None, 255, root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
None,
255,
Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3)),
); );
let _ = Scheduler::do_schedule( let _ = Scheduler::do_schedule(
4, 4, None, 127, root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
None,
127,
Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2)),
); );
let _ = Scheduler::do_schedule( let _ = Scheduler::do_schedule(
4, 4, None, 126, root(), Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))
None,
126,
Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2)),
); );
// 2600 does not fit with 69 or 42, but has higher priority, so will go through // 2600 does not fit with 69 or 42, but has higher priority, so will go through
run_to_block(4); run_to_block(4);
assert_eq!(logger::log(), vec![2600u32]); assert_eq!(logger::log(), vec![(root(), 2600u32)]);
// 69 and 42 fit together // 69 and 42 fit together
run_to_block(5); run_to_block(5);
assert_eq!(logger::log(), vec![2600u32, 69u32, 42u32]); assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);
}); });
} }
@@ -703,47 +858,45 @@ mod tests {
let periodic_multiplier = <Test as frame_system::Trait>::DbWeight::get().reads_writes(1, 1); let periodic_multiplier = <Test as frame_system::Trait>::DbWeight::get().reads_writes(1, 1);
// Named // Named
assert_ok!(Scheduler::do_schedule_named(1u32.encode(), 1, None, 255, Call::Logger(logger::Call::log(3, MaximumSchedulerWeight::get() / 3)))); assert_ok!(
Scheduler::do_schedule_named(
1u32.encode(), 1, None, 255, root(),
Call::Logger(logger::Call::log(3, MaximumSchedulerWeight::get() / 3))
)
);
// Anon Periodic // Anon Periodic
let _ = Scheduler::do_schedule( let _ = Scheduler::do_schedule(
1, 1, Some((1000, 3)), 128, root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
Some((1000, 3)),
128,
Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3)),
); );
// Anon // Anon
let _ = Scheduler::do_schedule( let _ = Scheduler::do_schedule(
1, 1, None, 127, root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
None,
127,
Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2)),
); );
// Named Periodic // Named Periodic
assert_ok!(Scheduler::do_schedule_named( assert_ok!(Scheduler::do_schedule_named(
2u32.encode(), 2u32.encode(), 1, Some((1000, 3)), 126, root(),
1, Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2)))
Some((1000, 3)), );
126,
Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2)),
));
// Will include the named periodic only // Will include the named periodic only
let actual_weight = Scheduler::on_initialize(1); let actual_weight = Scheduler::on_initialize(1);
let call_weight = MaximumSchedulerWeight::get() / 2; let call_weight = MaximumSchedulerWeight::get() / 2;
assert_eq!(actual_weight, call_weight + base_weight + base_multiplier + named_multiplier + periodic_multiplier); assert_eq!(
assert_eq!(logger::log(), vec![2600u32]); actual_weight, call_weight + base_weight + base_multiplier + named_multiplier + periodic_multiplier
);
assert_eq!(logger::log(), vec![(root(), 2600u32)]);
// Will include anon and anon periodic // Will include anon and anon periodic
let actual_weight = Scheduler::on_initialize(2); let actual_weight = Scheduler::on_initialize(2);
let call_weight = MaximumSchedulerWeight::get() / 2 + MaximumSchedulerWeight::get() / 3; let call_weight = MaximumSchedulerWeight::get() / 2 + MaximumSchedulerWeight::get() / 3;
assert_eq!(actual_weight, call_weight + base_weight + base_multiplier * 2 + periodic_multiplier); assert_eq!(actual_weight, call_weight + base_weight + base_multiplier * 2 + periodic_multiplier);
assert_eq!(logger::log(), vec![2600u32, 69u32, 42u32]); assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);
// Will include named only // Will include named only
let actual_weight = Scheduler::on_initialize(3); let actual_weight = Scheduler::on_initialize(3);
let call_weight = MaximumSchedulerWeight::get() / 3; let call_weight = MaximumSchedulerWeight::get() / 3;
assert_eq!(actual_weight, call_weight + base_weight + base_multiplier + named_multiplier); assert_eq!(actual_weight, call_weight + base_weight + base_multiplier + named_multiplier);
assert_eq!(logger::log(), vec![2600u32, 69u32, 42u32, 3u32]); assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32), (root(), 3u32)]);
// Will contain none // Will contain none
let actual_weight = Scheduler::on_initialize(4); let actual_weight = Scheduler::on_initialize(4);
@@ -794,4 +947,169 @@ mod tests {
); );
}); });
} }
#[test]
fn should_use_orign() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
assert_ok!(
Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)
);
assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));
run_to_block(3);
// Scheduled calls are in the agenda.
assert_eq!(Agenda::<Test>::get(4).len(), 2);
assert!(logger::log().is_empty());
assert_ok!(Scheduler::cancel_named(system::RawOrigin::Signed(1).into(), 1u32.encode()));
assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
// Scheduled calls are made NONE, so should not effect state
run_to_block(100);
assert!(logger::log().is_empty());
});
}
#[test]
fn should_check_orign() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
assert_noop!(
Scheduler::schedule_named(system::RawOrigin::Signed(2).into(), 1u32.encode(), 4, None, 127, call),
BadOrigin
);
assert_noop!(Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, 127, call2), BadOrigin);
});
}
#[test]
fn should_check_orign_for_cancel() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Logger(logger::Call::log_without_filter(69, 1000)));
let call2 = Box::new(Call::Logger(logger::Call::log_without_filter(42, 1000)));
assert_ok!(
Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)
);
assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));
run_to_block(3);
// Scheduled calls are in the agenda.
assert_eq!(Agenda::<Test>::get(4).len(), 2);
assert!(logger::log().is_empty());
assert_noop!(Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), 1u32.encode()), BadOrigin);
assert_noop!(Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1), BadOrigin);
assert_noop!(Scheduler::cancel_named(system::RawOrigin::Root.into(), 1u32.encode()), BadOrigin);
assert_noop!(Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1), BadOrigin);
run_to_block(5);
assert_eq!(
logger::log(),
vec![(system::RawOrigin::Signed(1).into(), 69u32), (system::RawOrigin::Signed(1).into(), 42u32)]
);
});
}
#[test]
fn migration_to_v2_works() {
use substrate_test_utils::assert_eq_uvec;
new_test_ext().execute_with(|| {
for i in 0..3u64 {
let k = i.twox_64_concat();
let old = vec![
Some(ScheduledV1 {
maybe_id: None,
priority: i as u8 + 10,
call: Call::Logger(logger::Call::log(96, 100)),
maybe_periodic: None,
}),
None,
Some(ScheduledV1 {
maybe_id: Some(b"test".to_vec()),
priority: 123,
call: Call::Logger(logger::Call::log(69, 1000)),
maybe_periodic: Some((456u64, 10)),
}),
];
frame_support::migration::put_storage_value(
b"Scheduler",
b"Agenda",
&k,
old,
);
}
assert_eq!(StorageVersion::get(), Releases::V1);
assert!(Scheduler::migrate_v1_to_t2());
assert_eq_uvec!(Agenda::<Test>::iter().collect::<Vec<_>>(), vec![
(
0,
vec![
Some(ScheduledV2 {
maybe_id: None,
priority: 10,
call: Call::Logger(logger::Call::log(96, 100)),
maybe_periodic: None,
origin: root(),
_phantom: PhantomData::<u64>::default(),
}),
None,
Some(ScheduledV2 {
maybe_id: Some(b"test".to_vec()),
priority: 123,
call: Call::Logger(logger::Call::log(69, 1000)),
maybe_periodic: Some((456u64, 10)),
origin: root(),
_phantom: PhantomData::<u64>::default(),
}),
]),
(
1,
vec![
Some(ScheduledV2 {
maybe_id: None,
priority: 11,
call: Call::Logger(logger::Call::log(96, 100)),
maybe_periodic: None,
origin: root(),
_phantom: PhantomData::<u64>::default(),
}),
None,
Some(ScheduledV2 {
maybe_id: Some(b"test".to_vec()),
priority: 123,
call: Call::Logger(logger::Call::log(69, 1000)),
maybe_periodic: Some((456u64, 10)),
origin: root(),
_phantom: PhantomData::<u64>::default(),
}),
]
),
(
2,
vec![
Some(ScheduledV2 {
maybe_id: None,
priority: 12,
call: Call::Logger(logger::Call::log(96, 100)),
maybe_periodic: None,
origin: root(),
_phantom: PhantomData::<u64>::default(),
}),
None,
Some(ScheduledV2 {
maybe_id: Some(b"test".to_vec()),
priority: 123,
call: Call::Logger(logger::Call::log(69, 1000)),
maybe_periodic: Some((456u64, 10)),
origin: root(),
_phantom: PhantomData::<u64>::default(),
}),
]
)
]);
assert_eq!(StorageVersion::get(), Releases::V2);
});
}
} }
+3 -1
View File
@@ -2310,6 +2310,8 @@ mod tests {
} }
pub mod system { pub mod system {
use codec::{Encode, Decode};
pub trait Trait { pub trait Trait {
type AccountId; type AccountId;
type Call; type Call;
@@ -2317,7 +2319,7 @@ mod tests {
type Origin: crate::traits::OriginTrait<Call = Self::Call>; type Origin: crate::traits::OriginTrait<Call = Self::Call>;
} }
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
pub enum RawOrigin<AccountId> { pub enum RawOrigin<AccountId> {
Root, Root,
Signed(AccountId), Signed(AccountId),
+1 -1
View File
@@ -316,7 +316,7 @@ mod tests {
} }
); );
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
pub enum RawOrigin<AccountId> { pub enum RawOrigin<AccountId> {
Root, Root,
Signed(AccountId), Signed(AccountId),
+39 -12
View File
@@ -222,10 +222,14 @@ macro_rules! impl_outer_origin {
fn filter_call(&self, call: &Self::Call) -> bool { fn filter_call(&self, call: &Self::Call) -> bool {
(self.filter)(call) (self.filter)(call)
} }
fn caller(&self) -> &Self::PalletsOrigin {
&self.caller
}
} }
$crate::paste::item! { $crate::paste::item! {
#[derive(Clone, PartialEq, Eq, $crate::RuntimeDebug)] #[derive(Clone, PartialEq, Eq, $crate::RuntimeDebug, $crate::codec::Encode, $crate::codec::Decode)]
$(#[$attr])* $(#[$attr])*
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
pub enum $caller_name { pub enum $caller_name {
@@ -255,13 +259,25 @@ macro_rules! impl_outer_origin {
} }
} }
impl From<$system::Origin<$runtime>> for $caller_name {
fn from(x: $system::Origin<$runtime>) -> Self {
$caller_name::system(x)
}
}
impl From<$system::Origin<$runtime>> for $name { impl From<$system::Origin<$runtime>> for $name {
/// Convert to runtime origin: /// Convert to runtime origin:
/// * root origin is built with no filter /// * root origin is built with no filter
/// * others use `frame-system::Trait::BaseCallFilter` /// * others use `frame-system::Trait::BaseCallFilter`
fn from(x: $system::Origin<$runtime>) -> Self { fn from(x: $system::Origin<$runtime>) -> Self {
let o: $caller_name = x.into();
o.into()
}
}
impl From<$caller_name> for $name {
fn from(x: $caller_name) -> Self {
let mut o = $name { let mut o = $name {
caller: $caller_name::system(x), caller: x,
filter: $crate::sp_std::rc::Rc::new(Box::new(|_| true)), filter: $crate::sp_std::rc::Rc::new(Box::new(|_| true)),
}; };
@@ -273,6 +289,7 @@ macro_rules! impl_outer_origin {
o o
} }
} }
impl Into<$crate::sp_std::result::Result<$system::Origin<$runtime>, $name>> for $name { impl Into<$crate::sp_std::result::Result<$system::Origin<$runtime>, $name>> for $name {
/// NOTE: converting to pallet origin loses the origin filter information. /// NOTE: converting to pallet origin loses the origin filter information.
fn into(self) -> $crate::sp_std::result::Result<$system::Origin<$runtime>, Self> { fn into(self) -> $crate::sp_std::result::Result<$system::Origin<$runtime>, Self> {
@@ -290,17 +307,20 @@ macro_rules! impl_outer_origin {
<$system::Origin<$runtime>>::from(x).into() <$system::Origin<$runtime>>::from(x).into()
} }
} }
$( $(
$crate::paste::item! { $crate::paste::item! {
impl From<$module::Origin < $( $generic )? $(, $module::$generic_instance )? > > for $caller_name {
fn from(x: $module::Origin < $( $generic )? $(, $module::$generic_instance )? >) -> Self {
$caller_name::[< $module $( _ $generic_instance )? >](x)
}
}
impl From<$module::Origin < $( $generic )? $(, $module::$generic_instance )? > > for $name { impl From<$module::Origin < $( $generic )? $(, $module::$generic_instance )? > > for $name {
/// Convert to runtime origin using `frame-system::Trait::BaseCallFilter`. /// Convert to runtime origin using `frame-system::Trait::BaseCallFilter`.
fn from(x: $module::Origin < $( $generic )? $(, $module::$generic_instance )? >) -> Self { fn from(x: $module::Origin < $( $generic )? $(, $module::$generic_instance )? >) -> Self {
let mut o = $name { let x: $caller_name = x.into();
caller: $caller_name::[< $module $( _ $generic_instance )? >](x), x.into()
filter: $crate::sp_std::rc::Rc::new(Box::new(|_| true)),
};
$crate::traits::OriginTrait::reset_filter(&mut o);
o
} }
} }
impl Into< impl Into<
@@ -328,15 +348,18 @@ macro_rules! impl_outer_origin {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use codec::{Encode, Decode};
use crate::traits::{Filter, OriginTrait}; use crate::traits::{Filter, OriginTrait};
mod system { mod system {
use super::*;
pub trait Trait { pub trait Trait {
type AccountId; type AccountId;
type Call; type Call;
type BaseCallFilter; type BaseCallFilter;
} }
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
pub enum RawOrigin<AccountId> { pub enum RawOrigin<AccountId> {
Root, Root,
Signed(AccountId), Signed(AccountId),
@@ -356,18 +379,22 @@ mod tests {
} }
mod origin_without_generic { mod origin_without_generic {
#[derive(Clone, PartialEq, Eq, Debug)] use super::*;
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
pub struct Origin; pub struct Origin;
} }
mod origin_with_generic { mod origin_with_generic {
#[derive(Clone, PartialEq, Eq, Debug)] use super::*;
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
pub struct Origin<T> { pub struct Origin<T> {
t: T t: T
} }
} }
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
pub struct TestRuntime; pub struct TestRuntime;
pub struct BaseCallFilter; pub struct BaseCallFilter;
+7 -2
View File
@@ -1500,7 +1500,7 @@ pub mod schedule {
pub const LOWEST_PRIORITY: Priority = 255; pub const LOWEST_PRIORITY: Priority = 255;
/// A type that can be used as a scheduler. /// A type that can be used as a scheduler.
pub trait Anon<BlockNumber, Call> { pub trait Anon<BlockNumber, Call, Origin> {
/// An address which can be used for removing a scheduled task. /// An address which can be used for removing a scheduled task.
type Address: Codec + Clone + Eq + EncodeLike + Debug; type Address: Codec + Clone + Eq + EncodeLike + Debug;
@@ -1513,6 +1513,7 @@ pub mod schedule {
when: BlockNumber, when: BlockNumber,
maybe_periodic: Option<Period<BlockNumber>>, maybe_periodic: Option<Period<BlockNumber>>,
priority: Priority, priority: Priority,
origin: Origin,
call: Call call: Call
) -> Result<Self::Address, DispatchError>; ) -> Result<Self::Address, DispatchError>;
@@ -1530,7 +1531,7 @@ pub mod schedule {
} }
/// A type that can be used as a scheduler. /// A type that can be used as a scheduler.
pub trait Named<BlockNumber, Call> { pub trait Named<BlockNumber, Call, Origin> {
/// An address which can be used for removing a scheduled task. /// An address which can be used for removing a scheduled task.
type Address: Codec + Clone + Eq + EncodeLike + sp_std::fmt::Debug; type Address: Codec + Clone + Eq + EncodeLike + sp_std::fmt::Debug;
@@ -1542,6 +1543,7 @@ pub mod schedule {
when: BlockNumber, when: BlockNumber,
maybe_periodic: Option<Period<BlockNumber>>, maybe_periodic: Option<Period<BlockNumber>>,
priority: Priority, priority: Priority,
origin: Origin,
call: Call call: Call
) -> Result<Self::Address, ()>; ) -> Result<Self::Address, ()>;
@@ -1605,6 +1607,9 @@ pub trait OriginTrait: Sized {
/// Filter the call, if false then call is filtered out. /// Filter the call, if false then call is filtered out.
fn filter_call(&self, call: &Self::Call) -> bool; fn filter_call(&self, call: &Self::Call) -> bool;
/// Get the caller.
fn caller(&self) -> &Self::PalletsOrigin;
} }
/// Trait to be used when types are exactly same. /// Trait to be used when types are exactly same.
@@ -17,6 +17,7 @@
#![recursion_limit="128"] #![recursion_limit="128"]
use codec::{Codec, EncodeLike, Encode, Decode};
use sp_runtime::{generic, BuildStorage, traits::{BlakeTwo256, Block as _, Verify}}; use sp_runtime::{generic, BuildStorage, traits::{BlakeTwo256, Block as _, Verify}};
use frame_support::{ use frame_support::{
Parameter, traits::Get, parameter_types, Parameter, traits::Get, parameter_types,
@@ -44,7 +45,7 @@ mod module1 {
type Event: From<Event<Self, I>> + Into<<Self as system::Trait>::Event>; type Event: From<Event<Self, I>> + Into<<Self as system::Trait>::Event>;
type Origin: From<Origin<Self, I>>; type Origin: From<Origin<Self, I>>;
type SomeParameter: Get<u32>; type SomeParameter: Get<u32>;
type GenericType: Default + Clone + codec::Codec + codec::EncodeLike; type GenericType: Default + Clone + Codec + EncodeLike;
} }
frame_support::decl_module! { frame_support::decl_module! {
@@ -87,7 +88,7 @@ mod module1 {
} }
} }
#[derive(PartialEq, Eq, Clone, sp_runtime::RuntimeDebug)] #[derive(PartialEq, Eq, Clone, sp_runtime::RuntimeDebug, Encode, Decode)]
pub enum Origin<T: Trait<I>, I> where T::BlockNumber: From<u32> { pub enum Origin<T: Trait<I>, I> where T::BlockNumber: From<u32> {
Members(u32), Members(u32),
_Phantom(std::marker::PhantomData<(T, I)>), _Phantom(std::marker::PhantomData<(T, I)>),
@@ -148,7 +149,7 @@ mod module2 {
} }
} }
#[derive(PartialEq, Eq, Clone, sp_runtime::RuntimeDebug)] #[derive(PartialEq, Eq, Clone, sp_runtime::RuntimeDebug, Encode, Decode)]
pub enum Origin<T: Trait<I>, I=DefaultInstance> { pub enum Origin<T: Trait<I>, I=DefaultInstance> {
Members(u32), Members(u32),
_Phantom(std::marker::PhantomData<(T, I)>), _Phantom(std::marker::PhantomData<(T, I)>),
+1 -1
View File
@@ -57,7 +57,7 @@ frame_support::decl_error! {
} }
/// Origin for the system module. /// Origin for the system module.
#[derive(PartialEq, Eq, Clone, sp_runtime::RuntimeDebug)] #[derive(PartialEq, Eq, Clone, sp_runtime::RuntimeDebug, Encode, Decode)]
pub enum RawOrigin<AccountId> { pub enum RawOrigin<AccountId> {
Root, Root,
Signed(AccountId), Signed(AccountId),
+1 -1
View File
@@ -301,7 +301,7 @@ pub struct EventRecord<E: Parameter + Member, T> {
} }
/// Origin for the System module. /// Origin for the System module.
#[derive(PartialEq, Eq, Clone, RuntimeDebug)] #[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)]
pub enum RawOrigin<AccountId> { pub enum RawOrigin<AccountId> {
/// The system itself ordained this dispatch to happen: this is the highest privilege level. /// The system itself ordained this dispatch to happen: this is the highest privilege level.
Root, Root,