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