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
use crate::{Config, Key};
19
use codec::{Decode, Encode};
20
use core::{fmt, marker::PhantomData};
21
use frame_support::{dispatch::DispatchInfo, ensure};
22
use scale_info::TypeInfo;
23
use sp_runtime::{
24
	traits::{DispatchInfoOf, Dispatchable, SignedExtension},
25
	transaction_validity::{
26
		InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,
27
		UnknownTransaction, ValidTransaction,
28
	},
29
};
30

            
31
/// Ensure that signed transactions are only valid if they are signed by sudo account.
32
///
33
/// In the initial phase of a chain without any tokens you can not prevent accounts from sending
34
/// transactions.
35
/// These transactions would enter the transaction pool as the succeed the validation, but would
36
/// fail on applying them as they are not allowed/disabled/whatever. This would be some huge dos
37
/// vector to any kind of chain. This extension solves the dos vector by preventing any kind of
38
/// transaction entering the pool as long as it is not signed by the sudo account.
39
#[derive(Clone, Eq, PartialEq, Encode, Decode, TypeInfo)]
40
#[scale_info(skip_type_params(T))]
41
pub struct CheckOnlySudoAccount<T: Config + Send + Sync>(PhantomData<T>);
42

            
43
impl<T: Config + Send + Sync> Default for CheckOnlySudoAccount<T> {
44
	fn default() -> Self {
45
		Self(Default::default())
46
	}
47
}
48

            
49
impl<T: Config + Send + Sync> fmt::Debug for CheckOnlySudoAccount<T> {
50
	#[cfg(feature = "std")]
51
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52
		write!(f, "CheckOnlySudoAccount")
53
	}
54

            
55
	#[cfg(not(feature = "std"))]
56
	fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
57
		Ok(())
58
	}
59
}
60

            
61
impl<T: Config + Send + Sync> CheckOnlySudoAccount<T> {
62
	/// Creates new `SignedExtension` to check sudo key.
63
	pub fn new() -> Self {
64
		Self::default()
65
	}
66
}
67

            
68
impl<T: Config + Send + Sync> SignedExtension for CheckOnlySudoAccount<T>
69
where
70
	<T as Config>::RuntimeCall: Dispatchable<Info = DispatchInfo>,
71
{
72
	const IDENTIFIER: &'static str = "CheckOnlySudoAccount";
73
	type AccountId = T::AccountId;
74
	type Call = <T as Config>::RuntimeCall;
75
	type AdditionalSigned = ();
76
	type Pre = ();
77

            
78
	fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
79
		Ok(())
80
	}
81

            
82
	fn validate(
83
		&self,
84
		who: &Self::AccountId,
85
		_call: &Self::Call,
86
		info: &DispatchInfoOf<Self::Call>,
87
		_len: usize,
88
	) -> TransactionValidity {
89
		let sudo_key: T::AccountId = Key::<T>::get().ok_or(UnknownTransaction::CannotLookup)?;
90
		ensure!(*who == sudo_key, InvalidTransaction::BadSigner);
91

            
92
		Ok(ValidTransaction {
93
			priority: info.weight.ref_time() as TransactionPriority,
94
			..Default::default()
95
		})
96
	}
97

            
98
	fn pre_dispatch(
99
		self,
100
		who: &Self::AccountId,
101
		call: &Self::Call,
102
		info: &DispatchInfoOf<Self::Call>,
103
		len: usize,
104
	) -> Result<Self::Pre, TransactionValidityError> {
105
		self.validate(who, call, info, len).map(|_| ())
106
	}
107
}