Skip to main content

reth_transaction_pool/pool/
mod.rs

1//! Transaction Pool internals.
2//!
3//! Incoming transactions are validated before they enter the pool first. The validation outcome can
4//! have 3 states:
5//!
6//!  1. Transaction can _never_ be valid
7//!  2. Transaction is _currently_ valid
8//!  3. Transaction is _currently_ invalid, but could potentially become valid in the future
9//!
10//! However, (2.) and (3.) of a transaction can only be determined on the basis of the current
11//! state, whereas (1.) holds indefinitely. This means once the state changes (2.) and (3.) the
12//! state of a transaction needs to be reevaluated again.
13//!
14//! The transaction pool is responsible for storing new, valid transactions and providing the next
15//! best transactions sorted by their priority. Where priority is determined by the transaction's
16//! score ([`TransactionOrdering`]).
17//!
18//! Furthermore, the following characteristics fall under (3.):
19//!
20//!  a) Nonce of a transaction is higher than the expected nonce for the next transaction of its
21//! sender. A distinction is made here whether multiple transactions from the same sender have
22//! gapless nonce increments.
23//!
24//!  a)(1) If _no_ transaction is missing in a chain of multiple
25//! transactions from the same sender (all nonce in row), all of them can in principle be executed
26//! on the current state one after the other.
27//!
28//!  a)(2) If there's a nonce gap, then all
29//! transactions after the missing transaction are blocked until the missing transaction arrives.
30//!
31//!  b) Transaction does not meet the dynamic fee cap requirement introduced by EIP-1559: The
32//! fee cap of the transaction needs to be no less than the base fee of block.
33//!
34//!
35//! In essence the transaction pool is made of three separate sub-pools:
36//!
37//!  - Pending Pool: Contains all transactions that are valid on the current state and satisfy (3.
38//!    a)(1): _No_ nonce gaps. A _pending_ transaction is considered _ready_ when it has the lowest
39//!    nonce of all transactions from the same sender. Once a _ready_ transaction with nonce `n` has
40//!    been executed, the next highest transaction from the same sender `n + 1` becomes ready.
41//!
42//!  - Queued Pool: Contains all transactions that are currently blocked by missing transactions:
43//!    (3. a)(2): _With_ nonce gaps or due to lack of funds.
44//!
45//!  - Basefee Pool: To account for the dynamic base fee requirement (3. b) which could render an
46//!    EIP-1559 and all subsequent transactions of the sender currently invalid.
47//!
48//! The classification of transactions is always dependent on the current state that is changed as
49//! soon as a new block is mined. Once a new block is mined, the account changeset must be applied
50//! to the transaction pool.
51//!
52//!
53//! Depending on the use case, consumers of the [`TransactionPool`](crate::traits::TransactionPool)
54//! are interested in (2.) and/or (3.).
55
56//! A generic [`TransactionPool`](crate::traits::TransactionPool) that only handles transactions.
57//!
58//! This Pool maintains two separate sub-pools for (2.) and (3.)
59//!
60//! ## Terminology
61//!
62//!  - _Pending_: pending transactions are transactions that fall under (2.). These transactions can
63//!    currently be executed and are stored in the pending sub-pool
64//!  - _Queued_: queued transactions are transactions that fall under category (3.). Those
65//!    transactions are _currently_ waiting for state changes that eventually move them into
66//!    category (2.) and become pending.
67
68use crate::{
69    blobstore::{BlobStore, PooledBlobSidecar},
70    error::{PoolError, PoolErrorKind, PoolResult},
71    identifier::{SenderId, SenderIdentifiers, TransactionId},
72    metrics::BlobStoreMetrics,
73    pool::{
74        listener::{
75            BlobTransactionSidecarListener, PendingTransactionHashListener, PoolEventBroadcast,
76            TransactionListener,
77        },
78        state::SubPool,
79        txpool::{SenderInfo, TxPool},
80        update::UpdateOutcome,
81    },
82    traits::{
83        AllPoolTransactions, BestTransactionsAttributes, BlockInfo, GetPooledTransactionLimit,
84        NewBlobSidecar, PoolSize, PoolTransaction, PropagatedTransactions, TransactionOrigin,
85    },
86    validate::{TransactionValidationOutcome, ValidPoolTransaction, ValidTransaction},
87    CanonicalStateUpdate, EthPoolTransaction, PoolConfig, TransactionOrdering,
88    TransactionValidator,
89};
90
91use alloy_primitives::{
92    map::{AddressSet, B256Set},
93    Address, TxHash, B256,
94};
95use parking_lot::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
96use reth_eth_wire_types::HandleMempoolData;
97use reth_execution_types::ChangedAccount;
98
99use alloy_eips::{eip7594::BlobTransactionSidecarVariant, Typed2718};
100use reth_primitives_traits::Recovered;
101use rustc_hash::FxHashMap;
102use std::{
103    fmt,
104    sync::{
105        atomic::{AtomicBool, Ordering},
106        Arc,
107    },
108    time::Instant,
109};
110use tokio::sync::mpsc;
111use tracing::{debug, trace, warn};
112mod events;
113pub use best::{BestTransactionFilter, BestTransactionsWithPrioritizedSenders};
114pub use blob::{blob_tx_priority, fee_delta, BlobOrd, BlobTransactions};
115pub use events::{FullTransactionEvent, NewTransactionEvent, TransactionEvent};
116pub use listener::{AllTransactionsEvents, TransactionEvents, TransactionListenerKind};
117pub use parked::{BasefeeOrd, ParkedOrd, ParkedPool, QueuedOrd};
118pub use pending::PendingPool;
119
120mod best;
121pub use best::BestTransactions;
122
123mod blob;
124pub mod listener;
125mod parked;
126pub mod pending;
127pub mod size;
128pub(crate) mod state;
129pub mod txpool;
130mod update;
131
132/// Bound on number of pending transactions from `reth_network::TransactionsManager` to buffer.
133pub const PENDING_TX_LISTENER_BUFFER_SIZE: usize = 2048;
134/// Bound on number of new transactions from `reth_network::TransactionsManager` to buffer.
135pub const NEW_TX_LISTENER_BUFFER_SIZE: usize = 1024;
136
137const BLOB_SIDECAR_LISTENER_BUFFER_SIZE: usize = 512;
138
139/// Transaction pool internals.
140pub struct PoolInner<V, T, S>
141where
142    T: TransactionOrdering,
143{
144    /// Internal mapping of addresses to plain ints.
145    identifiers: RwLock<SenderIdentifiers>,
146    /// Transaction validator.
147    validator: V,
148    /// Storage for blob transactions
149    blob_store: S,
150    /// The internal pool that manages all transactions.
151    pool: RwLock<TxPool<T>>,
152    /// Pool settings.
153    config: PoolConfig,
154    /// Manages listeners for transaction state change events.
155    event_listener: RwLock<PoolEventBroadcast<T::Transaction>>,
156    /// Tracks whether any event listeners have ever been installed.
157    has_event_listeners: AtomicBool,
158    /// Listeners for new _full_ pending transactions.
159    pending_transaction_listener: RwLock<Vec<PendingTransactionHashListener>>,
160    /// Listeners for new transactions added to the pool.
161    transaction_listener: RwLock<Vec<TransactionListener<T::Transaction>>>,
162    /// Listener for new blob transaction sidecars added to the pool.
163    blob_transaction_sidecar_listener: Mutex<Vec<BlobTransactionSidecarListener>>,
164    /// Metrics for the blob store
165    blob_store_metrics: BlobStoreMetrics,
166}
167
168// === impl PoolInner ===
169
170impl<V, T, S> PoolInner<V, T, S>
171where
172    V: TransactionValidator,
173    T: TransactionOrdering<Transaction = <V as TransactionValidator>::Transaction>,
174    S: BlobStore,
175{
176    /// Create a new transaction pool instance.
177    pub fn new(validator: V, ordering: T, blob_store: S, config: PoolConfig) -> Self {
178        Self {
179            identifiers: Default::default(),
180            validator,
181            event_listener: Default::default(),
182            has_event_listeners: AtomicBool::new(false),
183            pool: RwLock::new(TxPool::new(ordering, config.clone())),
184            pending_transaction_listener: Default::default(),
185            transaction_listener: Default::default(),
186            blob_transaction_sidecar_listener: Default::default(),
187            config,
188            blob_store,
189            blob_store_metrics: Default::default(),
190        }
191    }
192
193    /// Returns the configured blob store.
194    pub const fn blob_store(&self) -> &S {
195        &self.blob_store
196    }
197
198    /// Returns stats about the size of the pool.
199    pub fn size(&self) -> PoolSize {
200        self.get_pool_data().size()
201    }
202
203    /// Returns the currently tracked block
204    pub fn block_info(&self) -> BlockInfo {
205        self.get_pool_data().block_info()
206    }
207    /// Sets the currently tracked block.
208    ///
209    /// This will also notify subscribers about any transactions that were promoted to the pending
210    /// pool due to fee changes.
211    pub fn set_block_info(&self, info: BlockInfo) {
212        let outcome = self.pool.write().set_block_info(info);
213
214        // Notify subscribers about promoted transactions due to fee changes
215        self.notify_on_transaction_updates(outcome.promoted, outcome.discarded);
216    }
217
218    /// Returns the internal [`SenderId`] for this address, allocating a new mapping when the
219    /// address is first observed.
220    ///
221    /// This must only be used on paths that intentionally begin tracking a sender, such as
222    /// transaction insertion. Read-only lookups should prefer [`Self::sender_id`] to avoid
223    /// growing the sender-id map for unknown addresses.
224    pub fn get_sender_id(&self, addr: Address) -> SenderId {
225        self.identifiers.write().sender_id_or_create(addr)
226    }
227
228    /// Returns the internal [`SenderId`] for this address if it is already tracked.
229    ///
230    /// Unlike [`Self::get_sender_id`], this never allocates a new sender mapping and is therefore
231    /// suitable for read-only queries or best-effort cleanup on unknown addresses.
232    pub fn sender_id(&self, addr: &Address) -> Option<SenderId> {
233        self.identifiers.read().sender_id(addr)
234    }
235
236    /// Returns the internal [`SenderId`]s for the given addresses.
237    pub fn get_sender_ids(&self, addrs: impl IntoIterator<Item = Address>) -> Vec<SenderId> {
238        self.identifiers.write().sender_ids_or_create(addrs)
239    }
240
241    /// Returns all senders in the pool
242    pub fn unique_senders(&self) -> AddressSet {
243        self.get_pool_data().unique_senders()
244    }
245
246    /// Converts the changed accounts to a map of sender ids to sender info (internal identifier
247    /// used for __tracked__ accounts)
248    fn changed_senders(
249        &self,
250        accs: impl Iterator<Item = ChangedAccount>,
251    ) -> FxHashMap<SenderId, SenderInfo> {
252        let identifiers = self.identifiers.read();
253        accs.into_iter()
254            .filter_map(|acc| {
255                let ChangedAccount { address, nonce, balance } = acc;
256                let sender_id = identifiers.sender_id(&address)?;
257                Some((sender_id, SenderInfo { state_nonce: nonce, balance }))
258            })
259            .collect()
260    }
261
262    /// Get the config the pool was configured with.
263    pub const fn config(&self) -> &PoolConfig {
264        &self.config
265    }
266
267    /// Get the validator reference.
268    pub const fn validator(&self) -> &V {
269        &self.validator
270    }
271
272    /// Adds a new transaction listener to the pool that gets notified about every new _pending_
273    /// transaction inserted into the pool
274    pub fn add_pending_listener(&self, kind: TransactionListenerKind) -> mpsc::Receiver<TxHash> {
275        let (sender, rx) = mpsc::channel(self.config.pending_tx_listener_buffer_size);
276        let listener = PendingTransactionHashListener { sender, kind };
277
278        let mut listeners = self.pending_transaction_listener.write();
279        // Clean up dead listeners before adding new one
280        listeners.retain(|l| !l.sender.is_closed());
281        listeners.push(listener);
282
283        rx
284    }
285
286    /// Adds a new transaction listener to the pool that gets notified about every new transaction.
287    pub fn add_new_transaction_listener(
288        &self,
289        kind: TransactionListenerKind,
290    ) -> mpsc::Receiver<NewTransactionEvent<T::Transaction>> {
291        let (sender, rx) = mpsc::channel(self.config.new_tx_listener_buffer_size);
292        let listener = TransactionListener { sender, kind };
293
294        let mut listeners = self.transaction_listener.write();
295        // Clean up dead listeners before adding new one
296        listeners.retain(|l| !l.sender.is_closed());
297        listeners.push(listener);
298
299        rx
300    }
301    /// Adds a new blob sidecar listener to the pool that gets notified about every new
302    /// eip4844 transaction's blob sidecar.
303    pub fn add_blob_sidecar_listener(&self) -> mpsc::Receiver<NewBlobSidecar> {
304        let (sender, rx) = mpsc::channel(BLOB_SIDECAR_LISTENER_BUFFER_SIZE);
305        let listener = BlobTransactionSidecarListener { sender };
306        self.blob_transaction_sidecar_listener.lock().push(listener);
307        rx
308    }
309
310    /// If the pool contains the transaction, this adds a new listener that gets notified about
311    /// transaction events.
312    pub fn add_transaction_event_listener(&self, tx_hash: TxHash) -> Option<TransactionEvents> {
313        if !self.get_pool_data().contains(&tx_hash) {
314            return None
315        }
316        Some(self.subscribe_transaction_events(tx_hash))
317    }
318
319    /// Adds a listener for events of the given transaction without checking that this pool
320    /// holds it.
321    ///
322    /// For [`TransactionPool`](crate::TransactionPool) implementations that keep some
323    /// transactions outside this pool and report their events through
324    /// [`Self::notify_event_listeners`]. Only subscribe to transactions the caller holds: a
325    /// subscription is removed once its hash gets a final event.
326    pub fn subscribe_transaction_events(&self, tx_hash: TxHash) -> TransactionEvents {
327        let events = self.event_listener.write().subscribe(tx_hash);
328        self.mark_event_listener_installed();
329        events
330    }
331
332    /// Adds a listener for all transaction events.
333    pub fn add_all_transactions_event_listener(&self) -> AllTransactionsEvents<T::Transaction> {
334        let mut listener = self.event_listener.write();
335        let events = listener.subscribe_all();
336        self.mark_event_listener_installed();
337        events
338    }
339
340    #[inline]
341    fn has_event_listeners(&self) -> bool {
342        self.has_event_listeners.load(Ordering::Relaxed)
343    }
344
345    #[inline]
346    fn mark_event_listener_installed(&self) {
347        self.has_event_listeners.store(true, Ordering::Relaxed);
348    }
349
350    #[inline]
351    fn update_event_listener_state(&self, listener: &PoolEventBroadcast<T::Transaction>) {
352        if listener.is_empty() {
353            self.has_event_listeners.store(false, Ordering::Relaxed);
354        }
355    }
356
357    #[inline]
358    fn with_event_listener<F>(&self, emit: F)
359    where
360        F: FnOnce(&mut PoolEventBroadcast<T::Transaction>),
361    {
362        if !self.has_event_listeners() {
363            return
364        }
365        let mut listener = self.event_listener.write();
366        if !listener.is_empty() {
367            emit(&mut listener);
368        }
369        self.update_event_listener_state(&listener);
370    }
371
372    /// Returns a read lock to the pool's data.
373    pub fn get_pool_data(&self) -> RwLockReadGuard<'_, TxPool<T>> {
374        self.pool.read()
375    }
376
377    /// Returns transactions in the pool that can be propagated
378    pub fn pooled_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
379        let mut out = Vec::new();
380        self.append_pooled_transactions(&mut out);
381        out
382    }
383
384    /// Returns hashes of transactions in the pool that can be propagated.
385    pub fn pooled_transactions_hashes(&self) -> Vec<TxHash> {
386        let mut out = Vec::new();
387        self.append_pooled_transactions_hashes(&mut out);
388        out
389    }
390
391    /// Returns only the first `max` transactions in the pool that can be propagated.
392    pub fn pooled_transactions_max(
393        &self,
394        max: usize,
395    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
396        if max == 0 {
397            return Vec::new()
398        }
399
400        let pool = self.get_pool_data();
401        let mut out = Vec::with_capacity(max.min(pool.all().len()));
402        out.extend(pool.all().transactions_iter().filter(|tx| tx.propagate).take(max).cloned());
403        out
404    }
405
406    /// Extends the given vector with all transactions in the pool that can be propagated.
407    pub fn append_pooled_transactions(
408        &self,
409        out: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
410    ) {
411        out.extend(
412            self.get_pool_data().all().transactions_iter().filter(|tx| tx.propagate).cloned(),
413        );
414    }
415
416    /// Extends the given vector with pooled transactions for the given hashes that are allowed to
417    /// be propagated.
418    pub fn append_pooled_transaction_elements(
419        &self,
420        tx_hashes: &[TxHash],
421        limit: GetPooledTransactionLimit,
422        out: &mut Vec<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>,
423    ) where
424        <V as TransactionValidator>::Transaction: EthPoolTransaction,
425    {
426        let transactions = self.get_all_propagatable(tx_hashes);
427        let mut size = 0;
428        for transaction in transactions {
429            let encoded_len = transaction.encoded_length();
430            let Some(pooled) = self.to_pooled_transaction(transaction) else {
431                continue;
432            };
433
434            size += encoded_len;
435            out.push(pooled.into_inner());
436
437            if limit.exceeds(size) {
438                break
439            }
440        }
441    }
442
443    /// Extends the given vector with the hashes of all transactions in the pool that can be
444    /// propagated.
445    pub fn append_pooled_transactions_hashes(&self, out: &mut Vec<TxHash>) {
446        out.extend(
447            self.get_pool_data()
448                .all()
449                .transactions_iter()
450                .filter(|tx| tx.propagate)
451                .map(|tx| *tx.hash()),
452        );
453    }
454
455    /// Extends the given vector with only the first `max` transactions in the pool that can be
456    /// propagated.
457    pub fn append_pooled_transactions_max(
458        &self,
459        max: usize,
460        out: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
461    ) {
462        out.extend(
463            self.get_pool_data()
464                .all()
465                .transactions_iter()
466                .filter(|tx| tx.propagate)
467                .take(max)
468                .cloned(),
469        );
470    }
471
472    /// Returns only the first `max` hashes of transactions in the pool that can be propagated.
473    pub fn pooled_transactions_hashes_max(&self, max: usize) -> Vec<TxHash> {
474        if max == 0 {
475            return Vec::new();
476        }
477
478        let pool = self.get_pool_data();
479        let mut out = Vec::with_capacity(max.min(pool.all().len()));
480        out.extend(
481            pool.all().transactions_iter().filter(|tx| tx.propagate).take(max).map(|tx| *tx.hash()),
482        );
483        out
484    }
485
486    /// Converts the internally tracked transaction to the pooled format.
487    ///
488    /// If the transaction is an EIP-4844 transaction, the blob sidecar is fetched from the blob
489    /// store and attached to the transaction.
490    fn to_pooled_transaction(
491        &self,
492        transaction: Arc<ValidPoolTransaction<T::Transaction>>,
493    ) -> Option<Recovered<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>>
494    where
495        <V as TransactionValidator>::Transaction: EthPoolTransaction,
496    {
497        if transaction.is_eip4844() {
498            let sidecar = self.blob_store.get(*transaction.hash()).ok()??;
499            transaction.transaction.clone().try_into_pooled_eip4844(sidecar)
500        } else {
501            transaction
502                .transaction
503                .clone_into_pooled()
504                .inspect_err(|err| {
505                    debug!(
506                        target: "txpool", %err,
507                        "failed to convert transaction to pooled element; skipping",
508                    );
509                })
510                .ok()
511        }
512    }
513
514    /// Returns pooled transactions for the given transaction hashes that are allowed to be
515    /// propagated.
516    pub fn get_pooled_transaction_elements(
517        &self,
518        tx_hashes: Vec<TxHash>,
519        limit: GetPooledTransactionLimit,
520    ) -> Vec<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>
521    where
522        <V as TransactionValidator>::Transaction: EthPoolTransaction,
523    {
524        let mut elements = Vec::new();
525        self.append_pooled_transaction_elements(&tx_hashes, limit, &mut elements);
526        elements.shrink_to_fit();
527        elements
528    }
529
530    /// Returns converted pooled transaction for the given transaction hash.
531    pub fn get_pooled_transaction_element(
532        &self,
533        tx_hash: TxHash,
534    ) -> Option<Recovered<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>>
535    where
536        <V as TransactionValidator>::Transaction: EthPoolTransaction,
537    {
538        self.get(&tx_hash).and_then(|tx| self.to_pooled_transaction(tx))
539    }
540
541    /// Updates the entire pool after a new block was executed.
542    pub fn on_canonical_state_change(&self, update: CanonicalStateUpdate<'_, V::Block>) {
543        trace!(target: "txpool", ?update, "updating pool on canonical state change");
544
545        let block_info = update.block_info();
546        let CanonicalStateUpdate {
547            new_tip, changed_accounts, mined_transactions, update_kind, ..
548        } = update;
549        self.validator.on_new_head_block(new_tip);
550
551        let changed_senders = self.changed_senders(changed_accounts.into_iter());
552
553        // update the pool
554        let outcome = self.pool.write().on_canonical_state_change(
555            block_info,
556            mined_transactions,
557            changed_senders,
558            update_kind,
559        );
560
561        // This will discard outdated transactions based on the account's nonce
562        self.delete_discarded_blobs(outcome.discarded.iter());
563
564        // notify listeners about updates
565        self.notify_on_new_state(outcome);
566    }
567
568    /// Performs account updates on the pool.
569    ///
570    /// This will either promote or discard transactions based on the new account state.
571    ///
572    /// This should be invoked when the pool drifted and accounts are updated manually
573    pub fn update_accounts(&self, accounts: Vec<ChangedAccount>) {
574        let changed_senders = self.changed_senders(accounts.into_iter());
575        let UpdateOutcome { promoted, discarded } =
576            self.pool.write().update_accounts(changed_senders);
577
578        self.notify_on_transaction_updates(promoted, discarded);
579    }
580
581    /// Add a single validated transaction into the pool.
582    ///
583    /// Returns the outcome and optionally metadata to be processed after the pool lock is
584    /// released.
585    ///
586    /// Note: this is only used internally by [`Self::add_transactions()`], all new transaction(s)
587    /// come in through that function, either as a batch or `std::iter::once`.
588    fn add_transaction(
589        &self,
590        pool: &mut RwLockWriteGuard<'_, TxPool<T>>,
591        origin: TransactionOrigin,
592        tx: TransactionValidationOutcome<T::Transaction>,
593        timestamp: Instant,
594    ) -> (PoolResult<AddedTransactionOutcome>, Option<AddedTransactionMeta<T::Transaction>>) {
595        match tx {
596            TransactionValidationOutcome::Valid {
597                balance,
598                state_nonce,
599                transaction,
600                propagate,
601                bytecode_hash,
602                authorities,
603            } => {
604                let sender_id = self.get_sender_id(transaction.sender());
605                let transaction_id = TransactionId::new(sender_id, transaction.nonce());
606
607                // split the valid transaction and the blob sidecar if it has any
608                let (transaction, blob_sidecar) = match transaction {
609                    ValidTransaction::Valid(tx) => (tx, None),
610                    ValidTransaction::ValidWithSidecar { transaction, sidecar } => {
611                        debug_assert!(
612                            transaction.is_eip4844(),
613                            "validator returned sidecar for non EIP-4844 transaction"
614                        );
615                        (transaction, Some(sidecar))
616                    }
617                };
618
619                let tx = ValidPoolTransaction {
620                    transaction,
621                    transaction_id,
622                    propagate,
623                    timestamp,
624                    origin,
625                    authority_ids: authorities.map(|auths| self.get_sender_ids(auths)),
626                };
627
628                let added = match pool.add_transaction(tx, balance, state_nonce, bytecode_hash) {
629                    Ok(added) => added,
630                    Err(err) => return (Err(err), None),
631                };
632                let hash = *added.hash();
633                let state = added.transaction_state();
634
635                let meta = AddedTransactionMeta { added, blob_sidecar };
636
637                (Ok(AddedTransactionOutcome { hash, state }), Some(meta))
638            }
639            TransactionValidationOutcome::Invalid(tx, err) => {
640                self.with_event_listener(|listener| listener.invalid(tx.hash()));
641                (Err(PoolError::new(*tx.hash(), err)), None)
642            }
643            TransactionValidationOutcome::Error(tx_hash, err) => {
644                self.with_event_listener(|listener| listener.discarded(&tx_hash));
645                (Err(PoolError::other(tx_hash, err)), None)
646            }
647        }
648    }
649
650    /// Adds a transaction and returns the event stream.
651    pub fn add_transaction_and_subscribe(
652        &self,
653        origin: TransactionOrigin,
654        tx: TransactionValidationOutcome<T::Transaction>,
655    ) -> PoolResult<TransactionEvents> {
656        let listener = {
657            let mut listener = self.event_listener.write();
658            let events = listener.subscribe(tx.tx_hash());
659            self.mark_event_listener_installed();
660            events
661        };
662        let mut results = self.add_transactions(origin, std::iter::once(tx));
663        results.pop().expect("result length is the same as the input")?;
664        Ok(listener)
665    }
666
667    /// Adds all transactions in the iterator to the pool, returning a list of results.
668    ///
669    /// Convenience method that assigns the same origin to all transactions. Delegates to
670    /// [`Self::add_transactions_with_origins`].
671    pub fn add_transactions(
672        &self,
673        origin: TransactionOrigin,
674        transactions: impl IntoIterator<Item = TransactionValidationOutcome<T::Transaction>>,
675    ) -> Vec<PoolResult<AddedTransactionOutcome>> {
676        self.add_transactions_with_origins(transactions.into_iter().map(|tx| (origin, tx)))
677    }
678
679    /// Adds all transactions in the iterator to the pool, each with its own
680    /// [`TransactionOrigin`], returning a list of results.
681    pub fn add_transactions_with_origins(
682        &self,
683        transactions: impl IntoIterator<
684            Item = (TransactionOrigin, TransactionValidationOutcome<T::Transaction>),
685        >,
686    ) -> Vec<PoolResult<AddedTransactionOutcome>> {
687        let transactions = transactions.into_iter();
688        let mut added_metas = Vec::with_capacity(transactions.size_hint().0);
689
690        // Collect results and metadata while holding the pool write lock
691        let (mut results, added_metas, discarded) = {
692            let mut pool = self.pool.write();
693            let timestamp = Instant::now();
694
695            let results = transactions
696                .map(|(origin, tx)| {
697                    let (result, meta) = self.add_transaction(&mut pool, origin, tx, timestamp);
698
699                    // Only collect metadata for successful insertions
700                    if result.is_ok() &&
701                        let Some(meta) = meta
702                    {
703                        added_metas.push(meta);
704                    }
705
706                    result
707                })
708                .collect::<Vec<_>>();
709
710            // Enforce the pool size limits if at least one transaction was added successfully
711            let discarded = if results.iter().any(Result::is_ok) {
712                let discarded = pool.discard_worst();
713                pool.update_size_metrics();
714                discarded
715            } else {
716                Default::default()
717            };
718
719            (results, added_metas, discarded)
720        };
721
722        for meta in added_metas {
723            self.on_added_transaction(meta);
724        }
725
726        if !discarded.is_empty() {
727            // Delete any blobs associated with discarded blob transactions
728            self.delete_discarded_blobs(discarded.iter());
729            self.with_event_listener(|listener| listener.discarded_many(&discarded));
730
731            // Linear search avoids allocating a hash set for small eviction batches.
732            const MAX_LINEAR_SEARCH_DISCARDS: usize = 4;
733            let discarded_hashes = (discarded.len() > MAX_LINEAR_SEARCH_DISCARDS)
734                .then(|| discarded.iter().map(|tx| *tx.hash()).collect::<B256Set>());
735            let is_discarded = |hash: &TxHash| match &discarded_hashes {
736                Some(hashes) => hashes.contains(hash),
737                None => discarded.iter().any(|tx| tx.hash() == hash),
738            };
739
740            // A newly added transaction may be immediately discarded, so we need to
741            // adjust the result here
742            for res in &mut results {
743                if let Ok(AddedTransactionOutcome { hash, .. }) = res &&
744                    is_discarded(hash)
745                {
746                    *res = Err(PoolError::new(*hash, PoolErrorKind::DiscardedOnInsert))
747                }
748            }
749        };
750
751        results
752    }
753
754    /// Process a transaction that was added to the pool.
755    ///
756    /// Performs blob storage operations and sends all notifications. This should be called
757    /// after the pool write lock has been released to avoid blocking pool operations.
758    fn on_added_transaction(&self, mut meta: AddedTransactionMeta<T::Transaction>) {
759        // Handle blob sidecar storage and notifications for EIP-4844 transactions
760        if let Some(sidecar) = meta.blob_sidecar {
761            let hash = *meta.added.hash();
762            self.on_new_blob_sidecar(&hash, &sidecar);
763            self.insert_blob(hash, sidecar);
764        }
765
766        // Delete replaced blob sidecar if any
767        if let Some(replaced) = meta.added.replaced_blob_transaction() {
768            debug!(target: "txpool", "[{:?}] delete replaced blob sidecar", replaced);
769            self.delete_blob(replaced);
770        }
771
772        // Delete discarded blob sidecars if any, this doesnt do any IO.
773        if let Some(discarded) = meta.added.discarded_transactions() {
774            self.delete_discarded_blobs(discarded.iter());
775        }
776
777        // Notify pending transaction listeners
778        if let Some(pending) = meta.added.as_pending() {
779            self.on_new_pending_transaction(pending);
780        }
781
782        // A parked insertion can promote older transactions when validation observes newer
783        // account state. Notify those promotions independently of the inserted transaction.
784        let promoted = meta.added.take_parked_promoted();
785        if !promoted.is_empty() {
786            self.notify_on_transaction_updates(promoted, Vec::new());
787        }
788
789        // Notify event listeners
790        self.notify_event_listeners(&meta.added);
791
792        // Notify new transaction listeners
793        self.on_new_transaction(meta.added.into_new_transaction_event());
794    }
795
796    /// Notify all listeners about a new pending transaction.
797    ///
798    /// See also [`Self::add_pending_listener`]
799    ///
800    /// CAUTION: This function is only intended to be used manually in order to use this type's
801    /// pending transaction receivers when manually implementing the
802    /// [`TransactionPool`](crate::TransactionPool) trait for a custom pool implementation
803    /// [`TransactionPool::pending_transactions_listener_for`](crate::TransactionPool).
804    pub fn on_new_pending_transaction(&self, pending: &AddedPendingTransaction<T::Transaction>) {
805        let mut needs_cleanup = false;
806
807        {
808            let listeners = self.pending_transaction_listener.read();
809            for listener in listeners.iter() {
810                if !listener.send_all(pending.pending_transactions(listener.kind)) {
811                    needs_cleanup = true;
812                }
813            }
814        }
815
816        // Clean up dead listeners if we detected any closed channels
817        if needs_cleanup {
818            self.pending_transaction_listener
819                .write()
820                .retain(|listener| !listener.sender.is_closed());
821        }
822    }
823
824    /// Notify all listeners about a newly inserted pending transaction.
825    ///
826    /// See also [`Self::add_new_transaction_listener`]
827    ///
828    /// CAUTION: This function is only intended to be used manually in order to use this type's
829    /// transaction receivers when manually implementing the
830    /// [`TransactionPool`](crate::TransactionPool) trait for a custom pool implementation
831    /// [`TransactionPool::new_transactions_listener_for`](crate::TransactionPool).
832    pub fn on_new_transaction(&self, event: NewTransactionEvent<T::Transaction>) {
833        let mut needs_cleanup = false;
834
835        {
836            let listeners = self.transaction_listener.read();
837            for listener in listeners.iter() {
838                if listener.kind.is_propagate_only() && !event.transaction.propagate {
839                    if listener.sender.is_closed() {
840                        needs_cleanup = true;
841                    }
842                    // Skip non-propagate transactions for propagate-only listeners
843                    continue
844                }
845
846                if !listener.send(event.clone()) {
847                    needs_cleanup = true;
848                }
849            }
850        }
851
852        // Clean up dead listeners if we detected any closed channels
853        if needs_cleanup {
854            self.transaction_listener.write().retain(|listener| !listener.sender.is_closed());
855        }
856    }
857
858    /// Notify all listeners about a blob sidecar for a newly inserted blob (eip4844) transaction.
859    fn on_new_blob_sidecar(&self, tx_hash: &TxHash, sidecar: &BlobTransactionSidecarVariant) {
860        let mut sidecar_listeners = self.blob_transaction_sidecar_listener.lock();
861        if sidecar_listeners.is_empty() {
862            return
863        }
864        let sidecar = Arc::new(sidecar.clone());
865        sidecar_listeners.retain_mut(|listener| {
866            let new_blob_event = NewBlobSidecar { tx_hash: *tx_hash, sidecar: sidecar.clone() };
867            match listener.sender.try_send(new_blob_event) {
868                Ok(()) => true,
869                Err(err) => {
870                    if matches!(err, mpsc::error::TrySendError::Full(_)) {
871                        debug!(
872                            target: "txpool",
873                            "[{:?}] failed to send blob sidecar; channel full",
874                            sidecar,
875                        );
876                        true
877                    } else {
878                        false
879                    }
880                }
881            }
882        })
883    }
884
885    /// Notifies transaction listeners about changes once a block was processed.
886    fn notify_on_new_state(&self, outcome: OnNewCanonicalStateOutcome<T::Transaction>) {
887        trace!(target: "txpool", promoted=outcome.promoted.len(), discarded= outcome.discarded.len() ,"notifying listeners on state change");
888
889        // notify about promoted pending transactions - emit hashes
890        let mut needs_pending_cleanup = false;
891        {
892            let listeners = self.pending_transaction_listener.read();
893            for listener in listeners.iter() {
894                if !listener.send_all(outcome.pending_transactions(listener.kind)) {
895                    needs_pending_cleanup = true;
896                }
897            }
898        }
899        if needs_pending_cleanup {
900            self.pending_transaction_listener.write().retain(|l| !l.sender.is_closed());
901        }
902
903        // emit full transactions
904        let mut needs_tx_cleanup = false;
905        {
906            let listeners = self.transaction_listener.read();
907            for listener in listeners.iter() {
908                if !listener.send_all(outcome.full_pending_transactions(listener.kind)) {
909                    needs_tx_cleanup = true;
910                }
911            }
912        }
913        if needs_tx_cleanup {
914            self.transaction_listener.write().retain(|l| !l.sender.is_closed());
915        }
916
917        let OnNewCanonicalStateOutcome { mined, promoted, discarded, block_hash } = outcome;
918
919        // broadcast specific transaction events
920        self.with_event_listener(|listener| {
921            for tx in &mined {
922                listener.mined(tx, block_hash);
923            }
924            for tx in &promoted {
925                listener.pending(tx.hash(), None);
926            }
927            for tx in &discarded {
928                listener.discarded(tx.hash());
929            }
930        })
931    }
932
933    /// Notifies all listeners about the transaction movements.
934    ///
935    /// This will emit events according to the provided changes.
936    ///
937    /// CAUTION: This function is only intended to be used manually in order to use this type's
938    /// [`TransactionEvents`] receivers when manually implementing the
939    /// [`TransactionPool`](crate::TransactionPool) trait for a custom pool implementation
940    /// [`TransactionPool::transaction_event_listener`](crate::TransactionPool).
941    pub fn notify_on_transaction_updates(
942        &self,
943        promoted: Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
944        discarded: Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
945    ) {
946        // Notify about promoted pending transactions (similar to notify_on_new_state)
947        if !promoted.is_empty() {
948            let mut needs_pending_cleanup = false;
949            {
950                let listeners = self.pending_transaction_listener.read();
951                for listener in listeners.iter() {
952                    let promoted_hashes = promoted.iter().filter_map(|tx| {
953                        if listener.kind.is_propagate_only() && !tx.propagate {
954                            None
955                        } else {
956                            Some(*tx.hash())
957                        }
958                    });
959                    if !listener.send_all(promoted_hashes) {
960                        needs_pending_cleanup = true;
961                    }
962                }
963            }
964            if needs_pending_cleanup {
965                self.pending_transaction_listener.write().retain(|l| !l.sender.is_closed());
966            }
967
968            // in this case we should also emit promoted transactions in full
969            let mut needs_tx_cleanup = false;
970            {
971                let listeners = self.transaction_listener.read();
972                for listener in listeners.iter() {
973                    let promoted_txs = promoted.iter().filter_map(|tx| {
974                        if listener.kind.is_propagate_only() && !tx.propagate {
975                            None
976                        } else {
977                            Some(NewTransactionEvent::pending(tx.clone()))
978                        }
979                    });
980                    if !listener.send_all(promoted_txs) {
981                        needs_tx_cleanup = true;
982                    }
983                }
984            }
985            if needs_tx_cleanup {
986                self.transaction_listener.write().retain(|l| !l.sender.is_closed());
987            }
988        }
989
990        self.with_event_listener(|listener| {
991            for tx in &promoted {
992                listener.pending(tx.hash(), None);
993            }
994            for tx in &discarded {
995                listener.discarded(tx.hash());
996            }
997        });
998
999        if !discarded.is_empty() {
1000            // This deletes outdated blob txs from the blob store, based on the account's nonce.
1001            // This is called during txpool maintenance when the pool drifted.
1002            self.delete_discarded_blobs(discarded.iter());
1003        }
1004    }
1005
1006    /// Fire events for the newly added transaction if there are any.
1007    ///
1008    /// See also [`Self::add_transaction_event_listener`].
1009    ///
1010    /// CAUTION: This function is only intended to be used manually in order to use this type's
1011    /// [`TransactionEvents`] receivers when manually implementing the
1012    /// [`TransactionPool`](crate::TransactionPool) trait for a custom pool implementation
1013    /// [`TransactionPool::transaction_event_listener`](crate::TransactionPool).
1014    pub fn notify_event_listeners(&self, tx: &AddedTransaction<T::Transaction>) {
1015        self.with_event_listener(|listener| match tx {
1016            AddedTransaction::Pending(tx) => {
1017                let AddedPendingTransaction { transaction, promoted, discarded, replaced } = tx;
1018
1019                listener.pending(transaction.hash(), replaced.clone());
1020                for tx in promoted {
1021                    listener.pending(tx.hash(), None);
1022                }
1023                for tx in discarded {
1024                    listener.discarded(tx.hash());
1025                }
1026            }
1027            AddedTransaction::Parked { transaction, replaced, queued_reason, .. } => {
1028                listener.queued(transaction.hash(), queued_reason.clone());
1029                if let Some(replaced) = replaced {
1030                    listener.replaced(replaced.clone(), *transaction.hash());
1031                }
1032            }
1033        });
1034    }
1035
1036    /// Returns an iterator that yields transactions that are ready to be included in the block.
1037    pub fn best_transactions(&self) -> BestTransactions<T> {
1038        self.get_pool_data().best_transactions()
1039    }
1040
1041    /// Returns an iterator that yields transactions that are ready to be included in the block with
1042    /// the given base fee and optional blob fee attributes.
1043    pub fn best_transactions_with_attributes(
1044        &self,
1045        best_transactions_attributes: BestTransactionsAttributes,
1046    ) -> Box<dyn crate::traits::BestTransactions<Item = Arc<ValidPoolTransaction<T::Transaction>>>>
1047    {
1048        self.get_pool_data().best_transactions_with_attributes(best_transactions_attributes)
1049    }
1050
1051    /// Returns only the first `max` transactions in the pending pool.
1052    pub fn pending_transactions_max(
1053        &self,
1054        max: usize,
1055    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1056        self.get_pool_data().pending_transactions_iter().take(max).collect()
1057    }
1058
1059    /// Returns all transactions from the pending sub-pool
1060    pub fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1061        self.get_pool_data().pending_transactions()
1062    }
1063
1064    /// Returns all transactions from parked pools
1065    pub fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1066        self.get_pool_data().queued_transactions()
1067    }
1068
1069    /// Returns all transactions in the pool
1070    pub fn all_transactions(&self) -> AllPoolTransactions<T::Transaction> {
1071        let pool = self.get_pool_data();
1072        AllPoolTransactions {
1073            pending: pool.pending_transactions(),
1074            queued: pool.queued_transactions(),
1075        }
1076    }
1077
1078    /// Returns all transactions of the given sender, collected under a single read guard so that
1079    /// both sides reflect the same pool state.
1080    pub fn all_transactions_by_sender(
1081        &self,
1082        sender: Address,
1083    ) -> AllPoolTransactions<T::Transaction> {
1084        let Some(sender_id) = self.sender_id(&sender) else { return Default::default() };
1085        let pool = self.get_pool_data();
1086        AllPoolTransactions {
1087            pending: pool.pending_txs_by_sender(sender_id),
1088            queued: pool.queued_txs_by_sender(sender_id),
1089        }
1090    }
1091
1092    /// Returns _all_ transactions in the pool
1093    pub fn all_transaction_hashes(&self) -> Vec<TxHash> {
1094        self.get_pool_data().all().transactions_iter().map(|tx| *tx.hash()).collect()
1095    }
1096
1097    /// Removes and returns all matching transactions from the pool.
1098    ///
1099    /// This behaves as if the transactions got discarded (_not_ mined), effectively introducing a
1100    /// nonce gap for the given transactions.
1101    pub fn remove_transactions(
1102        &self,
1103        hashes: Vec<TxHash>,
1104    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1105        if hashes.is_empty() {
1106            return Vec::new()
1107        }
1108        let removed = self.pool.write().remove_transactions(hashes);
1109
1110        self.with_event_listener(|listener| listener.discarded_many(&removed));
1111
1112        removed
1113    }
1114
1115    /// Removes and returns all matching transactions and their dependent transactions from the
1116    /// pool.
1117    pub fn remove_transactions_and_descendants(
1118        &self,
1119        hashes: Vec<TxHash>,
1120    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1121        if hashes.is_empty() {
1122            return Vec::new()
1123        }
1124        let removed = self.pool.write().remove_transactions_and_descendants(hashes);
1125
1126        self.with_event_listener(|listener| {
1127            for tx in &removed {
1128                listener.discarded(tx.hash());
1129            }
1130        });
1131
1132        removed
1133    }
1134
1135    /// Removes and returns all transactions by the specified sender from the pool.
1136    pub fn remove_transactions_by_sender(
1137        &self,
1138        sender: Address,
1139    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1140        let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1141        let removed = self.pool.write().remove_transactions_by_sender(sender_id);
1142
1143        self.with_event_listener(|listener| listener.discarded_many(&removed));
1144
1145        removed
1146    }
1147
1148    /// Prunes and returns all matching transactions from the pool.
1149    ///
1150    /// This removes the transactions as if they were mined: descendant transactions are **not**
1151    /// parked and remain eligible for inclusion.
1152    pub fn prune_transactions(
1153        &self,
1154        hashes: Vec<TxHash>,
1155    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1156        if hashes.is_empty() {
1157            return Vec::new()
1158        }
1159
1160        self.pool.write().prune_transactions(hashes)
1161    }
1162
1163    /// Retains only transactions that are not present in the pool.
1164    pub fn retain_unknown<A>(&self, announcement: &mut A)
1165    where
1166        A: HandleMempoolData,
1167    {
1168        if announcement.is_empty() {
1169            return
1170        }
1171        let pool = self.get_pool_data();
1172        announcement.retain_by_hash(|tx| !pool.contains(tx))
1173    }
1174
1175    /// Retains only transactions that are present in the pool.
1176    pub fn retain_contains<A>(&self, announcement: &mut A)
1177    where
1178        A: HandleMempoolData,
1179    {
1180        if announcement.is_empty() {
1181            return
1182        }
1183        let pool = self.get_pool_data();
1184        announcement.retain_by_hash(|tx| pool.contains(tx))
1185    }
1186
1187    /// Returns the transaction by hash.
1188    pub fn get(&self, tx_hash: &TxHash) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1189        self.get_pool_data().get(tx_hash)
1190    }
1191
1192    /// Returns all transactions of the address
1193    pub fn get_transactions_by_sender(
1194        &self,
1195        sender: Address,
1196    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1197        let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1198        self.get_pool_data().get_transactions_by_sender(sender_id)
1199    }
1200
1201    /// Returns a pending transaction sent by the given sender with the given nonce.
1202    pub fn get_pending_transaction_by_sender_and_nonce(
1203        &self,
1204        sender: Address,
1205        nonce: u64,
1206    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1207        let sender_id = self.sender_id(&sender)?;
1208        self.get_pool_data().get_pending_transaction_by_sender_and_nonce(sender_id, nonce)
1209    }
1210
1211    /// Returns all queued transactions of the address by sender
1212    pub fn get_queued_transactions_by_sender(
1213        &self,
1214        sender: Address,
1215    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1216        let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1217        self.get_pool_data().queued_txs_by_sender(sender_id)
1218    }
1219
1220    /// Returns all pending transactions filtered by predicate
1221    pub fn pending_transactions_with_predicate(
1222        &self,
1223        predicate: impl FnMut(&ValidPoolTransaction<T::Transaction>) -> bool,
1224    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1225        self.get_pool_data().pending_transactions_with_predicate(predicate)
1226    }
1227
1228    /// Returns all pending transactions of the address by sender
1229    pub fn get_pending_transactions_by_sender(
1230        &self,
1231        sender: Address,
1232    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1233        let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1234        self.get_pending_transactions_by_sender_id(sender_id)
1235    }
1236
1237    /// Returns all pending transactions for a resolved sender ID.
1238    pub fn get_pending_transactions_by_sender_id(
1239        &self,
1240        sender_id: SenderId,
1241    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1242        self.get_pool_data().pending_txs_by_sender(sender_id)
1243    }
1244
1245    /// Returns the highest transaction of the address
1246    pub fn get_highest_transaction_by_sender(
1247        &self,
1248        sender: Address,
1249    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1250        let sender_id = self.sender_id(&sender)?;
1251        self.get_highest_transaction_by_sender_id(sender_id)
1252    }
1253
1254    /// Returns the highest transaction for a resolved sender ID.
1255    pub fn get_highest_transaction_by_sender_id(
1256        &self,
1257        sender_id: SenderId,
1258    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1259        self.get_pool_data().get_highest_transaction_by_sender(sender_id)
1260    }
1261
1262    /// Returns the transaction with the highest nonce that is executable given the on chain nonce.
1263    pub fn get_highest_consecutive_transaction_by_sender(
1264        &self,
1265        sender: Address,
1266        on_chain_nonce: u64,
1267    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1268        let sender_id = self.sender_id(&sender)?;
1269        self.get_highest_consecutive_transaction_by_sender_id(sender_id, on_chain_nonce)
1270    }
1271
1272    /// Returns the highest consecutive transaction for a resolved sender ID and on-chain nonce.
1273    pub fn get_highest_consecutive_transaction_by_sender_id(
1274        &self,
1275        sender_id: SenderId,
1276        on_chain_nonce: u64,
1277    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1278        self.get_pool_data().get_highest_consecutive_transaction_by_sender(
1279            sender_id.into_transaction_id(on_chain_nonce),
1280        )
1281    }
1282
1283    /// Returns the transaction given a [`TransactionId`]
1284    pub fn get_transaction_by_transaction_id(
1285        &self,
1286        transaction_id: &TransactionId,
1287    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1288        self.get_pool_data().all().get(transaction_id).map(|tx| tx.transaction.clone())
1289    }
1290
1291    /// Returns all transactions that where submitted with the given [`TransactionOrigin`]
1292    pub fn get_transactions_by_origin(
1293        &self,
1294        origin: TransactionOrigin,
1295    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1296        self.get_pool_data()
1297            .all()
1298            .transactions_iter()
1299            .filter(|tx| tx.origin == origin)
1300            .cloned()
1301            .collect()
1302    }
1303
1304    /// Returns all pending transactions filtered by [`TransactionOrigin`]
1305    pub fn get_pending_transactions_by_origin(
1306        &self,
1307        origin: TransactionOrigin,
1308    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1309        self.get_pool_data().pending_transactions_iter().filter(|tx| tx.origin == origin).collect()
1310    }
1311
1312    /// Returns all the transactions belonging to the hashes.
1313    ///
1314    /// If no transaction exists, it is skipped.
1315    pub fn get_all(&self, txs: Vec<TxHash>) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1316        if txs.is_empty() {
1317            return Vec::new()
1318        }
1319        self.get_pool_data().get_all(txs).collect()
1320    }
1321
1322    /// Returns all the transactions belonging to the hashes that are propagatable.
1323    ///
1324    /// If no transaction exists, it is skipped.
1325    fn get_all_propagatable(
1326        &self,
1327        txs: &[TxHash],
1328    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1329        if txs.is_empty() {
1330            return Vec::new()
1331        }
1332        let pool = self.get_pool_data();
1333        txs.iter().filter_map(|tx| pool.get(tx).filter(|tx| tx.propagate)).collect()
1334    }
1335
1336    /// Notify about propagated transactions.
1337    pub fn on_propagated(&self, txs: PropagatedTransactions) {
1338        if txs.is_empty() {
1339            return
1340        }
1341        self.with_event_listener(|listener| {
1342            txs.into_iter().for_each(|(hash, peers)| listener.propagated(&hash, peers));
1343        });
1344    }
1345
1346    /// Number of transactions in the entire pool
1347    pub fn len(&self) -> usize {
1348        self.get_pool_data().len()
1349    }
1350
1351    /// Whether the pool is empty
1352    pub fn is_empty(&self) -> bool {
1353        self.get_pool_data().is_empty()
1354    }
1355
1356    /// Returns whether or not the pool is over its configured size and transaction count limits.
1357    pub fn is_exceeded(&self) -> bool {
1358        self.pool.read().is_exceeded()
1359    }
1360
1361    /// Inserts a blob transaction into the blob store
1362    fn insert_blob(&self, hash: TxHash, blob: PooledBlobSidecar) {
1363        debug!(target: "txpool", "[{:?}] storing blob sidecar", hash);
1364        if let Err(err) = self.blob_store.insert(hash, blob) {
1365            warn!(target: "txpool", %err, "[{:?}] failed to insert blob", hash);
1366            self.blob_store_metrics.blobstore_failed_inserts.increment(1);
1367        }
1368        self.update_blob_store_metrics();
1369    }
1370
1371    /// Delete a blob from the blob store
1372    pub fn delete_blob(&self, blob: TxHash) {
1373        let _ = self.blob_store.delete(blob);
1374    }
1375
1376    /// Delete all blobs from the blob store
1377    pub fn delete_blobs(&self, txs: Vec<TxHash>) {
1378        let _ = self.blob_store.delete_all(txs);
1379    }
1380
1381    /// Cleans up the blob store
1382    pub fn cleanup_blobs(&self) {
1383        let stat = self.blob_store.cleanup();
1384        self.blob_store_metrics.blobstore_failed_deletes.increment(stat.delete_failed as u64);
1385        self.update_blob_store_metrics();
1386    }
1387
1388    fn update_blob_store_metrics(&self) {
1389        if let Some(data_size) = self.blob_store.data_size_hint() {
1390            self.blob_store_metrics.blobstore_byte_size.set(data_size as f64);
1391        }
1392        self.blob_store_metrics.blobstore_entries.set(self.blob_store.blobs_len() as f64);
1393    }
1394
1395    /// Deletes all blob transactions that were discarded.
1396    fn delete_discarded_blobs<'a>(
1397        &'a self,
1398        transactions: impl IntoIterator<Item = &'a Arc<ValidPoolTransaction<T::Transaction>>>,
1399    ) {
1400        let blob_txs = transactions
1401            .into_iter()
1402            .filter(|tx| tx.transaction.is_eip4844())
1403            .map(|tx| *tx.hash())
1404            .collect();
1405        self.delete_blobs(blob_txs);
1406    }
1407}
1408
1409impl<V, T: TransactionOrdering, S> fmt::Debug for PoolInner<V, T, S> {
1410    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1411        f.debug_struct("PoolInner").field("config", &self.config).finish_non_exhaustive()
1412    }
1413}
1414
1415/// Metadata for a transaction that was added to the pool.
1416///
1417/// This holds all the data needed to complete post-insertion operations (notifications,
1418/// blob storage).
1419#[derive(Debug)]
1420struct AddedTransactionMeta<T: PoolTransaction> {
1421    /// The transaction that was added to the pool
1422    added: AddedTransaction<T>,
1423    /// Optional blob sidecar for EIP-4844 transactions
1424    blob_sidecar: Option<PooledBlobSidecar>,
1425}
1426
1427/// Tracks an added transaction and all graph changes caused by adding it.
1428#[derive(Debug, Clone)]
1429pub struct AddedPendingTransaction<T: PoolTransaction> {
1430    /// Inserted transaction.
1431    pub transaction: Arc<ValidPoolTransaction<T>>,
1432    /// Replaced transaction.
1433    pub replaced: Option<Arc<ValidPoolTransaction<T>>>,
1434    /// transactions promoted to the pending queue
1435    pub promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1436    /// transactions that failed and became discarded
1437    pub discarded: Vec<Arc<ValidPoolTransaction<T>>>,
1438}
1439
1440impl<T: PoolTransaction> AddedPendingTransaction<T> {
1441    /// Returns all transactions that were promoted to the pending pool and adhere to the given
1442    /// [`TransactionListenerKind`].
1443    ///
1444    /// If the kind is [`TransactionListenerKind::PropagateOnly`], then only transactions that
1445    /// are allowed to be propagated are returned.
1446    pub(crate) fn pending_transactions(
1447        &self,
1448        kind: TransactionListenerKind,
1449    ) -> impl Iterator<Item = B256> + '_ {
1450        let iter = std::iter::once(&self.transaction).chain(self.promoted.iter());
1451        PendingTransactionIter { kind, iter }
1452    }
1453}
1454
1455pub(crate) struct PendingTransactionIter<Iter> {
1456    kind: TransactionListenerKind,
1457    iter: Iter,
1458}
1459
1460impl<'a, Iter, T> Iterator for PendingTransactionIter<Iter>
1461where
1462    Iter: Iterator<Item = &'a Arc<ValidPoolTransaction<T>>>,
1463    T: PoolTransaction + 'a,
1464{
1465    type Item = B256;
1466
1467    fn next(&mut self) -> Option<Self::Item> {
1468        loop {
1469            let next = self.iter.next()?;
1470            if self.kind.is_propagate_only() && !next.propagate {
1471                continue
1472            }
1473            return Some(*next.hash())
1474        }
1475    }
1476}
1477
1478/// An iterator over full pending transactions
1479pub(crate) struct FullPendingTransactionIter<Iter> {
1480    kind: TransactionListenerKind,
1481    iter: Iter,
1482}
1483
1484impl<'a, Iter, T> Iterator for FullPendingTransactionIter<Iter>
1485where
1486    Iter: Iterator<Item = &'a Arc<ValidPoolTransaction<T>>>,
1487    T: PoolTransaction + 'a,
1488{
1489    type Item = NewTransactionEvent<T>;
1490
1491    fn next(&mut self) -> Option<Self::Item> {
1492        loop {
1493            let next = self.iter.next()?;
1494            if self.kind.is_propagate_only() && !next.propagate {
1495                continue
1496            }
1497            return Some(NewTransactionEvent {
1498                subpool: SubPool::Pending,
1499                transaction: next.clone(),
1500            })
1501        }
1502    }
1503}
1504
1505/// Represents a transaction that was added into the pool and its state
1506#[derive(Debug, Clone)]
1507pub enum AddedTransaction<T: PoolTransaction> {
1508    /// Transaction was successfully added and moved to the pending pool.
1509    Pending(AddedPendingTransaction<T>),
1510    /// Transaction was successfully added but not yet ready for processing and moved to a
1511    /// parked pool instead.
1512    Parked {
1513        /// Inserted transaction.
1514        transaction: Arc<ValidPoolTransaction<T>>,
1515        /// Replaced transaction.
1516        replaced: Option<Arc<ValidPoolTransaction<T>>>,
1517        /// The subpool it was moved to.
1518        subpool: SubPool,
1519        /// The specific reason why the transaction is queued (if applicable).
1520        queued_reason: Option<QueuedReason>,
1521        /// Existing transactions promoted to pending by this insertion.
1522        ///
1523        /// Validation can observe newer account state before pool maintenance applies it.
1524        /// Insertion rechecks the sender's transactions against that state, so lower-nonce
1525        /// transactions can become pending while the inserted transaction remains parked.
1526        promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1527    },
1528}
1529
1530impl<T: PoolTransaction> AddedTransaction<T> {
1531    /// Returns whether the transaction has been added to the pending pool.
1532    pub const fn as_pending(&self) -> Option<&AddedPendingTransaction<T>> {
1533        match self {
1534            Self::Pending(tx) => Some(tx),
1535            _ => None,
1536        }
1537    }
1538
1539    /// Returns the replaced transaction if there was one
1540    pub const fn replaced(&self) -> Option<&Arc<ValidPoolTransaction<T>>> {
1541        match self {
1542            Self::Pending(tx) => tx.replaced.as_ref(),
1543            Self::Parked { replaced, .. } => replaced.as_ref(),
1544        }
1545    }
1546
1547    /// Takes promotions caused by a parked insertion for separate notification.
1548    ///
1549    /// Call before notifying listeners about the inserted transaction. This drains only the
1550    /// parked promotions; subsequent parked event conversion handles the inserted transaction.
1551    pub(crate) fn take_parked_promoted(&mut self) -> Vec<Arc<ValidPoolTransaction<T>>> {
1552        match self {
1553            Self::Parked { promoted, .. } => std::mem::take(promoted),
1554            Self::Pending(_) => Vec::new(),
1555        }
1556    }
1557
1558    /// Returns the discarded transactions if there were any
1559    pub(crate) fn discarded_transactions(&self) -> Option<&[Arc<ValidPoolTransaction<T>>]> {
1560        match self {
1561            Self::Pending(tx) => Some(&tx.discarded),
1562            Self::Parked { .. } => None,
1563        }
1564    }
1565
1566    /// Returns the hash of the replaced transaction if it is a blob transaction.
1567    pub(crate) fn replaced_blob_transaction(&self) -> Option<B256> {
1568        self.replaced().filter(|tx| tx.transaction.is_eip4844()).map(|tx| *tx.transaction.hash())
1569    }
1570
1571    /// Returns the hash of the transaction
1572    pub fn hash(&self) -> &TxHash {
1573        match self {
1574            Self::Pending(tx) => tx.transaction.hash(),
1575            Self::Parked { transaction, .. } => transaction.hash(),
1576        }
1577    }
1578
1579    /// Converts this type into the event type for listeners
1580    pub fn into_new_transaction_event(self) -> NewTransactionEvent<T> {
1581        match self {
1582            Self::Pending(tx) => {
1583                NewTransactionEvent { subpool: SubPool::Pending, transaction: tx.transaction }
1584            }
1585            Self::Parked { transaction, subpool, .. } => {
1586                NewTransactionEvent { transaction, subpool }
1587            }
1588        }
1589    }
1590
1591    /// Returns the subpool this transaction was added to
1592    pub(crate) const fn subpool(&self) -> SubPool {
1593        match self {
1594            Self::Pending(_) => SubPool::Pending,
1595            Self::Parked { subpool, .. } => *subpool,
1596        }
1597    }
1598
1599    /// Returns the [`TransactionId`] of the added transaction
1600    #[cfg(test)]
1601    pub(crate) fn id(&self) -> &TransactionId {
1602        match self {
1603            Self::Pending(added) => added.transaction.id(),
1604            Self::Parked { transaction, .. } => transaction.id(),
1605        }
1606    }
1607
1608    /// Returns the queued reason if the transaction is parked with a queued reason.
1609    pub const fn queued_reason(&self) -> Option<&QueuedReason> {
1610        match self {
1611            Self::Pending(_) => None,
1612            Self::Parked { queued_reason, .. } => queued_reason.as_ref(),
1613        }
1614    }
1615
1616    /// Returns the transaction state based on the subpool and queued reason.
1617    pub fn transaction_state(&self) -> AddedTransactionState {
1618        match self.subpool() {
1619            SubPool::Pending => AddedTransactionState::Pending,
1620            _ => {
1621                // For non-pending transactions, use the queued reason directly from the
1622                // AddedTransaction
1623                if let Some(reason) = self.queued_reason() {
1624                    AddedTransactionState::Queued(reason.clone())
1625                } else {
1626                    // Fallback - this shouldn't happen with the new implementation
1627                    AddedTransactionState::Queued(QueuedReason::NonceGap)
1628                }
1629            }
1630        }
1631    }
1632}
1633
1634/// The specific reason why a transaction is queued (not ready for execution)
1635#[derive(Debug, Clone, PartialEq, Eq)]
1636pub enum QueuedReason {
1637    /// Transaction has a nonce gap - missing prior transactions
1638    NonceGap,
1639    /// Transaction has parked ancestors - waiting for other transactions to be mined
1640    ParkedAncestors,
1641    /// Sender has insufficient balance to cover the transaction cost
1642    InsufficientBalance,
1643    /// Transaction exceeds the block gas limit
1644    TooMuchGas,
1645    /// Transaction doesn't meet the base fee requirement
1646    InsufficientBaseFee,
1647    /// Transaction doesn't meet the blob fee requirement (EIP-4844)
1648    InsufficientBlobFee,
1649}
1650
1651/// The state of a transaction when is was added to the pool
1652#[derive(Debug, Clone, PartialEq, Eq)]
1653pub enum AddedTransactionState {
1654    /// Ready for execution
1655    Pending,
1656    /// Not ready for execution due to a specific condition
1657    Queued(QueuedReason),
1658}
1659
1660impl AddedTransactionState {
1661    /// Returns whether the transaction was submitted as queued.
1662    pub const fn is_queued(&self) -> bool {
1663        matches!(self, Self::Queued(_))
1664    }
1665
1666    /// Returns whether the transaction was submitted as pending.
1667    pub const fn is_pending(&self) -> bool {
1668        matches!(self, Self::Pending)
1669    }
1670
1671    /// Returns the specific queued reason if the transaction is queued.
1672    pub const fn queued_reason(&self) -> Option<&QueuedReason> {
1673        match self {
1674            Self::Queued(reason) => Some(reason),
1675            Self::Pending => None,
1676        }
1677    }
1678}
1679
1680/// The outcome of a successful transaction addition
1681#[derive(Debug, Clone, PartialEq, Eq)]
1682pub struct AddedTransactionOutcome {
1683    /// The hash of the transaction
1684    pub hash: TxHash,
1685    /// The state of the transaction
1686    pub state: AddedTransactionState,
1687}
1688
1689impl AddedTransactionOutcome {
1690    /// Returns whether the transaction was submitted as queued.
1691    pub const fn is_queued(&self) -> bool {
1692        self.state.is_queued()
1693    }
1694
1695    /// Returns whether the transaction was submitted as pending.
1696    pub const fn is_pending(&self) -> bool {
1697        self.state.is_pending()
1698    }
1699}
1700
1701/// Contains all state changes after a [`CanonicalStateUpdate`] was processed
1702#[derive(Debug)]
1703pub(crate) struct OnNewCanonicalStateOutcome<T: PoolTransaction> {
1704    /// Hash of the block.
1705    pub(crate) block_hash: B256,
1706    /// All mined transactions.
1707    pub(crate) mined: Vec<TxHash>,
1708    /// Transactions promoted to the pending pool.
1709    pub(crate) promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1710    /// transaction that were discarded during the update
1711    pub(crate) discarded: Vec<Arc<ValidPoolTransaction<T>>>,
1712}
1713
1714impl<T: PoolTransaction> OnNewCanonicalStateOutcome<T> {
1715    /// Returns all transactions that were promoted to the pending pool and adhere to the given
1716    /// [`TransactionListenerKind`].
1717    ///
1718    /// If the kind is [`TransactionListenerKind::PropagateOnly`], then only transactions that
1719    /// are allowed to be propagated are returned.
1720    pub(crate) fn pending_transactions(
1721        &self,
1722        kind: TransactionListenerKind,
1723    ) -> impl Iterator<Item = B256> + '_ {
1724        let iter = self.promoted.iter();
1725        PendingTransactionIter { kind, iter }
1726    }
1727
1728    /// Returns all FULL transactions that were promoted to the pending pool and adhere to the given
1729    /// [`TransactionListenerKind`].
1730    ///
1731    /// If the kind is [`TransactionListenerKind::PropagateOnly`], then only transactions that
1732    /// are allowed to be propagated are returned.
1733    pub(crate) fn full_pending_transactions(
1734        &self,
1735        kind: TransactionListenerKind,
1736    ) -> impl Iterator<Item = NewTransactionEvent<T>> + '_ {
1737        let iter = self.promoted.iter();
1738        FullPendingTransactionIter { kind, iter }
1739    }
1740}
1741
1742#[cfg(test)]
1743mod tests {
1744    use super::{AddedPendingTransaction, AddedTransaction};
1745    use crate::{
1746        blobstore::{BlobStore, InMemoryBlobStore, PooledBlobSidecar},
1747        identifier::SenderId,
1748        test_utils::{
1749            testing_pool, MockTransaction, MockTransactionFactory, TestPool, TestPoolBuilder,
1750        },
1751        validate::ValidTransaction,
1752        BlockInfo, FullTransactionEvent, PoolConfig, SubPool, SubPoolLimit, TransactionEvent,
1753        TransactionListenerKind, TransactionOrigin, TransactionPool, TransactionPoolExt,
1754        TransactionValidationOutcome, ValidPoolTransaction, U256,
1755    };
1756    use alloy_consensus::Transaction;
1757    use alloy_eips::{
1758        eip4844::{Blob, BlobTransactionSidecar, Bytes48},
1759        eip7594::BlobTransactionSidecarVariant,
1760    };
1761    use alloy_primitives::{Address, B256};
1762    use futures_util::{FutureExt, StreamExt};
1763    use std::sync::Arc;
1764    use tokio::sync::mpsc::error::TryRecvError;
1765
1766    /// Inserts a transaction with an explicit validator snapshot, without running maintenance.
1767    fn insert_with_state_nonce(pool: &TestPool, nonce: u64, state_nonce: u64, propagate: bool) {
1768        let transaction = MockTransaction::eip1559()
1769            .with_sender(Address::with_last_byte(1))
1770            .with_nonce(nonce)
1771            .with_hash(B256::repeat_byte(nonce as u8));
1772        pool.pool
1773            .add_transactions(
1774                TransactionOrigin::External,
1775                [TransactionValidationOutcome::Valid {
1776                    balance: U256::MAX,
1777                    state_nonce,
1778                    bytecode_hash: None,
1779                    transaction: ValidTransaction::Valid(transaction),
1780                    propagate,
1781                    authorities: None,
1782                }],
1783            )
1784            .pop()
1785            .unwrap()
1786            .unwrap();
1787    }
1788
1789    fn transaction_nonces(txs: &[Arc<ValidPoolTransaction<MockTransaction>>]) -> Vec<u64> {
1790        let mut nonces: Vec<_> = txs.iter().map(|tx| tx.transaction.nonce()).collect();
1791        nonces.sort_unstable();
1792        nonces
1793    }
1794
1795    #[tokio::test]
1796    async fn all_transactions_by_sender_across_reclassification() {
1797        let pool = testing_pool();
1798        let sender = Address::with_last_byte(1);
1799        // nonces 0 and 1 are pending, the gapped nonce 9 is queued
1800        for nonce in [0, 1, 9] {
1801            let tx =
1802                MockTransaction::legacy().with_sender(sender).with_nonce(nonce).with_gas_price(100);
1803            pool.add_transaction(TransactionOrigin::External, tx).await.unwrap();
1804        }
1805        let nonces = |txs: &[Arc<ValidPoolTransaction<MockTransaction>>]| {
1806            let mut nonces: Vec<_> = txs.iter().map(|tx| tx.transaction.nonce()).collect();
1807            nonces.sort_unstable();
1808            nonces
1809        };
1810
1811        let txs = pool.all_transactions_by_sender(sender);
1812        assert_eq!(nonces(&txs.pending), [0, 1]);
1813        assert_eq!(nonces(&txs.queued), [9]);
1814
1815        let sender_id = pool.inner().sender_id(&sender).unwrap();
1816        assert_eq!(nonces(&pool.inner().get_pending_transactions_by_sender_id(sender_id)), [0, 1]);
1817        assert_eq!(
1818            pool.inner().get_highest_transaction_by_sender_id(sender_id).unwrap().nonce(),
1819            9
1820        );
1821        assert_eq!(
1822            pool.inner()
1823                .get_highest_consecutive_transaction_by_sender_id(sender_id, 0)
1824                .unwrap()
1825                .nonce(),
1826            1
1827        );
1828
1829        // a higher base fee reclassifies the pending transactions as queued; the snapshot must
1830        // report each of them on exactly one side
1831        pool.set_block_info(BlockInfo {
1832            pending_basefee: 200,
1833            block_gas_limit: 30_000_000,
1834            ..Default::default()
1835        });
1836        let txs = pool.all_transactions_by_sender(sender);
1837        assert!(txs.pending.is_empty());
1838        assert_eq!(nonces(&txs.queued), [0, 1, 9]);
1839        assert_eq!(nonces(&pool.get_transactions_by_sender(sender)), [0, 1, 9]);
1840    }
1841
1842    #[test]
1843    fn subscribe_transaction_events_without_pool_residency() {
1844        let test_pool = testing_pool();
1845        let pool = &test_pool.pool;
1846        let tx = MockTransactionFactory::default().validated_arc(MockTransaction::eip1559());
1847        assert!(pool.add_transaction_event_listener(*tx.hash()).is_none());
1848
1849        let mut events = pool.subscribe_transaction_events(*tx.hash());
1850        pool.notify_event_listeners(&AddedTransaction::Pending(AddedPendingTransaction {
1851            transaction: tx,
1852            replaced: None,
1853            promoted: vec![],
1854            discarded: vec![],
1855        }));
1856        assert_eq!(events.next().now_or_never(), Some(Some(TransactionEvent::Pending)));
1857    }
1858
1859    #[test]
1860    fn queued_insertion_notifies_older_promotions() {
1861        let test_pool = testing_pool();
1862        let pool = &test_pool.pool;
1863        let mut network = pool.add_pending_listener(TransactionListenerKind::PropagateOnly);
1864        let mut all = pool.add_pending_listener(TransactionListenerKind::All);
1865        // Missing nonce 0 keeps both transactions queued.
1866        insert_with_state_nonce(&test_pool, 1, 0, true);
1867        insert_with_state_nonce(&test_pool, 2, 0, true);
1868        let txs = test_pool.all_transactions_by_sender(Address::with_last_byte(1));
1869        assert!(txs.pending.is_empty());
1870        assert_eq!(transaction_nonces(&txs.queued), [1, 2]);
1871        assert_eq!(network.try_recv(), Err(TryRecvError::Empty));
1872        assert_eq!(all.try_recv(), Err(TryRecvError::Empty));
1873
1874        let mut full_network =
1875            pool.add_new_transaction_listener(TransactionListenerKind::PropagateOnly);
1876        let mut full_all = pool.add_new_transaction_listener(TransactionListenerKind::All);
1877        let mut events = pool.add_all_transactions_event_listener();
1878
1879        // A newer validation result says nonce 0 is mined. Nonces 1 and 2 become
1880        // pending, but inserting 4 leaves a gap at 3.
1881        insert_with_state_nonce(&test_pool, 4, 1, true);
1882        let txs = test_pool.all_transactions_by_sender(Address::with_last_byte(1));
1883        assert_eq!(transaction_nonces(&txs.pending), [1, 2]);
1884        assert_eq!(transaction_nonces(&txs.queued), [4]);
1885
1886        let expected = vec![B256::repeat_byte(1), B256::repeat_byte(2)];
1887        for (kind, listener) in [("network", &mut network), ("all", &mut all)] {
1888            let mut received = Vec::new();
1889            while let Ok(hash) = listener.try_recv() {
1890                received.push(hash);
1891            }
1892            received.sort_unstable();
1893            assert_eq!(received, expected, "{kind} pending notifications");
1894        }
1895
1896        // Full-transaction subscribers get each promotion once and the inserted
1897        // transaction once, still marked queued. Propagation filtering applies here too.
1898        for (kind, listener) in [("network", &mut full_network), ("all", &mut full_all)] {
1899            let mut received = Vec::new();
1900            while let Ok(event) = listener.try_recv() {
1901                received.push((*event.transaction.hash(), event.subpool));
1902            }
1903            received.sort_unstable_by_key(|(hash, _)| *hash);
1904            let expected = vec![
1905                (B256::repeat_byte(1), SubPool::Pending),
1906                (B256::repeat_byte(2), SubPool::Pending),
1907                (B256::repeat_byte(4), SubPool::Queued),
1908            ];
1909            assert_eq!(received, expected, "{kind} full transaction notifications");
1910        }
1911
1912        let mut pending_events = Vec::new();
1913        let mut queued_events = Vec::new();
1914        while let Some(Some(event)) = events.next().now_or_never() {
1915            match event {
1916                FullTransactionEvent::Pending(hash) => pending_events.push(hash),
1917                FullTransactionEvent::Queued(hash, _) => queued_events.push(hash),
1918                other => panic!("unexpected event: {other:?}"),
1919            }
1920        }
1921        pending_events.sort_unstable();
1922        assert_eq!(pending_events, expected);
1923        assert_eq!(queued_events, vec![B256::repeat_byte(4)]);
1924
1925        // A later insertion observing the same state must not notify those promotions again.
1926        insert_with_state_nonce(&test_pool, 5, 1, true);
1927        assert_eq!(network.try_recv(), Err(TryRecvError::Empty));
1928        assert_eq!(all.try_recv(), Err(TryRecvError::Empty));
1929        for listener in [&mut full_network, &mut full_all] {
1930            let event = listener.try_recv().unwrap();
1931            assert_eq!(*event.transaction.hash(), B256::repeat_byte(5));
1932            assert_eq!(event.subpool, SubPool::Queued);
1933            assert!(matches!(listener.try_recv(), Err(TryRecvError::Empty)));
1934        }
1935        assert!(matches!(
1936            events.next().now_or_never(),
1937            Some(Some(FullTransactionEvent::Queued(hash, _))) if hash == B256::repeat_byte(5)
1938        ));
1939        assert!(events.next().now_or_never().is_none());
1940    }
1941
1942    #[test]
1943    fn queued_insertion_promotions_respect_propagation_filter() {
1944        let test_pool = testing_pool();
1945        let pool = &test_pool.pool;
1946        insert_with_state_nonce(&test_pool, 1, 0, false);
1947        insert_with_state_nonce(&test_pool, 2, 0, true);
1948
1949        let mut network = pool.add_pending_listener(TransactionListenerKind::PropagateOnly);
1950        let mut all = pool.add_pending_listener(TransactionListenerKind::All);
1951        let mut full_network =
1952            pool.add_new_transaction_listener(TransactionListenerKind::PropagateOnly);
1953        let mut full_all = pool.add_new_transaction_listener(TransactionListenerKind::All);
1954        insert_with_state_nonce(&test_pool, 4, 1, true);
1955
1956        assert_eq!(network.try_recv().unwrap(), B256::repeat_byte(2));
1957        assert_eq!(network.try_recv(), Err(TryRecvError::Empty));
1958        let mut received = Vec::new();
1959        while let Ok(hash) = all.try_recv() {
1960            received.push(hash);
1961        }
1962        received.sort_unstable();
1963        assert_eq!(received, [B256::repeat_byte(1), B256::repeat_byte(2)]);
1964
1965        for (listener, expected) in [
1966            (
1967                &mut full_network,
1968                vec![
1969                    (B256::repeat_byte(2), SubPool::Pending),
1970                    (B256::repeat_byte(4), SubPool::Queued),
1971                ],
1972            ),
1973            (
1974                &mut full_all,
1975                vec![
1976                    (B256::repeat_byte(1), SubPool::Pending),
1977                    (B256::repeat_byte(2), SubPool::Pending),
1978                    (B256::repeat_byte(4), SubPool::Queued),
1979                ],
1980            ),
1981        ] {
1982            let mut received = Vec::new();
1983            while let Ok(event) = listener.try_recv() {
1984                received.push((*event.transaction.hash(), event.subpool));
1985            }
1986            received.sort_unstable_by_key(|(hash, _)| *hash);
1987            assert_eq!(received, expected);
1988        }
1989    }
1990
1991    #[test]
1992    fn pending_insertion_notifies_older_promotions() {
1993        let test_pool = testing_pool();
1994        let pool = &test_pool.pool;
1995        insert_with_state_nonce(&test_pool, 1, 0, true);
1996        insert_with_state_nonce(&test_pool, 2, 0, true);
1997        let mut network = pool.add_pending_listener(TransactionListenerKind::PropagateOnly);
1998        let mut all = pool.add_pending_listener(TransactionListenerKind::All);
1999
2000        // Filling the gap makes both the older transactions and the insertion pending.
2001        insert_with_state_nonce(&test_pool, 3, 1, true);
2002        let txs = test_pool.all_transactions_by_sender(Address::with_last_byte(1));
2003        assert_eq!(transaction_nonces(&txs.pending), [1, 2, 3]);
2004        assert!(txs.queued.is_empty());
2005        for listener in [&mut network, &mut all] {
2006            let mut received = Vec::new();
2007            while let Ok(hash) = listener.try_recv() {
2008                received.push(hash);
2009            }
2010            received.sort_unstable();
2011            assert_eq!(
2012                received,
2013                [B256::repeat_byte(1), B256::repeat_byte(2), B256::repeat_byte(3)]
2014            );
2015        }
2016    }
2017
2018    #[test]
2019    fn test_discard_blobs_on_blob_tx_eviction() {
2020        // A zero blob, whose commitment and proof are the point at infinity, is a valid sidecar
2021        // that doesn't need the KZG trusted setup.
2022        let mut point_at_infinity = [0; 48];
2023        point_at_infinity[0] = 0xc0;
2024        let sidecar = BlobTransactionSidecarVariant::Eip4844(BlobTransactionSidecar::new(
2025            vec![Blob::default()],
2026            vec![Bytes48::from(point_at_infinity)],
2027            vec![Bytes48::from(point_at_infinity)],
2028        ));
2029
2030        // Define the maximum limit for blobs in the sub-pool.
2031        let blob_limit = SubPoolLimit::new(1000, usize::MAX);
2032
2033        // Create a test pool with default configuration and the specified blob limit.
2034        let test_pool = &TestPoolBuilder::default()
2035            .with_config(PoolConfig { blob_limit, ..Default::default() })
2036            .pool;
2037
2038        // Set the block info for the pool, including a pending blob fee.
2039        test_pool
2040            .set_block_info(BlockInfo { pending_blob_fee: Some(10_000_000), ..Default::default() });
2041
2042        // Create an in-memory blob store.
2043        let blob_store = InMemoryBlobStore::default();
2044
2045        // Loop to add transactions to the pool and test blob eviction.
2046        for n in 0..blob_limit.max_txs + 10 {
2047            // Create a mock transaction with the generated blob sidecar.
2048            let mut tx = MockTransaction::eip4844_with_sidecar(sidecar.clone());
2049
2050            // Set non zero size
2051            tx.set_size(1844674407370951);
2052
2053            // Insert the sidecar into the blob store if the current index is within the blob limit.
2054            if n < blob_limit.max_txs {
2055                blob_store.insert(*tx.get_hash(), sidecar.clone().into()).unwrap();
2056            }
2057
2058            // Add the transaction to the pool with external origin and valid outcome.
2059            test_pool.add_transactions(
2060                TransactionOrigin::External,
2061                [TransactionValidationOutcome::Valid {
2062                    balance: U256::from(1_000),
2063                    state_nonce: 0,
2064                    bytecode_hash: None,
2065                    transaction: ValidTransaction::ValidWithSidecar {
2066                        transaction: tx,
2067                        sidecar: PooledBlobSidecar::from(sidecar.clone()),
2068                    },
2069                    propagate: true,
2070                    authorities: None,
2071                }],
2072            );
2073        }
2074
2075        // Assert that the size of the pool's blob component is equal to the maximum blob limit.
2076        assert_eq!(test_pool.size().blob, blob_limit.max_txs);
2077
2078        // Assert that the size of the pool's blob_size component matches the expected value.
2079        assert_eq!(test_pool.size().blob_size, 1844674407370951000);
2080
2081        // Assert that the pool's blob store matches the expected blob store.
2082        assert_eq!(*test_pool.blob_store(), blob_store);
2083    }
2084
2085    #[test]
2086    fn test_auths_stored_in_identifiers() {
2087        // Create a test pool with default configuration.
2088        let test_pool = &TestPoolBuilder::default().with_config(Default::default()).pool;
2089
2090        let auth = Address::repeat_byte(1);
2091        let tx = MockTransaction::eip7702();
2092
2093        test_pool.add_transactions(
2094            TransactionOrigin::Local,
2095            [TransactionValidationOutcome::Valid {
2096                balance: U256::from(1_000),
2097                state_nonce: 0,
2098                bytecode_hash: None,
2099                transaction: ValidTransaction::Valid(tx),
2100                propagate: true,
2101                authorities: Some(vec![auth]),
2102            }],
2103        );
2104
2105        let identifiers = test_pool.identifiers.read();
2106        assert_eq!(identifiers.sender_id(&auth), Some(SenderId::from(1)));
2107    }
2108
2109    #[test]
2110    fn sender_queries_do_not_allocate_ids_for_unknown_addresses() {
2111        let test_pool = &TestPoolBuilder::default().with_config(Default::default()).pool;
2112        let sender = Address::repeat_byte(9);
2113
2114        assert_eq!(test_pool.sender_id(&sender), None);
2115        assert!(test_pool.get_transactions_by_sender(sender).is_empty());
2116        assert!(test_pool.get_pending_transaction_by_sender_and_nonce(sender, 0).is_none());
2117        assert!(test_pool.get_queued_transactions_by_sender(sender).is_empty());
2118        assert!(test_pool.get_pending_transactions_by_sender(sender).is_empty());
2119        assert!(test_pool.get_highest_transaction_by_sender(sender).is_none());
2120        assert!(test_pool.get_highest_consecutive_transaction_by_sender(sender, 0).is_none());
2121        assert!(test_pool.remove_transactions_by_sender(sender).is_empty());
2122        assert_eq!(test_pool.sender_id(&sender), None);
2123    }
2124}