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