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