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