tp_runtime/
transaction_validity.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2017-2021 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 tetcore_std::prelude::*;
21use crate::codec::{Encode, Decode};
22use crate::RuntimeDebug;
23
24/// Priority for a transaction. Additive. Higher is better.
25pub type TransactionPriority = u64;
26
27/// Minimum number of blocks a transaction will remain valid for.
28/// `TransactionLongevity::max_value()` means "forever".
29pub type TransactionLongevity = u64;
30
31/// Tag for a transaction. No two transactions with the same tag should be placed on-chain.
32pub type TransactionTag = Vec<u8>;
33
34/// An invalid transaction validity.
35#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug)]
36#[cfg_attr(feature = "std", derive(serde::Serialize))]
37pub enum InvalidTransaction {
38	/// The call of the transaction is not expected.
39	Call,
40	/// General error to do with the inability to pay some fees (e.g. account balance too low).
41	Payment,
42	/// General error to do with the transaction not yet being valid (e.g. nonce too high).
43	Future,
44	/// General error to do with the transaction being outdated (e.g. nonce too low).
45	Stale,
46	/// General error to do with the transaction's proofs (e.g. signature).
47	///
48	/// # Possible causes
49	///
50	/// When using a signed extension that provides additional data for signing, it is required
51	/// that the signing and the verifying side use the same additional data. Additional
52	/// data will only be used to generate the signature, but will not be part of the transaction
53	/// itself. As the verifying side does not know which additional data was used while signing
54	/// it will only be able to assume a bad signature and cannot express a more meaningful error.
55	BadProof,
56	/// The transaction birth block is ancient.
57	///
58	/// # Possible causes
59	///
60	/// For `FABRIC`-based runtimes this would be caused by `current block number
61	/// - Era::birth block number > BlockHashCount`. (e.g. in Tetcoin `BlockHashCount` = 2400, so a
62	/// transaction with birth block number 1337 would be valid up until block number 1337 + 2400,
63	/// after which point the transaction would be considered to have an ancient birth block.)
64	AncientBirthBlock,
65	/// The transaction would exhaust the resources of current block.
66	///
67	/// The transaction might be valid, but there are not enough resources
68	/// left in the current block.
69	ExhaustsResources,
70	/// Any other custom invalid validity that is not covered by this enum.
71	Custom(u8),
72	/// An extrinsic with a Mandatory dispatch resulted in Error. This is indicative of either a
73	/// malicious validator or a buggy `provide_inherent`. In any case, it can result in dangerously
74	/// overweight blocks and therefore if found, invalidates the block.
75	BadMandatory,
76	/// A transaction with a mandatory dispatch. This is invalid; only inherent extrinsics are
77	/// allowed to have mandatory dispatches.
78	MandatoryDispatch,
79}
80
81impl InvalidTransaction {
82	/// Returns if the reason for the invalidity was block resource exhaustion.
83	pub fn exhausted_resources(&self) -> bool {
84		match self {
85			Self::ExhaustsResources => true,
86			_ => false,
87		}
88	}
89
90	/// Returns if the reason for the invalidity was a mandatory call failing.
91	pub fn was_mandatory(&self) -> bool {
92		match self {
93			Self::BadMandatory => true,
94			_ => false,
95		}
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 =>
108				"Transaction would exhaust the block limits",
109			InvalidTransaction::Payment =>
110				"Inability to pay some fees (e.g. account balance too low)",
111			InvalidTransaction::BadMandatory =>
112				"A call was labelled as mandatory, but resulted in an Error.",
113			InvalidTransaction::MandatoryDispatch =>
114				"Transaction dispatch is mandatory; transactions may not have mandatory dispatches.",
115			InvalidTransaction::Custom(_) => "InvalidTransaction custom error",
116		}
117	}
118}
119
120/// An unknown transaction validity.
121#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug)]
122#[cfg_attr(feature = "std", derive(serde::Serialize))]
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)]
146#[cfg_attr(feature = "std", derive(serde::Serialize))]
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 Into<TransactionValidity> for InvalidTransaction {
213	fn into(self) -> TransactionValidity {
214		Err(self.into())
215	}
216}
217
218impl Into<TransactionValidity> for UnknownTransaction {
219	fn into(self) -> TransactionValidity {
220		Err(self.into())
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, tetsy_util_mem::MallocSizeOf)]
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)]
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 Tetcore 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		ValidTransaction {
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 {
305			prefix: Some(prefix),
306			validity: Default::default(),
307		}
308	}
309
310	/// Combine two instances into one, as a best effort. This will take the superset of each of the
311	/// `provides` and `requires` tags, it will sum the priorities, take the minimum longevity and
312	/// the logic *And* of the propagate flags.
313	pub fn combine_with(mut self, mut other: ValidTransaction) -> Self {
314		ValidTransaction {
315			priority: self.priority.saturating_add(other.priority),
316			requires: { self.requires.append(&mut other.requires); self.requires },
317			provides: { self.provides.append(&mut other.provides); self.provides },
318			longevity: self.longevity.min(other.longevity),
319			propagate: self.propagate && other.propagate,
320		}
321	}
322}
323
324/// `ValidTransaction` builder.
325///
326///
327/// Allows to easily construct `ValidTransaction` and most importantly takes care of
328/// prefixing `requires` and `provides` tags to avoid conflicts.
329#[derive(Default, Clone, RuntimeDebug)]
330pub struct ValidTransactionBuilder {
331	prefix: Option<&'static str>,
332	validity: ValidTransaction,
333}
334
335impl ValidTransactionBuilder {
336	/// Set the priority of a transaction.
337	///
338	/// Note that the final priority for `FABRIC` is combined from all `SignedExtension`s.
339	/// Most likely for unsigned transactions you want the priority to be higher
340	/// than for regular transactions. We recommend exposing a base priority for unsigned
341	/// transactions as a runtime module parameter, so that the runtime can tune inter-module
342	/// priorities.
343	pub fn priority(mut self, priority: TransactionPriority) -> Self {
344		self.validity.priority = priority;
345		self
346	}
347
348	/// Set the longevity of a transaction.
349	///
350	/// By default the transaction will be considered valid forever and will not be revalidated
351	/// by the transaction pool. It's recommended though to set the longevity to a finite value
352	/// though. If unsure, it's also reasonable to expose this parameter via module configuration
353	/// and let the runtime decide.
354	pub fn longevity(mut self, longevity: TransactionLongevity) -> Self {
355		self.validity.longevity = longevity;
356		self
357	}
358
359	/// Set the propagate flag.
360	///
361	/// Set to `false` if the transaction is not meant to be gossiped to peers. Combined with
362	/// `TransactionSource::Local` validation it can be used to have special kind of
363	/// transactions that are only produced and included by the validator nodes.
364	pub fn propagate(mut self, propagate: bool) -> Self {
365		self.validity.propagate = propagate;
366		self
367	}
368
369	/// Add a `TransactionTag` to the set of required tags.
370	///
371	/// The tag will be encoded and prefixed with module prefix (if any).
372	/// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
373	pub fn and_requires(mut self, tag: impl Encode) -> Self {
374		self.validity.requires.push(match self.prefix.as_ref() {
375			Some(prefix) => (prefix, tag).encode(),
376			None => tag.encode(),
377		});
378		self
379	}
380
381	/// Add a `TransactionTag` to the set of provided tags.
382	///
383	/// The tag will be encoded and prefixed with module prefix (if any).
384	/// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
385	pub fn and_provides(mut self, tag: impl Encode) -> Self {
386		self.validity.provides.push(match self.prefix.as_ref() {
387			Some(prefix) => (prefix, tag).encode(),
388			None => tag.encode(),
389		});
390		self
391	}
392
393	/// Augment the builder with existing `ValidTransaction`.
394	///
395	/// This method does add the prefix to `require` or `provides` tags.
396	pub fn combine_with(mut self, validity: ValidTransaction) -> Self {
397		self.validity = core::mem::take(&mut self.validity).combine_with(validity);
398		self
399	}
400
401	/// Finalize the builder and produce `TransactionValidity`.
402	///
403	/// Note the result will always be `Ok`. Use `Into` to produce `ValidTransaction`.
404	pub fn build(self) -> TransactionValidity {
405		self.into()
406	}
407}
408
409impl From<ValidTransactionBuilder> for TransactionValidity {
410	fn from(builder: ValidTransactionBuilder) -> Self {
411		Ok(builder.into())
412	}
413}
414
415impl From<ValidTransactionBuilder> for ValidTransaction {
416	fn from(builder: ValidTransactionBuilder) -> Self {
417		builder.validity
418	}
419}
420
421
422#[cfg(test)]
423mod tests {
424	use super::*;
425
426	#[test]
427	fn should_encode_and_decode() {
428		let v: TransactionValidity = Ok(ValidTransaction {
429			priority: 5,
430			requires: vec![vec![1, 2, 3, 4]],
431			provides: vec![vec![4, 5, 6]],
432			longevity: 42,
433			propagate: false,
434		});
435
436		let encoded = v.encode();
437		assert_eq!(
438			encoded,
439			vec![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, 0, 0]
440		);
441
442		// decode back
443		assert_eq!(TransactionValidity::decode(&mut &*encoded), Ok(v));
444	}
445
446	#[test]
447	fn builder_should_prefix_the_tags() {
448		const PREFIX: &str = "test";
449		let a: ValidTransaction = ValidTransaction::with_tag_prefix(PREFIX)
450			.and_requires(1)
451			.and_requires(2)
452			.and_provides(3)
453			.and_provides(4)
454			.propagate(false)
455			.longevity(5)
456			.priority(3)
457			.priority(6)
458			.into();
459		assert_eq!(a, ValidTransaction {
460			propagate: false,
461			longevity: 5,
462			priority: 6,
463			requires: vec![(PREFIX, 1).encode(), (PREFIX, 2).encode()],
464			provides: vec![(PREFIX, 3).encode(), (PREFIX, 4).encode()],
465		});
466	}
467}