reth_transaction_pool/error.rs
1//! Transaction pool errors
2
3use std::any::Any;
4
5use alloy_eips::eip4844::BlobTransactionValidationError;
6use alloy_primitives::{Address, TxHash, U256};
7use reth_primitives_traits::transaction::error::InvalidTransactionError;
8
9/// Transaction pool result type.
10pub type PoolResult<T> = Result<T, PoolError>;
11
12/// Errors that can happen while recovering a raw transaction into a pool transaction.
13#[derive(Debug, thiserror::Error)]
14pub enum RawPoolTransactionError {
15 /// The raw transaction data is empty.
16 #[error("empty transaction data")]
17 EmptyRawTransactionData,
18 /// Decoding the signed transaction failed.
19 #[error("failed to decode signed transaction")]
20 FailedToDecodeSignedTransaction,
21 /// The transaction signature is invalid.
22 #[error("invalid transaction signature")]
23 InvalidTransactionSignature,
24 /// Any other error that occurred while recovering the raw pool transaction.
25 #[error(transparent)]
26 Other(#[from] Box<dyn core::error::Error + Send + Sync>),
27}
28
29impl RawPoolTransactionError {
30 /// Creates a new [`RawPoolTransactionError::Other`] variant.
31 pub fn other(error: impl Into<Box<dyn core::error::Error + Send + Sync>>) -> Self {
32 Self::Other(error.into())
33 }
34}
35
36/// A trait for additional errors that can be thrown by the transaction pool.
37///
38/// For example during validation
39/// [`TransactionValidator::validate_transaction`](crate::validate::TransactionValidator::validate_transaction)
40pub trait PoolTransactionError: core::error::Error + Send + Sync {
41 /// Returns `true` if the error was caused by a transaction that is considered bad in the
42 /// context of the transaction pool and warrants peer penalization.
43 ///
44 /// See [`PoolError::is_bad_transaction`].
45 fn is_bad_transaction(&self) -> bool;
46
47 /// Returns a reference to `self` as a `&dyn Any`, enabling downcasting.
48 fn as_any(&self) -> &dyn Any;
49}
50
51// Needed for `#[error(transparent)]`
52impl core::error::Error for Box<dyn PoolTransactionError> {
53 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
54 (**self).source()
55 }
56}
57
58/// Transaction pool error.
59#[derive(Debug, thiserror::Error)]
60#[error("[{hash}]: {kind}")]
61pub struct PoolError {
62 /// The transaction hash that caused the error.
63 pub hash: TxHash,
64 /// The error kind.
65 pub kind: PoolErrorKind,
66}
67
68/// Transaction pool error kind.
69#[derive(Debug, thiserror::Error)]
70pub enum PoolErrorKind {
71 /// Same transaction already imported
72 #[error("already imported")]
73 AlreadyImported,
74 /// Thrown if a replacement transaction's gas price is below the already imported transaction
75 #[error("insufficient gas price to replace existing transaction")]
76 ReplacementUnderpriced,
77 /// The fee cap of the transaction is below the minimum fee cap determined by the protocol
78 #[error("transaction feeCap {0} below chain minimum")]
79 FeeCapBelowMinimumProtocolFeeCap(u128),
80 /// Thrown when the number of unique transactions of a sender exceeded the slot capacity.
81 #[error("rejected due to {0} being identified as a spammer")]
82 SpammerExceededCapacity(Address),
83 /// Thrown when a new transaction is added to the pool, but then immediately discarded to
84 /// respect the size limits of the pool.
85 #[error("transaction discarded outright due to pool size constraints")]
86 DiscardedOnInsert,
87 /// Thrown when the transaction is considered invalid.
88 #[error(transparent)]
89 InvalidTransaction(#[from] InvalidPoolTransactionError),
90 /// Thrown if the mutual exclusivity constraint (blob vs normal transaction) is violated.
91 #[error("transaction type {1} conflicts with existing transaction for {0}")]
92 ExistingConflictingTransactionType(Address, u8),
93 /// Any other error that occurred while inserting/validating a transaction. e.g. IO database
94 /// error
95 #[error(transparent)]
96 Other(#[from] Box<dyn core::error::Error + Send + Sync>),
97}
98
99// === impl PoolError ===
100
101impl PoolError {
102 /// Creates a new pool error.
103 pub fn new(hash: TxHash, kind: impl Into<PoolErrorKind>) -> Self {
104 Self { hash, kind: kind.into() }
105 }
106
107 /// Creates a new pool error with the `Other` kind.
108 pub fn other(
109 hash: TxHash,
110 error: impl Into<Box<dyn core::error::Error + Send + Sync>>,
111 ) -> Self {
112 Self { hash, kind: PoolErrorKind::Other(error.into()) }
113 }
114
115 /// Returns `true` if the error was caused by a transaction that is considered bad in the
116 /// context of the transaction pool and warrants peer penalization.
117 ///
118 /// Not all error variants are caused by the incorrect composition of the transaction (See also
119 /// [`InvalidPoolTransactionError`]) and can be caused by the current state of the transaction
120 /// pool. For example the transaction pool is already full or the error was caused by an
121 /// internal error, such as database errors.
122 ///
123 /// This function returns true only if the transaction will never make it into the pool because
124 /// its composition is invalid and the original sender should have detected this as well. This
125 /// is used to determine whether the original sender should be penalized for sending an
126 /// erroneous transaction.
127 #[inline]
128 pub fn is_bad_transaction(&self) -> bool {
129 #[expect(clippy::match_same_arms)]
130 match &self.kind {
131 PoolErrorKind::AlreadyImported => {
132 // already imported but not bad
133 false
134 }
135 PoolErrorKind::ReplacementUnderpriced => {
136 // already imported but not bad
137 false
138 }
139 PoolErrorKind::FeeCapBelowMinimumProtocolFeeCap(_) => {
140 // fee cap of the tx below the technical minimum determined by the protocol, see
141 // [MINIMUM_PROTOCOL_FEE_CAP](alloy_primitives::constants::MIN_PROTOCOL_BASE_FEE)
142 // although this transaction will always be invalid, we do not want to penalize the
143 // sender because this check simply could not be implemented by the client
144 false
145 }
146 PoolErrorKind::SpammerExceededCapacity(_) => {
147 // the sender exceeded the slot capacity, we should not penalize the peer for
148 // sending the tx because we don't know if all the transactions are sent from the
149 // same peer, there's also a chance that old transactions haven't been cleared yet
150 // (pool lags behind) and old transaction still occupy a slot in the pool
151 false
152 }
153 PoolErrorKind::DiscardedOnInsert => {
154 // valid tx but dropped due to size constraints
155 false
156 }
157 PoolErrorKind::InvalidTransaction(err) => {
158 // transaction rejected because it violates constraints
159 err.is_bad_transaction()
160 }
161 PoolErrorKind::Other(_) => {
162 // internal error unrelated to the transaction
163 false
164 }
165 PoolErrorKind::ExistingConflictingTransactionType(_, _) => {
166 // this is not a protocol error but an implementation error since the pool enforces
167 // exclusivity (blob vs normal tx) for all senders
168 false
169 }
170 }
171 }
172
173 /// Returns `true` if this is a blob sidecar error that should NOT be cached as a bad import.
174 ///
175 /// The transaction hash may be valid — the issue is peer-specific (e.g. malformed sidecar
176 /// data), so we penalize the peer but allow re-fetching from other peers.
177 #[inline]
178 pub const fn is_bad_blob_sidecar(&self) -> bool {
179 match &self.kind {
180 PoolErrorKind::InvalidTransaction(err) => err.is_bad_blob_sidecar(),
181 _ => false,
182 }
183 }
184}
185
186/// Represents all errors that can happen when validating transactions for the pool for EIP-4844
187/// transactions
188#[derive(Debug, thiserror::Error)]
189pub enum Eip4844PoolTransactionError {
190 /// Thrown if we're unable to find the blob for a transaction that was previously extracted
191 #[error("blob sidecar not found for EIP4844 transaction")]
192 MissingEip4844BlobSidecar,
193 /// Thrown if an EIP-4844 transaction without any blobs arrives
194 #[error("blobless blob transaction")]
195 NoEip4844Blobs,
196 /// Thrown if an EIP-4844 transaction arrives with too many blobs
197 #[error("too many blobs in transaction: have {have}, permitted {permitted}")]
198 TooManyEip4844Blobs {
199 /// Number of blobs the transaction has
200 have: u64,
201 /// Number of maximum blobs the transaction can have
202 permitted: u64,
203 },
204 /// Thrown if validating the blob sidecar for the transaction failed.
205 #[error(transparent)]
206 InvalidEip4844Blob(BlobTransactionValidationError),
207 /// EIP-4844 transactions are only accepted if they're gapless, meaning the previous nonce of
208 /// the transaction (`tx.nonce -1`) must either be in the pool or match the on chain nonce of
209 /// the sender.
210 ///
211 /// This error is thrown on validation if a valid blob transaction arrives with a nonce that
212 /// would introduce gap in the nonce sequence.
213 #[error("nonce too high")]
214 Eip4844NonceGap,
215 /// Thrown if blob transaction has an EIP-7594 style sidecar before Osaka.
216 #[error("unexpected eip-7594 sidecar before osaka")]
217 UnexpectedEip7594SidecarBeforeOsaka,
218 /// Thrown if blob transaction has an EIP-4844 style sidecar after Osaka.
219 #[error("unexpected eip-4844 sidecar after osaka")]
220 UnexpectedEip4844SidecarAfterOsaka,
221 /// Thrown if blob transaction has an EIP-7594 style sidecar but EIP-7594 support is disabled.
222 #[error("eip-7594 sidecar disallowed")]
223 Eip7594SidecarDisallowed,
224 /// Thrown if a blob transaction fetched as cells keeps fewer than the 64 columns needed to
225 /// rebuild its blobs, since the pool doesn't hold partial sidecars yet.
226 #[error("too few eip-7594 cells to rebuild the blobs")]
227 TooFewEip7594Cells,
228}
229
230/// Represents all errors that can happen when validating transactions for the pool for EIP-7702
231/// transactions
232#[derive(Debug, thiserror::Error)]
233pub enum Eip7702PoolTransactionError {
234 /// Thrown if the transaction has no items in its authorization list
235 #[error("no items in authorization list for EIP7702 transaction")]
236 MissingEip7702AuthorizationList,
237 /// Returned when a transaction with a nonce
238 /// gap is received from accounts with a deployed delegation or pending delegation.
239 #[error("gapped-nonce tx from delegated accounts")]
240 OutOfOrderTxFromDelegated,
241 /// Returned when the maximum number of in-flight
242 /// transactions is reached for specific accounts.
243 #[error("in-flight transaction limit reached for delegated accounts")]
244 InflightTxLimitReached,
245 /// Returned if a transaction has an authorization
246 /// signed by an address which already has in-flight transactions known to the
247 /// pool.
248 #[error("authority already reserved")]
249 AuthorityReserved,
250}
251
252/// Represents errors that can happen when validating transactions for the pool
253///
254/// See [`TransactionValidator`](crate::TransactionValidator).
255#[derive(Debug, thiserror::Error)]
256pub enum InvalidPoolTransactionError {
257 /// Hard consensus errors
258 #[error(transparent)]
259 Consensus(#[from] InvalidTransactionError),
260 /// Thrown when a new transaction is added to the pool, but then immediately discarded to
261 /// respect the size limits of the pool.
262 #[error("transaction's gas limit {0} exceeds block's gas limit {1}")]
263 ExceedsGasLimit(u64, u64),
264 /// Thrown when a transaction's gas limit exceeds the configured maximum per-transaction limit.
265 #[error("transaction's gas limit {0} exceeds maximum per-transaction gas limit {1}")]
266 MaxTxGasLimitExceeded(u64, u64),
267 /// Thrown when a new transaction is added to the pool, but then immediately discarded to
268 /// respect the tx fee exceeds the configured cap
269 #[error("tx fee ({max_tx_fee_wei} wei) exceeds the configured cap ({tx_fee_cap_wei} wei)")]
270 ExceedsFeeCap {
271 /// max fee in wei of new tx submitted to the pool (e.g. 0.11534 ETH)
272 max_tx_fee_wei: u128,
273 /// configured tx fee cap in wei (e.g. 1.0 ETH)
274 tx_fee_cap_wei: u128,
275 },
276 /// Thrown when a new transaction is added to the pool, but then immediately discarded to
277 /// respect the `max_init_code_size`.
278 #[error("transaction's input size {0} exceeds max_init_code_size {1}")]
279 ExceedsMaxInitCodeSize(usize, usize),
280 /// Thrown if the input data of a transaction is greater
281 /// than some meaningful limit a user might use. This is not a consensus error
282 /// making the transaction invalid, rather a DOS protection.
283 #[error("oversized data: transaction size {size}, limit {limit}")]
284 OversizedData {
285 /// Size of the transaction/input data that exceeded the limit.
286 size: usize,
287 /// Configured limit that was exceeded.
288 limit: usize,
289 },
290 /// Thrown if the transaction's fee is below the minimum fee
291 #[error("transaction underpriced")]
292 Underpriced,
293 /// Thrown if the transaction's would require an account to be overdrawn
294 #[error("transaction overdraws from account, balance: {balance}, cost: {cost}")]
295 Overdraft {
296 /// Cost transaction is allowed to consume. See `reth_transaction_pool::PoolTransaction`.
297 cost: U256,
298 /// Balance of account.
299 balance: U256,
300 },
301 /// EIP-2681 error thrown if the nonce is higher or equal than `U64::max`
302 /// `<https://eips.ethereum.org/EIPS/eip-2681>`
303 #[error("nonce exceeds u64 limit")]
304 Eip2681,
305 /// EIP-4844 related errors
306 #[error(transparent)]
307 Eip4844(#[from] Eip4844PoolTransactionError),
308 /// EIP-7702 related errors
309 #[error(transparent)]
310 Eip7702(#[from] Eip7702PoolTransactionError),
311 /// Any other error that occurred while inserting/validating that is transaction specific
312 #[error(transparent)]
313 Other(Box<dyn PoolTransactionError>),
314 /// The transaction is specified to use less gas than required to start the
315 /// invocation.
316 #[error("intrinsic gas too low")]
317 IntrinsicGasTooLow,
318 /// The transaction priority fee is below the minimum required priority fee.
319 #[error("transaction priority fee below minimum required priority fee {minimum_priority_fee}")]
320 PriorityFeeBelowMinimum {
321 /// Minimum required priority fee.
322 minimum_priority_fee: u128,
323 },
324}
325
326// === impl InvalidPoolTransactionError ===
327
328impl InvalidPoolTransactionError {
329 /// Returns a new [`InvalidPoolTransactionError::Other`] instance with the given
330 /// [`PoolTransactionError`].
331 pub fn other<E: PoolTransactionError + 'static>(err: E) -> Self {
332 Self::Other(Box::new(err))
333 }
334
335 /// Returns `true` if the error was caused by a transaction that is considered bad in the
336 /// context of the transaction pool and warrants peer penalization.
337 ///
338 /// See [`PoolError::is_bad_transaction`].
339 #[expect(clippy::match_same_arms)]
340 #[inline]
341 fn is_bad_transaction(&self) -> bool {
342 match self {
343 Self::Consensus(err) => {
344 // transaction considered invalid by the consensus rules
345 // We do not consider the following errors to be erroneous transactions, since they
346 // depend on dynamic environmental conditions and should not be assumed to have been
347 // intentionally caused by the sender
348 match err {
349 InvalidTransactionError::InsufficientFunds { .. } |
350 InvalidTransactionError::NonceNotConsistent { .. } => {
351 // transaction could just have arrived late/early
352 false
353 }
354 InvalidTransactionError::GasTooLow |
355 InvalidTransactionError::GasTooHigh |
356 InvalidTransactionError::TipAboveFeeCap => {
357 // these are technically not invalid
358 false
359 }
360 InvalidTransactionError::FeeCapTooLow => {
361 // dynamic, but not used during validation
362 false
363 }
364 InvalidTransactionError::Eip2930Disabled |
365 InvalidTransactionError::Eip1559Disabled |
366 InvalidTransactionError::Eip4844Disabled |
367 InvalidTransactionError::Eip7702Disabled => {
368 // settings
369 false
370 }
371 InvalidTransactionError::OldLegacyChainId |
372 InvalidTransactionError::ChainIdMismatch |
373 InvalidTransactionError::GasUintOverflow |
374 InvalidTransactionError::TxTypeNotSupported |
375 InvalidTransactionError::SignerAccountHasBytecode |
376 InvalidTransactionError::GasLimitTooHigh => true,
377 }
378 }
379 Self::ExceedsGasLimit(_, _) => true,
380 Self::MaxTxGasLimitExceeded(_, _) => {
381 // local setting
382 false
383 }
384 Self::ExceedsFeeCap { max_tx_fee_wei: _, tx_fee_cap_wei: _ } => {
385 // local setting
386 false
387 }
388 Self::ExceedsMaxInitCodeSize(_, _) => true,
389 Self::OversizedData { .. } => {
390 // local setting
391 false
392 }
393 Self::Underpriced => {
394 // local setting
395 false
396 }
397 Self::IntrinsicGasTooLow => true,
398 Self::Overdraft { .. } => false,
399 Self::Other(err) => err.is_bad_transaction(),
400 Self::Eip2681 => true,
401 Self::Eip4844(eip4844_err) => {
402 match eip4844_err {
403 Eip4844PoolTransactionError::MissingEip4844BlobSidecar => {
404 // this is only reachable when blob transactions are reinjected and we're
405 // unable to find the previously extracted blob
406 false
407 }
408 Eip4844PoolTransactionError::InvalidEip4844Blob(_) => {
409 // This is only reachable when the blob is invalid
410 true
411 }
412 Eip4844PoolTransactionError::Eip4844NonceGap => {
413 // it is possible that the pool sees `nonce n` before `nonce n-1` and this
414 // is only thrown for valid(good) blob transactions
415 false
416 }
417 Eip4844PoolTransactionError::NoEip4844Blobs => {
418 // this is a malformed transaction and should not be sent over the network
419 true
420 }
421 Eip4844PoolTransactionError::TooManyEip4844Blobs { .. } => {
422 // this is a malformed transaction and should not be sent over the network
423 true
424 }
425 Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka |
426 Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka |
427 Eip4844PoolTransactionError::Eip7594SidecarDisallowed |
428 Eip4844PoolTransactionError::TooFewEip7594Cells => {
429 // for now we do not want to penalize peers for broadcasting different
430 // sidecars
431 false
432 }
433 }
434 }
435 Self::Eip7702(eip7702_err) => match eip7702_err {
436 Eip7702PoolTransactionError::MissingEip7702AuthorizationList => {
437 // as EIP-7702 specifies, 7702 transactions must have an non-empty authorization
438 // list so this is a malformed transaction and should not be
439 // sent over the network
440 true
441 }
442 Eip7702PoolTransactionError::OutOfOrderTxFromDelegated => false,
443 Eip7702PoolTransactionError::InflightTxLimitReached => false,
444 Eip7702PoolTransactionError::AuthorityReserved => false,
445 },
446 Self::PriorityFeeBelowMinimum { .. } => false,
447 }
448 }
449
450 /// Returns `true` if this is a blob sidecar error (e.g. invalid proof, missing sidecar).
451 ///
452 /// These errors indicate the sidecar data from a specific peer was bad, but the transaction
453 /// hash itself may be valid when fetched from another peer.
454 #[inline]
455 pub const fn is_bad_blob_sidecar(&self) -> bool {
456 matches!(
457 self,
458 Self::Eip4844(
459 Eip4844PoolTransactionError::MissingEip4844BlobSidecar |
460 Eip4844PoolTransactionError::InvalidEip4844Blob(_) |
461 Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka |
462 Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka |
463 Eip4844PoolTransactionError::Eip7594SidecarDisallowed
464 )
465 )
466 }
467
468 /// Returns true if this is a [`Self::Consensus`] variant.
469 pub const fn as_consensus(&self) -> Option<&InvalidTransactionError> {
470 match self {
471 Self::Consensus(err) => Some(err),
472 _ => None,
473 }
474 }
475
476 /// Returns true if this is [`InvalidTransactionError::NonceNotConsistent`] and the
477 /// transaction's nonce is lower than the state's.
478 pub fn is_nonce_too_low(&self) -> bool {
479 match self {
480 Self::Consensus(err) => err.is_nonce_too_low(),
481 _ => false,
482 }
483 }
484
485 /// Returns `true` if an import failed due to an oversized transaction
486 pub const fn is_oversized(&self) -> bool {
487 matches!(self, Self::OversizedData { .. })
488 }
489
490 /// Returns `true` if an import failed due to nonce gap.
491 pub const fn is_nonce_gap(&self) -> bool {
492 matches!(self, Self::Consensus(InvalidTransactionError::NonceNotConsistent { .. })) ||
493 matches!(self, Self::Eip4844(Eip4844PoolTransactionError::Eip4844NonceGap))
494 }
495
496 /// Returns the arbitrary error if it is [`InvalidPoolTransactionError::Other`]
497 pub fn as_other(&self) -> Option<&dyn PoolTransactionError> {
498 match self {
499 Self::Other(err) => Some(&**err),
500 _ => None,
501 }
502 }
503
504 /// Returns a reference to the [`InvalidPoolTransactionError::Other`] value if this type is a
505 /// [`InvalidPoolTransactionError::Other`] of that type. Returns None otherwise.
506 pub fn downcast_other_ref<T: core::error::Error + 'static>(&self) -> Option<&T> {
507 let other = self.as_other()?;
508 other.as_any().downcast_ref()
509 }
510
511 /// Returns true if the this type is a [`InvalidPoolTransactionError::Other`] of that error
512 /// type. Returns false otherwise.
513 pub fn is_other<T: core::error::Error + 'static>(&self) -> bool {
514 self.as_other().is_some_and(|err| err.as_any().is::<T>())
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521
522 #[derive(thiserror::Error, Debug)]
523 #[error("err")]
524 struct E;
525
526 impl PoolTransactionError for E {
527 fn is_bad_transaction(&self) -> bool {
528 false
529 }
530
531 fn as_any(&self) -> &dyn Any {
532 self
533 }
534 }
535
536 #[test]
537 fn other_downcast() {
538 let err = InvalidPoolTransactionError::Other(Box::new(E));
539 assert!(err.is_other::<E>());
540
541 assert!(err.downcast_other_ref::<E>().is_some());
542 }
543
544 #[test]
545 fn bad_blob_sidecar_detection() {
546 let err = PoolError::new(
547 TxHash::ZERO,
548 InvalidPoolTransactionError::Eip4844(Eip4844PoolTransactionError::InvalidEip4844Blob(
549 BlobTransactionValidationError::InvalidProof,
550 )),
551 );
552
553 assert!(err.is_bad_blob_sidecar());
554
555 let err = PoolError::new(
556 TxHash::ZERO,
557 InvalidPoolTransactionError::Eip4844(
558 Eip4844PoolTransactionError::MissingEip4844BlobSidecar,
559 ),
560 );
561
562 assert!(err.is_bad_blob_sidecar());
563
564 let err = PoolError::new(
565 TxHash::ZERO,
566 InvalidPoolTransactionError::Eip4844(Eip4844PoolTransactionError::NoEip4844Blobs),
567 );
568
569 assert!(!err.is_bad_blob_sidecar());
570 }
571
572 #[test]
573 fn oversized_data_is_not_bad_transaction() {
574 let err = InvalidPoolTransactionError::OversizedData { size: 2048, limit: 1024 };
575 assert!(err.is_oversized());
576 assert!(!err.is_bad_transaction());
577 assert!(!PoolError::new(TxHash::ZERO, err).is_bad_transaction());
578 }
579}