sp_runtime/generic/
checked_extrinsic.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//! Generic implementation of an extrinsic that has passed the verification
19//! stage.
20
21use codec::Encode;
22use sp_weights::Weight;
23
24use crate::{
25	traits::{
26		self, transaction_extension::TransactionExtension, AsTransactionAuthorizedOrigin,
27		DispatchInfoOf, DispatchTransaction, Dispatchable, MaybeDisplay, Member,
28		PostDispatchInfoOf, ValidateUnsigned,
29	},
30	transaction_validity::{TransactionSource, TransactionValidity},
31};
32
33use super::unchecked_extrinsic::ExtensionVersion;
34
35/// Default version of the [Extension](TransactionExtension) used to construct the inherited
36/// implication for legacy transactions.
37const DEFAULT_EXTENSION_VERSION: ExtensionVersion = 0;
38
39/// The kind of extrinsic this is, including any fields required of that kind. This is basically
40/// the full extrinsic except the `Call`.
41#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)]
42pub enum ExtrinsicFormat<AccountId, Extension> {
43	/// Extrinsic is bare; it must pass either the bare forms of `TransactionExtension` or
44	/// `ValidateUnsigned`, both deprecated, or alternatively a `ProvideInherent`.
45	Bare,
46	/// Extrinsic has a default `Origin` of `Signed(AccountId)` and must pass all
47	/// `TransactionExtension`s regular checks and includes all extension data.
48	Signed(AccountId, Extension),
49	/// Extrinsic has a default `Origin` of `None` and must pass all `TransactionExtension`s.
50	/// regular checks and includes all extension data.
51	General(ExtensionVersion, Extension),
52}
53
54/// Definition of something that the external world might want to say; its existence implies that it
55/// has been checked and is good, particularly with regards to the signature.
56///
57/// This is typically passed into [`traits::Applyable::apply`], which should execute
58/// [`CheckedExtrinsic::function`], alongside all other bits and bobs.
59#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)]
60pub struct CheckedExtrinsic<AccountId, Call, Extension> {
61	/// Who this purports to be from and the number of extrinsics have come before
62	/// from the same signer, if anyone (note this is not a signature).
63	pub format: ExtrinsicFormat<AccountId, Extension>,
64
65	/// The function that should be called.
66	pub function: Call,
67}
68
69impl<AccountId, Call, Extension, RuntimeOrigin> traits::Applyable
70	for CheckedExtrinsic<AccountId, Call, Extension>
71where
72	AccountId: Member + MaybeDisplay,
73	Call: Member + Dispatchable<RuntimeOrigin = RuntimeOrigin> + Encode,
74	Extension: TransactionExtension<Call>,
75	RuntimeOrigin: From<Option<AccountId>> + AsTransactionAuthorizedOrigin,
76{
77	type Call = Call;
78
79	fn validate<I: ValidateUnsigned<Call = Self::Call>>(
80		&self,
81		source: TransactionSource,
82		info: &DispatchInfoOf<Self::Call>,
83		len: usize,
84	) -> TransactionValidity {
85		match self.format {
86			ExtrinsicFormat::Bare => {
87				let inherent_validation = I::validate_unsigned(source, &self.function)?;
88				let legacy_validation = Extension::bare_validate(&self.function, info, len)?;
89				Ok(legacy_validation.combine_with(inherent_validation))
90			},
91			ExtrinsicFormat::Signed(ref signer, ref extension) => {
92				let origin = Some(signer.clone()).into();
93				extension
94					.validate_only(
95						origin,
96						&self.function,
97						info,
98						len,
99						source,
100						DEFAULT_EXTENSION_VERSION,
101					)
102					.map(|x| x.0)
103			},
104			ExtrinsicFormat::General(extension_version, ref extension) => extension
105				.validate_only(None.into(), &self.function, info, len, source, extension_version)
106				.map(|x| x.0),
107		}
108	}
109
110	fn apply<I: ValidateUnsigned<Call = Self::Call>>(
111		self,
112		info: &DispatchInfoOf<Self::Call>,
113		len: usize,
114	) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>> {
115		match self.format {
116			ExtrinsicFormat::Bare => {
117				I::pre_dispatch(&self.function)?;
118				// TODO: Separate logic from `TransactionExtension` into a new `InherentExtension`
119				// interface.
120				Extension::bare_validate_and_prepare(&self.function, info, len)?;
121				let res = self.function.dispatch(None.into());
122				let mut post_info = res.unwrap_or_else(|err| err.post_info);
123				let pd_res = res.map(|_| ()).map_err(|e| e.error);
124				// TODO: Separate logic from `TransactionExtension` into a new `InherentExtension`
125				// interface.
126				Extension::bare_post_dispatch(info, &mut post_info, len, &pd_res)?;
127				Ok(res)
128			},
129			ExtrinsicFormat::Signed(signer, extension) => extension.dispatch_transaction(
130				Some(signer).into(),
131				self.function,
132				info,
133				len,
134				DEFAULT_EXTENSION_VERSION,
135			),
136			ExtrinsicFormat::General(extension_version, extension) => extension
137				.dispatch_transaction(None.into(), self.function, info, len, extension_version),
138		}
139	}
140}
141
142impl<AccountId, Call: Dispatchable, Extension: TransactionExtension<Call>>
143	CheckedExtrinsic<AccountId, Call, Extension>
144{
145	/// Returns the weight of the extension of this transaction, if present. If the transaction
146	/// doesn't use any extension, the weight returned is equal to zero.
147	pub fn extension_weight(&self) -> Weight {
148		match &self.format {
149			ExtrinsicFormat::Bare => Weight::zero(),
150			ExtrinsicFormat::Signed(_, ext) | ExtrinsicFormat::General(_, ext) =>
151				ext.weight(&self.function),
152		}
153	}
154}