referrerpolicy=no-referrer-when-downgrade

sp_runtime/
transaction_validity.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 validity interface.
19
20use crate::{
21	codec::{Decode, Encode},
22	RuntimeDebug,
23};
24use alloc::{vec, vec::Vec};
25use scale_info::TypeInfo;
26use sp_weights::Weight;
27
28/// Priority for a transaction. Additive. Higher is better.
29pub type TransactionPriority = u64;
30
31/// Minimum number of blocks a transaction will remain valid for.
32/// `TransactionLongevity::max_value()` means "forever".
33pub type TransactionLongevity = u64;
34
35/// Tag for a transaction. No two transactions with the same tag should be placed on-chain.
36pub type TransactionTag = Vec<u8>;
37
38/// An invalid transaction validity.
39#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug, TypeInfo)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
41pub enum InvalidTransaction {
42	/// The call of the transaction is not expected.
43	Call,
44	/// General error to do with the inability to pay some fees (e.g. account balance too low).
45	Payment,
46	/// General error to do with the transaction not yet being valid (e.g. nonce too high).
47	Future,
48	/// General error to do with the transaction being outdated (e.g. nonce too low).
49	Stale,
50	/// General error to do with the transaction's proofs (e.g. signature).
51	///
52	/// # Possible causes
53	///
54	/// When using a signed extension that provides additional data for signing, it is required
55	/// that the signing and the verifying side use the same additional data. Additional
56	/// data will only be used to generate the signature, but will not be part of the transaction
57	/// itself. As the verifying side does not know which additional data was used while signing
58	/// it will only be able to assume a bad signature and cannot express a more meaningful error.
59	BadProof,
60	/// The transaction birth block is ancient.
61	///
62	/// # Possible causes
63	///
64	/// For `FRAME`-based runtimes this would be caused by `current block number
65	/// - Era::birth block number > BlockHashCount`. (e.g. in Polkadot `BlockHashCount` = 2400, so
66	///   a
67	/// transaction with birth block number 1337 would be valid up until block number 1337 + 2400,
68	/// after which point the transaction would be considered to have an ancient birth block.)
69	AncientBirthBlock,
70	/// The transaction would exhaust the resources of current block.
71	///
72	/// The transaction might be valid, but there are not enough resources
73	/// left in the current block.
74	ExhaustsResources,
75	/// Any other custom invalid validity that is not covered by this enum.
76	Custom(u8),
77	/// An extrinsic with a Mandatory dispatch resulted in Error. This is indicative of either a
78	/// malicious validator or a buggy `provide_inherent`. In any case, it can result in
79	/// dangerously overweight blocks and therefore if found, invalidates the block.
80	BadMandatory,
81	/// An extrinsic with a mandatory dispatch tried to be validated.
82	/// This is invalid; only inherent extrinsics are allowed to have mandatory dispatches.
83	MandatoryValidation,
84	/// The sending address is disabled or known to be invalid.
85	BadSigner,
86	/// The implicit data was unable to be calculated.
87	IndeterminateImplicit,
88	/// The transaction extension did not authorize any origin.
89	UnknownOrigin,
90}
91
92impl InvalidTransaction {
93	/// Returns if the reason for the invalidity was block resource exhaustion.
94	pub fn exhausted_resources(&self) -> bool {
95		matches!(self, Self::ExhaustsResources)
96	}
97
98	/// Returns if the reason for the invalidity was a mandatory call failing.
99	pub fn was_mandatory(&self) -> bool {
100		matches!(self, Self::BadMandatory)
101	}
102}
103
104impl From<InvalidTransaction> for &'static str {
105	fn from(invalid: InvalidTransaction) -> &'static str {
106		match invalid {
107			InvalidTransaction::Call => "Transaction call is not expected",
108			InvalidTransaction::Future => "Transaction will be valid in the future",
109			InvalidTransaction::Stale => "Transaction is outdated",
110			InvalidTransaction::BadProof => "Transaction has a bad signature",
111			InvalidTransaction::AncientBirthBlock => "Transaction has an ancient birth block",
112			InvalidTransaction::ExhaustsResources => "Transaction would exhaust the block limits",
113			InvalidTransaction::Payment =>
114				"Inability to pay some fees (e.g. account balance too low)",
115			InvalidTransaction::BadMandatory =>
116				"A call was labelled as mandatory, but resulted in an Error.",
117			InvalidTransaction::MandatoryValidation =>
118				"Transaction dispatch is mandatory; transactions must not be validated.",
119			InvalidTransaction::Custom(_) => "InvalidTransaction custom error",
120			InvalidTransaction::BadSigner => "Invalid signing address",
121			InvalidTransaction::IndeterminateImplicit =>
122				"The implicit data was unable to be calculated",
123			InvalidTransaction::UnknownOrigin =>
124				"The transaction extension did not authorize any origin",
125		}
126	}
127}
128
129/// An unknown transaction validity.
130#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug, TypeInfo)]
131#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
132pub enum UnknownTransaction {
133	/// Could not lookup some information that is required to validate the transaction.
134	CannotLookup,
135	/// No validator found for the given unsigned transaction.
136	NoUnsignedValidator,
137	/// Any other custom unknown validity that is not covered by this enum.
138	Custom(u8),
139}
140
141impl From<UnknownTransaction> for &'static str {
142	fn from(unknown: UnknownTransaction) -> &'static str {
143		match unknown {
144			UnknownTransaction::CannotLookup =>
145				"Could not lookup information required to validate the transaction",
146			UnknownTransaction::NoUnsignedValidator =>
147				"Could not find an unsigned validator for the unsigned transaction",
148			UnknownTransaction::Custom(_) => "UnknownTransaction custom error",
149		}
150	}
151}
152
153/// Errors that can occur while checking the validity of a transaction.
154#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug, TypeInfo)]
155#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
156pub enum TransactionValidityError {
157	/// The transaction is invalid.
158	Invalid(InvalidTransaction),
159	/// Transaction validity can't be determined.
160	Unknown(UnknownTransaction),
161}
162
163impl TransactionValidityError {
164	/// Returns `true` if the reason for the error was block resource exhaustion.
165	pub fn exhausted_resources(&self) -> bool {
166		match self {
167			Self::Invalid(e) => e.exhausted_resources(),
168			Self::Unknown(_) => false,
169		}
170	}
171
172	/// Returns `true` if the reason for the error was it being a mandatory dispatch that could not
173	/// be completed successfully.
174	pub fn was_mandatory(&self) -> bool {
175		match self {
176			Self::Invalid(e) => e.was_mandatory(),
177			Self::Unknown(_) => false,
178		}
179	}
180}
181
182impl From<TransactionValidityError> for &'static str {
183	fn from(err: TransactionValidityError) -> &'static str {
184		match err {
185			TransactionValidityError::Invalid(invalid) => invalid.into(),
186			TransactionValidityError::Unknown(unknown) => unknown.into(),
187		}
188	}
189}
190
191impl From<InvalidTransaction> for TransactionValidityError {
192	fn from(err: InvalidTransaction) -> Self {
193		TransactionValidityError::Invalid(err)
194	}
195}
196
197impl From<UnknownTransaction> for TransactionValidityError {
198	fn from(err: UnknownTransaction) -> Self {
199		TransactionValidityError::Unknown(err)
200	}
201}
202
203#[cfg(feature = "std")]
204impl std::error::Error for TransactionValidityError {
205	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
206		None
207	}
208}
209
210#[cfg(feature = "std")]
211impl std::fmt::Display for TransactionValidityError {
212	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213		let s: &'static str = (*self).into();
214		write!(f, "{}", s)
215	}
216}
217
218/// Information on a transaction's validity and, if valid, on how it relates to other transactions.
219pub type TransactionValidity = Result<ValidTransaction, TransactionValidityError>;
220
221/// Information on a transaction's validity and, if valid, on how it relates to other transactions
222/// and some refund for the operation.
223pub type TransactionValidityWithRefund =
224	Result<(ValidTransaction, Weight), TransactionValidityError>;
225
226impl From<InvalidTransaction> for TransactionValidity {
227	fn from(invalid_transaction: InvalidTransaction) -> Self {
228		Err(TransactionValidityError::Invalid(invalid_transaction))
229	}
230}
231
232impl From<UnknownTransaction> for TransactionValidity {
233	fn from(unknown_transaction: UnknownTransaction) -> Self {
234		Err(TransactionValidityError::Unknown(unknown_transaction))
235	}
236}
237
238/// The source of the transaction.
239///
240/// Depending on the source we might apply different validation schemes.
241/// For instance we can disallow specific kinds of transactions if they were not produced
242/// by our local node (for instance off-chain workers).
243#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo, Hash)]
244pub enum TransactionSource {
245	/// Transaction is already included in block.
246	///
247	/// This means that we can't really tell where the transaction is coming from,
248	/// since it's already in the received block. Note that the custom validation logic
249	/// using either `Local` or `External` should most likely just allow `InBlock`
250	/// transactions as well.
251	InBlock,
252
253	/// Transaction is coming from a local source.
254	///
255	/// This means that the transaction was produced internally by the node
256	/// (for instance an Off-Chain Worker, or an Off-Chain Call), as opposed
257	/// to being received over the network.
258	Local,
259
260	/// Transaction has been received externally.
261	///
262	/// This means the transaction has been received from (usually) "untrusted" source,
263	/// for instance received over the network or RPC.
264	External,
265}
266
267/// Information concerning a valid transaction.
268#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)]
269pub struct ValidTransaction {
270	/// Priority of the transaction.
271	///
272	/// Priority determines the ordering of two transactions that have all
273	/// their dependencies (required tags) satisfied.
274	pub priority: TransactionPriority,
275	/// Transaction dependencies
276	///
277	/// A non-empty list signifies that some other transactions which provide
278	/// given tags are required to be included before that one.
279	pub requires: Vec<TransactionTag>,
280	/// Provided tags
281	///
282	/// A list of tags this transaction provides. Successfully importing the transaction
283	/// will enable other transactions that depend on (require) those tags to be included as well.
284	/// Provided and required tags allow Substrate to build a dependency graph of transactions
285	/// and import them in the right (linear) order.
286	pub provides: Vec<TransactionTag>,
287	/// Transaction longevity
288	///
289	/// Longevity describes minimum number of blocks the validity is correct.
290	/// After this period transaction should be removed from the pool or revalidated.
291	pub longevity: TransactionLongevity,
292	/// A flag indicating if the transaction should be propagated to other peers.
293	///
294	/// By setting `false` here the transaction will still be considered for
295	/// including in blocks that are authored on the current node, but will
296	/// never be sent to other peers.
297	pub propagate: bool,
298}
299
300impl Default for ValidTransaction {
301	fn default() -> Self {
302		Self {
303			priority: 0,
304			requires: vec![],
305			provides: vec![],
306			longevity: TransactionLongevity::max_value(),
307			propagate: true,
308		}
309	}
310}
311
312impl ValidTransaction {
313	/// Initiate `ValidTransaction` builder object with a particular prefix for tags.
314	///
315	/// To avoid conflicts between different parts in runtime it's recommended to build `requires`
316	/// and `provides` tags with a unique prefix.
317	pub fn with_tag_prefix(prefix: &'static str) -> ValidTransactionBuilder {
318		ValidTransactionBuilder { prefix: Some(prefix), validity: Default::default() }
319	}
320
321	/// Combine two instances into one, as a best effort. This will take the superset of each of the
322	/// `provides` and `requires` tags, it will sum the priorities, take the minimum longevity and
323	/// the logic *And* of the propagate flags.
324	pub fn combine_with(mut self, mut other: ValidTransaction) -> Self {
325		Self {
326			priority: self.priority.saturating_add(other.priority),
327			requires: {
328				self.requires.append(&mut other.requires);
329				self.requires
330			},
331			provides: {
332				self.provides.append(&mut other.provides);
333				self.provides
334			},
335			longevity: self.longevity.min(other.longevity),
336			propagate: self.propagate && other.propagate,
337		}
338	}
339}
340
341/// `ValidTransaction` builder.
342///
343///
344/// Allows to easily construct `ValidTransaction` and most importantly takes care of
345/// prefixing `requires` and `provides` tags to avoid conflicts.
346#[derive(Default, Clone, RuntimeDebug)]
347pub struct ValidTransactionBuilder {
348	prefix: Option<&'static str>,
349	validity: ValidTransaction,
350}
351
352impl ValidTransactionBuilder {
353	/// Set the priority of a transaction.
354	///
355	/// Note that the final priority for `FRAME` is combined from all `TransactionExtension`s.
356	/// Most likely for unsigned transactions you want the priority to be higher
357	/// than for regular transactions. We recommend exposing a base priority for unsigned
358	/// transactions as a runtime module parameter, so that the runtime can tune inter-module
359	/// priorities.
360	pub fn priority(mut self, priority: TransactionPriority) -> Self {
361		self.validity.priority = priority;
362		self
363	}
364
365	/// Set the longevity of a transaction.
366	///
367	/// By default the transaction will be considered valid forever and will not be revalidated
368	/// by the transaction pool. It's recommended though to set the longevity to a finite value
369	/// though. If unsure, it's also reasonable to expose this parameter via module configuration
370	/// and let the runtime decide.
371	pub fn longevity(mut self, longevity: TransactionLongevity) -> Self {
372		self.validity.longevity = longevity;
373		self
374	}
375
376	/// Set the propagate flag.
377	///
378	/// Set to `false` if the transaction is not meant to be gossiped to peers. Combined with
379	/// `TransactionSource::Local` validation it can be used to have special kind of
380	/// transactions that are only produced and included by the validator nodes.
381	pub fn propagate(mut self, propagate: bool) -> Self {
382		self.validity.propagate = propagate;
383		self
384	}
385
386	/// Add a `TransactionTag` to the set of required tags.
387	///
388	/// The tag will be encoded and prefixed with module prefix (if any).
389	/// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
390	pub fn and_requires(mut self, tag: impl Encode) -> Self {
391		self.validity.requires.push(match self.prefix.as_ref() {
392			Some(prefix) => (prefix, tag).encode(),
393			None => tag.encode(),
394		});
395		self
396	}
397
398	/// Add a `TransactionTag` to the set of provided tags.
399	///
400	/// The tag will be encoded and prefixed with module prefix (if any).
401	/// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
402	pub fn and_provides(mut self, tag: impl Encode) -> Self {
403		self.validity.provides.push(match self.prefix.as_ref() {
404			Some(prefix) => (prefix, tag).encode(),
405			None => tag.encode(),
406		});
407		self
408	}
409
410	/// Augment the builder with existing `ValidTransaction`.
411	///
412	/// This method does add the prefix to `require` or `provides` tags.
413	pub fn combine_with(mut self, validity: ValidTransaction) -> Self {
414		self.validity = core::mem::take(&mut self.validity).combine_with(validity);
415		self
416	}
417
418	/// Finalize the builder and produce `TransactionValidity`.
419	///
420	/// Note the result will always be `Ok`. Use `Into` to produce `ValidTransaction`.
421	pub fn build(self) -> TransactionValidity {
422		self.into()
423	}
424}
425
426impl From<ValidTransactionBuilder> for TransactionValidity {
427	fn from(builder: ValidTransactionBuilder) -> Self {
428		Ok(builder.into())
429	}
430}
431
432impl From<ValidTransactionBuilder> for ValidTransaction {
433	fn from(builder: ValidTransactionBuilder) -> Self {
434		builder.validity
435	}
436}
437
438#[cfg(test)]
439mod tests {
440	use super::*;
441
442	#[test]
443	fn should_encode_and_decode() {
444		let v: TransactionValidity = Ok(ValidTransaction {
445			priority: 5,
446			requires: vec![vec![1, 2, 3, 4]],
447			provides: vec![vec![4, 5, 6]],
448			longevity: 42,
449			propagate: false,
450		});
451
452		let encoded = v.encode();
453		assert_eq!(
454			encoded,
455			vec![
456				0, 5, 0, 0, 0, 0, 0, 0, 0, 4, 16, 1, 2, 3, 4, 4, 12, 4, 5, 6, 42, 0, 0, 0, 0, 0, 0,
457				0, 0
458			]
459		);
460
461		// decode back
462		assert_eq!(TransactionValidity::decode(&mut &*encoded), Ok(v));
463	}
464
465	#[test]
466	fn builder_should_prefix_the_tags() {
467		const PREFIX: &str = "test";
468		let a: ValidTransaction = ValidTransaction::with_tag_prefix(PREFIX)
469			.and_requires(1)
470			.and_requires(2)
471			.and_provides(3)
472			.and_provides(4)
473			.propagate(false)
474			.longevity(5)
475			.priority(3)
476			.priority(6)
477			.into();
478		assert_eq!(
479			a,
480			ValidTransaction {
481				propagate: false,
482				longevity: 5,
483				priority: 6,
484				requires: vec![(PREFIX, 1).encode(), (PREFIX, 2).encode()],
485				provides: vec![(PREFIX, 3).encode(), (PREFIX, 4).encode()],
486			}
487		);
488	}
489}