Files
biguint
chain_spec_builder
compact
fixed_point
fork_tree
frame_benchmarking
frame_benchmarking_cli
frame_election_provider_support
frame_executive
frame_metadata
frame_support
frame_support_procedural
frame_support_procedural_tools
frame_support_procedural_tools_derive
frame_support_test
frame_support_test_pallet
frame_system
frame_system_benchmarking
frame_system_rpc_runtime_api
frame_try_runtime
multiply_by_rational
node_bench
node_browser_testing
node_cli
node_executor
node_inspect
node_primitives
node_rpc
node_rpc_client
node_runtime
node_template
node_template_runtime
node_testing
normalize
pallet_assets
pallet_atomic_swap
pallet_aura
pallet_authority_discovery
pallet_authorship
pallet_babe
pallet_balances
pallet_bounties
pallet_collective
pallet_contracts
pallet_contracts_primitives
pallet_contracts_proc_macro
pallet_contracts_rpc
pallet_contracts_rpc_runtime_api
pallet_democracy
pallet_election_provider_multi_phase
pallet_elections
pallet_elections_phragmen
pallet_example
pallet_example_offchain_worker
pallet_example_parallel
pallet_gilt
pallet_grandpa
pallet_identity
pallet_im_online
pallet_indices
pallet_lottery
pallet_membership
pallet_mmr
pallet_mmr_primitives
pallet_mmr_rpc
pallet_multisig
pallet_nicks
pallet_node_authorization
pallet_offences
pallet_offences_benchmarking
pallet_proxy
pallet_randomness_collective_flip
pallet_recovery
pallet_scheduler
pallet_scored_pool
pallet_session
pallet_session_benchmarking
pallet_society
pallet_staking
pallet_staking_reward_curve
pallet_staking_reward_fn
pallet_sudo
pallet_template
pallet_timestamp
pallet_tips
pallet_transaction_payment
pallet_transaction_payment_rpc
pallet_transaction_payment_rpc_runtime_api
pallet_transaction_storage
pallet_treasury
pallet_uniques
pallet_utility
pallet_vesting
per_thing_rational
phragmen_balancing
phragmen_pjr
phragmms_balancing
reduce
remote_externalities
sc_allocator
sc_authority_discovery
sc_basic_authorship
sc_block_builder
sc_chain_spec
sc_chain_spec_derive
sc_cli
sc_client_api
sc_client_db
sc_consensus
sc_consensus_aura
sc_consensus_babe
sc_consensus_babe_rpc
sc_consensus_epochs
sc_consensus_manual_seal
sc_consensus_pow
sc_consensus_slots
sc_consensus_uncles
sc_executor
sc_executor_common
sc_executor_wasmi
sc_executor_wasmtime
sc_finality_grandpa
sc_finality_grandpa_rpc
sc_informant
sc_keystore
sc_light
sc_network
sc_network_gossip
sc_network_test
sc_offchain
sc_peerset
sc_proposer_metrics
sc_rpc
sc_rpc_api
sc_rpc_server
sc_runtime_test
sc_service
sc_service_test
sc_state_db
sc_sync_state_rpc
sc_telemetry
sc_tracing
sc_tracing_proc_macro
sc_transaction_pool
sc_transaction_pool_api
sp_api
sp_api_proc_macro
sp_application_crypto
sp_application_crypto_test
sp_arithmetic
sp_authority_discovery
sp_authorship
sp_block_builder
sp_blockchain
sp_consensus
sp_consensus_aura
sp_consensus_babe
sp_consensus_pow
sp_consensus_slots
sp_consensus_vrf
sp_core
sp_database
sp_debug_derive
sp_externalities
sp_finality_grandpa
sp_inherents
sp_io
sp_keyring
sp_keystore
sp_maybe_compressed_blob
sp_npos_elections
sp_npos_elections_solution_type
sp_offchain
sp_panic_handler
sp_rpc
sp_runtime
sp_runtime_interface
sp_runtime_interface_proc_macro
sp_runtime_interface_test
sp_runtime_interface_test_wasm
sp_runtime_interface_test_wasm_deprecated
sp_sandbox
sp_serializer
sp_session
sp_staking
sp_state_machine
sp_std
sp_storage
sp_tasks
sp_test_primitives
sp_timestamp
sp_tracing
sp_transaction_pool
sp_transaction_storage_proof
sp_trie
sp_utils
sp_version
sp_version_proc_macro
sp_wasm_interface
subkey
substrate
substrate_browser_utils
substrate_build_script_utils
substrate_frame_cli
substrate_frame_rpc_support
substrate_frame_rpc_system
substrate_prometheus_endpoint
substrate_test_client
substrate_test_runtime
substrate_test_runtime_client
substrate_test_runtime_transaction_pool
substrate_test_utils
substrate_test_utils_derive
substrate_test_utils_test_crate
substrate_wasm_builder
test_runner
test_runner_example
try_runtime_cli
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// This file is part of Substrate.

// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Transaction validity interface.

use crate::{
	codec::{Decode, Encode},
	RuntimeDebug,
};
use sp_std::prelude::*;

/// Priority for a transaction. Additive. Higher is better.
pub type TransactionPriority = u64;

/// Minimum number of blocks a transaction will remain valid for.
/// `TransactionLongevity::max_value()` means "forever".
pub type TransactionLongevity = u64;

/// Tag for a transaction. No two transactions with the same tag should be placed on-chain.
pub type TransactionTag = Vec<u8>;

/// An invalid transaction validity.
#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum InvalidTransaction {
	/// The call of the transaction is not expected.
	Call,
	/// General error to do with the inability to pay some fees (e.g. account balance too low).
	Payment,
	/// General error to do with the transaction not yet being valid (e.g. nonce too high).
	Future,
	/// General error to do with the transaction being outdated (e.g. nonce too low).
	Stale,
	/// General error to do with the transaction's proofs (e.g. signature).
	///
	/// # Possible causes
	///
	/// When using a signed extension that provides additional data for signing, it is required
	/// that the signing and the verifying side use the same additional data. Additional
	/// data will only be used to generate the signature, but will not be part of the transaction
	/// itself. As the verifying side does not know which additional data was used while signing
	/// it will only be able to assume a bad signature and cannot express a more meaningful error.
	BadProof,
	/// The transaction birth block is ancient.
	///
	/// # Possible causes
	///
	/// For `FRAME`-based runtimes this would be caused by `current block number
	/// - Era::birth block number > BlockHashCount`. (e.g. in Polkadot `BlockHashCount` = 2400, so
	///   a
	/// transaction with birth block number 1337 would be valid up until block number 1337 + 2400,
	/// after which point the transaction would be considered to have an ancient birth block.)
	AncientBirthBlock,
	/// The transaction would exhaust the resources of current block.
	///
	/// The transaction might be valid, but there are not enough resources
	/// left in the current block.
	ExhaustsResources,
	/// Any other custom invalid validity that is not covered by this enum.
	Custom(u8),
	/// An extrinsic with a Mandatory dispatch resulted in Error. This is indicative of either a
	/// malicious validator or a buggy `provide_inherent`. In any case, it can result in
	/// dangerously overweight blocks and therefore if found, invalidates the block.
	BadMandatory,
	/// A transaction with a mandatory dispatch. This is invalid; only inherent extrinsics are
	/// allowed to have mandatory dispatches.
	MandatoryDispatch,
}

impl InvalidTransaction {
	/// Returns if the reason for the invalidity was block resource exhaustion.
	pub fn exhausted_resources(&self) -> bool {
		matches!(self, Self::ExhaustsResources)
	}

	/// Returns if the reason for the invalidity was a mandatory call failing.
	pub fn was_mandatory(&self) -> bool {
		matches!(self, Self::BadMandatory)
	}
}

impl From<InvalidTransaction> for &'static str {
	fn from(invalid: InvalidTransaction) -> &'static str {
		match invalid {
			InvalidTransaction::Call => "Transaction call is not expected",
			InvalidTransaction::Future => "Transaction will be valid in the future",
			InvalidTransaction::Stale => "Transaction is outdated",
			InvalidTransaction::BadProof => "Transaction has a bad signature",
			InvalidTransaction::AncientBirthBlock => "Transaction has an ancient birth block",
			InvalidTransaction::ExhaustsResources => "Transaction would exhaust the block limits",
			InvalidTransaction::Payment =>
				"Inability to pay some fees (e.g. account balance too low)",
			InvalidTransaction::BadMandatory =>
				"A call was labelled as mandatory, but resulted in an Error.",
			InvalidTransaction::MandatoryDispatch =>
				"Transaction dispatch is mandatory; transactions may not have mandatory dispatches.",
			InvalidTransaction::Custom(_) => "InvalidTransaction custom error",
		}
	}
}

/// An unknown transaction validity.
#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum UnknownTransaction {
	/// Could not lookup some information that is required to validate the transaction.
	CannotLookup,
	/// No validator found for the given unsigned transaction.
	NoUnsignedValidator,
	/// Any other custom unknown validity that is not covered by this enum.
	Custom(u8),
}

impl From<UnknownTransaction> for &'static str {
	fn from(unknown: UnknownTransaction) -> &'static str {
		match unknown {
			UnknownTransaction::CannotLookup =>
				"Could not lookup information required to validate the transaction",
			UnknownTransaction::NoUnsignedValidator =>
				"Could not find an unsigned validator for the unsigned transaction",
			UnknownTransaction::Custom(_) => "UnknownTransaction custom error",
		}
	}
}

/// Errors that can occur while checking the validity of a transaction.
#[derive(Clone, PartialEq, Eq, Encode, Decode, Copy, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum TransactionValidityError {
	/// The transaction is invalid.
	Invalid(InvalidTransaction),
	/// Transaction validity can't be determined.
	Unknown(UnknownTransaction),
}

impl TransactionValidityError {
	/// Returns `true` if the reason for the error was block resource exhaustion.
	pub fn exhausted_resources(&self) -> bool {
		match self {
			Self::Invalid(e) => e.exhausted_resources(),
			Self::Unknown(_) => false,
		}
	}

	/// Returns `true` if the reason for the error was it being a mandatory dispatch that could not
	/// be completed successfully.
	pub fn was_mandatory(&self) -> bool {
		match self {
			Self::Invalid(e) => e.was_mandatory(),
			Self::Unknown(_) => false,
		}
	}
}

impl From<TransactionValidityError> for &'static str {
	fn from(err: TransactionValidityError) -> &'static str {
		match err {
			TransactionValidityError::Invalid(invalid) => invalid.into(),
			TransactionValidityError::Unknown(unknown) => unknown.into(),
		}
	}
}

impl From<InvalidTransaction> for TransactionValidityError {
	fn from(err: InvalidTransaction) -> Self {
		TransactionValidityError::Invalid(err)
	}
}

impl From<UnknownTransaction> for TransactionValidityError {
	fn from(err: UnknownTransaction) -> Self {
		TransactionValidityError::Unknown(err)
	}
}

#[cfg(feature = "std")]
impl std::error::Error for TransactionValidityError {
	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
		None
	}
}

#[cfg(feature = "std")]
impl std::fmt::Display for TransactionValidityError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		let s: &'static str = (*self).into();
		write!(f, "{}", s)
	}
}

/// Information on a transaction's validity and, if valid, on how it relates to other transactions.
pub type TransactionValidity = Result<ValidTransaction, TransactionValidityError>;

impl From<InvalidTransaction> for TransactionValidity {
	fn from(invalid_transaction: InvalidTransaction) -> Self {
		Err(TransactionValidityError::Invalid(invalid_transaction))
	}
}

impl From<UnknownTransaction> for TransactionValidity {
	fn from(unknown_transaction: UnknownTransaction) -> Self {
		Err(TransactionValidityError::Unknown(unknown_transaction))
	}
}

/// The source of the transaction.
///
/// Depending on the source we might apply different validation schemes.
/// For instance we can disallow specific kinds of transactions if they were not produced
/// by our local node (for instance off-chain workers).
#[derive(
	Copy, Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, parity_util_mem::MallocSizeOf,
)]
pub enum TransactionSource {
	/// Transaction is already included in block.
	///
	/// This means that we can't really tell where the transaction is coming from,
	/// since it's already in the received block. Note that the custom validation logic
	/// using either `Local` or `External` should most likely just allow `InBlock`
	/// transactions as well.
	InBlock,

	/// Transaction is coming from a local source.
	///
	/// This means that the transaction was produced internally by the node
	/// (for instance an Off-Chain Worker, or an Off-Chain Call), as opposed
	/// to being received over the network.
	Local,

	/// Transaction has been received externally.
	///
	/// This means the transaction has been received from (usually) "untrusted" source,
	/// for instance received over the network or RPC.
	External,
}

/// Information concerning a valid transaction.
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
pub struct ValidTransaction {
	/// Priority of the transaction.
	///
	/// Priority determines the ordering of two transactions that have all
	/// their dependencies (required tags) satisfied.
	pub priority: TransactionPriority,
	/// Transaction dependencies
	///
	/// A non-empty list signifies that some other transactions which provide
	/// given tags are required to be included before that one.
	pub requires: Vec<TransactionTag>,
	/// Provided tags
	///
	/// A list of tags this transaction provides. Successfully importing the transaction
	/// will enable other transactions that depend on (require) those tags to be included as well.
	/// Provided and required tags allow Substrate to build a dependency graph of transactions
	/// and import them in the right (linear) order.
	pub provides: Vec<TransactionTag>,
	/// Transaction longevity
	///
	/// Longevity describes minimum number of blocks the validity is correct.
	/// After this period transaction should be removed from the pool or revalidated.
	pub longevity: TransactionLongevity,
	/// A flag indicating if the transaction should be propagated to other peers.
	///
	/// By setting `false` here the transaction will still be considered for
	/// including in blocks that are authored on the current node, but will
	/// never be sent to other peers.
	pub propagate: bool,
}

impl Default for ValidTransaction {
	fn default() -> Self {
		Self {
			priority: 0,
			requires: vec![],
			provides: vec![],
			longevity: TransactionLongevity::max_value(),
			propagate: true,
		}
	}
}

impl ValidTransaction {
	/// Initiate `ValidTransaction` builder object with a particular prefix for tags.
	///
	/// To avoid conflicts between different parts in runtime it's recommended to build `requires`
	/// and `provides` tags with a unique prefix.
	pub fn with_tag_prefix(prefix: &'static str) -> ValidTransactionBuilder {
		ValidTransactionBuilder { prefix: Some(prefix), validity: Default::default() }
	}

	/// Combine two instances into one, as a best effort. This will take the superset of each of the
	/// `provides` and `requires` tags, it will sum the priorities, take the minimum longevity and
	/// the logic *And* of the propagate flags.
	pub fn combine_with(mut self, mut other: ValidTransaction) -> Self {
		Self {
			priority: self.priority.saturating_add(other.priority),
			requires: {
				self.requires.append(&mut other.requires);
				self.requires
			},
			provides: {
				self.provides.append(&mut other.provides);
				self.provides
			},
			longevity: self.longevity.min(other.longevity),
			propagate: self.propagate && other.propagate,
		}
	}
}

/// `ValidTransaction` builder.
///
///
/// Allows to easily construct `ValidTransaction` and most importantly takes care of
/// prefixing `requires` and `provides` tags to avoid conflicts.
#[derive(Default, Clone, RuntimeDebug)]
pub struct ValidTransactionBuilder {
	prefix: Option<&'static str>,
	validity: ValidTransaction,
}

impl ValidTransactionBuilder {
	/// Set the priority of a transaction.
	///
	/// Note that the final priority for `FRAME` is combined from all `SignedExtension`s.
	/// Most likely for unsigned transactions you want the priority to be higher
	/// than for regular transactions. We recommend exposing a base priority for unsigned
	/// transactions as a runtime module parameter, so that the runtime can tune inter-module
	/// priorities.
	pub fn priority(mut self, priority: TransactionPriority) -> Self {
		self.validity.priority = priority;
		self
	}

	/// Set the longevity of a transaction.
	///
	/// By default the transaction will be considered valid forever and will not be revalidated
	/// by the transaction pool. It's recommended though to set the longevity to a finite value
	/// though. If unsure, it's also reasonable to expose this parameter via module configuration
	/// and let the runtime decide.
	pub fn longevity(mut self, longevity: TransactionLongevity) -> Self {
		self.validity.longevity = longevity;
		self
	}

	/// Set the propagate flag.
	///
	/// Set to `false` if the transaction is not meant to be gossiped to peers. Combined with
	/// `TransactionSource::Local` validation it can be used to have special kind of
	/// transactions that are only produced and included by the validator nodes.
	pub fn propagate(mut self, propagate: bool) -> Self {
		self.validity.propagate = propagate;
		self
	}

	/// Add a `TransactionTag` to the set of required tags.
	///
	/// The tag will be encoded and prefixed with module prefix (if any).
	/// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
	pub fn and_requires(mut self, tag: impl Encode) -> Self {
		self.validity.requires.push(match self.prefix.as_ref() {
			Some(prefix) => (prefix, tag).encode(),
			None => tag.encode(),
		});
		self
	}

	/// Add a `TransactionTag` to the set of provided tags.
	///
	/// The tag will be encoded and prefixed with module prefix (if any).
	/// If you'd rather add a raw `require` tag, consider using `#combine_with` method.
	pub fn and_provides(mut self, tag: impl Encode) -> Self {
		self.validity.provides.push(match self.prefix.as_ref() {
			Some(prefix) => (prefix, tag).encode(),
			None => tag.encode(),
		});
		self
	}

	/// Augment the builder with existing `ValidTransaction`.
	///
	/// This method does add the prefix to `require` or `provides` tags.
	pub fn combine_with(mut self, validity: ValidTransaction) -> Self {
		self.validity = core::mem::take(&mut self.validity).combine_with(validity);
		self
	}

	/// Finalize the builder and produce `TransactionValidity`.
	///
	/// Note the result will always be `Ok`. Use `Into` to produce `ValidTransaction`.
	pub fn build(self) -> TransactionValidity {
		self.into()
	}
}

impl From<ValidTransactionBuilder> for TransactionValidity {
	fn from(builder: ValidTransactionBuilder) -> Self {
		Ok(builder.into())
	}
}

impl From<ValidTransactionBuilder> for ValidTransaction {
	fn from(builder: ValidTransactionBuilder) -> Self {
		builder.validity
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn should_encode_and_decode() {
		let v: TransactionValidity = Ok(ValidTransaction {
			priority: 5,
			requires: vec![vec![1, 2, 3, 4]],
			provides: vec![vec![4, 5, 6]],
			longevity: 42,
			propagate: false,
		});

		let encoded = v.encode();
		assert_eq!(
			encoded,
			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
			]
		);

		// decode back
		assert_eq!(TransactionValidity::decode(&mut &*encoded), Ok(v));
	}

	#[test]
	fn builder_should_prefix_the_tags() {
		const PREFIX: &str = "test";
		let a: ValidTransaction = ValidTransaction::with_tag_prefix(PREFIX)
			.and_requires(1)
			.and_requires(2)
			.and_provides(3)
			.and_provides(4)
			.propagate(false)
			.longevity(5)
			.priority(3)
			.priority(6)
			.into();
		assert_eq!(
			a,
			ValidTransaction {
				propagate: false,
				longevity: 5,
				priority: 6,
				requires: vec![(PREFIX, 1).encode(), (PREFIX, 2).encode()],
				provides: vec![(PREFIX, 3).encode(), (PREFIX, 4).encode()],
			}
		);
	}
}