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 ///
287 /// <div class="warning">
288 ///
289 /// If two different transactions have the same `provides` tags, the transaction pool
290 /// treats them as conflicting. One of these transactions will be dropped - e.g. depending on
291 /// submission time, priority of transaction.
292 ///
293 /// A transaction that has no provided tags, will be dropped by the transaction pool.
294 ///
295 /// </div>
296 pub provides: Vec<TransactionTag>,
297 /// Transaction longevity
298 ///
299 /// Longevity describes minimum number of blocks the validity is correct.
300 /// After this period transaction should be removed from the pool or revalidated.
301 pub longevity: TransactionLongevity,
302 /// A flag indicating if the transaction should be propagated to other peers.
303 ///
304 /// By setting `false` here the transaction will still be considered for
305 /// including in blocks that are authored on the current node, but will
306 /// never be sent to other peers.
307 pub propagate: bool,
308}
309
310impl Default for ValidTransaction {
311 fn default() -> Self {
312 Self {
313 priority: 0,
314 requires: vec![],
315 provides: vec![],
316 longevity: TransactionLongevity::max_value(),
317 propagate: true,
318 }
319 }
320}
321
322impl ValidTransaction {
323 /// Initiate `ValidTransaction` builder object with a particular prefix for tags.
324 ///
325 /// To avoid conflicts between different parts in runtime it's recommended to build `requires`
326 /// and `provides` tags with a unique prefix.
327 pub fn with_tag_prefix(prefix: &'static str) -> ValidTransactionBuilder {
328 ValidTransactionBuilder { prefix: Some(prefix), validity: Default::default() }
329 }
330
331 /// Combine two instances into one, as a best effort. This will take the superset of each of the
332 /// `provides` and `requires` tags, it will sum the priorities, take the minimum longevity and
333 /// the logic *And* of the propagate flags.
334 pub fn combine_with(mut self, mut other: ValidTransaction) -> Self {
335 Self {
336 priority: self.priority.saturating_add(other.priority),
337 requires: {
338 self.requires.append(&mut other.requires);
339 self.requires
340 },
341 provides: {
342 self.provides.append(&mut other.provides);
343 self.provides
344 },
345 longevity: self.longevity.min(other.longevity),
346 propagate: self.propagate && other.propagate,
347 }
348 }
349}
350
351/// `ValidTransaction` builder.
352///
353///
354/// Allows to easily construct `ValidTransaction` and most importantly takes care of
355/// prefixing `requires` and `provides` tags to avoid conflicts.
356#[derive(Default, Clone, RuntimeDebug)]
357pub struct ValidTransactionBuilder {
358 prefix: Option<&'static str>,
359 validity: ValidTransaction,
360}
361
362impl ValidTransactionBuilder {
363 /// Set the priority of a transaction.
364 ///
365 /// Note that the final priority for `FRAME` is combined from all `TransactionExtension`s.
366 /// Most likely for unsigned transactions you want the priority to be higher
367 /// than for regular transactions. We recommend exposing a base priority for unsigned
368 /// transactions as a runtime module parameter, so that the runtime can tune inter-module
369 /// priorities.
370 pub fn priority(mut self, priority: TransactionPriority) -> Self {
371 self.validity.priority = priority;
372 self
373 }
374
375 /// Set the longevity of a transaction.
376 ///
377 /// By default the transaction will be considered valid forever and will not be revalidated
378 /// by the transaction pool. It's recommended though to set the longevity to a finite value
379 /// though. If unsure, it's also reasonable to expose this parameter via module configuration
380 /// and let the runtime decide.
381 pub fn longevity(mut self, longevity: TransactionLongevity) -> Self {
382 self.validity.longevity = longevity;
383 self
384 }
385
386 /// Set the propagate flag.
387 ///
388 /// Set to `false` if the transaction is not meant to be gossiped to peers. Combined with
389 /// `TransactionSource::Local` validation it can be used to have special kind of
390 /// transactions that are only produced and included by the validator nodes.
391 pub fn propagate(mut self, propagate: bool) -> Self {
392 self.validity.propagate = propagate;
393 self
394 }
395
396 /// Add a `TransactionTag` to the set of required tags.
397 ///
398 /// The tag will be encoded and prefixed with module prefix (if any).
399 /// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
400 pub fn and_requires(mut self, tag: impl Encode) -> Self {
401 self.validity.requires.push(match self.prefix.as_ref() {
402 Some(prefix) => (prefix, tag).encode(),
403 None => tag.encode(),
404 });
405 self
406 }
407
408 /// Add a `TransactionTag` to the set of provided tags.
409 ///
410 /// The tag will be encoded and prefixed with module prefix (if any).
411 /// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
412 pub fn and_provides(mut self, tag: impl Encode) -> Self {
413 self.validity.provides.push(match self.prefix.as_ref() {
414 Some(prefix) => (prefix, tag).encode(),
415 None => tag.encode(),
416 });
417 self
418 }
419
420 /// Augment the builder with existing `ValidTransaction`.
421 ///
422 /// This method does add the prefix to `require` or `provides` tags.
423 pub fn combine_with(mut self, validity: ValidTransaction) -> Self {
424 self.validity = core::mem::take(&mut self.validity).combine_with(validity);
425 self
426 }
427
428 /// Finalize the builder and produce `TransactionValidity`.
429 ///
430 /// Note the result will always be `Ok`. Use `Into` to produce `ValidTransaction`.
431 pub fn build(self) -> TransactionValidity {
432 self.into()
433 }
434}
435
436impl From<ValidTransactionBuilder> for TransactionValidity {
437 fn from(builder: ValidTransactionBuilder) -> Self {
438 Ok(builder.into())
439 }
440}
441
442impl From<ValidTransactionBuilder> for ValidTransaction {
443 fn from(builder: ValidTransactionBuilder) -> Self {
444 builder.validity
445 }
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451
452 #[test]
453 fn should_encode_and_decode() {
454 let v: TransactionValidity = Ok(ValidTransaction {
455 priority: 5,
456 requires: vec![vec![1, 2, 3, 4]],
457 provides: vec![vec![4, 5, 6]],
458 longevity: 42,
459 propagate: false,
460 });
461
462 let encoded = v.encode();
463 assert_eq!(
464 encoded,
465 vec![
466 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,
467 0, 0
468 ]
469 );
470
471 // decode back
472 assert_eq!(TransactionValidity::decode(&mut &*encoded), Ok(v));
473 }
474
475 #[test]
476 fn builder_should_prefix_the_tags() {
477 const PREFIX: &str = "test";
478 let a: ValidTransaction = ValidTransaction::with_tag_prefix(PREFIX)
479 .and_requires(1)
480 .and_requires(2)
481 .and_provides(3)
482 .and_provides(4)
483 .propagate(false)
484 .longevity(5)
485 .priority(3)
486 .priority(6)
487 .into();
488 assert_eq!(
489 a,
490 ValidTransaction {
491 propagate: false,
492 longevity: 5,
493 priority: 6,
494 requires: vec![(PREFIX, 1).encode(), (PREFIX, 2).encode()],
495 provides: vec![(PREFIX, 3).encode(), (PREFIX, 4).encode()],
496 }
497 );
498 }
499}