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