referrerpolicy=no-referrer-when-downgrade

pallet_sudo/
extension.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
18use crate::{Config, Key};
19use alloc::vec;
20use codec::{Decode, DecodeWithMemTracking, Encode};
21use core::{fmt, marker::PhantomData};
22use frame_support::{dispatch::DispatchInfo, ensure, pallet_prelude::TransactionSource};
23use scale_info::TypeInfo;
24use sp_runtime::{
25	impl_tx_ext_default,
26	traits::{AsSystemOriginSigner, DispatchInfoOf, Dispatchable, Hash, TransactionExtension},
27	transaction_validity::{
28		InvalidTransaction, TransactionPriority, TransactionValidityError, UnknownTransaction,
29		ValidTransaction,
30	},
31};
32
33/// Ensure that signed transactions are only valid if they are signed by sudo account.
34///
35/// In the initial phase of a chain without any tokens you cannot prevent accounts from sending
36/// transactions.
37/// These transactions would enter the transaction pool as the succeed the validation, but would
38/// fail on applying them as they are not allowed/disabled/whatever. This would be some huge dos
39/// vector to any kind of chain. This extension solves the dos vector by preventing any kind of
40/// transaction entering the pool as long as it is not signed by the sudo account.
41#[derive(Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, TypeInfo)]
42#[scale_info(skip_type_params(T))]
43pub struct CheckOnlySudoAccount<T: Config + Send + Sync>(PhantomData<T>);
44
45impl<T: Config + Send + Sync> Default for CheckOnlySudoAccount<T> {
46	fn default() -> Self {
47		Self(Default::default())
48	}
49}
50
51impl<T: Config + Send + Sync> fmt::Debug for CheckOnlySudoAccount<T> {
52	#[cfg(feature = "std")]
53	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54		write!(f, "CheckOnlySudoAccount")
55	}
56
57	#[cfg(not(feature = "std"))]
58	fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
59		Ok(())
60	}
61}
62
63impl<T: Config + Send + Sync> CheckOnlySudoAccount<T> {
64	/// Creates new `TransactionExtension` to check sudo key.
65	pub fn new() -> Self {
66		Self::default()
67	}
68}
69
70impl<T: Config + Send + Sync> TransactionExtension<<T as frame_system::Config>::RuntimeCall>
71	for CheckOnlySudoAccount<T>
72where
73	<T as frame_system::Config>::RuntimeCall: Dispatchable<Info = DispatchInfo>,
74	<<T as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
75		AsSystemOriginSigner<T::AccountId> + Clone,
76{
77	const IDENTIFIER: &'static str = "CheckOnlySudoAccount";
78	type Implicit = ();
79	type Pre = ();
80	type Val = ();
81
82	fn weight(
83		&self,
84		_: &<T as frame_system::Config>::RuntimeCall,
85	) -> frame_support::weights::Weight {
86		use crate::weights::WeightInfo;
87		T::WeightInfo::check_only_sudo_account()
88	}
89
90	fn validate(
91		&self,
92		origin: <<T as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin,
93		call: &<T as frame_system::Config>::RuntimeCall,
94		info: &DispatchInfoOf<<T as frame_system::Config>::RuntimeCall>,
95		_len: usize,
96		_self_implicit: Self::Implicit,
97		_inherited_implication: &impl Encode,
98		_source: TransactionSource,
99	) -> Result<
100		(
101			ValidTransaction,
102			Self::Val,
103			<<T as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin,
104		),
105		TransactionValidityError,
106	> {
107		let who = origin.as_system_origin_signer().ok_or(InvalidTransaction::BadSigner)?;
108		let sudo_key: T::AccountId = Key::<T>::get().ok_or(UnknownTransaction::CannotLookup)?;
109		ensure!(*who == sudo_key, InvalidTransaction::BadSigner);
110
111		Ok((
112			ValidTransaction {
113				priority: info.total_weight().ref_time() as TransactionPriority,
114				provides: vec![(who, T::Hashing::hash_of(call)).encode()],
115				..Default::default()
116			},
117			(),
118			origin,
119		))
120	}
121
122	impl_tx_ext_default!(<T as frame_system::Config>::RuntimeCall; prepare);
123}