Skip to main content

orml_authority/
lib.rs

1//! # Authority
2//! A module to provide features for governance including dispatch method on
3//! behalf of other accounts and schedule dispatchables.
4//!
5//! - [`Config`](./trait.Config.html)
6//! - [`Call`](./enum.Call.html)
7//! - [`Module`](./struct.Module.html)
8//!
9//! ## Overview
10//!
11//! Two functionalities are provided by this module:
12//! - schedule a dispatchable
13//! - dispatch method with on behalf of other origins
14//!
15//! NOTE:
16//!
17//! In order to derive a feasible max encoded len for `DelayedOrigin`, it is
18//! assumed that there are no nested `DelayedOrigin` in `OriginCaller`.
19//! In practice, this means there should not be nested `schedule_dispatch`.
20//! Otherwise the proof size estimation may not be accurate.
21
22#![cfg_attr(not(feature = "std"), no_std)]
23// Disable the following three lints since they originate from an external macro
24#![allow(clippy::string_lit_as_bytes)]
25#![allow(clippy::boxed_local)]
26#![allow(clippy::borrowed_box)]
27#![allow(clippy::unused_unit)]
28#![allow(clippy::useless_conversion)]
29
30use frame_support::{
31	dispatch::PostDispatchInfo,
32	dispatch::{DispatchClass, GetDispatchInfo, Pays},
33	pallet_prelude::*,
34	traits::{
35		schedule::{DispatchTime, Priority},
36		Bounded, EitherOfDiverse, EnsureOrigin, Get, IsType, OriginTrait,
37	},
38};
39use frame_system::{pallet_prelude::*, EnsureRoot, EnsureSigned};
40use parity_scale_codec::MaxEncodedLen;
41use scale_info::TypeInfo;
42use sp_core::defer;
43use sp_io::hashing::blake2_256;
44use sp_runtime::{
45	traits::{CheckedSub, Dispatchable, Hash, Saturating},
46	ArithmeticError, DispatchError, DispatchResult, Either, RuntimeDebug,
47};
48use sp_std::prelude::*;
49
50use frame_support::traits::schedule::v3::Named as ScheduleNamed;
51
52mod mock;
53mod tests;
54mod weights;
55
56pub use weights::WeightInfo;
57
58/// A delayed origin. Can only be dispatched via `dispatch_as` with a delay.
59#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo, DecodeWithMemTracking)]
60pub struct DelayedOrigin<BlockNumber, PalletsOrigin> {
61	/// Number of blocks that this call have been delayed.
62	pub(crate) delay: BlockNumber,
63	/// The initial origin.
64	pub(crate) origin: Box<PalletsOrigin>,
65}
66
67#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
68impl<BlockNumber, PalletsOrigin> DelayedOrigin<BlockNumber, PalletsOrigin> {
69	pub fn new(delay: BlockNumber, origin: Box<PalletsOrigin>) -> Self {
70		Self { delay, origin }
71	}
72}
73
74#[cfg(feature = "std")]
75mod helper {
76	use std::cell::RefCell;
77
78	thread_local! {
79		static NESTED_MAX_ENCODED_LEN: RefCell<bool> = const {
80			RefCell::new(false)
81		};
82	}
83
84	pub fn set_nested_max_encoded_len(val: bool) {
85		NESTED_MAX_ENCODED_LEN.with(|v| *v.borrow_mut() = val);
86	}
87
88	pub fn nested_max_encoded_len() -> bool {
89		NESTED_MAX_ENCODED_LEN.with(|v| *v.borrow())
90	}
91}
92
93#[cfg(not(feature = "std"))]
94mod helper {
95	static mut NESTED_MAX_ENCODED_LEN: bool = false;
96
97	pub fn set_nested_max_encoded_len(val: bool) {
98		unsafe {
99			NESTED_MAX_ENCODED_LEN = val;
100		}
101	}
102
103	pub fn nested_max_encoded_len() -> bool {
104		unsafe { NESTED_MAX_ENCODED_LEN }
105	}
106}
107
108// Manual implementation to break recursive calls of `MaxEncodedLen` as the
109// implementation of `PalletsOrigin::max_encoded_len` will also call
110// `MaxEncodedLen` on `DelayedOrigin`. This is only safe if there are no nested
111// `DelayedOrigin`. It is only possible to construct a `DelayedOrigin` via
112// `schedule_dispatch` which is a protected call only accessible via governance.
113impl<BlockNumber: MaxEncodedLen, PalletsOrigin: MaxEncodedLen> MaxEncodedLen
114	for DelayedOrigin<BlockNumber, PalletsOrigin>
115{
116	fn max_encoded_len() -> usize {
117		if helper::nested_max_encoded_len() {
118			return 0;
119		}
120
121		helper::set_nested_max_encoded_len(true);
122		defer!(helper::set_nested_max_encoded_len(false));
123
124		BlockNumber::max_encoded_len() + PalletsOrigin::max_encoded_len()
125	}
126}
127
128/// Ensure the origin have a minimum amount of delay.
129pub struct EnsureDelayed<Delay, Inner, BlockNumber, PalletsOrigin>(
130	sp_std::marker::PhantomData<(Delay, Inner, BlockNumber, PalletsOrigin)>,
131);
132impl<
133		PalletsOrigin: Into<O>,
134		O: Into<Result<DelayedOrigin<BlockNumber, PalletsOrigin>, O>> + From<DelayedOrigin<BlockNumber, PalletsOrigin>>,
135		Delay: Get<BlockNumber>,
136		Inner: EnsureOrigin<O>,
137		BlockNumber: PartialOrd,
138	> EnsureOrigin<O> for EnsureDelayed<Delay, Inner, BlockNumber, PalletsOrigin>
139{
140	type Success = Inner::Success;
141
142	fn try_origin(o: O) -> Result<Self::Success, O> {
143		o.into().and_then(|delayed_origin| {
144			if delayed_origin.delay >= Delay::get() {
145				let pallets_origin = *delayed_origin.origin;
146				Inner::try_origin(pallets_origin.into())
147			} else {
148				Err(delayed_origin.into())
149			}
150		})
151	}
152
153	#[cfg(feature = "runtime-benchmarks")]
154	fn try_successful_origin() -> Result<O, ()> {
155		unimplemented!()
156	}
157}
158
159/// Config for orml-authority
160pub trait AuthorityConfig<Origin, PalletsOrigin, BlockNumber> {
161	/// Check if the `origin` is allowed to schedule a dispatchable call
162	/// with a given `priority`.
163	fn check_schedule_dispatch(origin: Origin, priority: Priority) -> DispatchResult;
164	/// Check if the `origin` is allow to fast track a scheduled task that
165	/// initially created by `initial_origin`. `new_delay` is number of
166	/// blocks this dispatchable will be dispatched from now after fast
167	/// track.
168	fn check_fast_track_schedule(
169		origin: Origin,
170		initial_origin: &PalletsOrigin,
171		new_delay: BlockNumber,
172	) -> DispatchResult;
173	/// Check if the `origin` is allow to delay a scheduled task that
174	/// initially created by `initial_origin`.
175	fn check_delay_schedule(origin: Origin, initial_origin: &PalletsOrigin) -> DispatchResult;
176	/// Check if the `origin` is allow to cancel a scheduled task that
177	/// initially created by `initial_origin`.
178	fn check_cancel_schedule(origin: Origin, initial_origin: &PalletsOrigin) -> DispatchResult;
179}
180
181/// Represent an origin that can be dispatched by other origins with
182/// permission check.
183pub trait AsOriginId<Origin, PalletsOrigin> {
184	/// Convert into `PalletsOrigin`
185	fn into_origin(self) -> PalletsOrigin;
186	/// Check if the `origin` is allow to dispatch call on behalf of this
187	/// origin.
188	fn check_dispatch_from(&self, origin: Origin) -> DispatchResult;
189}
190
191/// The schedule task index type.
192pub type ScheduleTaskIndex = u32;
193
194pub use module::*;
195
196#[frame_support::pallet]
197pub mod module {
198	use super::*;
199
200	/// Origin for the authority module.
201	#[pallet::origin]
202	pub type Origin<T> = DelayedOrigin<BlockNumberFor<T>, <T as Config>::PalletsOrigin>;
203	pub(crate) type CallOf<T> = <T as Config>::RuntimeCall;
204	pub(crate) type BoundedCallOf<T> = Bounded<CallOf<T>, <T as frame_system::Config>::Hashing>;
205
206	#[pallet::config]
207	pub trait Config: frame_system::Config {
208		/// The outer origin type.
209		type RuntimeOrigin: From<DelayedOrigin<BlockNumberFor<Self>, <Self as Config>::PalletsOrigin>>
210			+ IsType<<Self as frame_system::Config>::RuntimeOrigin>
211			+ OriginTrait<PalletsOrigin = Self::PalletsOrigin>;
212
213		/// The caller origin, overarching type of all pallets origins.
214		type PalletsOrigin: Parameter + Into<<Self as frame_system::Config>::RuntimeOrigin>;
215
216		/// The aggregated call type.
217		type RuntimeCall: Parameter
218			+ Dispatchable<RuntimeOrigin = <Self as frame_system::Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>
219			+ GetDispatchInfo;
220
221		/// The Scheduler.
222		type Scheduler: ScheduleNamed<
223			BlockNumberFor<Self>,
224			<Self as Config>::RuntimeCall,
225			Self::PalletsOrigin,
226			Hasher = Self::Hashing,
227		>;
228
229		/// The type represent origin that can be dispatched by other origins.
230		type AsOriginId: Parameter + AsOriginId<<Self as frame_system::Config>::RuntimeOrigin, Self::PalletsOrigin>;
231
232		/// Additional permission config.
233		type AuthorityConfig: AuthorityConfig<
234			<Self as frame_system::Config>::RuntimeOrigin,
235			Self::PalletsOrigin,
236			BlockNumberFor<Self>,
237		>;
238
239		/// Weight information for extrinsics in this module.
240		type WeightInfo: WeightInfo;
241	}
242
243	#[pallet::error]
244	pub enum Error<T> {
245		/// Failed to schedule a task.
246		FailedToSchedule,
247		/// Failed to cancel a task.
248		FailedToCancel,
249		/// Failed to fast track a task.
250		FailedToFastTrack,
251		/// Failed to delay a task.
252		FailedToDelay,
253		/// Call is not authorized.
254		CallNotAuthorized,
255		/// Triggering the call is not permitted.
256		TriggerCallNotPermitted,
257		/// Call weight bound is wrong.
258		WrongCallWeightBound,
259	}
260
261	#[pallet::event]
262	#[pallet::generate_deposit(fn deposit_event)]
263	pub enum Event<T: Config> {
264		/// A call is dispatched.
265		Dispatched { result: DispatchResult },
266		/// A call is scheduled.
267		Scheduled {
268			origin: T::PalletsOrigin,
269			index: ScheduleTaskIndex,
270		},
271		/// A scheduled call is fast tracked.
272		FastTracked {
273			origin: T::PalletsOrigin,
274			index: ScheduleTaskIndex,
275			when: BlockNumberFor<T>,
276		},
277		/// A scheduled call is delayed.
278		Delayed {
279			origin: T::PalletsOrigin,
280			index: ScheduleTaskIndex,
281			when: BlockNumberFor<T>,
282		},
283		/// A scheduled call is cancelled.
284		Cancelled {
285			origin: T::PalletsOrigin,
286			index: ScheduleTaskIndex,
287		},
288		/// A call is authorized.
289		AuthorizedCall {
290			hash: T::Hash,
291			caller: Option<T::AccountId>,
292		},
293		/// An authorized call was removed.
294		RemovedAuthorizedCall { hash: T::Hash },
295		/// An authorized call was triggered.
296		TriggeredCallBy { hash: T::Hash, caller: T::AccountId },
297	}
298
299	#[pallet::storage]
300	#[pallet::getter(fn next_task_index)]
301	pub type NextTaskIndex<T: Config> = StorageValue<_, ScheduleTaskIndex, ValueQuery>;
302
303	#[pallet::storage]
304	#[pallet::getter(fn saved_calls)]
305	pub type SavedCalls<T: Config> = StorageMap<_, Identity, T::Hash, (CallOf<T>, Option<T::AccountId>), OptionQuery>;
306
307	#[pallet::pallet]
308	#[pallet::without_storage_info]
309	pub struct Pallet<T>(_);
310
311	#[pallet::hooks]
312	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
313
314	#[pallet::call]
315	impl<T: Config> Pallet<T> {
316		/// Dispatch a dispatchable on behalf of other origin
317		#[pallet::call_index(0)]
318		#[pallet::weight({
319			let info = call.get_dispatch_info();
320			(T::WeightInfo::dispatch_as().saturating_add(info.total_weight()), info.class)
321		})]
322		pub fn dispatch_as(origin: OriginFor<T>, as_origin: T::AsOriginId, call: Box<CallOf<T>>) -> DispatchResult {
323			as_origin.check_dispatch_from(origin)?;
324
325			let e = call.dispatch(as_origin.into_origin().into());
326
327			Self::deposit_event(Event::Dispatched {
328				result: e.map(|_| ()).map_err(|e| e.error),
329			});
330			Ok(())
331		}
332
333		/// Schedule a dispatchable to be dispatched at later block.
334		/// This is the only way to dispatch a call with `DelayedOrigin`.
335		#[pallet::call_index(1)]
336		#[pallet::weight(T::WeightInfo::schedule_dispatch_without_delay())]
337		pub fn schedule_dispatch(
338			origin: OriginFor<T>,
339			when: DispatchTime<BlockNumberFor<T>>,
340			priority: Priority,
341			with_delayed_origin: bool,
342			call: Box<BoundedCallOf<T>>,
343		) -> DispatchResult {
344			T::AuthorityConfig::check_schedule_dispatch(origin.clone(), priority)?;
345
346			let id = NextTaskIndex::<T>::mutate(|id| -> sp_std::result::Result<ScheduleTaskIndex, DispatchError> {
347				let current_id = *id;
348				*id = id.checked_add(1).ok_or(ArithmeticError::Overflow)?;
349				Ok(current_id)
350			})?;
351			let now = frame_system::Pallet::<T>::block_number();
352			let delay = match when {
353				DispatchTime::At(x) => x.checked_sub(&now).ok_or(ArithmeticError::Overflow)?,
354				DispatchTime::After(x) => x,
355			};
356			let schedule_origin = if with_delayed_origin {
357				let origin: <T as Config>::RuntimeOrigin = From::from(origin);
358				let origin: <T as Config>::RuntimeOrigin =
359					From::from(DelayedOrigin::<BlockNumberFor<T>, T::PalletsOrigin> {
360						delay,
361						origin: Box::new(origin.caller().clone()),
362					});
363				origin
364			} else {
365				<T as Config>::RuntimeOrigin::from(origin)
366			};
367			let pallets_origin = schedule_origin.caller().clone();
368
369			let task_name = (&pallets_origin, id).using_encoded(blake2_256);
370			T::Scheduler::schedule_named(task_name, when, None, priority, pallets_origin.clone(), *call)
371				.map_err(|_| Error::<T>::FailedToSchedule)?;
372
373			Self::deposit_event(Event::Scheduled {
374				origin: pallets_origin,
375				index: id,
376			});
377			Ok(())
378		}
379
380		/// Fast track a scheduled dispatchable.
381		#[pallet::call_index(2)]
382		#[pallet::weight(T::WeightInfo::fast_track_scheduled_dispatch())]
383		pub fn fast_track_scheduled_dispatch(
384			origin: OriginFor<T>,
385			initial_origin: Box<T::PalletsOrigin>,
386			task_id: ScheduleTaskIndex,
387			when: DispatchTime<BlockNumberFor<T>>,
388		) -> DispatchResult {
389			let now = frame_system::Pallet::<T>::block_number();
390			let new_delay = match when {
391				DispatchTime::At(x) => x.checked_sub(&now).ok_or(ArithmeticError::Overflow)?,
392				DispatchTime::After(x) => x,
393			};
394			let dispatch_at = match when {
395				DispatchTime::At(x) => x,
396				DispatchTime::After(x) => now.saturating_add(x),
397			};
398
399			T::AuthorityConfig::check_fast_track_schedule(origin, &initial_origin, new_delay)?;
400			let task_name = (&initial_origin, task_id).using_encoded(blake2_256);
401			T::Scheduler::reschedule_named(task_name, when).map_err(|_| Error::<T>::FailedToFastTrack)?;
402
403			Self::deposit_event(Event::FastTracked {
404				origin: *initial_origin,
405				index: task_id,
406				when: dispatch_at,
407			});
408			Ok(())
409		}
410
411		/// Delay a scheduled dispatchable.
412		#[pallet::call_index(3)]
413		#[pallet::weight(T::WeightInfo::delay_scheduled_dispatch())]
414		pub fn delay_scheduled_dispatch(
415			origin: OriginFor<T>,
416			initial_origin: Box<T::PalletsOrigin>,
417			task_id: ScheduleTaskIndex,
418			additional_delay: BlockNumberFor<T>,
419		) -> DispatchResult {
420			T::AuthorityConfig::check_delay_schedule(origin, &initial_origin)?;
421
422			let task_name = (&initial_origin, task_id).using_encoded(blake2_256);
423			T::Scheduler::reschedule_named(task_name, DispatchTime::After(additional_delay))
424				.map_err(|_| Error::<T>::FailedToDelay)?;
425
426			let now = frame_system::Pallet::<T>::block_number();
427			let dispatch_at = now.saturating_add(additional_delay);
428
429			Self::deposit_event(Event::Delayed {
430				origin: *initial_origin,
431				index: task_id,
432				when: dispatch_at,
433			});
434			Ok(())
435		}
436
437		/// Cancel a scheduled dispatchable.
438		#[pallet::call_index(4)]
439		#[pallet::weight(T::WeightInfo::cancel_scheduled_dispatch())]
440		pub fn cancel_scheduled_dispatch(
441			origin: OriginFor<T>,
442			initial_origin: Box<T::PalletsOrigin>,
443			task_id: ScheduleTaskIndex,
444		) -> DispatchResult {
445			T::AuthorityConfig::check_cancel_schedule(origin, &initial_origin)?;
446
447			let task_name = (&initial_origin, task_id).using_encoded(blake2_256);
448			T::Scheduler::cancel_named(task_name).map_err(|_| Error::<T>::FailedToCancel)?;
449
450			Self::deposit_event(Event::Cancelled {
451				origin: *initial_origin,
452				index: task_id,
453			});
454			Ok(())
455		}
456
457		#[pallet::call_index(5)]
458		#[pallet::weight(T::WeightInfo::authorize_call())]
459		pub fn authorize_call(
460			origin: OriginFor<T>,
461			call: Box<CallOf<T>>,
462			caller: Option<T::AccountId>,
463		) -> DispatchResult {
464			ensure_root(origin)?;
465			let hash = T::Hashing::hash_of(&call);
466			SavedCalls::<T>::insert(hash, (call, caller.clone()));
467			Self::deposit_event(Event::AuthorizedCall { hash, caller });
468			Ok(())
469		}
470
471		#[pallet::call_index(6)]
472		#[pallet::weight(T::WeightInfo::remove_authorized_call())]
473		pub fn remove_authorized_call(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
474			let root_or_signed =
475				EitherOfDiverse::<EnsureRoot<T::AccountId>, EnsureSigned<T::AccountId>>::ensure_origin(origin)?;
476
477			SavedCalls::<T>::try_mutate_exists(hash, |maybe_call| {
478				let (_, maybe_caller) = maybe_call.take().ok_or(Error::<T>::CallNotAuthorized)?;
479				match root_or_signed {
480					Either::Left(_) => {} // root, do nothing
481					Either::Right(who) => {
482						// signed, ensure it's the caller
483						let caller = maybe_caller.ok_or(Error::<T>::CallNotAuthorized)?;
484						ensure!(who == caller, Error::<T>::CallNotAuthorized);
485					}
486				}
487				Self::deposit_event(Event::RemovedAuthorizedCall { hash });
488				Ok(())
489			})
490		}
491
492		#[pallet::call_index(8)]
493		#[pallet::weight((
494			T::WeightInfo::trigger_call().saturating_add(*call_weight_bound),
495			DispatchClass::Operational,
496		))]
497		pub fn trigger_call(
498			origin: OriginFor<T>,
499			hash: T::Hash,
500			call_weight_bound: Weight,
501		) -> DispatchResultWithPostInfo {
502			let who = ensure_signed(origin)?;
503			SavedCalls::<T>::try_mutate_exists(hash, |maybe_call| {
504				let (call, maybe_caller) = maybe_call.take().ok_or(Error::<T>::CallNotAuthorized)?;
505				if let Some(caller) = maybe_caller {
506					ensure!(who == caller, Error::<T>::TriggerCallNotPermitted);
507				}
508				ensure!(
509					call_weight_bound.all_gte(call.get_dispatch_info().total_weight()),
510					Error::<T>::WrongCallWeightBound
511				);
512				let result = call.dispatch(OriginFor::<T>::root());
513				Self::deposit_event(Event::TriggeredCallBy { hash, caller: who });
514				Self::deposit_event(Event::Dispatched {
515					result: result.map(|_| ()).map_err(|e| e.error),
516				});
517				Ok(Pays::No.into())
518			})
519		}
520	}
521}