referrerpolicy=no-referrer-when-downgrade

pallet_tx_pause/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Transaction Pause
19//!
20//! Allows dynamic, chain-state-based pausing and unpausing of specific extrinsics via call filters.
21//!
22//! ## Pallet API
23//!
24//! See the [`pallet`] module for more information about the interfaces this pallet exposes,
25//! including its configuration trait, dispatchables, storage items, events, and errors.
26//!
27//! ## Overview
28//!
29//! A dynamic call filter that can be controlled with extrinsics.
30//!
31//! Pausing an extrinsic means that the extrinsic CANNOT be called again until it is unpaused.
32//! The exception is calls that use `dispatch_bypass_filter`, typically only with the root origin.
33//!
34//! ### Primary Features
35//!
36//! - Calls that should never be paused can be added to a whitelist.
37//! - Separate origins are configurable for pausing and pausing.
38//! - Pausing is triggered using the string representation of the call.
39//! - Pauses can target a single extrinsic or an entire pallet.
40//! - Pauses can target future extrinsics or pallets.
41//!
42//! ### Example
43//!
44//! Configuration of call filters:
45//!
46//! ```ignore
47//! impl frame_system::Config for Runtime {
48//!   // …
49//!   type BaseCallFilter = InsideBoth<DefaultFilter, TxPause>;
50//!   // …
51//! }
52//! ```
53//!
54//! Pause specific all:
55#![doc = docify::embed!("src/tests.rs", can_pause_specific_call)]
56//!
57//! Unpause specific all:
58#![doc = docify::embed!("src/tests.rs", can_unpause_specific_call)]
59//!
60//! Pause all calls in a pallet:
61#![doc = docify::embed!("src/tests.rs", can_pause_all_calls_in_pallet_except_on_whitelist)]
62//!
63//! ## Low Level / Implementation Details
64//!
65//! ### Use Cost
66//!
67//! A storage map (`PausedCalls`) is used to store currently paused calls.
68//! Using the call filter will require a db read of that storage on each extrinsic.
69
70#![cfg_attr(not(feature = "std"), no_std)]
71#![deny(rustdoc::broken_intra_doc_links)]
72
73mod benchmarking;
74pub mod mock;
75mod tests;
76pub mod weights;
77
78extern crate alloc;
79
80use alloc::vec::Vec;
81use frame::{
82	prelude::*,
83	traits::{TransactionPause, TransactionPauseError},
84};
85pub use pallet::*;
86pub use weights::*;
87
88/// The stringy name of a pallet from [`GetCallMetadata`] for [`Config::RuntimeCall`] variants.
89pub type PalletNameOf<T> = BoundedVec<u8, <T as Config>::MaxNameLen>;
90
91/// The stringy name of a call (within a pallet) from [`GetCallMetadata`] for
92/// [`Config::RuntimeCall`] variants.
93pub type PalletCallNameOf<T> = BoundedVec<u8, <T as Config>::MaxNameLen>;
94
95/// A fully specified pallet ([`PalletNameOf`]) and optional call ([`PalletCallNameOf`])
96/// to partially or fully specify an item a variant of a  [`Config::RuntimeCall`].
97pub type RuntimeCallNameOf<T> = (PalletNameOf<T>, PalletCallNameOf<T>);
98
99#[frame::pallet]
100pub mod pallet {
101	use super::*;
102
103	#[pallet::pallet]
104	pub struct Pallet<T>(PhantomData<T>);
105
106	#[pallet::config]
107	pub trait Config: frame_system::Config {
108		/// The overarching event type.
109		#[allow(deprecated)]
110		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
111
112		/// The overarching call type.
113		type RuntimeCall: Parameter
114			+ Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
115			+ GetDispatchInfo
116			+ GetCallMetadata
117			+ From<frame_system::Call<Self>>
118			+ IsSubType<Call<Self>>
119			+ IsType<<Self as frame_system::Config>::RuntimeCall>;
120
121		/// The only origin that can pause calls.
122		type PauseOrigin: EnsureOrigin<Self::RuntimeOrigin>;
123
124		/// The only origin that can un-pause calls.
125		type UnpauseOrigin: EnsureOrigin<Self::RuntimeOrigin>;
126
127		/// Contains all calls that cannot be paused.
128		///
129		/// The `TxMode` pallet cannot pause its own calls, and does not need to be explicitly
130		/// added here.
131		type WhitelistedCalls: Contains<RuntimeCallNameOf<Self>>;
132
133		/// Maximum length for pallet name and call name SCALE encoded string names.
134		///
135		/// TOO LONG NAMES WILL BE TREATED AS PAUSED.
136		#[pallet::constant]
137		type MaxNameLen: Get<u32>;
138
139		// Weight information for extrinsics in this pallet.
140		type WeightInfo: WeightInfo;
141	}
142
143	/// The set of calls that are explicitly paused.
144	#[pallet::storage]
145	pub type PausedCalls<T: Config> =
146		StorageMap<_, Blake2_128Concat, RuntimeCallNameOf<T>, (), OptionQuery>;
147
148	#[pallet::error]
149	pub enum Error<T> {
150		/// The call is paused.
151		IsPaused,
152
153		/// The call is unpaused.
154		IsUnpaused,
155
156		/// The call is whitelisted and cannot be paused.
157		Unpausable,
158
159		// The pallet or call does not exist in the runtime.
160		NotFound,
161	}
162
163	#[pallet::event]
164	#[pallet::generate_deposit(pub(super) fn deposit_event)]
165	pub enum Event<T: Config> {
166		/// This pallet, or a specific call is now paused.
167		CallPaused { full_name: RuntimeCallNameOf<T> },
168		/// This pallet, or a specific call is now unpaused.
169		CallUnpaused { full_name: RuntimeCallNameOf<T> },
170	}
171
172	/// Configure the initial state of this pallet in the genesis block.
173	#[pallet::genesis_config]
174	#[derive(DefaultNoBound)]
175	pub struct GenesisConfig<T: Config> {
176		/// Initially paused calls.
177		pub paused: Vec<RuntimeCallNameOf<T>>,
178	}
179
180	#[pallet::genesis_build]
181	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
182		fn build(&self) {
183			for call in &self.paused {
184				Pallet::<T>::ensure_can_pause(&call).expect("Genesis data is known good; qed");
185				PausedCalls::<T>::insert(&call, ());
186			}
187		}
188	}
189
190	#[pallet::call]
191	impl<T: Config> Pallet<T> {
192		/// Pause a call.
193		///
194		/// Can only be called by [`Config::PauseOrigin`].
195		/// Emits an [`Event::CallPaused`] event on success.
196		#[pallet::call_index(0)]
197		#[pallet::weight(T::WeightInfo::pause())]
198		pub fn pause(origin: OriginFor<T>, full_name: RuntimeCallNameOf<T>) -> DispatchResult {
199			T::PauseOrigin::ensure_origin(origin)?;
200
201			Self::do_pause(full_name).map_err(Into::into)
202		}
203
204		/// Un-pause a call.
205		///
206		/// Can only be called by [`Config::UnpauseOrigin`].
207		/// Emits an [`Event::CallUnpaused`] event on success.
208		#[pallet::call_index(1)]
209		#[pallet::weight(T::WeightInfo::unpause())]
210		pub fn unpause(origin: OriginFor<T>, ident: RuntimeCallNameOf<T>) -> DispatchResult {
211			T::UnpauseOrigin::ensure_origin(origin)?;
212
213			Self::do_unpause(ident).map_err(Into::into)
214		}
215	}
216}
217
218impl<T: Config> Pallet<T> {
219	pub(crate) fn do_pause(ident: RuntimeCallNameOf<T>) -> Result<(), Error<T>> {
220		Self::ensure_can_pause(&ident)?;
221		PausedCalls::<T>::insert(&ident, ());
222		Self::deposit_event(Event::CallPaused { full_name: ident });
223
224		Ok(())
225	}
226
227	pub(crate) fn do_unpause(ident: RuntimeCallNameOf<T>) -> Result<(), Error<T>> {
228		Self::ensure_can_unpause(&ident)?;
229		PausedCalls::<T>::remove(&ident);
230		Self::deposit_event(Event::CallUnpaused { full_name: ident });
231
232		Ok(())
233	}
234
235	/// Return whether this call is paused.
236	pub fn is_paused(full_name: &RuntimeCallNameOf<T>) -> bool {
237		if T::WhitelistedCalls::contains(full_name) {
238			return false
239		}
240
241		<PausedCalls<T>>::contains_key(full_name)
242	}
243
244	/// Same as [`Self::is_paused`] but for inputs unbound by max-encoded-len.
245	pub fn is_paused_unbound(pallet: Vec<u8>, call: Vec<u8>) -> bool {
246		let pallet = PalletNameOf::<T>::try_from(pallet);
247		let call = PalletCallNameOf::<T>::try_from(call);
248
249		match (pallet, call) {
250			(Ok(pallet), Ok(call)) => Self::is_paused(&(pallet, call)),
251			_ => true,
252		}
253	}
254
255	/// Ensure that this call can be paused.
256	pub fn ensure_can_pause(full_name: &RuntimeCallNameOf<T>) -> Result<(), Error<T>> {
257		// SAFETY: The `TxPause` pallet can never pause itself.
258		if full_name.0.as_slice() == <Self as PalletInfoAccess>::name().as_bytes() {
259			return Err(Error::<T>::Unpausable)
260		}
261
262		if T::WhitelistedCalls::contains(&full_name) {
263			return Err(Error::<T>::Unpausable)
264		}
265		if Self::is_paused(&full_name) {
266			return Err(Error::<T>::IsPaused)
267		}
268		Ok(())
269	}
270
271	/// Ensure that this call can be un-paused.
272	pub fn ensure_can_unpause(full_name: &RuntimeCallNameOf<T>) -> Result<(), Error<T>> {
273		if Self::is_paused(&full_name) {
274			// SAFETY: Everything that is paused, can be un-paused.
275			Ok(())
276		} else {
277			Err(Error::IsUnpaused)
278		}
279	}
280}
281
282impl<T: pallet::Config> Contains<<T as frame_system::Config>::RuntimeCall> for Pallet<T>
283where
284	<T as frame_system::Config>::RuntimeCall: GetCallMetadata,
285{
286	/// Return whether the call is allowed to be dispatched.
287	fn contains(call: &<T as frame_system::Config>::RuntimeCall) -> bool {
288		let CallMetadata { pallet_name, function_name } = call.get_call_metadata();
289		!Pallet::<T>::is_paused_unbound(pallet_name.into(), function_name.into())
290	}
291}
292
293impl<T: Config> TransactionPause for Pallet<T> {
294	type CallIdentifier = RuntimeCallNameOf<T>;
295
296	fn is_paused(full_name: Self::CallIdentifier) -> bool {
297		Self::is_paused(&full_name)
298	}
299
300	fn can_pause(full_name: Self::CallIdentifier) -> bool {
301		Self::ensure_can_pause(&full_name).is_ok()
302	}
303
304	fn pause(full_name: Self::CallIdentifier) -> Result<(), TransactionPauseError> {
305		Self::do_pause(full_name).map_err(Into::into)
306	}
307
308	fn unpause(full_name: Self::CallIdentifier) -> Result<(), TransactionPauseError> {
309		Self::do_unpause(full_name).map_err(Into::into)
310	}
311}
312
313impl<T: Config> From<Error<T>> for TransactionPauseError {
314	fn from(err: Error<T>) -> Self {
315		match err {
316			Error::<T>::NotFound => Self::NotFound,
317			Error::<T>::Unpausable => Self::Unpausable,
318			Error::<T>::IsPaused => Self::AlreadyPaused,
319			Error::<T>::IsUnpaused => Self::AlreadyUnpaused,
320			_ => Self::Unknown,
321		}
322	}
323}