1use crate::Config;
19use frame_support::{
20 dispatch::DispatchInfo,
21 pallet_prelude::{
22 Decode, DecodeWithMemTracking, DispatchResult, Encode, TransactionSource, TypeInfo, Weight,
23 },
24 traits::{Authorize, OriginTrait},
25 CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound,
26};
27use sp_runtime::{
28 traits::{
29 AsTransactionAuthorizedOrigin, Dispatchable, Implication, PostDispatchInfoOf,
30 TransactionExtension, ValidateResult,
31 },
32 transaction_validity::{InvalidTransaction, TransactionValidityError},
33};
34
35#[derive(
44 Encode,
45 Decode,
46 CloneNoBound,
47 EqNoBound,
48 PartialEqNoBound,
49 TypeInfo,
50 DebugNoBound,
51 DecodeWithMemTracking,
52)]
53#[scale_info(skip_type_params(T))]
54pub struct AuthorizeCall<T>(core::marker::PhantomData<T>);
55
56impl<T> AuthorizeCall<T> {
57 pub fn new() -> Self {
58 Self(Default::default())
59 }
60}
61
62impl<T: Config + Send + Sync> TransactionExtension<T::RuntimeCall> for AuthorizeCall<T>
63where
64 T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
65{
66 const IDENTIFIER: &'static str = "AuthorizeCall";
67 type Implicit = ();
68 type Val = Weight;
69 type Pre = Weight;
70
71 fn validate(
72 &self,
73 origin: T::RuntimeOrigin,
74 call: &T::RuntimeCall,
75 _info: &DispatchInfo,
76 _len: usize,
77 _self_implicit: Self::Implicit,
78 _inherited_implication: &impl Implication,
79 source: TransactionSource,
80 ) -> ValidateResult<Self::Val, T::RuntimeCall> {
81 if !origin.is_transaction_authorized() {
82 if let Some(authorize) = call.authorize(source) {
83 let (validity, unspent) = authorize?;
84 let authorized: T::RuntimeOrigin = crate::Origin::<T>::Authorized.into();
85 if !authorized.filter_call(call) {
87 return Err(InvalidTransaction::Call.into());
88 }
89 return Ok((validity, unspent, authorized));
90 }
91 }
92
93 Ok((Default::default(), call.weight_of_authorize(), origin))
95 }
96
97 fn prepare(
98 self,
99 val: Self::Val,
100 _origin: &T::RuntimeOrigin,
101 _call: &T::RuntimeCall,
102 _info: &DispatchInfo,
103 _len: usize,
104 ) -> Result<Self::Pre, TransactionValidityError> {
105 Ok(val)
106 }
107
108 fn post_dispatch_details(
109 pre: Self::Pre,
110 _info: &DispatchInfo,
111 _post_info: &PostDispatchInfoOf<T::RuntimeCall>,
112 _len: usize,
113 _result: &DispatchResult,
114 ) -> Result<Weight, TransactionValidityError> {
115 Ok(pre)
116 }
117
118 fn weight(&self, call: &T::RuntimeCall) -> Weight {
119 call.weight_of_authorize()
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use crate as frame_system;
126 use codec::Encode;
127 use frame_support::{
128 derive_impl, dispatch::GetDispatchInfo, pallet_prelude::TransactionSource,
129 traits::OriginTrait,
130 };
131 use sp_runtime::{
132 testing::UintAuthorityId,
133 traits::{Applyable, Checkable, TransactionExtension as _, TxBaseImplication},
134 transaction_validity::{
135 InvalidTransaction, TransactionSource::External, TransactionValidityError,
136 },
137 BuildStorage, DispatchError,
138 };
139
140 #[frame_support::pallet]
141 pub mod pallet1 {
142 use crate as frame_system;
143 use frame_support::pallet_prelude::*;
144 use frame_system::pallet_prelude::*;
145
146 pub const CALL_WEIGHT: Weight = Weight::from_all(4);
147 pub const AUTH_WEIGHT: Weight = Weight::from_all(5);
148
149 pub fn valid_transaction() -> ValidTransaction {
150 ValidTransaction {
151 priority: 10,
152 provides: vec![1u8.encode()],
153 requires: vec![],
154 longevity: 1000,
155 propagate: true,
156 }
157 }
158
159 #[pallet::pallet]
160 pub struct Pallet<T>(_);
161
162 #[pallet::config]
163 pub trait Config: frame_system::Config {}
164
165 #[pallet::call]
166 impl<T: Config> Pallet<T> {
167 #[pallet::weight(CALL_WEIGHT)]
168 #[pallet::call_index(0)]
169 #[pallet::authorize(|_source, valid| if *valid {
170 Ok((valid_transaction(), Weight::zero()))
171 } else {
172 Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
173 })]
174 #[pallet::weight_of_authorize(AUTH_WEIGHT)]
175 pub fn call1(origin: OriginFor<T>, valid: bool) -> DispatchResult {
176 crate::ensure_authorized(origin)?;
177 let _ = valid;
178 Ok(())
179 }
180 }
181 }
182
183 #[frame_support::runtime]
184 mod runtime {
185 #[runtime::runtime]
186 #[runtime::derive(
187 RuntimeCall,
188 RuntimeEvent,
189 RuntimeError,
190 RuntimeOrigin,
191 RuntimeFreezeReason,
192 RuntimeHoldReason,
193 RuntimeSlashReason,
194 RuntimeLockId,
195 RuntimeTask
196 )]
197 pub struct Runtime;
198
199 #[runtime::pallet_index(0)]
200 pub type System = frame_system::Pallet<Runtime>;
201
202 #[runtime::pallet_index(1)]
203 pub type Pallet1 = pallet1::Pallet<Runtime>;
204 }
205
206 pub type TransactionExtension = (frame_system::AuthorizeCall<Runtime>,);
207
208 pub type Header = sp_runtime::generic::Header<u32, sp_runtime::traits::BlakeTwo256>;
209 pub type Block = sp_runtime::generic::Block<Header, UncheckedExtrinsic>;
210 pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic<
211 u64,
212 RuntimeCall,
213 UintAuthorityId,
214 TransactionExtension,
215 >;
216
217 frame_support::parameter_types! {
218 pub static Pallet1Paused: bool = false;
219 }
220
221 pub struct PausablePallet1;
223 impl frame_support::traits::Contains<RuntimeCall> for PausablePallet1 {
224 fn contains(call: &RuntimeCall) -> bool {
225 !(Pallet1Paused::get() && matches!(call, RuntimeCall::Pallet1(_)))
226 }
227 }
228
229 #[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
230 impl frame_system::Config for Runtime {
231 type Block = Block;
232 type BaseCallFilter = PausablePallet1;
233 }
234
235 impl pallet1::Config for Runtime {}
236
237 pub fn new_test_ext() -> sp_io::TestExternalities {
238 let t = RuntimeGenesisConfig { ..Default::default() }.build_storage().unwrap();
239 t.into()
240 }
241
242 #[test]
243 fn valid_transaction() {
244 let call = RuntimeCall::Pallet1(pallet1::Call::call1 { valid: true });
245
246 new_test_ext().execute_with(|| {
247 let tx_ext = (frame_system::AuthorizeCall::<Runtime>::new(),);
248
249 let tx = UncheckedExtrinsic::new_transaction(call, tx_ext);
250
251 let info = tx.get_dispatch_info();
252 let len = tx.using_encoded(|e| e.len());
253
254 let checked = Checkable::check(tx, &frame_system::ChainContext::<Runtime>::default())
255 .expect("Transaction is general so signature is good");
256
257 let valid_tx = checked
258 .validate::<Runtime>(TransactionSource::External, &info, len)
259 .expect("call valid");
260
261 let dispatch_result =
262 checked.apply::<Runtime>(&info, len).expect("Transaction is valid");
263
264 assert!(dispatch_result.is_ok());
265
266 let post_info = dispatch_result.unwrap_or_else(|e| e.post_info);
267
268 assert_eq!(valid_tx, pallet1::valid_transaction());
269 assert_eq!(info.call_weight, pallet1::CALL_WEIGHT);
270 assert_eq!(info.extension_weight, pallet1::AUTH_WEIGHT);
271 assert_eq!(post_info.actual_weight, Some(pallet1::CALL_WEIGHT + pallet1::AUTH_WEIGHT));
272 });
273 }
274
275 #[test]
276 fn invalid_transaction_fail_authorization() {
277 let call = RuntimeCall::Pallet1(pallet1::Call::call1 { valid: false });
278
279 new_test_ext().execute_with(|| {
280 let tx_ext = (frame_system::AuthorizeCall::<Runtime>::new(),);
281
282 let tx = UncheckedExtrinsic::new_transaction(call, tx_ext);
283
284 let info = tx.get_dispatch_info();
285 let len = tx.using_encoded(|e| e.len());
286
287 let checked = Checkable::check(tx, &frame_system::ChainContext::<Runtime>::default())
288 .expect("Transaction is general so signature is good");
289
290 let validate_err = checked
291 .validate::<Runtime>(TransactionSource::External, &info, len)
292 .expect_err("call is invalid");
293
294 let apply_err =
295 checked.apply::<Runtime>(&info, len).expect_err("Transaction is invalid");
296
297 assert_eq!(validate_err, TransactionValidityError::Invalid(InvalidTransaction::Call));
298 assert_eq!(apply_err, TransactionValidityError::Invalid(InvalidTransaction::Call));
299 assert_eq!(info.call_weight, pallet1::CALL_WEIGHT);
300 assert_eq!(info.extension_weight, pallet1::AUTH_WEIGHT);
301 });
302 }
303
304 #[test]
305 fn failing_transaction_invalid_origin() {
306 let call = RuntimeCall::Pallet1(pallet1::Call::call1 { valid: true });
307
308 new_test_ext().execute_with(|| {
309 let tx_ext = (frame_system::AuthorizeCall::<Runtime>::new(),);
310
311 let tx = UncheckedExtrinsic::new_signed(call, 42, 42.into(), tx_ext);
312
313 let info = tx.get_dispatch_info();
314 let len = tx.using_encoded(|e| e.len());
315
316 let checked = Checkable::check(tx, &frame_system::ChainContext::<Runtime>::default())
317 .expect("Signature is good");
318
319 checked
320 .validate::<Runtime>(TransactionSource::External, &info, len)
321 .expect("Transaction is valid, tx ext doesn't deny none");
322
323 let dispatch_res = checked
324 .apply::<Runtime>(&info, len)
325 .expect("Transaction is valid")
326 .expect_err("Transaction is failing, because origin is wrong");
327
328 assert_eq!(dispatch_res.error, DispatchError::BadOrigin);
329 assert_eq!(dispatch_res.post_info.actual_weight, Some(pallet1::CALL_WEIGHT));
331 assert_eq!(info.call_weight, pallet1::CALL_WEIGHT);
332 assert_eq!(info.extension_weight, pallet1::AUTH_WEIGHT);
333 });
334 }
335
336 #[test]
337 fn call_filter_preserved() {
338 new_test_ext().execute_with(|| {
339 let ext = frame_system::AuthorizeCall::<Runtime>::new();
340 let filtered_call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] });
341
342 let origin = {
343 let mut o: RuntimeOrigin = crate::Origin::<Runtime>::Signed(42).into();
344 let filter_clone = filtered_call.clone();
345 o.add_filter(move |call| filter_clone != *call);
346 o
347 };
348
349 assert!(!origin.filter_call(&filtered_call));
350
351 let (_, _, new_origin) = ext
352 .validate(
353 origin,
354 &RuntimeCall::Pallet1(pallet1::Call::call1 { valid: true }),
355 &crate::DispatchInfo::default(),
356 Default::default(),
357 (),
358 &TxBaseImplication(()),
359 External,
360 )
361 .expect("valid");
362
363 assert!(!new_origin.filter_call(&filtered_call));
364 });
365 }
366
367 #[test]
368 fn skipped_authorization_refunds_its_weight() {
369 new_test_ext().execute_with(|| {
370 let ext = frame_system::AuthorizeCall::<Runtime>::new();
371 let call = RuntimeCall::Pallet1(pallet1::Call::call1 { valid: true });
372 let origin: RuntimeOrigin = crate::Origin::<Runtime>::Signed(42).into();
373
374 assert_eq!(ext.weight(&call), pallet1::AUTH_WEIGHT);
376
377 let (_, unspent, _) = ext
378 .validate(
379 origin,
380 &call,
381 &crate::DispatchInfo::default(),
382 Default::default(),
383 (),
384 &TxBaseImplication(()),
385 External,
386 )
387 .expect("valid");
388
389 assert_eq!(unspent, pallet1::AUTH_WEIGHT);
392 });
393 }
394
395 #[test]
396 fn filtered_call_is_not_authorized() {
397 let call = RuntimeCall::Pallet1(pallet1::Call::call1 { valid: true });
398
399 new_test_ext().execute_with(|| {
400 Pallet1Paused::set(true);
401
402 let tx = UncheckedExtrinsic::new_transaction(
403 call,
404 (frame_system::AuthorizeCall::<Runtime>::new(),),
405 );
406 let info = tx.get_dispatch_info();
407 let len = tx.using_encoded(|e| e.len());
408 let checked = Checkable::check(tx, &frame_system::ChainContext::<Runtime>::default())
409 .expect("Transaction is general so signature is good");
410
411 assert_eq!(
413 checked.validate::<Runtime>(TransactionSource::External, &info, len),
414 Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
415 );
416 assert_eq!(
417 checked.apply::<Runtime>(&info, len).map(|_| ()),
418 Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
419 );
420 });
421 }
422}