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