Skip to main content

reth_transaction_pool/pool/
txpool.rs

1//! The internal transaction pool implementation.
2
3use crate::{
4    config::{LocalTransactionConfig, TXPOOL_MAX_ACCOUNT_SLOTS_PER_SENDER},
5    error::{
6        Eip4844PoolTransactionError, Eip7702PoolTransactionError, InvalidPoolTransactionError,
7        PoolError, PoolErrorKind,
8    },
9    identifier::{SenderId, TransactionId},
10    metrics::{AllTransactionsMetrics, TxPoolMetrics},
11    pool::{
12        best::BestTransactions,
13        blob::BlobTransactions,
14        parked::{BasefeeOrd, ParkedPool, QueuedOrd},
15        pending::PendingPool,
16        state::{SubPool, TxState},
17        update::{Destination, PoolUpdate, UpdateOutcome},
18        AddedPendingTransaction, AddedTransaction, OnNewCanonicalStateOutcome,
19    },
20    traits::{BestTransactionsAttributes, BlockInfo, PoolSize},
21    PoolConfig, PoolResult, PoolTransaction, PoolUpdateKind, PriceBumpConfig, TransactionOrdering,
22    ValidPoolTransaction, U256,
23};
24use alloy_consensus::constants::{
25    EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, EIP7702_TX_TYPE_ID, KECCAK_EMPTY,
26    LEGACY_TX_TYPE_ID,
27};
28use alloy_eips::{
29    eip1559::{ETHEREUM_BLOCK_GAS_LIMIT_30M, MIN_PROTOCOL_BASE_FEE},
30    eip4844::BLOB_TX_MIN_BLOB_GASPRICE,
31};
32#[cfg(test)]
33use alloy_primitives::Address;
34use alloy_primitives::{
35    map::{AddressSet, B256Map, B256Set},
36    TxHash, B256,
37};
38use reth_primitives_traits::transaction::error::InvalidTransactionError;
39use rustc_hash::FxHashMap;
40use smallvec::SmallVec;
41#[cfg(test)]
42use std::collections::{HashMap, HashSet};
43use std::{
44    cmp::Ordering,
45    collections::{btree_map::Entry, hash_map, BTreeMap},
46    fmt,
47    ops::Bound::{Excluded, Unbounded},
48    sync::Arc,
49};
50use tracing::{trace, warn};
51
52#[cfg_attr(doc, aquamarine::aquamarine)]
53// TODO: Inlined diagram due to a bug in aquamarine library, should become an include when it's
54// fixed. See https://github.com/mersinvald/aquamarine/issues/50
55// include_mmd!("docs/mermaid/txpool.mmd")
56/// A pool that manages transactions.
57///
58/// This pool maintains the state of all transactions and stores them accordingly.
59///
60/// ```mermaid
61/// graph TB
62///   subgraph TxPool
63///     direction TB
64///     pool[(All Transactions)]
65///     subgraph Subpools
66///         direction TB
67///         B3[(Queued)]
68///         B1[(Pending)]
69///         B2[(Basefee)]
70///         B4[(Blob)]
71///     end
72///   end
73///   discard([discard])
74///   production([Block Production])
75///   new([New Block])
76///   A[Incoming Tx] --> B[Validation] -->|ins
77///   pool --> |if ready + blobfee too low| B4
78///   pool --> |if ready| B1
79///   pool --> |if ready + basfee too low| B2
80///   pool --> |nonce gap or lack of funds| B3
81///   pool --> |update| pool
82///   B1 --> |best| production
83///   B2 --> |worst| discard
84///   B3 --> |worst| discard
85///   B4 --> |worst| discard
86///   B1 --> |increased blob fee| B4
87///   B4 --> |decreased blob fee| B1
88///   B1 --> |increased base fee| B2
89///   B2 --> |decreased base fee| B1
90///   B3 --> |promote| B1
91///   B3 --> |promote| B2
92///   new --> |apply state changes| pool
93/// ```
94pub struct TxPool<T: TransactionOrdering> {
95    /// pending subpool
96    ///
97    /// Holds transactions that are ready to be executed on the current state.
98    pending_pool: PendingPool<T>,
99    /// Pool settings to enforce limits etc.
100    config: PoolConfig,
101    /// queued subpool
102    ///
103    /// Holds all parked transactions that depend on external changes from the sender:
104    ///
105    ///    - blocked by missing ancestor transaction (has nonce gaps)
106    ///    - sender lacks funds to pay for this transaction.
107    queued_pool: ParkedPool<QueuedOrd<T::Transaction>>,
108    /// base fee subpool
109    ///
110    /// Holds all parked transactions that currently violate the dynamic fee requirement but could
111    /// be moved to pending if the base fee changes in their favor (decreases) in future blocks.
112    basefee_pool: ParkedPool<BasefeeOrd<T::Transaction>>,
113    /// Blob transactions in the pool that are __not pending__.
114    ///
115    /// This means they either do not satisfy the dynamic fee requirement or the blob fee
116    /// requirement. These transactions can be moved to pending if the base fee or blob fee changes
117    /// in their favor (decreases) in future blocks. The transaction may need both the base fee and
118    /// blob fee to decrease to become executable.
119    blob_pool: BlobTransactions<T::Transaction>,
120    /// All transactions in the pool.
121    all_transactions: AllTransactions<T::Transaction>,
122    /// Transaction pool metrics
123    metrics: TxPoolMetrics,
124}
125
126// === impl TxPool ===
127
128impl<T: TransactionOrdering> TxPool<T> {
129    /// Create a new graph pool instance.
130    pub fn new(ordering: T, config: PoolConfig) -> Self {
131        let all_transactions = AllTransactions::new(&config);
132        Self {
133            pending_pool: PendingPool::with_buffer(
134                ordering,
135                config.max_new_pending_txs_notifications,
136            )
137            .with_local_transactions_config(Arc::clone(
138                &all_transactions.local_transactions_config,
139            )),
140            queued_pool: Default::default(),
141            basefee_pool: Default::default(),
142            blob_pool: Default::default(),
143            all_transactions,
144            config,
145            metrics: Default::default(),
146        }
147    }
148
149    /// Retrieves the highest nonce for a specific sender from the transaction pool.
150    pub fn get_highest_nonce_by_sender(&self, sender: SenderId) -> Option<u64> {
151        self.all().txs_iter(sender).last().map(|(_, tx)| tx.transaction.nonce())
152    }
153
154    /// Retrieves the highest transaction (wrapped in an `Arc`) for a specific sender from the
155    /// transaction pool.
156    pub fn get_highest_transaction_by_sender(
157        &self,
158        sender: SenderId,
159    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
160        self.all().txs_iter(sender).last().map(|(_, tx)| Arc::clone(&tx.transaction))
161    }
162
163    /// Returns the transaction with the highest nonce that is executable given the on chain nonce.
164    ///
165    /// If the pool already tracks a higher nonce for the given sender, then this nonce is used
166    /// instead.
167    ///
168    /// Note: The next pending pooled transaction must have the on chain nonce.
169    pub(crate) fn get_highest_consecutive_transaction_by_sender(
170        &self,
171        mut on_chain: TransactionId,
172    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
173        let mut last_consecutive_tx = None;
174
175        // ensure this operates on the most recent
176        if let Some(current) = self.all_transactions.sender_info.get(&on_chain.sender) {
177            on_chain.nonce = on_chain.nonce.max(current.state_nonce);
178        }
179
180        let mut next_expected_nonce = on_chain.nonce;
181        for (id, tx) in self.all().descendant_txs_inclusive(&on_chain) {
182            if next_expected_nonce != id.nonce {
183                break
184            }
185            next_expected_nonce = id.next_nonce();
186            last_consecutive_tx = Some(tx);
187        }
188
189        last_consecutive_tx.map(|tx| Arc::clone(&tx.transaction))
190    }
191
192    /// Returns access to the [`AllTransactions`] container.
193    pub(crate) const fn all(&self) -> &AllTransactions<T::Transaction> {
194        &self.all_transactions
195    }
196
197    /// Returns all senders in the pool
198    pub(crate) fn unique_senders(&self) -> AddressSet {
199        self.all_transactions.txs.values().map(|tx| tx.transaction.sender()).collect()
200    }
201
202    /// Returns stats about the size of pool.
203    pub fn size(&self) -> PoolSize {
204        PoolSize {
205            pending: self.pending_pool.len(),
206            pending_size: self.pending_pool.size(),
207            basefee: self.basefee_pool.len(),
208            basefee_size: self.basefee_pool.size(),
209            queued: self.queued_pool.len(),
210            queued_size: self.queued_pool.size(),
211            blob: self.blob_pool.len(),
212            blob_size: self.blob_pool.size(),
213            total: self.all_transactions.len(),
214        }
215    }
216
217    /// Returns the currently tracked block values
218    pub const fn block_info(&self) -> BlockInfo {
219        BlockInfo {
220            block_gas_limit: self.all_transactions.block_gas_limit,
221            last_seen_block_hash: self.all_transactions.last_seen_block_hash,
222            last_seen_block_number: self.all_transactions.last_seen_block_number,
223            pending_basefee: self.all_transactions.pending_fees.base_fee,
224            pending_blob_fee: Some(self.all_transactions.pending_fees.blob_fee),
225        }
226    }
227
228    /// Updates the tracked blob fee
229    fn update_blob_fee<F>(
230        &mut self,
231        mut pending_blob_fee: u128,
232        base_fee_update: Ordering,
233        mut on_promoted: F,
234    ) where
235        F: FnMut(&Arc<ValidPoolTransaction<T::Transaction>>),
236    {
237        std::mem::swap(&mut self.all_transactions.pending_fees.blob_fee, &mut pending_blob_fee);
238        match (self.all_transactions.pending_fees.blob_fee.cmp(&pending_blob_fee), base_fee_update)
239        {
240            (Ordering::Equal, Ordering::Equal | Ordering::Greater) => {
241                // fee unchanged, nothing to update
242            }
243            (Ordering::Greater, Ordering::Equal | Ordering::Greater) => {
244                // increased blob fee: recheck pending pool and remove all that are no longer valid
245                let removed =
246                    self.pending_pool.update_blob_fee(self.all_transactions.pending_fees.blob_fee);
247                for tx in removed {
248                    let to = {
249                        let tx =
250                            self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
251
252                        // the blob fee is too high now, unset the blob fee cap block flag
253                        tx.state.remove(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
254                        tx.subpool = tx.state.into();
255                        tx.subpool
256                    };
257                    self.add_transaction_to_subpool(to, tx);
258                }
259            }
260            (Ordering::Greater, Ordering::Less) => {
261                // The blob fee increased while the base fee decreased, so this update must both
262                // park transactions that no longer cover the blob fee and promote transactions
263                // that now cover both fees. Demote first so the promotion check sees the final
264                // fee state.
265                let removed =
266                    self.pending_pool.update_blob_fee(self.all_transactions.pending_fees.blob_fee);
267                for tx in removed {
268                    let to = {
269                        let tx =
270                            self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
271
272                        tx.state.remove(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
273                        tx.subpool = tx.state.into();
274                        tx.subpool
275                    };
276                    self.add_transaction_to_subpool(to, tx);
277                }
278
279                let removed =
280                    self.blob_pool.enforce_pending_fees(&self.all_transactions.pending_fees);
281                for tx in removed {
282                    let subpool = {
283                        let tx_meta =
284                            self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
285                        tx_meta.state.insert(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
286                        tx_meta.state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
287                        tx_meta.subpool = tx_meta.state.into();
288                        tx_meta.subpool
289                    };
290
291                    if subpool.is_pending() {
292                        on_promoted(&tx);
293                    }
294
295                    self.add_transaction_to_subpool(subpool, tx);
296                }
297            }
298            (Ordering::Less, _) | (Ordering::Equal, Ordering::Less) => {
299                // decreased blob/base fee: recheck blob pool and promote all that are now valid
300                let removed =
301                    self.blob_pool.enforce_pending_fees(&self.all_transactions.pending_fees);
302                for tx in removed {
303                    let subpool = {
304                        let tx_meta =
305                            self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
306                        tx_meta.state.insert(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
307                        tx_meta.state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
308                        tx_meta.subpool = tx_meta.state.into();
309                        tx_meta.subpool
310                    };
311
312                    if subpool.is_pending() {
313                        on_promoted(&tx);
314                    }
315
316                    self.add_transaction_to_subpool(subpool, tx);
317                }
318            }
319        }
320    }
321
322    /// Updates the tracked basefee
323    ///
324    /// Depending on the change in direction of the basefee, this will promote or demote
325    /// transactions from the basefee pool.
326    fn update_basefee<F>(&mut self, mut pending_basefee: u64, mut on_promoted: F) -> Ordering
327    where
328        F: FnMut(&Arc<ValidPoolTransaction<T::Transaction>>),
329    {
330        std::mem::swap(&mut self.all_transactions.pending_fees.base_fee, &mut pending_basefee);
331        match self.all_transactions.pending_fees.base_fee.cmp(&pending_basefee) {
332            Ordering::Equal => {
333                // fee unchanged, nothing to update
334                Ordering::Equal
335            }
336            Ordering::Greater => {
337                // increased base fee: recheck pending pool and remove all that are no longer valid
338                let removed =
339                    self.pending_pool.update_base_fee(self.all_transactions.pending_fees.base_fee);
340                for tx in removed {
341                    let to = {
342                        let tx =
343                            self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
344                        tx.state.remove(TxState::ENOUGH_FEE_CAP_BLOCK);
345                        tx.subpool = tx.state.into();
346                        tx.subpool
347                    };
348                    self.add_transaction_to_subpool(to, tx);
349                }
350
351                Ordering::Greater
352            }
353            Ordering::Less => {
354                // Base fee decreased: recheck BaseFee and promote.
355                // Invariants:
356                // - BaseFee contains only non-blob txs (blob txs live in Blob) and they already
357                //   have ENOUGH_BLOB_FEE_CAP_BLOCK.
358                // - PENDING_POOL_BITS = BASE_FEE_POOL_BITS | ENOUGH_FEE_CAP_BLOCK |
359                //   ENOUGH_BLOB_FEE_CAP_BLOCK.
360                // With the lower base fee they gain ENOUGH_FEE_CAP_BLOCK, so we can set the bit and
361                // insert directly into Pending (skip generic routing).
362                let current_base_fee = self.all_transactions.pending_fees.base_fee;
363                self.basefee_pool.enforce_basefee_with(current_base_fee, |tx| {
364                    // Update transaction state — guaranteed Pending by the invariants above
365                    let subpool = {
366                        let meta =
367                            self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
368                        meta.state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
369                        meta.subpool = meta.state.into();
370                        meta.subpool
371                    };
372
373                    if subpool.is_pending() {
374                        on_promoted(&tx);
375                    }
376
377                    trace!(target: "txpool", hash=%tx.transaction.hash(), pool=?subpool, "Adding transaction to a subpool");
378                    match subpool {
379                        SubPool::Queued => self.queued_pool.add_transaction(tx),
380                        SubPool::Pending => {
381                            self.pending_pool.add_transaction(tx, current_base_fee);
382                        }
383                        SubPool::Blob => {
384                            self.blob_pool.add_transaction(tx);
385                        }
386                        SubPool::BaseFee => {
387                            // This should be unreachable as transactions from BaseFee pool with decreased
388                            // basefee are guaranteed to become Pending
389                            warn!(target: "txpool", "BaseFee transactions should become Pending after basefee decrease");
390                        }
391                    }
392                });
393
394                Ordering::Less
395            }
396        }
397    }
398
399    /// Sets the current block info for the pool.
400    ///
401    /// This will also apply updates to the pool based on the new base fee and blob fee.
402    ///
403    /// Returns the outcome containing any transactions that were promoted due to fee changes.
404    pub fn set_block_info(&mut self, info: BlockInfo) -> UpdateOutcome<T::Transaction> {
405        let mut outcome = UpdateOutcome::default();
406
407        // first update the subpools based on the new values, collecting promoted transactions
408        let basefee_ordering = self.update_basefee(info.pending_basefee, |tx| {
409            outcome.promoted.push(tx.clone());
410        });
411        if let Some(blob_fee) = info.pending_blob_fee {
412            self.update_blob_fee(blob_fee, basefee_ordering, |tx| {
413                outcome.promoted.push(tx.clone());
414            })
415        }
416        // then update tracked values
417        self.all_transactions.set_block_info(info);
418
419        outcome
420    }
421
422    /// Returns an iterator that yields transactions that are ready to be included in the block with
423    /// the tracked fees.
424    pub(crate) fn best_transactions(&self) -> BestTransactions<T> {
425        self.pending_pool.best()
426    }
427
428    /// Returns an iterator that yields transactions that are ready to be included in the block with
429    /// the given base fee and optional blob fee.
430    ///
431    /// If the provided attributes differ from the currently tracked fees, this will also include
432    /// transactions that are unlocked by the new fees, or exclude transactions that are no longer
433    /// valid with the new fees.
434    pub(crate) fn best_transactions_with_attributes(
435        &self,
436        best_transactions_attributes: BestTransactionsAttributes,
437    ) -> Box<dyn crate::traits::BestTransactions<Item = Arc<ValidPoolTransaction<T::Transaction>>>>
438    {
439        // First we need to check if the given base fee is different than what's currently being
440        // tracked
441        match best_transactions_attributes.basefee.cmp(&self.all_transactions.pending_fees.base_fee)
442        {
443            Ordering::Equal => {
444                // for EIP-4844 transactions we also need to check if the blob fee is now lower than
445                // what's currently being tracked, if so we need to include transactions from the
446                // blob pool that are valid with the lower blob fee
447                let new_blob_fee = best_transactions_attributes.blob_fee.unwrap_or_default();
448                match new_blob_fee.cmp(&(self.all_transactions.pending_fees.blob_fee as u64)) {
449                    Ordering::Less => {
450                        // it's possible that this swing unlocked more blob transactions
451                        let unlocked =
452                            self.blob_pool.satisfy_attributes(best_transactions_attributes);
453                        Box::new(self.pending_pool.best_with_unlocked_and_attributes(
454                            unlocked,
455                            best_transactions_attributes.basefee,
456                            new_blob_fee,
457                        ))
458                    }
459                    Ordering::Equal => Box::new(self.pending_pool.best()),
460                    Ordering::Greater => {
461                        // no additional transactions unlocked
462                        Box::new(self.pending_pool.best_with_basefee_and_blobfee(
463                            best_transactions_attributes.basefee,
464                            best_transactions_attributes.blob_fee.unwrap_or_default(),
465                        ))
466                    }
467                }
468            }
469            Ordering::Greater => {
470                // base fee increased, we need to check how the blob fee moved
471                let new_blob_fee = best_transactions_attributes.blob_fee.unwrap_or_default();
472                match new_blob_fee.cmp(&(self.all_transactions.pending_fees.blob_fee as u64)) {
473                    Ordering::Less => {
474                        // it's possible that this swing unlocked more blob transactions
475                        let unlocked =
476                            self.blob_pool.satisfy_attributes(best_transactions_attributes);
477                        Box::new(self.pending_pool.best_with_unlocked_and_attributes(
478                            unlocked,
479                            best_transactions_attributes.basefee,
480                            new_blob_fee,
481                        ))
482                    }
483                    Ordering::Equal | Ordering::Greater => {
484                        // no additional transactions unlocked
485                        Box::new(self.pending_pool.best_with_basefee_and_blobfee(
486                            best_transactions_attributes.basefee,
487                            new_blob_fee,
488                        ))
489                    }
490                }
491            }
492            Ordering::Less => {
493                // base fee decreased, we need to move transactions from the basefee + blob pool to
494                // the pending pool that might be unlocked by the lower base fee
495                let mut unlocked = self
496                    .basefee_pool
497                    .satisfy_base_fee_transactions(best_transactions_attributes.basefee);
498
499                // also include blob pool transactions that are now unlocked
500                unlocked.extend(self.blob_pool.satisfy_attributes(best_transactions_attributes));
501
502                Box::new(self.pending_pool.best_with_unlocked_and_attributes(
503                    unlocked,
504                    best_transactions_attributes.basefee,
505                    best_transactions_attributes.blob_fee.unwrap_or_default(),
506                ))
507            }
508        }
509    }
510
511    /// Returns all transactions from the pending sub-pool
512    pub(crate) fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
513        self.pending_pool.all().collect()
514    }
515    /// Returns an iterator over all transactions from the pending sub-pool
516    pub(crate) fn pending_transactions_iter(
517        &self,
518    ) -> impl Iterator<Item = Arc<ValidPoolTransaction<T::Transaction>>> + '_ {
519        self.pending_pool.all()
520    }
521
522    /// Returns the number of transactions from the pending sub-pool
523    pub(crate) fn pending_transactions_count(&self) -> usize {
524        self.pending_pool.len()
525    }
526
527    /// Returns all pending transactions filtered by predicate
528    pub(crate) fn pending_transactions_with_predicate(
529        &self,
530        mut predicate: impl FnMut(&ValidPoolTransaction<T::Transaction>) -> bool,
531    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
532        self.pending_transactions_iter().filter(|tx| predicate(tx)).collect()
533    }
534
535    /// Returns all pending transactions for the specified sender
536    pub(crate) fn pending_txs_by_sender(
537        &self,
538        sender: SenderId,
539    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
540        self.pending_pool.txs_by_sender(sender).collect()
541    }
542
543    /// Returns all transactions from parked pools
544    pub(crate) fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
545        self.basefee_pool.all().chain(self.queued_pool.all()).chain(self.blob_pool.all()).collect()
546    }
547
548    /// Returns the number of transactions in parked pools
549    pub(crate) fn queued_transactions_count(&self) -> usize {
550        self.basefee_pool.len() + self.queued_pool.len() + self.blob_pool.len()
551    }
552
553    /// Returns queued and pending transactions for the specified sender
554    pub fn queued_and_pending_txs_by_sender(
555        &self,
556        sender: SenderId,
557    ) -> (SmallVec<[TransactionId; TXPOOL_MAX_ACCOUNT_SLOTS_PER_SENDER]>, Vec<TransactionId>) {
558        (self.queued_pool.get_txs_by_sender(sender), self.pending_pool.get_txs_by_sender(sender))
559    }
560
561    /// Returns all queued transactions for the specified sender
562    pub(crate) fn queued_txs_by_sender(
563        &self,
564        sender: SenderId,
565    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
566        self.basefee_pool
567            .txs_by_sender(sender)
568            .chain(self.queued_pool.txs_by_sender(sender))
569            .chain(self.blob_pool.txs_by_sender(sender))
570            .collect()
571    }
572
573    /// Returns `true` if the transaction with the given hash is already included in this pool.
574    pub(crate) fn contains(&self, tx_hash: &TxHash) -> bool {
575        self.all_transactions.contains(tx_hash)
576    }
577
578    /// Returns `true` if the transaction with the given id is already included in the given subpool
579    #[cfg(test)]
580    pub(crate) fn subpool_contains(&self, subpool: SubPool, id: &TransactionId) -> bool {
581        match subpool {
582            SubPool::Queued => self.queued_pool.contains(id),
583            SubPool::Pending => self.pending_pool.contains(id),
584            SubPool::BaseFee => self.basefee_pool.contains(id),
585            SubPool::Blob => self.blob_pool.contains(id),
586        }
587    }
588
589    /// Returns `true` if the pool is over its configured limits.
590    #[inline]
591    pub(crate) fn is_exceeded(&self) -> bool {
592        self.config.is_exceeded(self.size())
593    }
594
595    /// Returns the transaction for the given hash.
596    pub(crate) fn get(
597        &self,
598        tx_hash: &TxHash,
599    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
600        self.all_transactions.by_hash.get(tx_hash).cloned()
601    }
602
603    /// Returns transactions for the multiple given hashes, if they exist.
604    pub(crate) fn get_all(
605        &self,
606        txs: Vec<TxHash>,
607    ) -> impl Iterator<Item = Arc<ValidPoolTransaction<T::Transaction>>> + '_ {
608        txs.into_iter().filter_map(|tx| self.get(&tx))
609    }
610
611    /// Returns all transactions sent from the given sender.
612    pub(crate) fn get_transactions_by_sender(
613        &self,
614        sender: SenderId,
615    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
616        self.all_transactions.txs_iter(sender).map(|(_, tx)| Arc::clone(&tx.transaction)).collect()
617    }
618
619    /// Returns a pending transaction sent by the given sender with the given nonce.
620    pub(crate) fn get_pending_transaction_by_sender_and_nonce(
621        &self,
622        sender: SenderId,
623        nonce: u64,
624    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
625        self.all_transactions
626            .txs_iter(sender)
627            .find(|(id, tx)| id.nonce == nonce && tx.subpool.is_pending())
628            .map(|(_, tx)| Arc::clone(&tx.transaction))
629    }
630
631    /// Updates only the pending fees without triggering subpool updates.
632    /// Returns the previous base fee and blob fee values.
633    const fn update_pending_fees_only(
634        &mut self,
635        mut new_base_fee: u64,
636        new_blob_fee: Option<u128>,
637    ) -> (u64, u128) {
638        std::mem::swap(&mut self.all_transactions.pending_fees.base_fee, &mut new_base_fee);
639
640        let prev_blob_fee = if let Some(mut blob_fee) = new_blob_fee {
641            std::mem::swap(&mut self.all_transactions.pending_fees.blob_fee, &mut blob_fee);
642            blob_fee
643        } else {
644            self.all_transactions.pending_fees.blob_fee
645        };
646
647        (new_base_fee, prev_blob_fee)
648    }
649
650    /// Applies fee-based promotion updates based on the previous fees.
651    ///
652    /// Records promoted transactions based on fee swings.
653    ///
654    /// Caution: This expects that the fees were previously already updated via
655    /// [`Self::update_pending_fees_only`].
656    fn apply_fee_updates(
657        &mut self,
658        prev_base_fee: u64,
659        prev_blob_fee: u128,
660        outcome: &mut UpdateOutcome<T::Transaction>,
661    ) {
662        let new_base_fee = self.all_transactions.pending_fees.base_fee;
663        let new_blob_fee = self.all_transactions.pending_fees.blob_fee;
664
665        if new_base_fee == prev_base_fee && new_blob_fee == prev_blob_fee {
666            // nothing to update
667            return;
668        }
669
670        // IMPORTANT:
671        // Restore previous fees so that the update fee functions correctly handle fee swings
672        self.all_transactions.pending_fees.base_fee = prev_base_fee;
673        self.all_transactions.pending_fees.blob_fee = prev_blob_fee;
674
675        let base_fee_ordering = self.update_basefee(new_base_fee, |tx| {
676            outcome.promoted.push(tx.clone());
677        });
678
679        self.update_blob_fee(new_blob_fee, base_fee_ordering, |tx| {
680            outcome.promoted.push(tx.clone());
681        });
682    }
683
684    /// Updates the transactions for the changed senders.
685    pub(crate) fn update_accounts(
686        &mut self,
687        changed_senders: FxHashMap<SenderId, SenderInfo>,
688    ) -> UpdateOutcome<T::Transaction> {
689        // Apply the state changes to the total set of transactions which triggers sub-pool updates.
690        let mut updates = self.all_transactions.update(&changed_senders);
691
692        // Process the sub-pool updates
693        let mut outcome = UpdateOutcome::default();
694        if self.config.enforce_tracked_nonce {
695            // Track the changed accounts only after the discards: a discard that removes the
696            // sender's last transaction also removes its info, and the tracked nonce must survive
697            // for `add_transaction` to reject a stale validation result.
698            #[expect(clippy::iter_with_drain, reason = "retain the scratch buffer allocation")]
699            self.process_updates(updates.drain(..), &mut outcome);
700            self.all_transactions.sender_info.extend(changed_senders);
701        } else {
702            self.all_transactions.sender_info.extend(changed_senders);
703            #[expect(clippy::iter_with_drain, reason = "retain the scratch buffer allocation")]
704            self.process_updates(updates.drain(..), &mut outcome);
705        }
706        self.all_transactions.update_buffer = updates;
707        // update the metrics after the update
708        self.update_size_metrics();
709        outcome
710    }
711
712    /// Updates the entire pool after a new block was mined.
713    ///
714    /// This removes all mined transactions, updates according to the new base fee and blob fee and
715    /// rechecks sender allowance based on the given changed sender infos.
716    pub(crate) fn on_canonical_state_change(
717        &mut self,
718        block_info: BlockInfo,
719        mined_transactions: Vec<TxHash>,
720        changed_senders: FxHashMap<SenderId, SenderInfo>,
721        _update_kind: PoolUpdateKind,
722    ) -> OnNewCanonicalStateOutcome<T::Transaction> {
723        // update block info
724        let block_hash = block_info.last_seen_block_hash;
725
726        // This update changes many pending transactions and does not evict. Building the eviction
727        // order again at the next eviction is cheaper than keeping it up to date.
728        self.pending_pool.clear_highest_nonces_by_priority();
729
730        // Remove all transaction that were included in the block
731        let mut removed_txs_count = 0;
732        for tx_hash in &mined_transactions {
733            if self.prune_transaction_by_hash(tx_hash).is_some() {
734                removed_txs_count += 1;
735            }
736        }
737
738        // Update removed transactions metric
739        self.metrics.removed_transactions.increment(removed_txs_count);
740
741        // Update fees internally first without triggering subpool updates based on fee movements
742        // This must happen before we update the changed so that all account updates use the new fee
743        // values, this way all changed accounts remain unaffected by the fee updates that are
744        // performed in next step and we don't collect promotions twice
745        let (prev_base_fee, prev_blob_fee) =
746            self.update_pending_fees_only(block_info.pending_basefee, block_info.pending_blob_fee);
747
748        // Now update accounts with the new fees already set
749        let mut outcome = self.update_accounts(changed_senders);
750
751        // Apply subpool updates based on fee changes
752        // This will record any additional promotions based on fee movements
753        self.apply_fee_updates(prev_base_fee, prev_blob_fee, &mut outcome);
754
755        // Update the rest of block info (without triggering fee updates again)
756        self.all_transactions.set_block_info(block_info);
757
758        self.update_transaction_type_metrics();
759        self.metrics.performed_state_updates.increment(1);
760
761        OnNewCanonicalStateOutcome {
762            block_hash,
763            mined: mined_transactions,
764            promoted: outcome.promoted,
765            discarded: outcome.discarded,
766        }
767    }
768
769    /// Update sub-pools size metrics.
770    pub(crate) fn update_size_metrics(&self) {
771        self.all_transactions.update_size_metrics();
772        let stats = self.size();
773        self.metrics.pending_pool_transactions.set(stats.pending as f64);
774        self.metrics.pending_pool_size_bytes.set(stats.pending_size as f64);
775        self.metrics.basefee_pool_transactions.set(stats.basefee as f64);
776        self.metrics.basefee_pool_size_bytes.set(stats.basefee_size as f64);
777        self.metrics.queued_pool_transactions.set(stats.queued as f64);
778        self.metrics.queued_pool_size_bytes.set(stats.queued_size as f64);
779        self.metrics.blob_pool_transactions.set(stats.blob as f64);
780        self.metrics.blob_pool_size_bytes.set(stats.blob_size as f64);
781        self.metrics.total_transactions.set(stats.total as f64);
782    }
783
784    /// Updates transaction type metrics for the entire pool.
785    pub(crate) fn update_transaction_type_metrics(&self) {
786        let counts = &self.all_transactions.tx_type_counts;
787        self.metrics.total_legacy_transactions.set(counts.legacy as f64);
788        self.metrics.total_eip2930_transactions.set(counts.eip2930 as f64);
789        self.metrics.total_eip1559_transactions.set(counts.eip1559 as f64);
790        self.metrics.total_eip4844_transactions.set(counts.eip4844 as f64);
791        self.metrics.total_eip7702_transactions.set(counts.eip7702 as f64);
792        self.metrics.total_other_transactions.set(counts.other as f64);
793    }
794
795    pub(crate) fn add_transaction(
796        &mut self,
797        tx: ValidPoolTransaction<T::Transaction>,
798        mut on_chain_balance: U256,
799        mut on_chain_nonce: u64,
800        on_chain_code_hash: Option<B256>,
801    ) -> PoolResult<AddedTransaction<T::Transaction>> {
802        if self.contains(tx.hash()) {
803            return Err(PoolError::new(*tx.hash(), PoolErrorKind::AlreadyImported))
804        }
805
806        // Validation reads state outside the pool lock, so its snapshot can predate the last
807        // canonical update. Opt-in because it assumes nonces only move forward, which a reorg
808        // breaks. Transactions exempt from the nonce check keep the validator's verdict.
809        if self.config.enforce_tracked_nonce &&
810            tx.transaction.requires_nonce_check() &&
811            let Some(info) = self.all_transactions.sender_info.get(&tx.sender_id()) &&
812            info.state_nonce > on_chain_nonce
813        {
814            // Below the tracked nonce the transaction was validated against outdated state;
815            // inserted as pending it would shadow the sender's executable transactions in the
816            // payload builder.
817            if tx.nonce() < info.state_nonce {
818                return Err(PoolError::new(
819                    *tx.hash(),
820                    InvalidPoolTransactionError::Consensus(
821                        InvalidTransactionError::NonceNotConsistent {
822                            tx: tx.nonce(),
823                            state: info.state_nonce,
824                        },
825                    ),
826                ))
827            }
828            on_chain_nonce = info.state_nonce;
829            on_chain_balance = info.balance;
830        }
831
832        self.validate_auth(&tx, on_chain_nonce, on_chain_code_hash)?;
833
834        // Update sender info with balance and nonce
835        self.all_transactions
836            .sender_info
837            .entry(tx.sender_id())
838            .or_default()
839            .update(on_chain_nonce, on_chain_balance);
840
841        match self.all_transactions.insert_tx(tx, on_chain_balance, on_chain_nonce) {
842            Ok(InsertOk { transaction, move_to, replaced_tx, mut updates, state }) => {
843                // Interleave update processing and new-tx insertion so that live
844                // `BestTransactions` iterators always receive transactions in nonce order.
845                // Updates are already in nonce-ascending order, so we split them around
846                // the new transaction's nonce:
847                //  1. Promote lower-nonce txs first  (e.g. balance-unlock scenario)
848                //  2. Add the new transaction
849                //  3. Promote higher-nonce txs last   (e.g. gap-fill scenario)
850                let new_nonce = transaction.id().nonce;
851                let split = updates.partition_point(|u| u.id.nonce < new_nonce);
852                let mut outcome = UpdateOutcome::default();
853                #[expect(clippy::iter_with_drain, reason = "retain the scratch buffer allocation")]
854                let mut drain = updates.drain(..);
855                self.process_updates(drain.by_ref().take(split), &mut outcome);
856                self.add_new_transaction(transaction.clone(), replaced_tx.clone(), move_to);
857                self.process_updates(drain, &mut outcome);
858                self.all_transactions.update_buffer = updates;
859                let UpdateOutcome { promoted, discarded } = outcome;
860                self.metrics.inserted_transactions.increment(1);
861
862                let replaced = replaced_tx.map(|(tx, _)| tx);
863
864                // This transaction was moved to the pending pool.
865                let res = if move_to.is_pending() {
866                    AddedTransaction::Pending(AddedPendingTransaction {
867                        transaction,
868                        promoted,
869                        discarded,
870                        replaced,
871                    })
872                } else {
873                    // Determine the specific queued reason based on the transaction state
874                    let queued_reason = state.determine_queued_reason(move_to);
875                    AddedTransaction::Parked {
876                        transaction,
877                        subpool: move_to,
878                        replaced,
879                        queued_reason,
880                        promoted,
881                    }
882                };
883
884                Ok(res)
885            }
886            Err(err) => {
887                // Update invalid transactions metric
888                self.metrics.invalid_transactions.increment(1);
889                match err {
890                    InsertErr::Underpriced { existing: _, transaction } => Err(PoolError::new(
891                        *transaction.hash(),
892                        PoolErrorKind::ReplacementUnderpriced,
893                    )),
894                    InsertErr::FeeCapBelowMinimumProtocolFeeCap { transaction, fee_cap } => {
895                        Err(PoolError::new(
896                            *transaction.hash(),
897                            PoolErrorKind::FeeCapBelowMinimumProtocolFeeCap(fee_cap),
898                        ))
899                    }
900                    InsertErr::ExceededSenderTransactionsCapacity { transaction } => {
901                        Err(PoolError::new(
902                            *transaction.hash(),
903                            PoolErrorKind::SpammerExceededCapacity(transaction.sender()),
904                        ))
905                    }
906                    InsertErr::TxGasLimitMoreThanAvailableBlockGas {
907                        transaction,
908                        block_gas_limit,
909                        tx_gas_limit,
910                    } => Err(PoolError::new(
911                        *transaction.hash(),
912                        PoolErrorKind::InvalidTransaction(
913                            InvalidPoolTransactionError::ExceedsGasLimit(
914                                tx_gas_limit,
915                                block_gas_limit,
916                            ),
917                        ),
918                    )),
919                    InsertErr::BlobTxHasNonceGap { transaction } => Err(PoolError::new(
920                        *transaction.hash(),
921                        PoolErrorKind::InvalidTransaction(
922                            Eip4844PoolTransactionError::Eip4844NonceGap.into(),
923                        ),
924                    )),
925                    InsertErr::Overdraft { transaction } => Err(PoolError::new(
926                        *transaction.hash(),
927                        PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Overdraft {
928                            cost: *transaction.cost(),
929                            balance: on_chain_balance,
930                        }),
931                    )),
932                    InsertErr::TxTypeConflict { transaction } => Err(PoolError::new(
933                        *transaction.hash(),
934                        PoolErrorKind::ExistingConflictingTransactionType(
935                            transaction.sender(),
936                            transaction.tx_type(),
937                        ),
938                    )),
939                }
940            }
941        }
942    }
943
944    /// Determines if the tx sender is delegated or has a  pending delegation, and if so, ensures
945    /// they have at most one configured amount of in-flight **executable** transactions (default at
946    /// most one), e.g. disallow stacked and nonce-gapped transactions from the account.
947    fn check_delegation_limit(
948        &self,
949        transaction: &ValidPoolTransaction<T::Transaction>,
950        on_chain_nonce: u64,
951        on_chain_code_hash: Option<B256>,
952    ) -> Result<(), PoolError> {
953        // Short circuit if the sender has neither delegation nor pending delegation.
954        if (on_chain_code_hash.is_none() || on_chain_code_hash == Some(KECCAK_EMPTY)) &&
955            !self.all_transactions.auths.contains_key(&transaction.sender_id())
956        {
957            return Ok(())
958        }
959
960        let mut txs_by_sender =
961            self.pending_pool.iter_txs_by_sender(transaction.sender_id()).peekable();
962
963        if txs_by_sender.peek().is_none() {
964            // Transaction with gapped nonce is not supported for delegated accounts
965            // but transaction can arrive out of order if more slots are allowed
966            // by default with a slot limit of 1 this will fail if the transaction's nonce >
967            // on_chain
968            let nonce_gap_distance = transaction.nonce().saturating_sub(on_chain_nonce);
969            if nonce_gap_distance >= self.config.max_inflight_delegated_slot_limit as u64 {
970                return Err(PoolError::new(
971                    *transaction.hash(),
972                    PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip7702(
973                        Eip7702PoolTransactionError::OutOfOrderTxFromDelegated,
974                    )),
975                ))
976            }
977            return Ok(())
978        }
979
980        let mut count = 0;
981        for id in txs_by_sender {
982            if id == &transaction.transaction_id {
983                // Transaction replacement is supported
984                return Ok(())
985            }
986            count += 1;
987        }
988
989        if count < self.config.max_inflight_delegated_slot_limit {
990            // account still has an available slot
991            return Ok(())
992        }
993
994        Err(PoolError::new(
995            *transaction.hash(),
996            PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip7702(
997                Eip7702PoolTransactionError::InflightTxLimitReached,
998            )),
999        ))
1000    }
1001
1002    /// This verifies that the transaction complies with code authorization
1003    /// restrictions brought by EIP-7702 transaction type:
1004    /// 1. Any account with a deployed delegation or an in-flight authorization to deploy a
1005    ///    delegation will only be allowed a certain amount of transaction slots (default 1) instead
1006    ///    of the standard limit. This is due to the possibility of the account being sweeped by an
1007    ///    unrelated account.
1008    /// 2. In case the pool is tracking a pending / queued transaction from a specific account, at
1009    ///    most the configured inflight delegation slot limit of in-flight transactions is allowed;
1010    ///    any additional delegated transactions from that account will be rejected.
1011    fn validate_auth(
1012        &self,
1013        transaction: &ValidPoolTransaction<T::Transaction>,
1014        on_chain_nonce: u64,
1015        on_chain_code_hash: Option<B256>,
1016    ) -> Result<(), PoolError> {
1017        // Ensure in-flight limit for delegated accounts or those with a pending authorization.
1018        self.check_delegation_limit(transaction, on_chain_nonce, on_chain_code_hash)?;
1019
1020        if let Some(authority_list) = &transaction.authority_ids {
1021            for sender_id in authority_list {
1022                // Ensure authority does not exceed the configured inflight delegation slot limit.
1023                if self
1024                    .all_transactions
1025                    .txs_iter(*sender_id)
1026                    .nth(self.config.max_inflight_delegated_slot_limit)
1027                    .is_some()
1028                {
1029                    return Err(PoolError::new(
1030                        *transaction.hash(),
1031                        PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip7702(
1032                            Eip7702PoolTransactionError::AuthorityReserved,
1033                        )),
1034                    ))
1035                }
1036            }
1037        }
1038
1039        Ok(())
1040    }
1041
1042    /// Maintenance task to apply a series of updates.
1043    ///
1044    /// This will move/discard the given transaction according to the `PoolUpdate`
1045    fn process_updates(
1046        &mut self,
1047        updates: impl IntoIterator<Item = PoolUpdate>,
1048        outcome: &mut UpdateOutcome<T::Transaction>,
1049    ) {
1050        let mut removed = 0;
1051        for PoolUpdate { id, current, destination } in updates {
1052            match destination {
1053                Destination::Discard => {
1054                    // remove the transaction from the pool and subpool
1055                    if let Some(tx) = self.prune_transaction_by_id(&id) {
1056                        outcome.discarded.push(tx);
1057                    }
1058                    removed += 1;
1059                }
1060                Destination::Pool(move_to) => {
1061                    debug_assert_ne!(&move_to, &current, "destination must be different");
1062                    let moved = self.move_transaction(current, move_to, &id);
1063                    if move_to.is_pending() &&
1064                        let Some(tx) = moved
1065                    {
1066                        trace!(target: "txpool", hash=%tx.transaction.hash(), "Promoted transaction to pending");
1067                        outcome.promoted.push(tx);
1068                    }
1069                }
1070            }
1071        }
1072
1073        if removed > 0 {
1074            self.metrics.removed_transactions.increment(removed);
1075        }
1076    }
1077
1078    /// Moves a transaction from one sub pool to another.
1079    ///
1080    /// This will remove the given transaction from one sub-pool and insert it into the other
1081    /// sub-pool.
1082    fn move_transaction(
1083        &mut self,
1084        from: SubPool,
1085        to: SubPool,
1086        id: &TransactionId,
1087    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1088        let tx = self.remove_from_subpool(from, id)?;
1089        self.add_transaction_to_subpool(to, tx.clone());
1090        Some(tx)
1091    }
1092
1093    /// Removes and returns all matching transactions from the pool.
1094    ///
1095    /// Note: this does not advance any descendants of the removed transactions and does not apply
1096    /// any additional updates.
1097    pub(crate) fn remove_transactions(
1098        &mut self,
1099        hashes: Vec<TxHash>,
1100    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1101        let txs =
1102            hashes.into_iter().filter_map(|hash| self.remove_transaction_by_hash(&hash)).collect();
1103        self.update_size_metrics();
1104        txs
1105    }
1106
1107    /// Removes and returns all matching transactions and their descendants from the pool.
1108    pub(crate) fn remove_transactions_and_descendants(
1109        &mut self,
1110        hashes: Vec<TxHash>,
1111    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1112        let mut removed = Vec::new();
1113        for hash in hashes {
1114            if let Some(tx) = self.remove_transaction_by_hash(&hash) {
1115                removed.push(tx.clone());
1116                self.remove_descendants(tx.id(), &mut removed);
1117            }
1118        }
1119        self.update_size_metrics();
1120        removed
1121    }
1122
1123    /// Removes all transactions from the given sender.
1124    pub(crate) fn remove_transactions_by_sender(
1125        &mut self,
1126        sender_id: SenderId,
1127    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1128        let mut removed = Vec::new();
1129        let txs = self.get_transactions_by_sender(sender_id);
1130        for tx in txs {
1131            if let Some(tx) = self.remove_transaction(tx.id()) {
1132                removed.push(tx);
1133            }
1134        }
1135        self.update_size_metrics();
1136        removed
1137    }
1138
1139    /// Prunes and returns all matching transactions from the pool.
1140    ///
1141    /// This uses [`Self::prune_transaction_by_hash`] which does **not** park descendant
1142    /// transactions, so they remain in their current sub-pool and can be included in subsequent
1143    /// blocks.
1144    pub(crate) fn prune_transactions(
1145        &mut self,
1146        hashes: Vec<TxHash>,
1147    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1148        let txs =
1149            hashes.into_iter().filter_map(|hash| self.prune_transaction_by_hash(&hash)).collect();
1150        self.update_size_metrics();
1151        txs
1152    }
1153
1154    /// Remove the transaction from the __entire__ pool.
1155    ///
1156    /// This includes the total set of transaction and the subpool it currently resides in.
1157    fn remove_transaction(
1158        &mut self,
1159        id: &TransactionId,
1160    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1161        let (tx, pool) = self.all_transactions.remove_transaction(id)?;
1162        self.remove_from_subpool(pool, tx.id())
1163    }
1164
1165    /// Remove the transaction from the entire pool via its hash. This includes the total set of
1166    /// transactions and the subpool it currently resides in.
1167    ///
1168    /// This treats the descendants as if this transaction is discarded and removing the transaction
1169    /// reduces a nonce gap.
1170    fn remove_transaction_by_hash(
1171        &mut self,
1172        tx_hash: &B256,
1173    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1174        let (tx, pool) = self.all_transactions.remove_transaction_by_hash(tx_hash)?;
1175
1176        // After a tx is removed, its descendants must become parked due to the nonce gap
1177        let mut updates = self.all_transactions.park_descendant_transactions(tx.id());
1178        #[expect(clippy::iter_with_drain, reason = "retain the scratch buffer allocation")]
1179        self.process_updates(updates.drain(..), &mut UpdateOutcome::default());
1180        self.all_transactions.update_buffer = updates;
1181        self.remove_from_subpool(pool, tx.id())
1182    }
1183
1184    /// This removes the transaction from the pool and advances any descendant state inside the
1185    /// subpool.
1186    ///
1187    /// This is intended to be used when a transaction is included in a block,
1188    /// [`Self::on_canonical_state_change`]. So its descendants will not change from pending to
1189    /// parked, just like what we do in `remove_transaction_by_hash`.
1190    fn prune_transaction_by_hash(
1191        &mut self,
1192        tx_hash: &B256,
1193    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1194        let (tx, pool) = self.all_transactions.remove_transaction_by_hash(tx_hash)?;
1195        self.remove_from_subpool(pool, tx.id())
1196    }
1197    /// This removes the transaction from the pool and advances any descendant state inside the
1198    /// subpool.
1199    ///
1200    /// This is intended to be used when we call [`Self::process_updates`].
1201    fn prune_transaction_by_id(
1202        &mut self,
1203        tx_id: &TransactionId,
1204    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1205        let (tx, pool) = self.all_transactions.remove_transaction_by_id(tx_id)?;
1206        self.remove_from_subpool(pool, tx.id())
1207    }
1208
1209    /// Removes the transaction from the given pool.
1210    ///
1211    /// Caution: this only removes the tx from the sub-pool and not from the pool itself
1212    fn remove_from_subpool(
1213        &mut self,
1214        pool: SubPool,
1215        tx: &TransactionId,
1216    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1217        let tx = match pool {
1218            SubPool::Queued => self.queued_pool.remove_transaction(tx),
1219            SubPool::Pending => self.pending_pool.remove_transaction(tx),
1220            SubPool::BaseFee => self.basefee_pool.remove_transaction(tx),
1221            SubPool::Blob => self.blob_pool.remove_transaction(tx),
1222        };
1223
1224        if let Some(ref tx) = tx {
1225            // We trace here instead of in subpool structs directly, because the `ParkedPool` type
1226            // is generic and it would not be possible to distinguish whether a transaction is
1227            // being removed from the `BaseFee` pool, or the `Queued` pool.
1228            trace!(target: "txpool", hash=%tx.transaction.hash(), ?pool, "Removed transaction from a subpool");
1229        }
1230
1231        tx
1232    }
1233
1234    /// Removes _only_ the descendants of the given transaction from the __entire__ pool.
1235    ///
1236    /// All removed transactions are added to the `removed` vec.
1237    fn remove_descendants(
1238        &mut self,
1239        tx: &TransactionId,
1240        removed: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
1241    ) {
1242        let mut id = *tx;
1243
1244        // this will essentially pop _all_ descendant transactions one by one
1245        loop {
1246            let descendant =
1247                self.all_transactions.descendant_txs_exclusive(&id).map(|(id, _)| *id).next();
1248            if let Some(descendant) = descendant {
1249                if let Some(tx) = self.remove_transaction(&descendant) {
1250                    removed.push(tx)
1251                }
1252                id = descendant;
1253            } else {
1254                return
1255            }
1256        }
1257    }
1258
1259    /// Inserts the transaction into the given sub-pool.
1260    fn add_transaction_to_subpool(
1261        &mut self,
1262        pool: SubPool,
1263        tx: Arc<ValidPoolTransaction<T::Transaction>>,
1264    ) {
1265        // We trace here instead of in structs directly, because the `ParkedPool` type is
1266        // generic and it would not be possible to distinguish whether a transaction is being
1267        // added to the `BaseFee` pool, or the `Queued` pool.
1268        trace!(target: "txpool", hash=%tx.transaction.hash(), ?pool, "Adding transaction to a subpool");
1269        match pool {
1270            SubPool::Queued => self.queued_pool.add_transaction(tx),
1271            SubPool::Pending => {
1272                self.pending_pool.add_transaction(tx, self.all_transactions.pending_fees.base_fee);
1273            }
1274            SubPool::BaseFee => {
1275                self.basefee_pool.add_transaction(tx);
1276            }
1277            SubPool::Blob => {
1278                self.blob_pool.add_transaction(tx);
1279            }
1280        }
1281    }
1282
1283    /// Inserts the transaction into the given sub-pool.
1284    /// Optionally, removes the replacement transaction.
1285    fn add_new_transaction(
1286        &mut self,
1287        transaction: Arc<ValidPoolTransaction<T::Transaction>>,
1288        replaced: Option<(Arc<ValidPoolTransaction<T::Transaction>>, SubPool)>,
1289        pool: SubPool,
1290    ) {
1291        if let Some((replaced, replaced_pool)) = replaced {
1292            // Remove the replaced transaction
1293            self.remove_from_subpool(replaced_pool, replaced.id());
1294        }
1295
1296        self.add_transaction_to_subpool(pool, transaction)
1297    }
1298
1299    /// Ensures that the transactions in the sub-pools are within the given bounds.
1300    ///
1301    /// If the current size exceeds the given bounds, the worst transactions are evicted from the
1302    /// pool and returned.
1303    ///
1304    /// This returns all transactions that were removed from the entire pool.
1305    pub(crate) fn discard_worst(&mut self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1306        let mut removed = Vec::new();
1307
1308        // Helper macro that discards the worst transactions for the pools
1309        macro_rules! discard_worst {
1310            ($this:ident, $removed:ident, [$($limit:ident => ($pool:ident, $metric:ident)),* $(,)*]) => {
1311                $ (
1312                while $this.$pool.exceeds(&$this.config.$limit)
1313                    {
1314                        trace!(
1315                            target: "txpool",
1316                            "discarding transactions from {}, limit: {:?}, curr size: {}, curr len: {}",
1317                            stringify!($pool),
1318                            $this.config.$limit,
1319                            $this.$pool.size(),
1320                            $this.$pool.len(),
1321                        );
1322
1323                        // 1. first remove the worst transaction from the subpool
1324                        let removed_from_subpool = $this.$pool.truncate_pool($this.config.$limit.clone());
1325
1326                        trace!(
1327                            target: "txpool",
1328                            "removed {} transactions from {}, limit: {:?}, curr size: {}, curr len: {}",
1329                            removed_from_subpool.len(),
1330                            stringify!($pool),
1331                            $this.config.$limit,
1332                            $this.$pool.size(),
1333                            $this.$pool.len()
1334                        );
1335                        $this.metrics.$metric.increment(removed_from_subpool.len() as u64);
1336
1337                        // 2. remove all transactions from the total set
1338                        for tx in removed_from_subpool {
1339                            $this.all_transactions.remove_transaction(tx.id());
1340
1341                            let id = *tx.id();
1342
1343                            // keep track of removed transaction
1344                            removed.push(tx);
1345
1346                            // 3. remove all its descendants from the entire pool
1347                            $this.remove_descendants(&id, &mut $removed);
1348                        }
1349                    }
1350
1351                )*
1352            };
1353        }
1354
1355        discard_worst!(
1356            self, removed, [
1357                pending_limit => (pending_pool, pending_transactions_evicted),
1358                basefee_limit => (basefee_pool, basefee_transactions_evicted),
1359                blob_limit    => (blob_pool, blob_transactions_evicted),
1360                queued_limit  => (queued_pool, queued_transactions_evicted),
1361            ]
1362        );
1363
1364        removed
1365    }
1366
1367    /// Number of transactions in the entire pool
1368    pub(crate) fn len(&self) -> usize {
1369        self.all_transactions.len()
1370    }
1371
1372    /// Whether the pool is empty
1373    pub(crate) fn is_empty(&self) -> bool {
1374        self.all_transactions.is_empty()
1375    }
1376
1377    /// Asserts all invariants of the  pool's:
1378    ///
1379    ///  - All maps are bijections (`by_id`, `by_hash`)
1380    ///  - Total size is equal to the sum of all sub-pools
1381    ///
1382    /// # Panics
1383    /// if any invariant is violated
1384    #[cfg(any(test, feature = "test-utils"))]
1385    pub fn assert_invariants(&self) {
1386        let size = self.size();
1387        let actual = size.basefee + size.pending + size.queued + size.blob;
1388        assert_eq!(
1389            size.total, actual,
1390            "total size must be equal to the sum of all sub-pools, basefee:{}, pending:{}, queued:{}, blob:{}",
1391            size.basefee, size.pending, size.queued, size.blob
1392        );
1393        self.all_transactions.assert_invariants();
1394        self.pending_pool.assert_invariants();
1395        self.basefee_pool.assert_invariants();
1396        self.queued_pool.assert_invariants();
1397        self.blob_pool.assert_invariants();
1398    }
1399}
1400
1401#[cfg(any(test, feature = "test-utils"))]
1402impl TxPool<crate::test_utils::MockOrdering> {
1403    /// Creates a mock instance for testing.
1404    pub fn mock() -> Self {
1405        Self::new(crate::test_utils::MockOrdering::default(), PoolConfig::default())
1406    }
1407}
1408
1409#[cfg(test)]
1410impl<T: TransactionOrdering> Drop for TxPool<T> {
1411    fn drop(&mut self) {
1412        self.assert_invariants();
1413    }
1414}
1415
1416impl<T: TransactionOrdering> TxPool<T> {
1417    /// Pending subpool
1418    pub const fn pending(&self) -> &PendingPool<T> {
1419        &self.pending_pool
1420    }
1421
1422    /// Base fee subpool
1423    pub const fn base_fee(&self) -> &ParkedPool<BasefeeOrd<T::Transaction>> {
1424        &self.basefee_pool
1425    }
1426
1427    /// Queued sub pool
1428    pub const fn queued(&self) -> &ParkedPool<QueuedOrd<T::Transaction>> {
1429        &self.queued_pool
1430    }
1431}
1432
1433impl<T: TransactionOrdering> fmt::Debug for TxPool<T> {
1434    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1435        f.debug_struct("TxPool").field("config", &self.config).finish_non_exhaustive()
1436    }
1437}
1438
1439/// Minimum number of live senders before the changed-sender ratio can trigger a full update.
1440///
1441/// Account-update benchmarks put the paths near parity at 500 senders and favor a full traversal
1442/// from 1,000 senders at the ratio below.
1443const FULL_UPDATE_MIN_SENDERS: usize = 1_000;
1444
1445/// Run a full update when at least one in this many live senders changed.
1446const FULL_UPDATE_SENDER_RATIO: usize = 4;
1447
1448/// Container for _all_ transaction in the pool.
1449///
1450/// This is the sole entrypoint that's guarding all sub-pools, all sub-pool actions are always
1451/// derived from this set. Updates returned from this type must be applied to the sub-pools.
1452pub(crate) struct AllTransactions<T: PoolTransaction> {
1453    /// Minimum base fee required by the protocol.
1454    ///
1455    /// Transactions with a lower base fee will never be included by the chain
1456    minimal_protocol_basefee: u64,
1457    /// The max gas limit of the block
1458    block_gas_limit: u64,
1459    /// Max number of executable transaction slots guaranteed per account
1460    max_account_slots: usize,
1461    /// _All_ transactions identified by their hash.
1462    by_hash: B256Map<Arc<ValidPoolTransaction<T>>>,
1463    /// _All_ transaction in the pool sorted by their sender and nonce pair.
1464    txs: BTreeMap<TransactionId, PoolInternalTransaction<T>>,
1465    /// Contains the currently known information about the senders.
1466    ///
1467    /// With `PoolConfig::enforce_tracked_nonce` entries outlive a sender's transactions when an
1468    /// account update discards them, so a validation result computed against older state cannot
1469    /// regress the tracked nonce.
1470    sender_info: FxHashMap<SenderId, SenderInfo>,
1471    /// Tracks the number of transactions by sender that are currently in the pool.
1472    tx_counter: FxHashMap<SenderId, usize>,
1473    /// The current block number the pool keeps track of.
1474    last_seen_block_number: u64,
1475    /// The current block hash the pool keeps track of.
1476    last_seen_block_hash: B256,
1477    /// Expected blob and base fee for the pending block.
1478    pending_fees: PendingFees,
1479    /// Snapshot of [`Self::pending_fees`] recorded after the most recent all-transactions pass in
1480    /// [`Self::update`].
1481    ///
1482    /// The all-transactions pass calls [`Self::update_txs`] over every entry in [`Self::txs`].
1483    /// This field is initialized to the default fees because an empty pool trivially reflects
1484    /// them. It is not necessarily the immediately preceding fee value: partial sender updates
1485    /// and fee changes do not modify it.
1486    last_full_update_fees: PendingFees,
1487    /// Configured price bump settings for replacements
1488    price_bumps: PriceBumpConfig,
1489    /// How to handle [`TransactionOrigin::Local`](crate::TransactionOrigin) transactions.
1490    local_transactions_config: Arc<LocalTransactionConfig>,
1491    /// All accounts with a pooled authorization
1492    auths: FxHashMap<SenderId, B256Set>,
1493    /// Number of transactions in the pool by transaction type, tracked incrementally so metrics
1494    /// updates don't require iterating the entire pool.
1495    tx_type_counts: TxTypeCounts,
1496    /// Scratch space for sub-pool changes. Update methods take this buffer and return it to
1497    /// `TxPool`, which drains the updates and restores the empty buffer for reuse.
1498    update_buffer: Vec<PoolUpdate>,
1499    /// All Transactions metrics
1500    metrics: AllTransactionsMetrics,
1501}
1502
1503impl<T: PoolTransaction> AllTransactions<T> {
1504    /// Create a new instance
1505    fn new(config: &PoolConfig) -> Self {
1506        Self {
1507            max_account_slots: config.max_account_slots,
1508            price_bumps: config.price_bumps,
1509            local_transactions_config: Arc::new(config.local_transactions_config.clone()),
1510            minimal_protocol_basefee: config.minimal_protocol_basefee,
1511            block_gas_limit: config.gas_limit,
1512            ..Default::default()
1513        }
1514    }
1515
1516    /// Returns an iterator over all _unique_ hashes in the pool
1517    #[expect(dead_code)]
1518    pub(crate) fn hashes_iter(&self) -> impl Iterator<Item = TxHash> + '_ {
1519        self.by_hash.keys().copied()
1520    }
1521
1522    /// Returns an iterator over all transactions in the pool
1523    pub(crate) fn transactions_iter(
1524        &self,
1525    ) -> impl Iterator<Item = &Arc<ValidPoolTransaction<T>>> + '_ {
1526        self.by_hash.values()
1527    }
1528
1529    /// Returns if the transaction for the given hash is already included in this pool
1530    pub(crate) fn contains(&self, tx_hash: &TxHash) -> bool {
1531        self.by_hash.contains_key(tx_hash)
1532    }
1533
1534    /// Returns the internal transaction with additional metadata
1535    pub(crate) fn get(&self, id: &TransactionId) -> Option<&PoolInternalTransaction<T>> {
1536        self.txs.get(id)
1537    }
1538
1539    /// Increments the transaction counter for the sender
1540    pub(crate) fn tx_inc(&mut self, sender: SenderId) {
1541        let count = self.tx_counter.entry(sender).or_default();
1542        *count += 1;
1543        self.metrics.all_transactions_by_all_senders.increment(1.0);
1544    }
1545
1546    /// Decrements the transaction counter for the sender
1547    pub(crate) fn tx_decr(&mut self, sender: SenderId) {
1548        if let hash_map::Entry::Occupied(mut entry) = self.tx_counter.entry(sender) {
1549            let count = entry.get_mut();
1550            if *count == 1 {
1551                entry.remove();
1552                self.sender_info.remove(&sender);
1553                self.metrics.all_transactions_by_all_senders.decrement(1.0);
1554                return
1555            }
1556            *count -= 1;
1557            self.metrics.all_transactions_by_all_senders.decrement(1.0);
1558        }
1559    }
1560
1561    /// Updates the block specific info
1562    fn set_block_info(&mut self, block_info: BlockInfo) {
1563        let BlockInfo {
1564            block_gas_limit,
1565            last_seen_block_hash,
1566            last_seen_block_number,
1567            pending_basefee,
1568            pending_blob_fee,
1569        } = block_info;
1570        self.last_seen_block_number = last_seen_block_number;
1571        self.last_seen_block_hash = last_seen_block_hash;
1572
1573        self.pending_fees.base_fee = pending_basefee;
1574        self.metrics.base_fee.set(pending_basefee as f64);
1575
1576        self.block_gas_limit = block_gas_limit;
1577
1578        if let Some(pending_blob_fee) = pending_blob_fee {
1579            self.pending_fees.blob_fee = pending_blob_fee;
1580            self.metrics.blob_base_fee.set(pending_blob_fee as f64);
1581        }
1582    }
1583
1584    /// Updates the size metrics
1585    pub(crate) fn update_size_metrics(&self) {
1586        self.metrics.all_transactions_by_hash.set(self.by_hash.len() as f64);
1587        self.metrics.all_transactions_by_id.set(self.txs.len() as f64);
1588    }
1589
1590    /// Rechecks all transactions in the pool against the changes.
1591    ///
1592    /// Possible changes are:
1593    ///
1594    /// For all transactions:
1595    ///   - decreased basefee: promotes from `basefee` to `pending` sub-pool.
1596    ///   - increased basefee: demotes from `pending` to `basefee` sub-pool.
1597    ///
1598    /// Individually:
1599    ///   - decreased sender allowance: demote from (`basefee`|`pending`) to `queued`.
1600    ///   - increased sender allowance: promote from `queued` to
1601    ///       - `pending` if basefee condition is met.
1602    ///       - `basefee` if basefee condition is _not_ met.
1603    ///
1604    /// Additionally, this will also update the `cumulative_gas_used` for transactions of a sender
1605    /// that got transaction included in the block.
1606    pub(crate) fn update(
1607        &mut self,
1608        changed_accounts: &FxHashMap<SenderId, SenderInfo>,
1609    ) -> Vec<PoolUpdate> {
1610        let mut updates = std::mem::take(&mut self.update_buffer);
1611        let pending_fees = self.pending_fees;
1612
1613        let update_all = self.last_full_update_fees != self.pending_fees ||
1614            self.should_update_all_senders(changed_accounts.len());
1615
1616        if update_all {
1617            Self::update_txs(pending_fees, changed_accounts, &mut updates, self.txs.iter_mut());
1618            self.last_full_update_fees = self.pending_fees;
1619        } else {
1620            // Fee eligibility is unchanged, while nonce gaps, ancestors, and cumulative cost are
1621            // sender-local; only transactions from changed accounts can require updates.
1622            for sender in changed_accounts.keys() {
1623                let range = TransactionId::new(*sender, 0)..=TransactionId::new(*sender, u64::MAX);
1624                Self::update_txs(
1625                    pending_fees,
1626                    changed_accounts,
1627                    &mut updates,
1628                    self.txs.range_mut(range),
1629                );
1630            }
1631        }
1632
1633        updates
1634    }
1635
1636    /// Returns whether one full traversal is preferable to a range lookup per changed sender.
1637    fn should_update_all_senders(&self, changed_sender_count: usize) -> bool {
1638        let pool_sender_count = self.tx_counter.len();
1639        changed_sender_count >= pool_sender_count ||
1640            (pool_sender_count >= FULL_UPDATE_MIN_SENDERS &&
1641                changed_sender_count >= pool_sender_count.div_ceil(FULL_UPDATE_SENDER_RATIO))
1642    }
1643
1644    /// Updates the given transactions, which must be ordered by [`TransactionId`] and must start
1645    /// at the lowest tracked nonce of the first sender they contain.
1646    ///
1647    /// Records a [`PoolUpdate`] for every transaction whose sub-pool changed.
1648    fn update_txs<'a, I>(
1649        pending_fees: PendingFees,
1650        changed_accounts: &FxHashMap<SenderId, SenderInfo>,
1651        updates: &mut Vec<PoolUpdate>,
1652        txs: I,
1653    ) where
1654        T: 'a,
1655        I: Iterator<Item = (&'a TransactionId, &'a mut PoolInternalTransaction<T>)>,
1656    {
1657        let mut iter = txs.peekable();
1658
1659        // Loop over all individual senders and update all affected transactions.
1660        // One sender may have up to `max_account_slots` transactions here, which means, worst case
1661        // `max_accounts_slots` need to be updated, for example if the first transaction is blocked
1662        // due to too low base fee.
1663        // However, we don't have to necessarily check every transaction of a sender. If no updates
1664        // are possible (nonce gap) then we can skip to the next sender.
1665
1666        // The `unique_sender` loop will process the first transaction of all senders, update its
1667        // state and internally update all consecutive transactions
1668        'transactions: while let Some((id, tx)) = iter.next() {
1669            macro_rules! next_sender {
1670                ($iter:ident) => {
1671                    'this: while let Some((peek, _)) = iter.peek() {
1672                        if peek.sender != id.sender {
1673                            break 'this
1674                        }
1675                        iter.next();
1676                    }
1677                };
1678            }
1679
1680            // track the balance if the sender was changed in the block
1681            // check if this is a changed account
1682            let changed_balance = if let Some(info) = changed_accounts.get(&id.sender) {
1683                // discard all transactions with a nonce lower than the current state nonce
1684                if id.nonce < info.state_nonce {
1685                    updates.push(PoolUpdate {
1686                        id: *tx.transaction.id(),
1687                        current: tx.subpool,
1688                        destination: Destination::Discard,
1689                    });
1690                    continue 'transactions
1691                }
1692
1693                let ancestor = TransactionId::ancestor(id.nonce, info.state_nonce, id.sender);
1694                // If there's no ancestor then this is the next transaction.
1695                if ancestor.is_none() {
1696                    tx.state.insert(TxState::NO_NONCE_GAPS);
1697                    tx.state.insert(TxState::NO_PARKED_ANCESTORS);
1698                    tx.cumulative_cost = U256::ZERO;
1699                    if tx.transaction.cost() > &info.balance {
1700                        // sender lacks sufficient funds to pay for this transaction
1701                        tx.state.remove(TxState::ENOUGH_BALANCE);
1702                    } else {
1703                        tx.state.insert(TxState::ENOUGH_BALANCE);
1704                    }
1705                }
1706
1707                Some(&info.balance)
1708            } else {
1709                None
1710            };
1711
1712            // If there's a nonce gap, we can shortcircuit, because there's nothing to update yet.
1713            if tx.state.has_nonce_gap() {
1714                next_sender!(iter);
1715                continue 'transactions
1716            }
1717
1718            // Since this is the first transaction of the sender, it has no parked ancestors
1719            tx.state.insert(TxState::NO_PARKED_ANCESTORS);
1720
1721            // Update the first transaction of this sender.
1722            Self::update_tx_fees(pending_fees, tx);
1723            // Track if the transaction's sub-pool changed.
1724            Self::record_subpool_update(updates, tx);
1725
1726            // Track blocking transactions.
1727            let mut has_parked_ancestor = !tx.state.is_pending();
1728
1729            let mut cumulative_cost = tx.next_cumulative_cost();
1730
1731            // the next expected nonce after this transaction: nonce + 1
1732            let mut next_nonce_in_line = tx.transaction.nonce().saturating_add(1);
1733
1734            // Update all consecutive transaction of this sender
1735            while let Some((peek, tx)) = iter.peek_mut() {
1736                if peek.sender != id.sender {
1737                    // Found the next sender we need to check
1738                    continue 'transactions
1739                }
1740
1741                if tx.transaction.nonce() == next_nonce_in_line {
1742                    // no longer nonce gapped
1743                    tx.state.insert(TxState::NO_NONCE_GAPS);
1744                } else {
1745                    // can short circuit if there's still a nonce gap
1746                    next_sender!(iter);
1747                    continue 'transactions
1748                }
1749
1750                // update for next iteration of this sender's loop
1751                next_nonce_in_line = next_nonce_in_line.saturating_add(1);
1752
1753                // update cumulative cost
1754                tx.cumulative_cost = cumulative_cost;
1755                // Update for next transaction
1756                cumulative_cost = tx.next_cumulative_cost();
1757
1758                // If the account changed in the block, check the balance.
1759                if let Some(changed_balance) = changed_balance {
1760                    if &cumulative_cost > changed_balance {
1761                        // sender lacks sufficient funds to pay for this transaction
1762                        tx.state.remove(TxState::ENOUGH_BALANCE);
1763                    } else {
1764                        tx.state.insert(TxState::ENOUGH_BALANCE);
1765                    }
1766                }
1767
1768                // Update ancestor condition.
1769                if has_parked_ancestor {
1770                    tx.state.remove(TxState::NO_PARKED_ANCESTORS);
1771                } else {
1772                    tx.state.insert(TxState::NO_PARKED_ANCESTORS);
1773                }
1774
1775                // Update and record sub-pool changes.
1776                Self::update_tx_fees(pending_fees, tx);
1777                Self::record_subpool_update(updates, tx);
1778                has_parked_ancestor = !tx.state.is_pending();
1779
1780                // Advance iterator
1781                iter.next();
1782            }
1783        }
1784    }
1785
1786    /// This will update the transaction's `subpool` based on its state.
1787    ///
1788    /// If the sub-pool derived from the state differs from the current pool, it will record a
1789    /// `PoolUpdate` for this transaction to move it to the new sub-pool.
1790    fn record_subpool_update(updates: &mut Vec<PoolUpdate>, tx: &mut PoolInternalTransaction<T>) {
1791        let current_pool = tx.subpool;
1792        tx.subpool = tx.state.into();
1793        if current_pool != tx.subpool {
1794            updates.push(PoolUpdate {
1795                id: *tx.transaction.id(),
1796                current: current_pool,
1797                destination: tx.subpool.into(),
1798            })
1799        }
1800    }
1801
1802    /// Rechecks the transaction's dynamic fee conditions.
1803    fn update_tx_fees(pending_fees: PendingFees, tx: &mut PoolInternalTransaction<T>) {
1804        match tx.transaction.max_fee_per_gas().cmp(&(pending_fees.base_fee as u128)) {
1805            Ordering::Greater | Ordering::Equal => {
1806                tx.state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
1807            }
1808            Ordering::Less => {
1809                tx.state.remove(TxState::ENOUGH_FEE_CAP_BLOCK);
1810            }
1811        }
1812
1813        match tx.transaction.max_fee_per_blob_gas() {
1814            Some(blob_fee_cap) if blob_fee_cap < pending_fees.blob_fee => {
1815                tx.state.remove(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
1816            }
1817            _ => {
1818                tx.state.insert(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
1819            }
1820        }
1821    }
1822
1823    /// Returns an iterator over all transactions for the given sender, starting with the lowest
1824    /// nonce
1825    pub(crate) fn txs_iter(
1826        &self,
1827        sender: SenderId,
1828    ) -> impl Iterator<Item = (&TransactionId, &PoolInternalTransaction<T>)> + '_ {
1829        self.txs
1830            .range((sender.start_bound(), Unbounded))
1831            .take_while(move |(other, _)| sender == other.sender)
1832    }
1833
1834    /// Returns a mutable iterator over all transactions for the given sender, starting with the
1835    /// lowest nonce
1836    #[cfg(test)]
1837    #[expect(dead_code)]
1838    pub(crate) fn txs_iter_mut(
1839        &mut self,
1840        sender: SenderId,
1841    ) -> impl Iterator<Item = (&TransactionId, &mut PoolInternalTransaction<T>)> + '_ {
1842        self.txs
1843            .range_mut((sender.start_bound(), Unbounded))
1844            .take_while(move |(other, _)| sender == other.sender)
1845    }
1846
1847    /// Returns all transactions that _follow_ after the given id and have the same sender.
1848    ///
1849    /// NOTE: The range is _exclusive_
1850    pub(crate) fn descendant_txs_exclusive<'a, 'b: 'a>(
1851        &'a self,
1852        id: &'b TransactionId,
1853    ) -> impl Iterator<Item = (&'a TransactionId, &'a PoolInternalTransaction<T>)> + 'a {
1854        self.txs.range((Excluded(id), Unbounded)).take_while(|(other, _)| id.sender == other.sender)
1855    }
1856
1857    /// Returns all transactions that _follow_ after the given id but have the same sender.
1858    ///
1859    /// NOTE: The range is _inclusive_: if the transaction that belongs to `id` it will be the
1860    /// first value.
1861    pub(crate) fn descendant_txs_inclusive<'a, 'b: 'a>(
1862        &'a self,
1863        id: &'b TransactionId,
1864    ) -> impl Iterator<Item = (&'a TransactionId, &'a PoolInternalTransaction<T>)> + 'a {
1865        self.txs.range(id..).take_while(|(other, _)| id.sender == other.sender)
1866    }
1867
1868    /// Returns all mutable transactions that _follow_ after the given id but have the same sender.
1869    ///
1870    /// NOTE: The range is _inclusive_: if the transaction that belongs to `id` it field be the
1871    /// first value.
1872    pub(crate) fn descendant_txs_mut<'a, 'b: 'a>(
1873        &'a mut self,
1874        id: &'b TransactionId,
1875    ) -> impl Iterator<Item = (&'a TransactionId, &'a mut PoolInternalTransaction<T>)> + 'a {
1876        self.txs.range_mut(id..).take_while(|(other, _)| id.sender == other.sender)
1877    }
1878
1879    /// Removes a transaction from the set using its hash.
1880    pub(crate) fn remove_transaction_by_hash(
1881        &mut self,
1882        tx_hash: &B256,
1883    ) -> Option<(Arc<ValidPoolTransaction<T>>, SubPool)> {
1884        let tx = self.by_hash.remove(tx_hash)?;
1885        let internal = self.txs.remove(&tx.transaction_id)?;
1886        self.remove_auths(&internal);
1887        self.tx_type_counts.dec(internal.transaction.transaction.ty());
1888        // decrement the counter for the sender.
1889        self.tx_decr(tx.sender_id());
1890        Some((tx, internal.subpool))
1891    }
1892
1893    /// Removes a transaction from the set using its id.
1894    ///
1895    /// This is intended for processing updates after state changes.
1896    pub(crate) fn remove_transaction_by_id(
1897        &mut self,
1898        tx_id: &TransactionId,
1899    ) -> Option<(Arc<ValidPoolTransaction<T>>, SubPool)> {
1900        let internal = self.txs.remove(tx_id)?;
1901        let tx = self.by_hash.remove(internal.transaction.hash())?;
1902        self.remove_auths(&internal);
1903        self.tx_type_counts.dec(internal.transaction.transaction.ty());
1904        // decrement the counter for the sender.
1905        self.tx_decr(tx.sender_id());
1906        Some((tx, internal.subpool))
1907    }
1908
1909    /// If a tx is removed (_not_ mined), all descendants are set to parked due to the nonce gap
1910    pub(crate) fn park_descendant_transactions(
1911        &mut self,
1912        tx_id: &TransactionId,
1913    ) -> Vec<PoolUpdate> {
1914        let mut updates = std::mem::take(&mut self.update_buffer);
1915
1916        for (id, tx) in self.descendant_txs_mut(tx_id) {
1917            let current_pool = tx.subpool;
1918
1919            tx.state.remove(TxState::NO_NONCE_GAPS);
1920
1921            // update the pool based on the state.
1922            tx.subpool = tx.state.into();
1923
1924            // check if anything changed.
1925            if current_pool != tx.subpool {
1926                updates.push(PoolUpdate {
1927                    id: *id,
1928                    current: current_pool,
1929                    destination: tx.subpool.into(),
1930                })
1931            }
1932        }
1933
1934        updates
1935    }
1936
1937    /// Removes a transaction from the set.
1938    ///
1939    /// This will _not_ trigger additional updates, because descendants without nonce gaps are
1940    /// already in the pending pool, and this transaction will be the first transaction of the
1941    /// sender in this pool.
1942    pub(crate) fn remove_transaction(
1943        &mut self,
1944        id: &TransactionId,
1945    ) -> Option<(Arc<ValidPoolTransaction<T>>, SubPool)> {
1946        let internal = self.txs.remove(id)?;
1947
1948        // decrement the counter for the sender.
1949        self.tx_decr(internal.transaction.sender_id());
1950        self.tx_type_counts.dec(internal.transaction.transaction.ty());
1951
1952        let result =
1953            self.by_hash.remove(internal.transaction.hash()).map(|tx| (tx, internal.subpool));
1954
1955        self.remove_auths(&internal);
1956
1957        result
1958    }
1959
1960    /// Removes any pending auths for the given transaction.
1961    ///
1962    /// This is a noop for non EIP-7702 transactions.
1963    fn remove_auths(&mut self, tx: &PoolInternalTransaction<T>) {
1964        let Some(auths) = &tx.transaction.authority_ids else { return };
1965
1966        let tx_hash = tx.transaction.hash();
1967        for auth in auths {
1968            if let Some(list) = self.auths.get_mut(auth) {
1969                list.remove(tx_hash);
1970                if list.is_empty() {
1971                    self.auths.remove(auth);
1972                }
1973            }
1974        }
1975    }
1976
1977    /// Checks if the given transaction's type conflicts with an existing transaction.
1978    ///
1979    /// See also [`ValidPoolTransaction::tx_type_conflicts_with`].
1980    ///
1981    /// Caution: This assumes that mutually exclusive invariant is always true for the same sender.
1982    #[inline]
1983    fn contains_conflicting_transaction(&self, tx: &ValidPoolTransaction<T>) -> bool {
1984        self.txs_iter(tx.transaction_id.sender)
1985            .next()
1986            .is_some_and(|(_, existing)| tx.tx_type_conflicts_with(&existing.transaction))
1987    }
1988
1989    /// Additional checks for a new transaction.
1990    ///
1991    /// This will enforce all additional rules in the context of this pool, such as:
1992    ///   - Spam protection: reject new non-local transaction from a sender that exhausted its slot
1993    ///     capacity.
1994    ///   - Gas limit: reject transactions if they exceed a block's maximum gas.
1995    ///   - Ensures transaction types are not conflicting for the sender: blob vs normal
1996    ///     transactions are mutually exclusive for the same sender.
1997    fn ensure_valid(
1998        &self,
1999        transaction: ValidPoolTransaction<T>,
2000        on_chain_nonce: u64,
2001    ) -> Result<ValidPoolTransaction<T>, InsertErr<T>> {
2002        if !self.local_transactions_config.is_local(transaction.origin, transaction.sender_ref()) {
2003            let current_txs =
2004                self.tx_counter.get(&transaction.sender_id()).copied().unwrap_or_default();
2005
2006            // Reject transactions if sender's capacity is exceeded.
2007            // If transaction's nonce matches on-chain nonce always let it through.
2008            // Replacements of an existing transaction don't increase the sender's count.
2009            if current_txs >= self.max_account_slots &&
2010                transaction.nonce() > on_chain_nonce &&
2011                !self.txs.contains_key(&transaction.transaction_id)
2012            {
2013                return Err(InsertErr::ExceededSenderTransactionsCapacity {
2014                    transaction: Arc::new(transaction),
2015                })
2016            }
2017        }
2018        if transaction.gas_limit() > self.block_gas_limit {
2019            return Err(InsertErr::TxGasLimitMoreThanAvailableBlockGas {
2020                block_gas_limit: self.block_gas_limit,
2021                tx_gas_limit: transaction.gas_limit(),
2022                transaction: Arc::new(transaction),
2023            })
2024        }
2025
2026        if self.contains_conflicting_transaction(&transaction) {
2027            // blob vs non blob transactions are mutually exclusive for the same sender
2028            return Err(InsertErr::TxTypeConflict { transaction: Arc::new(transaction) })
2029        }
2030
2031        Ok(transaction)
2032    }
2033
2034    /// Enforces additional constraints for blob transactions before attempting to insert:
2035    ///    - new blob transactions must not have any nonce gaps
2036    ///    - blob transactions cannot go into overdraft
2037    ///    - replacement blob transaction with a higher fee must not shift an already propagated
2038    ///      descending blob transaction into overdraft
2039    fn ensure_valid_blob_transaction(
2040        &self,
2041        new_blob_tx: ValidPoolTransaction<T>,
2042        on_chain_balance: U256,
2043        ancestor: Option<TransactionId>,
2044    ) -> Result<ValidPoolTransaction<T>, InsertErr<T>> {
2045        // the cost of all preceding transactions of the sender
2046        let mut cumulative_cost = if let Some(ancestor) = ancestor {
2047            let Some(ancestor_tx) = self.txs.get(&ancestor) else {
2048                // ancestor tx is missing, so we can't insert the new blob
2049                self.metrics.blob_transactions_nonce_gaps.increment(1);
2050                return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) })
2051            };
2052            if ancestor_tx.state.has_nonce_gap() {
2053                // the ancestor transaction already has a nonce gap, so we can't insert the new
2054                // blob
2055                self.metrics.blob_transactions_nonce_gaps.increment(1);
2056                return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) })
2057            }
2058
2059            ancestor_tx.next_cumulative_cost()
2060        } else {
2061            U256::ZERO
2062        };
2063
2064        // the max cost executing this transaction requires
2065        cumulative_cost += new_blob_tx.cost();
2066
2067        // check if the new blob would go into overdraft
2068        if cumulative_cost > on_chain_balance {
2069            // the transaction would go into overdraft
2070            return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) })
2071        }
2072
2073        // ensure that a replacement would not shift already propagated blob transactions into
2074        // overdraft
2075        let id = new_blob_tx.transaction_id;
2076        let mut descendants = self.descendant_txs_inclusive(&id).peekable();
2077        if let Some((maybe_replacement, _)) = descendants.peek() &&
2078            **maybe_replacement == new_blob_tx.transaction_id
2079        {
2080            // replacement transaction
2081            descendants.next();
2082
2083            // check if any of descendant blob transactions should be shifted into overdraft
2084            for (_, tx) in descendants {
2085                cumulative_cost += tx.transaction.cost();
2086                if tx.transaction.is_eip4844() && cumulative_cost > on_chain_balance {
2087                    // the transaction would shift
2088                    return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) })
2089                }
2090            }
2091        }
2092
2093        Ok(new_blob_tx)
2094    }
2095
2096    /// Inserts a new _valid_ transaction into the pool.
2097    ///
2098    /// If the transaction already exists, it will be replaced if not underpriced.
2099    /// Returns info to which sub-pool the transaction should be moved.
2100    /// Also returns a set of pool updates triggered by this insert, that need to be handled by the
2101    /// caller.
2102    ///
2103    /// These can include:
2104    ///      - closing nonce gaps of descendant transactions
2105    ///      - enough balance updates
2106    ///
2107    /// Note: For EIP-4844 blob transactions additional constraints are enforced:
2108    ///      - new blob transactions must not have any nonce gaps
2109    ///      - blob transactions cannot go into overdraft
2110    ///
2111    /// ## Transaction type Exclusivity
2112    ///
2113    /// The pool enforces exclusivity of eip-4844 blob vs non-blob transactions on a per sender
2114    /// basis:
2115    ///  - If the pool already includes a blob transaction from the `transaction`'s sender, then the
2116    ///    `transaction` must also be a blob transaction
2117    ///  - If the pool already includes a non-blob transaction from the `transaction`'s sender, then
2118    ///    the `transaction` must _not_ be a blob transaction.
2119    ///
2120    /// In other words, the presence of blob transactions exclude non-blob transactions and vice
2121    /// versa.
2122    ///
2123    /// ## Replacements
2124    ///
2125    /// The replacement candidate must satisfy given price bump constraints: replacement candidate
2126    /// must not be underpriced
2127    pub(crate) fn insert_tx(
2128        &mut self,
2129        transaction: ValidPoolTransaction<T>,
2130        on_chain_balance: U256,
2131        on_chain_nonce: u64,
2132    ) -> InsertResult<T> {
2133        assert!(on_chain_nonce <= transaction.nonce(), "Invalid transaction");
2134
2135        let mut transaction = self.ensure_valid(transaction, on_chain_nonce)?;
2136
2137        let inserted_tx_id = *transaction.id();
2138        let mut state = TxState::default();
2139        let mut cumulative_cost = U256::ZERO;
2140
2141        // Current tx does not exceed block gas limit after ensure_valid check
2142        state.insert(TxState::NOT_TOO_MUCH_GAS);
2143
2144        // identifier of the ancestor transaction, will be None if the transaction is the next tx of
2145        // the sender
2146        let ancestor = TransactionId::ancestor(
2147            transaction.transaction.nonce(),
2148            on_chain_nonce,
2149            inserted_tx_id.sender,
2150        );
2151
2152        // before attempting to insert a blob transaction, we need to ensure that additional
2153        // constraints are met that only apply to blob transactions
2154        if transaction.is_eip4844() {
2155            state.insert(TxState::BLOB_TRANSACTION);
2156
2157            transaction =
2158                self.ensure_valid_blob_transaction(transaction, on_chain_balance, ancestor)?;
2159            let blob_fee_cap = transaction.transaction.max_fee_per_blob_gas().unwrap_or_default();
2160            if blob_fee_cap >= self.pending_fees.blob_fee {
2161                state.insert(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
2162            }
2163        } else {
2164            // Non-EIP4844 transaction always satisfy the blob fee cap condition
2165            state.insert(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
2166        }
2167
2168        let transaction = Arc::new(transaction);
2169
2170        // If there's no ancestor tx then this is the next transaction.
2171        if ancestor.is_none() {
2172            state.insert(TxState::NO_NONCE_GAPS);
2173            state.insert(TxState::NO_PARKED_ANCESTORS);
2174        }
2175
2176        // Check dynamic fee
2177        let fee_cap = transaction.max_fee_per_gas();
2178
2179        if fee_cap < self.minimal_protocol_basefee as u128 {
2180            return Err(InsertErr::FeeCapBelowMinimumProtocolFeeCap { transaction, fee_cap })
2181        }
2182        if fee_cap >= self.pending_fees.base_fee as u128 {
2183            state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
2184        }
2185
2186        // placeholder for the replaced transaction, if any
2187        let mut replaced_tx = None;
2188
2189        let pool_tx = PoolInternalTransaction {
2190            transaction: Arc::clone(&transaction),
2191            subpool: state.into(),
2192            state,
2193            cumulative_cost,
2194        };
2195
2196        // try to insert the transaction
2197        match self.txs.entry(*transaction.id()) {
2198            Entry::Vacant(entry) => {
2199                // Insert the transaction in both maps
2200                self.by_hash.insert(*pool_tx.transaction.hash(), pool_tx.transaction.clone());
2201                self.tx_type_counts.inc(pool_tx.transaction.transaction.ty());
2202                entry.insert(pool_tx);
2203            }
2204            Entry::Occupied(mut entry) => {
2205                // Transaction with the same nonce already exists: replacement candidate
2206                let existing_transaction = entry.get().transaction.as_ref();
2207                let maybe_replacement = transaction.as_ref();
2208
2209                // Ensure the new transaction is not underpriced
2210                if existing_transaction
2211                    .is_replacement_underpriced(maybe_replacement, &self.price_bumps)
2212                {
2213                    return Err(InsertErr::Underpriced {
2214                        transaction: pool_tx.transaction,
2215                        existing: *entry.get().transaction.hash(),
2216                    })
2217                }
2218                let new_hash = *pool_tx.transaction.hash();
2219                let new_transaction = pool_tx.transaction.clone();
2220                self.tx_type_counts.inc(pool_tx.transaction.transaction.ty());
2221                let replaced = entry.insert(pool_tx);
2222                self.tx_type_counts.dec(replaced.transaction.transaction.ty());
2223                self.by_hash.remove(replaced.transaction.hash());
2224                self.by_hash.insert(new_hash, new_transaction);
2225
2226                self.remove_auths(&replaced);
2227
2228                // also remove the hash
2229                replaced_tx = Some((replaced.transaction, replaced.subpool));
2230            }
2231        }
2232
2233        if let Some(auths) = &transaction.authority_ids {
2234            let tx_hash = transaction.hash();
2235            for auth in auths {
2236                self.auths.entry(*auth).or_default().insert(*tx_hash);
2237            }
2238        }
2239
2240        // Take the scratch buffer only after all fallible checks so rejected inserts retain it.
2241        let mut updates = std::mem::take(&mut self.update_buffer);
2242
2243        // The next transaction of this sender
2244        let on_chain_id = TransactionId::new(transaction.sender_id(), on_chain_nonce);
2245        let pending_fees = self.pending_fees;
2246        {
2247            // Tracks the next nonce we expect if the transactions are gapless
2248            let mut next_nonce = on_chain_id.nonce;
2249
2250            // We need to find out if the next transaction of the sender is considered pending
2251            // The direct descendant has _no_ parked ancestors because the `on_chain_nonce` is
2252            // pending, so we can set this to `false`
2253            let mut has_parked_ancestor = false;
2254
2255            // Traverse all future transactions of the sender starting with the on chain nonce, and
2256            // update existing transactions: `[on_chain_nonce,..]`
2257            for (id, tx) in self.descendant_txs_mut(&on_chain_id) {
2258                let current_pool = tx.subpool;
2259
2260                // If there's a nonce gap, we can shortcircuit
2261                if next_nonce != id.nonce {
2262                    break
2263                }
2264
2265                // close the nonce gap
2266                tx.state.insert(TxState::NO_NONCE_GAPS);
2267
2268                // set cumulative cost
2269                tx.cumulative_cost = cumulative_cost;
2270
2271                // Update for next transaction
2272                cumulative_cost = tx.next_cumulative_cost();
2273
2274                if cumulative_cost > on_chain_balance {
2275                    // sender lacks sufficient funds to pay for this transaction
2276                    tx.state.remove(TxState::ENOUGH_BALANCE);
2277                } else {
2278                    tx.state.insert(TxState::ENOUGH_BALANCE);
2279                }
2280
2281                // Update ancestor condition.
2282                if has_parked_ancestor {
2283                    tx.state.remove(TxState::NO_PARKED_ANCESTORS);
2284                } else {
2285                    tx.state.insert(TxState::NO_PARKED_ANCESTORS);
2286                }
2287
2288                Self::update_tx_fees(pending_fees, tx);
2289
2290                // update the pool based on the state
2291                tx.subpool = tx.state.into();
2292                has_parked_ancestor = !tx.state.is_pending();
2293
2294                if inserted_tx_id.eq(id) {
2295                    // if it is the new transaction, track its updated state
2296                    state = tx.state;
2297                } else {
2298                    // check if anything changed
2299                    if current_pool != tx.subpool {
2300                        updates.push(PoolUpdate {
2301                            id: *id,
2302                            current: current_pool,
2303                            destination: tx.subpool.into(),
2304                        })
2305                    }
2306                }
2307
2308                // increment for next iteration
2309                next_nonce = id.next_nonce();
2310            }
2311        }
2312
2313        // If this wasn't a replacement transaction we need to update the counter.
2314        if replaced_tx.is_none() {
2315            self.tx_inc(inserted_tx_id.sender);
2316        }
2317
2318        Ok(InsertOk { transaction, move_to: state.into(), state, replaced_tx, updates })
2319    }
2320
2321    /// Number of transactions in the entire pool
2322    pub(crate) fn len(&self) -> usize {
2323        self.txs.len()
2324    }
2325
2326    /// Whether the pool is empty
2327    pub(crate) fn is_empty(&self) -> bool {
2328        self.txs.is_empty()
2329    }
2330
2331    /// Asserts that the bijection between `by_hash` and `txs` is valid.
2332    #[cfg(any(test, feature = "test-utils"))]
2333    pub(crate) fn assert_invariants(&self) {
2334        assert_eq!(self.by_hash.len(), self.txs.len(), "by_hash.len() != txs.len()");
2335        assert!(self.auths.len() <= self.txs.len(), "auths.len() > txs.len()");
2336    }
2337}
2338
2339#[cfg(test)]
2340impl<T: PoolTransaction> AllTransactions<T> {
2341    /// This function retrieves the number of transactions stored in the pool for a specific sender.
2342    ///
2343    /// If there are no transactions for the given sender, it returns zero by default.
2344    pub(crate) fn tx_count(&self, sender: SenderId) -> usize {
2345        self.tx_counter.get(&sender).copied().unwrap_or_default()
2346    }
2347}
2348
2349impl<T: PoolTransaction> Default for AllTransactions<T> {
2350    fn default() -> Self {
2351        Self {
2352            max_account_slots: TXPOOL_MAX_ACCOUNT_SLOTS_PER_SENDER,
2353            minimal_protocol_basefee: MIN_PROTOCOL_BASE_FEE,
2354            block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,
2355            by_hash: Default::default(),
2356            txs: Default::default(),
2357            sender_info: Default::default(),
2358            tx_counter: Default::default(),
2359            last_seen_block_number: Default::default(),
2360            last_seen_block_hash: Default::default(),
2361            pending_fees: Default::default(),
2362            // an empty pool trivially reflects the initial fees
2363            last_full_update_fees: Default::default(),
2364            price_bumps: Default::default(),
2365            local_transactions_config: Default::default(),
2366            auths: Default::default(),
2367            tx_type_counts: Default::default(),
2368            update_buffer: Default::default(),
2369            metrics: Default::default(),
2370        }
2371    }
2372}
2373
2374/// Number of transactions in the pool grouped by transaction type.
2375///
2376/// Maintained incrementally on insert/remove so that metrics updates don't require iterating
2377/// all transactions.
2378#[derive(Debug, Clone, Copy, Default)]
2379pub(crate) struct TxTypeCounts {
2380    legacy: u64,
2381    eip2930: u64,
2382    eip1559: u64,
2383    eip4844: u64,
2384    eip7702: u64,
2385    other: u64,
2386}
2387
2388impl TxTypeCounts {
2389    /// Returns a mutable reference to the counter for the given transaction type.
2390    const fn counter_mut(&mut self, tx_type: u8) -> &mut u64 {
2391        match tx_type {
2392            LEGACY_TX_TYPE_ID => &mut self.legacy,
2393            EIP2930_TX_TYPE_ID => &mut self.eip2930,
2394            EIP1559_TX_TYPE_ID => &mut self.eip1559,
2395            EIP4844_TX_TYPE_ID => &mut self.eip4844,
2396            EIP7702_TX_TYPE_ID => &mut self.eip7702,
2397            _ => &mut self.other,
2398        }
2399    }
2400
2401    /// Increments the counter for the given transaction type.
2402    const fn inc(&mut self, tx_type: u8) {
2403        *self.counter_mut(tx_type) += 1;
2404    }
2405
2406    /// Decrements the counter for the given transaction type.
2407    const fn dec(&mut self, tx_type: u8) {
2408        *self.counter_mut(tx_type) -= 1;
2409    }
2410}
2411
2412/// Represents updated fees for the pending block.
2413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2414pub(crate) struct PendingFees {
2415    /// The pending base fee
2416    pub(crate) base_fee: u64,
2417    /// The pending blob fee
2418    pub(crate) blob_fee: u128,
2419}
2420
2421impl Default for PendingFees {
2422    fn default() -> Self {
2423        Self { base_fee: Default::default(), blob_fee: BLOB_TX_MIN_BLOB_GASPRICE }
2424    }
2425}
2426
2427/// Result type for inserting a transaction
2428pub(crate) type InsertResult<T> = Result<InsertOk<T>, InsertErr<T>>;
2429
2430/// Err variant of `InsertResult`
2431#[derive(Debug)]
2432pub(crate) enum InsertErr<T: PoolTransaction> {
2433    /// Attempted to replace existing transaction, but was underpriced
2434    Underpriced {
2435        transaction: Arc<ValidPoolTransaction<T>>,
2436        #[expect(dead_code)]
2437        existing: TxHash,
2438    },
2439    /// Attempted to insert a blob transaction with a nonce gap
2440    BlobTxHasNonceGap { transaction: Arc<ValidPoolTransaction<T>> },
2441    /// Attempted to insert a transaction that would overdraft the sender's balance at the time of
2442    /// insertion.
2443    Overdraft { transaction: Arc<ValidPoolTransaction<T>> },
2444    /// The transactions feeCap is lower than the chain's minimum fee requirement.
2445    ///
2446    /// See also [`MIN_PROTOCOL_BASE_FEE`]
2447    FeeCapBelowMinimumProtocolFeeCap { transaction: Arc<ValidPoolTransaction<T>>, fee_cap: u128 },
2448    /// Sender currently exceeds the configured limit for max account slots.
2449    ///
2450    /// The sender can be considered a spammer at this point.
2451    ExceededSenderTransactionsCapacity { transaction: Arc<ValidPoolTransaction<T>> },
2452    /// Transaction gas limit exceeds block's gas limit
2453    TxGasLimitMoreThanAvailableBlockGas {
2454        transaction: Arc<ValidPoolTransaction<T>>,
2455        block_gas_limit: u64,
2456        tx_gas_limit: u64,
2457    },
2458    /// Thrown if the mutual exclusivity constraint (blob vs normal transaction) is violated.
2459    TxTypeConflict { transaction: Arc<ValidPoolTransaction<T>> },
2460}
2461
2462/// Transaction was successfully inserted into the pool
2463#[derive(Debug)]
2464pub(crate) struct InsertOk<T: PoolTransaction> {
2465    /// Ref to the inserted transaction.
2466    transaction: Arc<ValidPoolTransaction<T>>,
2467    /// Where to move the transaction to.
2468    move_to: SubPool,
2469    /// Current state of the inserted tx.
2470    state: TxState,
2471    /// The transaction that was replaced by this.
2472    replaced_tx: Option<(Arc<ValidPoolTransaction<T>>, SubPool)>,
2473    /// Additional updates to transactions affected by this change.
2474    updates: Vec<PoolUpdate>,
2475}
2476
2477/// The internal transaction typed used by `AllTransactions` which also additional info used for
2478/// determining the current state of the transaction.
2479#[derive(Debug)]
2480pub(crate) struct PoolInternalTransaction<T: PoolTransaction> {
2481    /// The actual transaction object.
2482    pub(crate) transaction: Arc<ValidPoolTransaction<T>>,
2483    /// The `SubPool` that currently contains this transaction.
2484    pub(crate) subpool: SubPool,
2485    /// Keeps track of the current state of the transaction and therefore in which subpool it
2486    /// should reside
2487    pub(crate) state: TxState,
2488    /// The total cost all transactions before this transaction.
2489    ///
2490    /// This is the combined `cost` of all transactions from the same sender that currently
2491    /// come before this transaction.
2492    pub(crate) cumulative_cost: U256,
2493}
2494
2495// === impl PoolInternalTransaction ===
2496
2497impl<T: PoolTransaction> PoolInternalTransaction<T> {
2498    fn next_cumulative_cost(&self) -> U256 {
2499        self.cumulative_cost + self.transaction.cost()
2500    }
2501}
2502
2503/// Stores relevant context about a sender.
2504#[derive(Debug, Clone, Default)]
2505pub(crate) struct SenderInfo {
2506    /// current nonce of the sender.
2507    pub(crate) state_nonce: u64,
2508    /// Balance of the sender at the current point.
2509    pub(crate) balance: U256,
2510}
2511
2512// === impl SenderInfo ===
2513
2514impl SenderInfo {
2515    /// Updates the info with the new values.
2516    const fn update(&mut self, state_nonce: u64, balance: U256) {
2517        *self = Self { state_nonce, balance };
2518    }
2519}
2520
2521#[cfg(test)]
2522mod tests {
2523    use super::*;
2524    use crate::{
2525        test_utils::{MockOrdering, MockTransaction, MockTransactionFactory, MockTransactionSet},
2526        traits::TransactionOrigin,
2527        SubPoolLimit,
2528    };
2529    use alloy_consensus::{Transaction, TxType};
2530    use alloy_primitives::address;
2531
2532    #[test]
2533    fn test_insert_blob() {
2534        let on_chain_balance = U256::MAX;
2535        let on_chain_nonce = 0;
2536        let mut f = MockTransactionFactory::default();
2537        let mut pool = AllTransactions::default();
2538        let tx = MockTransaction::eip4844().inc_price().inc_limit();
2539        let valid_tx = f.validated(tx);
2540        let InsertOk { updates, replaced_tx, move_to, state, .. } =
2541            pool.insert_tx(valid_tx.clone(), on_chain_balance, on_chain_nonce).unwrap();
2542        assert!(updates.is_empty());
2543        assert!(replaced_tx.is_none());
2544        assert!(state.contains(TxState::NO_NONCE_GAPS));
2545        assert!(state.contains(TxState::ENOUGH_BALANCE));
2546        assert!(state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2547        assert_eq!(move_to, SubPool::Pending);
2548
2549        let inserted = pool.txs.get(&valid_tx.transaction_id).unwrap();
2550        assert_eq!(inserted.subpool, SubPool::Pending);
2551    }
2552
2553    #[test]
2554    fn test_blob_head_replacement_overdraft() {
2555        let on_chain_nonce = 0;
2556        let mut f = MockTransactionFactory::default();
2557        let mut pool = AllTransactions::default();
2558
2559        // `with_gas_limit` recomputes the cost after the fee setters
2560        let head = MockTransaction::eip4844()
2561            .with_max_fee(100)
2562            .with_priority_fee(100)
2563            .with_nonce(on_chain_nonce)
2564            .with_gas_limit(10);
2565        let child = head.next();
2566        let head_id = f.validated(head.clone()).transaction_id;
2567        let child_id = f.validated(child.clone()).transaction_id;
2568        assert_eq!(*head.cost(), U256::from(1_000));
2569
2570        // both fit the balance
2571        let on_chain_balance = U256::from(4_500);
2572        pool.insert_tx(f.validated(head.clone()), on_chain_balance, on_chain_nonce).unwrap();
2573        pool.insert_tx(f.validated(child), on_chain_balance, on_chain_nonce).unwrap();
2574        assert_eq!(pool.txs.get(&child_id).unwrap().subpool, SubPool::Pending);
2575
2576        // the replacement fits the balance on its own, but not together with the child
2577        let blob_fee = 3 * head.max_fee_per_blob_gas().unwrap();
2578        let replacement = head
2579            .rng_hash()
2580            .with_max_fee(400)
2581            .with_priority_fee(400)
2582            .with_blob_fee(blob_fee)
2583            .with_gas_limit(10);
2584        assert_eq!(*replacement.cost(), U256::from(4_000));
2585        let err =
2586            pool.insert_tx(f.validated(replacement), on_chain_balance, on_chain_nonce).unwrap_err();
2587        assert!(matches!(err, InsertErr::Overdraft { .. }), "{err:?}");
2588
2589        // nothing changed
2590        assert_eq!(pool.txs.get(&head_id).unwrap().transaction.cost(), &U256::from(1_000));
2591        assert_eq!(pool.txs.get(&child_id).unwrap().subpool, SubPool::Pending);
2592        assert!(pool.txs.get(&child_id).unwrap().state.contains(TxState::ENOUGH_BALANCE));
2593    }
2594
2595    #[test]
2596    fn test_insert_blob_not_enough_blob_fee() {
2597        let on_chain_balance = U256::MAX;
2598        let on_chain_nonce = 0;
2599        let mut f = MockTransactionFactory::default();
2600        let mut pool = AllTransactions {
2601            pending_fees: PendingFees { blob_fee: 10_000_000, ..Default::default() },
2602            ..Default::default()
2603        };
2604        let tx = MockTransaction::eip4844().inc_price().inc_limit();
2605        pool.pending_fees.blob_fee = tx.max_fee_per_blob_gas().unwrap() + 1;
2606        let valid_tx = f.validated(tx);
2607        let InsertOk { state, .. } =
2608            pool.insert_tx(valid_tx.clone(), on_chain_balance, on_chain_nonce).unwrap();
2609        assert!(state.contains(TxState::NO_NONCE_GAPS));
2610        assert!(!state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2611
2612        let _ = pool.txs.get(&valid_tx.transaction_id).unwrap();
2613    }
2614
2615    #[test]
2616    fn test_valid_tx_with_decreasing_blob_fee() {
2617        let on_chain_balance = U256::MAX;
2618        let on_chain_nonce = 0;
2619        let mut f = MockTransactionFactory::default();
2620        let mut pool = AllTransactions {
2621            pending_fees: PendingFees { blob_fee: 10_000_000, ..Default::default() },
2622            ..Default::default()
2623        };
2624        let tx = MockTransaction::eip4844().inc_price().inc_limit();
2625
2626        pool.pending_fees.blob_fee = tx.max_fee_per_blob_gas().unwrap() + 1;
2627        let valid_tx = f.validated(tx.clone());
2628        let InsertOk { state, .. } =
2629            pool.insert_tx(valid_tx.clone(), on_chain_balance, on_chain_nonce).unwrap();
2630        assert!(state.contains(TxState::NO_NONCE_GAPS));
2631        assert!(!state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2632
2633        let _ = pool.txs.get(&valid_tx.transaction_id).unwrap();
2634        pool.remove_transaction(&valid_tx.transaction_id);
2635
2636        pool.pending_fees.blob_fee = tx.max_fee_per_blob_gas().unwrap();
2637        let InsertOk { state, .. } =
2638            pool.insert_tx(valid_tx.clone(), on_chain_balance, on_chain_nonce).unwrap();
2639        assert!(state.contains(TxState::NO_NONCE_GAPS));
2640        assert!(state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2641    }
2642
2643    #[test]
2644    fn test_demote_valid_tx_with_increasing_blob_fee() {
2645        let on_chain_balance = U256::MAX;
2646        let on_chain_nonce = 0;
2647        let mut f = MockTransactionFactory::default();
2648        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
2649        let tx = MockTransaction::eip4844().inc_price().inc_limit();
2650
2651        // set block info so the tx is initially underpriced w.r.t. blob fee
2652        let mut block_info = pool.block_info();
2653        block_info.pending_blob_fee = Some(tx.max_fee_per_blob_gas().unwrap());
2654        pool.set_block_info(block_info);
2655
2656        let validated = f.validated(tx.clone());
2657        let id = *validated.id();
2658        pool.add_transaction(validated, on_chain_balance, on_chain_nonce, None).unwrap();
2659
2660        // assert pool lengths
2661        assert!(pool.blob_pool.is_empty());
2662        assert_eq!(pool.pending_pool.len(), 1);
2663
2664        // check tx state and derived subpool
2665        let internal_tx = pool.all_transactions.txs.get(&id).unwrap();
2666        assert!(internal_tx.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2667        assert_eq!(internal_tx.subpool, SubPool::Pending);
2668
2669        // set block info so the pools are updated
2670        block_info.pending_blob_fee = Some(tx.max_fee_per_blob_gas().unwrap() + 1);
2671        pool.set_block_info(block_info);
2672
2673        // check that the tx is promoted
2674        let internal_tx = pool.all_transactions.txs.get(&id).unwrap();
2675        assert!(!internal_tx.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2676        assert_eq!(internal_tx.subpool, SubPool::Blob);
2677
2678        // make sure the blob transaction was promoted into the pending pool
2679        assert_eq!(pool.blob_pool.len(), 1);
2680        assert!(pool.pending_pool.is_empty());
2681    }
2682
2683    #[test]
2684    fn test_promote_valid_tx_with_decreasing_blob_fee() {
2685        let on_chain_balance = U256::MAX;
2686        let on_chain_nonce = 0;
2687        let mut f = MockTransactionFactory::default();
2688        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
2689        let tx = MockTransaction::eip4844().inc_price().inc_limit();
2690
2691        // set block info so the tx is initially underpriced w.r.t. blob fee
2692        let mut block_info = pool.block_info();
2693        block_info.pending_blob_fee = Some(tx.max_fee_per_blob_gas().unwrap() + 1);
2694        pool.set_block_info(block_info);
2695
2696        let validated = f.validated(tx.clone());
2697        let id = *validated.id();
2698        pool.add_transaction(validated, on_chain_balance, on_chain_nonce, None).unwrap();
2699
2700        // assert pool lengths
2701        assert!(pool.pending_pool.is_empty());
2702        assert_eq!(pool.blob_pool.len(), 1);
2703
2704        // check tx state and derived subpool
2705        let internal_tx = pool.all_transactions.txs.get(&id).unwrap();
2706        assert!(!internal_tx.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2707        assert_eq!(internal_tx.subpool, SubPool::Blob);
2708
2709        // set block info so the pools are updated
2710        block_info.pending_blob_fee = Some(tx.max_fee_per_blob_gas().unwrap());
2711        pool.set_block_info(block_info);
2712
2713        // check that the tx is promoted
2714        let internal_tx = pool.all_transactions.txs.get(&id).unwrap();
2715        assert!(internal_tx.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
2716        assert_eq!(internal_tx.subpool, SubPool::Pending);
2717
2718        // make sure the blob transaction was promoted into the pending pool
2719        assert_eq!(pool.pending_pool.len(), 1);
2720        assert!(pool.blob_pool.is_empty());
2721    }
2722
2723    #[test]
2724    fn test_queued_count_includes_blob_pool() {
2725        let on_chain_balance = U256::MAX;
2726        let on_chain_nonce = 0;
2727        let mut f = MockTransactionFactory::default();
2728        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
2729        let tx = MockTransaction::eip4844().inc_price().inc_limit();
2730
2731        // set block info so the tx is underpriced w.r.t. blob fee and lands in the blob pool
2732        let mut block_info = pool.block_info();
2733        block_info.pending_blob_fee = Some(tx.max_fee_per_blob_gas().unwrap() + 1);
2734        pool.set_block_info(block_info);
2735
2736        let validated = f.validated(tx);
2737        pool.add_transaction(validated, on_chain_balance, on_chain_nonce, None).unwrap();
2738
2739        assert_eq!(pool.blob_pool.len(), 1);
2740        assert!(pool.pending_pool.is_empty());
2741
2742        // blob pool transactions are parked and must be reported as queued
2743        assert_eq!(pool.queued_transactions_count(), 1);
2744    }
2745
2746    /// A struct representing a txpool promotion test instance
2747    #[derive(Debug, PartialEq, Eq, Clone, Hash)]
2748    struct PromotionTest {
2749        /// The basefee at the start of the test
2750        basefee: u64,
2751        /// The blobfee at the start of the test
2752        blobfee: u128,
2753        /// The subpool at the start of the test
2754        subpool: SubPool,
2755        /// The basefee update
2756        basefee_update: u64,
2757        /// The blobfee update
2758        blobfee_update: u128,
2759        /// The subpool after the update
2760        new_subpool: SubPool,
2761    }
2762
2763    impl PromotionTest {
2764        /// Returns the test case for the opposite update
2765        const fn opposite(&self) -> Self {
2766            Self {
2767                basefee: self.basefee_update,
2768                blobfee: self.blobfee_update,
2769                subpool: self.new_subpool,
2770                blobfee_update: self.blobfee,
2771                basefee_update: self.basefee,
2772                new_subpool: self.subpool,
2773            }
2774        }
2775
2776        fn assert_subpool_lengths<T: TransactionOrdering>(
2777            &self,
2778            pool: &TxPool<T>,
2779            failure_message: String,
2780            check_subpool: SubPool,
2781        ) {
2782            match check_subpool {
2783                SubPool::Blob => {
2784                    assert_eq!(pool.blob_pool.len(), 1, "{failure_message}");
2785                    assert!(pool.pending_pool.is_empty(), "{failure_message}");
2786                    assert!(pool.basefee_pool.is_empty(), "{failure_message}");
2787                    assert!(pool.queued_pool.is_empty(), "{failure_message}");
2788                }
2789                SubPool::Pending => {
2790                    assert!(pool.blob_pool.is_empty(), "{failure_message}");
2791                    assert_eq!(pool.pending_pool.len(), 1, "{failure_message}");
2792                    assert!(pool.basefee_pool.is_empty(), "{failure_message}");
2793                    assert!(pool.queued_pool.is_empty(), "{failure_message}");
2794                }
2795                SubPool::BaseFee => {
2796                    assert!(pool.blob_pool.is_empty(), "{failure_message}");
2797                    assert!(pool.pending_pool.is_empty(), "{failure_message}");
2798                    assert_eq!(pool.basefee_pool.len(), 1, "{failure_message}");
2799                    assert!(pool.queued_pool.is_empty(), "{failure_message}");
2800                }
2801                SubPool::Queued => {
2802                    assert!(pool.blob_pool.is_empty(), "{failure_message}");
2803                    assert!(pool.pending_pool.is_empty(), "{failure_message}");
2804                    assert!(pool.basefee_pool.is_empty(), "{failure_message}");
2805                    assert_eq!(pool.queued_pool.len(), 1, "{failure_message}");
2806                }
2807            }
2808        }
2809
2810        /// Runs an assertion on the provided pool, ensuring that the transaction is in the correct
2811        /// subpool based on the starting condition of the test, assuming the pool contains only a
2812        /// single transaction.
2813        fn assert_single_tx_starting_subpool<T: TransactionOrdering>(&self, pool: &TxPool<T>) {
2814            self.assert_subpool_lengths(
2815                pool,
2816                format!("pool length check failed at start of test: {self:?}"),
2817                self.subpool,
2818            );
2819        }
2820
2821        /// Runs an assertion on the provided pool, ensuring that the transaction is in the correct
2822        /// subpool based on the ending condition of the test, assuming the pool contains only a
2823        /// single transaction.
2824        fn assert_single_tx_ending_subpool<T: TransactionOrdering>(&self, pool: &TxPool<T>) {
2825            self.assert_subpool_lengths(
2826                pool,
2827                format!("pool length check failed at end of test: {self:?}"),
2828                self.new_subpool,
2829            );
2830        }
2831    }
2832
2833    #[test]
2834    fn test_promote_blob_tx_with_both_pending_fee_updates() {
2835        // this exhaustively tests all possible promotion scenarios for a single transaction moving
2836        // between the blob and pending pool
2837        let on_chain_balance = U256::MAX;
2838        let on_chain_nonce = 0;
2839        let mut f = MockTransactionFactory::default();
2840        let tx = MockTransaction::eip4844().inc_price().inc_limit();
2841
2842        let max_fee_per_blob_gas = tx.max_fee_per_blob_gas().unwrap();
2843        let max_fee_per_gas = tx.max_fee_per_gas() as u64;
2844
2845        // These are all _promotion_ tests or idempotent tests.
2846        let mut expected_promotions = vec![
2847            PromotionTest {
2848                blobfee: max_fee_per_blob_gas + 1,
2849                basefee: max_fee_per_gas + 1,
2850                subpool: SubPool::Blob,
2851                blobfee_update: max_fee_per_blob_gas + 1,
2852                basefee_update: max_fee_per_gas + 1,
2853                new_subpool: SubPool::Blob,
2854            },
2855            PromotionTest {
2856                blobfee: max_fee_per_blob_gas + 1,
2857                basefee: max_fee_per_gas + 1,
2858                subpool: SubPool::Blob,
2859                blobfee_update: max_fee_per_blob_gas,
2860                basefee_update: max_fee_per_gas + 1,
2861                new_subpool: SubPool::Blob,
2862            },
2863            PromotionTest {
2864                blobfee: max_fee_per_blob_gas + 1,
2865                basefee: max_fee_per_gas + 1,
2866                subpool: SubPool::Blob,
2867                blobfee_update: max_fee_per_blob_gas + 1,
2868                basefee_update: max_fee_per_gas,
2869                new_subpool: SubPool::Blob,
2870            },
2871            PromotionTest {
2872                blobfee: max_fee_per_blob_gas + 1,
2873                basefee: max_fee_per_gas + 1,
2874                subpool: SubPool::Blob,
2875                blobfee_update: max_fee_per_blob_gas,
2876                basefee_update: max_fee_per_gas,
2877                new_subpool: SubPool::Pending,
2878            },
2879            PromotionTest {
2880                blobfee: max_fee_per_blob_gas,
2881                basefee: max_fee_per_gas + 1,
2882                subpool: SubPool::Blob,
2883                blobfee_update: max_fee_per_blob_gas,
2884                basefee_update: max_fee_per_gas,
2885                new_subpool: SubPool::Pending,
2886            },
2887            PromotionTest {
2888                blobfee: max_fee_per_blob_gas + 1,
2889                basefee: max_fee_per_gas,
2890                subpool: SubPool::Blob,
2891                blobfee_update: max_fee_per_blob_gas,
2892                basefee_update: max_fee_per_gas,
2893                new_subpool: SubPool::Pending,
2894            },
2895            PromotionTest {
2896                blobfee: max_fee_per_blob_gas,
2897                basefee: max_fee_per_gas,
2898                subpool: SubPool::Pending,
2899                blobfee_update: max_fee_per_blob_gas,
2900                basefee_update: max_fee_per_gas,
2901                new_subpool: SubPool::Pending,
2902            },
2903        ];
2904
2905        // extend the test cases with reversed updates - this will add all _demotion_ tests
2906        let reversed = expected_promotions.iter().map(|test| test.opposite()).collect::<Vec<_>>();
2907        expected_promotions.extend(reversed);
2908
2909        // dedup the test cases
2910        let expected_promotions = expected_promotions.into_iter().collect::<HashSet<_>>();
2911
2912        for promotion_test in &expected_promotions {
2913            let mut pool = TxPool::new(MockOrdering::default(), Default::default());
2914
2915            // set block info so the tx is initially underpriced w.r.t. blob fee
2916            let mut block_info = pool.block_info();
2917
2918            block_info.pending_blob_fee = Some(promotion_test.blobfee);
2919            block_info.pending_basefee = promotion_test.basefee;
2920            pool.set_block_info(block_info);
2921
2922            let validated = f.validated(tx.clone());
2923            let id = *validated.id();
2924            pool.add_transaction(validated, on_chain_balance, on_chain_nonce, None).unwrap();
2925
2926            // assert pool lengths
2927            promotion_test.assert_single_tx_starting_subpool(&pool);
2928
2929            // check tx state and derived subpool, it should not move into the blob pool
2930            let internal_tx = pool.all_transactions.txs.get(&id).unwrap();
2931            assert_eq!(
2932                internal_tx.subpool, promotion_test.subpool,
2933                "Subpools do not match at start of test: {promotion_test:?}"
2934            );
2935
2936            // set block info with new base fee
2937            block_info.pending_basefee = promotion_test.basefee_update;
2938            block_info.pending_blob_fee = Some(promotion_test.blobfee_update);
2939            pool.set_block_info(block_info);
2940
2941            // check tx state and derived subpool, it should not move into the blob pool
2942            let internal_tx = pool.all_transactions.txs.get(&id).unwrap();
2943            assert_eq!(
2944                internal_tx.subpool, promotion_test.new_subpool,
2945                "Subpools do not match at end of test: {promotion_test:?}"
2946            );
2947
2948            // assert new pool lengths
2949            promotion_test.assert_single_tx_ending_subpool(&pool);
2950        }
2951    }
2952
2953    #[test]
2954    fn test_insert_pending() {
2955        let on_chain_balance = U256::MAX;
2956        let on_chain_nonce = 0;
2957        let mut f = MockTransactionFactory::default();
2958        let mut pool = AllTransactions::default();
2959        let tx = MockTransaction::eip1559().inc_price().inc_limit();
2960        let valid_tx = f.validated(tx);
2961        let InsertOk { updates, replaced_tx, move_to, state, .. } =
2962            pool.insert_tx(valid_tx.clone(), on_chain_balance, on_chain_nonce).unwrap();
2963        assert!(updates.is_empty());
2964        assert!(replaced_tx.is_none());
2965        assert!(state.contains(TxState::NO_NONCE_GAPS));
2966        assert!(state.contains(TxState::ENOUGH_BALANCE));
2967        assert_eq!(move_to, SubPool::Pending);
2968
2969        let inserted = pool.txs.get(&valid_tx.transaction_id).unwrap();
2970        assert_eq!(inserted.subpool, SubPool::Pending);
2971    }
2972
2973    #[test]
2974    fn test_simple_insert() {
2975        let on_chain_balance = U256::ZERO;
2976        let on_chain_nonce = 0;
2977        let mut f = MockTransactionFactory::default();
2978        let mut pool = AllTransactions::default();
2979        let mut tx = MockTransaction::eip1559().inc_price().inc_limit();
2980        tx.set_priority_fee(100);
2981        tx.set_max_fee(100);
2982        let valid_tx = f.validated(tx.clone());
2983        let InsertOk { updates, replaced_tx, move_to, state, .. } =
2984            pool.insert_tx(valid_tx.clone(), on_chain_balance, on_chain_nonce).unwrap();
2985        assert!(updates.is_empty());
2986        assert!(replaced_tx.is_none());
2987        assert!(state.contains(TxState::NO_NONCE_GAPS));
2988        assert!(!state.contains(TxState::ENOUGH_BALANCE));
2989        assert_eq!(move_to, SubPool::Queued);
2990
2991        assert_eq!(pool.len(), 1);
2992        assert!(pool.contains(valid_tx.hash()));
2993        let expected_state = TxState::ENOUGH_FEE_CAP_BLOCK | TxState::NO_NONCE_GAPS;
2994        let inserted = pool.get(valid_tx.id()).unwrap();
2995        assert!(inserted.state.intersects(expected_state));
2996
2997        // insert the same tx again
2998        let res = pool.insert_tx(valid_tx, on_chain_balance, on_chain_nonce);
2999        res.unwrap_err();
3000        assert_eq!(pool.len(), 1);
3001
3002        let valid_tx = f.validated(tx.next());
3003        let InsertOk { updates, replaced_tx, move_to, state, .. } =
3004            pool.insert_tx(valid_tx.clone(), on_chain_balance, on_chain_nonce).unwrap();
3005
3006        assert!(updates.is_empty());
3007        assert!(replaced_tx.is_none());
3008        assert!(state.contains(TxState::NO_NONCE_GAPS));
3009        assert!(!state.contains(TxState::ENOUGH_BALANCE));
3010        assert_eq!(move_to, SubPool::Queued);
3011
3012        assert!(pool.contains(valid_tx.hash()));
3013        assert_eq!(pool.len(), 2);
3014        let inserted = pool.get(valid_tx.id()).unwrap();
3015        assert!(inserted.state.intersects(expected_state));
3016    }
3017
3018    #[test]
3019    // Test that on_canonical_state_change doesn't double-process transactions
3020    // when both fee and account updates would affect the same transaction
3021    fn test_on_canonical_state_change_no_double_processing() {
3022        let mut tx_factory = MockTransactionFactory::default();
3023        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3024
3025        // Setup: Create a sender with a transaction in basefee pool
3026        let tx = MockTransaction::eip1559().with_gas_price(50).with_gas_limit(30_000);
3027        let sender = tx.sender();
3028
3029        // Set high base fee initially
3030        let mut block_info = pool.block_info();
3031        block_info.pending_basefee = 100;
3032        pool.set_block_info(block_info);
3033
3034        let validated = tx_factory.validated(tx);
3035        pool.add_transaction(validated, U256::from(10_000_000), 0, None).unwrap();
3036
3037        // Get sender_id after the transaction has been added
3038        let sender_id = tx_factory.ids.sender_id(&sender).unwrap();
3039
3040        assert_eq!(pool.basefee_pool.len(), 1);
3041        assert_eq!(pool.pending_pool.len(), 0);
3042
3043        // Now simulate a canonical state change with:
3044        // 1. Lower base fee (would promote tx)
3045        // 2. Account balance update (would also evaluate tx)
3046        block_info.pending_basefee = 40;
3047
3048        let mut changed_senders = FxHashMap::default();
3049        changed_senders.insert(
3050            sender_id,
3051            SenderInfo {
3052                state_nonce: 0,
3053                balance: U256::from(20_000_000), // Increased balance
3054            },
3055        );
3056
3057        let outcome = pool.on_canonical_state_change(
3058            block_info,
3059            vec![], // no mined transactions
3060            changed_senders,
3061            PoolUpdateKind::Commit,
3062        );
3063
3064        // Transaction should be promoted exactly once
3065        assert_eq!(pool.pending_pool.len(), 1, "Transaction should be in pending pool");
3066        assert_eq!(pool.basefee_pool.len(), 0, "Transaction should not be in basefee pool");
3067        assert_eq!(outcome.promoted.len(), 1, "Should report exactly one promotion");
3068    }
3069
3070    #[test]
3071    // Regression test: ensure we don't double-count promotions when base fee
3072    // decreases and account is updated. This test would fail before the fix.
3073    fn test_canonical_state_change_with_basefee_update_regression() {
3074        let mut tx_factory = MockTransactionFactory::default();
3075        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3076
3077        // Create transactions from different senders to test independently
3078        let sender_balance = U256::from(100_000_000);
3079
3080        // Sender 1: tx will be promoted (gas price 60 > new base fee 50)
3081        let tx1 =
3082            MockTransaction::eip1559().with_gas_price(60).with_gas_limit(21_000).with_nonce(0);
3083        let sender1 = tx1.sender();
3084
3085        // Sender 2: tx will be promoted (gas price 55 > new base fee 50)
3086        let tx2 =
3087            MockTransaction::eip1559().with_gas_price(55).with_gas_limit(21_000).with_nonce(0);
3088        let sender2 = tx2.sender();
3089
3090        // Sender 3: tx will NOT be promoted (gas price 45 < new base fee 50)
3091        let tx3 =
3092            MockTransaction::eip1559().with_gas_price(45).with_gas_limit(21_000).with_nonce(0);
3093        let sender3 = tx3.sender();
3094
3095        // Set high initial base fee (all txs will go to basefee pool)
3096        let mut block_info = pool.block_info();
3097        block_info.pending_basefee = 70;
3098        pool.set_block_info(block_info);
3099
3100        // Add all transactions
3101        let validated1 = tx_factory.validated(tx1);
3102        let validated2 = tx_factory.validated(tx2);
3103        let validated3 = tx_factory.validated(tx3);
3104
3105        pool.add_transaction(validated1, sender_balance, 0, None).unwrap();
3106        pool.add_transaction(validated2, sender_balance, 0, None).unwrap();
3107        pool.add_transaction(validated3, sender_balance, 0, None).unwrap();
3108
3109        let sender1_id = tx_factory.ids.sender_id(&sender1).unwrap();
3110        let sender2_id = tx_factory.ids.sender_id(&sender2).unwrap();
3111        let sender3_id = tx_factory.ids.sender_id(&sender3).unwrap();
3112
3113        // All should be in basefee pool initially
3114        assert_eq!(pool.basefee_pool.len(), 3, "All txs should be in basefee pool");
3115        assert_eq!(pool.pending_pool.len(), 0, "No txs should be in pending pool");
3116
3117        // Now decrease base fee to 50 - this should promote tx1 and tx2 (prices 60 and 55)
3118        // but not tx3 (price 45)
3119        block_info.pending_basefee = 50;
3120
3121        // Update all senders' balances (simulating account state changes)
3122        let mut changed_senders = FxHashMap::default();
3123        changed_senders.insert(
3124            sender1_id,
3125            SenderInfo { state_nonce: 0, balance: sender_balance + U256::from(1000) },
3126        );
3127        changed_senders.insert(
3128            sender2_id,
3129            SenderInfo { state_nonce: 0, balance: sender_balance + U256::from(1000) },
3130        );
3131        changed_senders.insert(
3132            sender3_id,
3133            SenderInfo { state_nonce: 0, balance: sender_balance + U256::from(1000) },
3134        );
3135
3136        let outcome = pool.on_canonical_state_change(
3137            block_info,
3138            vec![],
3139            changed_senders,
3140            PoolUpdateKind::Commit,
3141        );
3142
3143        // Check final state
3144        assert_eq!(pool.pending_pool.len(), 2, "tx1 and tx2 should be promoted");
3145        assert_eq!(pool.basefee_pool.len(), 1, "tx3 should remain in basefee");
3146
3147        // CRITICAL: Should report exactly 2 promotions, not 4 (which would happen with
3148        // double-processing)
3149        assert_eq!(
3150            outcome.promoted.len(),
3151            2,
3152            "Should report exactly 2 promotions, not double-counted"
3153        );
3154
3155        // Verify the correct transactions were promoted
3156        let promoted_prices: Vec<u128> =
3157            outcome.promoted.iter().map(|tx| tx.max_fee_per_gas()).collect();
3158        assert!(promoted_prices.contains(&60));
3159        assert!(promoted_prices.contains(&55));
3160    }
3161
3162    #[test]
3163    fn test_basefee_decrease_with_empty_senders() {
3164        // Test that fee promotions still occur when basefee decreases
3165        // even with no changed_senders
3166        let mut tx_factory = MockTransactionFactory::default();
3167        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3168
3169        // Create transaction that will be promoted when fee drops
3170        let tx = MockTransaction::eip1559().with_gas_price(60).with_gas_limit(21_000);
3171
3172        // Set high initial base fee
3173        let mut block_info = pool.block_info();
3174        block_info.pending_basefee = 100;
3175        pool.set_block_info(block_info);
3176
3177        // Add transaction - should go to basefee pool
3178        let validated = tx_factory.validated(tx);
3179        pool.add_transaction(validated, U256::from(10_000_000), 0, None).unwrap();
3180
3181        assert_eq!(pool.basefee_pool.len(), 1);
3182        assert_eq!(pool.pending_pool.len(), 0);
3183
3184        // Decrease base fee with NO changed senders
3185        block_info.pending_basefee = 50;
3186        let outcome = pool.on_canonical_state_change(
3187            block_info,
3188            vec![],
3189            FxHashMap::default(), // Empty changed_senders!
3190            PoolUpdateKind::Commit,
3191        );
3192
3193        // Transaction should still be promoted by fee-driven logic
3194        assert_eq!(pool.pending_pool.len(), 1, "Fee decrease should promote tx");
3195        assert_eq!(pool.basefee_pool.len(), 0);
3196        assert_eq!(outcome.promoted.len(), 1, "Should report promotion from fee update");
3197    }
3198
3199    #[test]
3200    fn test_basefee_decrease_account_makes_unfundable() {
3201        // Test that when basefee decreases but account update makes tx unfundable,
3202        // we don't get transient promote-then-discard double counting
3203        let mut tx_factory = MockTransactionFactory::default();
3204        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3205
3206        let tx = MockTransaction::eip1559().with_gas_price(60).with_gas_limit(21_000);
3207        let sender = tx.sender();
3208
3209        // High initial base fee
3210        let mut block_info = pool.block_info();
3211        block_info.pending_basefee = 100;
3212        pool.set_block_info(block_info);
3213
3214        let validated = tx_factory.validated(tx);
3215        pool.add_transaction(validated, U256::from(10_000_000), 0, None).unwrap();
3216        let sender_id = tx_factory.ids.sender_id(&sender).unwrap();
3217
3218        assert_eq!(pool.basefee_pool.len(), 1);
3219
3220        // Decrease base fee (would normally promote) but also drain account
3221        block_info.pending_basefee = 50;
3222        let mut changed_senders = FxHashMap::default();
3223        changed_senders.insert(
3224            sender_id,
3225            SenderInfo {
3226                state_nonce: 0,
3227                balance: U256::from(100), // Too low to pay for gas!
3228            },
3229        );
3230
3231        let outcome = pool.on_canonical_state_change(
3232            block_info,
3233            vec![],
3234            changed_senders,
3235            PoolUpdateKind::Commit,
3236        );
3237
3238        // With insufficient balance, transaction goes to queued pool
3239        assert_eq!(pool.pending_pool.len(), 0, "Unfunded tx should not be in pending");
3240        assert_eq!(pool.basefee_pool.len(), 0, "Tx no longer in basefee pool");
3241        assert_eq!(pool.queued_pool.len(), 1, "Unfunded tx should be in queued pool");
3242
3243        // Transaction is not removed, just moved to queued
3244        let tx_count = pool.all_transactions.txs.len();
3245        assert_eq!(tx_count, 1, "Transaction should still be in pool (in queued)");
3246
3247        assert_eq!(outcome.promoted.len(), 0, "Should not report promotion");
3248        assert_eq!(outcome.discarded.len(), 0, "Queued tx is not reported as discarded");
3249    }
3250
3251    #[test]
3252    fn insert_already_imported() {
3253        let on_chain_balance = U256::ZERO;
3254        let on_chain_nonce = 0;
3255        let mut f = MockTransactionFactory::default();
3256        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3257        let tx = MockTransaction::eip1559().inc_price().inc_limit();
3258        let tx = f.validated(tx);
3259        pool.add_transaction(tx.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
3260        match pool.add_transaction(tx, on_chain_balance, on_chain_nonce, None).unwrap_err().kind {
3261            PoolErrorKind::AlreadyImported => {}
3262            _ => unreachable!(),
3263        }
3264    }
3265
3266    #[test]
3267    fn insert_replace() {
3268        let on_chain_balance = U256::ZERO;
3269        let on_chain_nonce = 0;
3270        let mut f = MockTransactionFactory::default();
3271        let mut pool = AllTransactions::default();
3272        let tx = MockTransaction::eip1559().inc_price().inc_limit();
3273        let first = f.validated(tx.clone());
3274        let _ = pool.insert_tx(first.clone(), on_chain_balance, on_chain_nonce).unwrap();
3275        let replacement = f.validated(tx.rng_hash().inc_price());
3276        let InsertOk { updates, replaced_tx, .. } =
3277            pool.insert_tx(replacement.clone(), on_chain_balance, on_chain_nonce).unwrap();
3278        assert!(updates.is_empty());
3279        let replaced = replaced_tx.unwrap();
3280        assert_eq!(replaced.0.hash(), first.hash());
3281
3282        // ensure replaced tx is fully removed
3283        assert!(!pool.contains(first.hash()));
3284        assert!(pool.contains(replacement.hash()));
3285        assert_eq!(pool.len(), 1);
3286    }
3287
3288    #[test]
3289    fn insert_replace_txpool() {
3290        let on_chain_balance = U256::ZERO;
3291        let on_chain_nonce = 0;
3292        let mut f = MockTransactionFactory::default();
3293        let mut pool = TxPool::mock();
3294
3295        let tx = MockTransaction::eip1559().inc_price().inc_limit();
3296        let first = f.validated(tx.clone());
3297        let first_added =
3298            pool.add_transaction(first, on_chain_balance, on_chain_nonce, None).unwrap();
3299        let replacement = f.validated(tx.rng_hash().inc_price());
3300        let replacement_added = pool
3301            .add_transaction(replacement.clone(), on_chain_balance, on_chain_nonce, None)
3302            .unwrap();
3303
3304        // // ensure replaced tx removed
3305        assert!(!pool.contains(first_added.hash()));
3306        // but the replacement is still there
3307        assert!(pool.subpool_contains(replacement_added.subpool(), replacement_added.id()));
3308
3309        assert!(pool.contains(replacement.hash()));
3310        let size = pool.size();
3311        assert_eq!(size.total, 1);
3312        size.assert_invariants();
3313    }
3314
3315    #[test]
3316    fn insert_replace_underpriced() {
3317        let on_chain_balance = U256::ZERO;
3318        let on_chain_nonce = 0;
3319        let mut f = MockTransactionFactory::default();
3320        let mut pool = AllTransactions::default();
3321        let tx = MockTransaction::eip1559().inc_price().inc_limit();
3322        let first = f.validated(tx.clone());
3323        let _res = pool.insert_tx(first, on_chain_balance, on_chain_nonce);
3324        let mut replacement = f.validated(tx.rng_hash());
3325        replacement.transaction = replacement.transaction.decr_price();
3326        let err = pool.insert_tx(replacement, on_chain_balance, on_chain_nonce).unwrap_err();
3327        assert!(matches!(err, InsertErr::Underpriced { .. }));
3328    }
3329
3330    #[test]
3331    fn insert_replace_underpriced_not_enough_bump() {
3332        let on_chain_balance = U256::ZERO;
3333        let on_chain_nonce = 0;
3334        let mut f = MockTransactionFactory::default();
3335        let mut pool = AllTransactions::default();
3336        let mut tx = MockTransaction::eip1559().inc_price().inc_limit();
3337        tx.set_priority_fee(100);
3338        tx.set_max_fee(100);
3339        let first = f.validated(tx.clone());
3340        let _ = pool.insert_tx(first.clone(), on_chain_balance, on_chain_nonce).unwrap();
3341        let mut replacement = f.validated(tx.rng_hash().inc_price());
3342
3343        // a price bump of 9% is not enough for a default min price bump of 10%
3344        replacement.transaction.set_priority_fee(109);
3345        replacement.transaction.set_max_fee(109);
3346        let err =
3347            pool.insert_tx(replacement.clone(), on_chain_balance, on_chain_nonce).unwrap_err();
3348        assert!(matches!(err, InsertErr::Underpriced { .. }));
3349        // ensure first tx is not removed
3350        assert!(pool.contains(first.hash()));
3351        assert_eq!(pool.len(), 1);
3352
3353        // should also fail if the bump in max fee is not enough
3354        replacement.transaction.set_priority_fee(110);
3355        replacement.transaction.set_max_fee(109);
3356        let err =
3357            pool.insert_tx(replacement.clone(), on_chain_balance, on_chain_nonce).unwrap_err();
3358        assert!(matches!(err, InsertErr::Underpriced { .. }));
3359        assert!(pool.contains(first.hash()));
3360        assert_eq!(pool.len(), 1);
3361
3362        // should also fail if the bump in priority fee is not enough
3363        replacement.transaction.set_priority_fee(109);
3364        replacement.transaction.set_max_fee(110);
3365        let err = pool.insert_tx(replacement, on_chain_balance, on_chain_nonce).unwrap_err();
3366        assert!(matches!(err, InsertErr::Underpriced { .. }));
3367        assert!(pool.contains(first.hash()));
3368        assert_eq!(pool.len(), 1);
3369    }
3370
3371    #[test]
3372    fn insert_replace_underpriced_rounds_up_minimum_bump() {
3373        let on_chain_balance = U256::ZERO;
3374        let on_chain_nonce = 0;
3375        let mut f = MockTransactionFactory::default();
3376        let mut pool = AllTransactions { minimal_protocol_basefee: 0, ..Default::default() };
3377        let mut tx = MockTransaction::eip1559().inc_price().inc_limit();
3378        tx.set_priority_fee(1);
3379        tx.set_max_fee(1);
3380
3381        let first = f.validated(tx.clone());
3382        let _ = pool.insert_tx(first.clone(), on_chain_balance, on_chain_nonce).unwrap();
3383
3384        let mut replacement = f.validated(tx.rng_hash().inc_price());
3385        replacement.transaction.set_priority_fee(1);
3386        replacement.transaction.set_max_fee(2);
3387        let err =
3388            pool.insert_tx(replacement.clone(), on_chain_balance, on_chain_nonce).unwrap_err();
3389        assert!(matches!(err, InsertErr::Underpriced { .. }));
3390        assert!(pool.contains(first.hash()));
3391        assert_eq!(pool.len(), 1);
3392
3393        replacement.transaction.set_priority_fee(2);
3394        replacement.transaction.set_max_fee(2);
3395        let replaced = pool.insert_tx(replacement, on_chain_balance, on_chain_nonce).unwrap();
3396        assert!(replaced.replaced_tx.is_some());
3397        assert_eq!(pool.len(), 1);
3398    }
3399
3400    #[test]
3401    fn insert_conflicting_type_normal_to_blob() {
3402        let on_chain_balance = U256::from(10_000);
3403        let on_chain_nonce = 0;
3404        let mut f = MockTransactionFactory::default();
3405        let mut pool = AllTransactions::default();
3406        let tx = MockTransaction::eip1559().inc_price().inc_limit();
3407        let first = f.validated(tx.clone());
3408        pool.insert_tx(first, on_chain_balance, on_chain_nonce).unwrap();
3409        let tx = MockTransaction::eip4844().set_sender(tx.sender()).inc_price_by(100).inc_limit();
3410        let blob = f.validated(tx);
3411        let err = pool.insert_tx(blob, on_chain_balance, on_chain_nonce).unwrap_err();
3412        assert!(matches!(err, InsertErr::TxTypeConflict { .. }), "{err:?}");
3413    }
3414
3415    #[test]
3416    fn insert_conflicting_type_blob_to_normal() {
3417        let on_chain_balance = U256::from(10_000);
3418        let on_chain_nonce = 0;
3419        let mut f = MockTransactionFactory::default();
3420        let mut pool = AllTransactions::default();
3421        let tx = MockTransaction::eip4844().inc_price().inc_limit();
3422        let first = f.validated(tx.clone());
3423        pool.insert_tx(first, on_chain_balance, on_chain_nonce).unwrap();
3424        let tx = MockTransaction::eip1559().set_sender(tx.sender()).inc_price_by(100).inc_limit();
3425        let tx = f.validated(tx);
3426        let err = pool.insert_tx(tx, on_chain_balance, on_chain_nonce).unwrap_err();
3427        assert!(matches!(err, InsertErr::TxTypeConflict { .. }), "{err:?}");
3428    }
3429
3430    // insert nonce then nonce - 1
3431    #[test]
3432    fn insert_previous() {
3433        let on_chain_balance = U256::ZERO;
3434        let on_chain_nonce = 0;
3435        let mut f = MockTransactionFactory::default();
3436        let mut pool = AllTransactions::default();
3437        let tx = MockTransaction::eip1559().inc_nonce().inc_price().inc_limit();
3438        let first = f.validated(tx.clone());
3439        let _res = pool.insert_tx(first.clone(), on_chain_balance, on_chain_nonce);
3440
3441        let first_in_pool = pool.get(first.id()).unwrap();
3442
3443        // has nonce gap
3444        assert!(!first_in_pool.state.contains(TxState::NO_NONCE_GAPS));
3445
3446        let prev = f.validated(tx.prev());
3447        let InsertOk { updates, replaced_tx, state, move_to, .. } =
3448            pool.insert_tx(prev, on_chain_balance, on_chain_nonce).unwrap();
3449
3450        // no updates since still in queued pool
3451        assert!(updates.is_empty());
3452        assert!(replaced_tx.is_none());
3453        assert!(state.contains(TxState::NO_NONCE_GAPS));
3454        assert_eq!(move_to, SubPool::Queued);
3455
3456        let first_in_pool = pool.get(first.id()).unwrap();
3457        // has non nonce gap
3458        assert!(first_in_pool.state.contains(TxState::NO_NONCE_GAPS));
3459    }
3460
3461    // insert nonce then nonce - 1
3462    #[test]
3463    fn insert_with_updates() {
3464        let on_chain_balance = U256::from(10_000);
3465        let on_chain_nonce = 0;
3466        let mut f = MockTransactionFactory::default();
3467        let mut pool = AllTransactions::default();
3468        let tx = MockTransaction::eip1559().inc_nonce().set_gas_price(100).inc_limit();
3469        let first = f.validated(tx.clone());
3470        let _res = pool.insert_tx(first.clone(), on_chain_balance, on_chain_nonce).unwrap();
3471
3472        let first_in_pool = pool.get(first.id()).unwrap();
3473        // has nonce gap
3474        assert!(!first_in_pool.state.contains(TxState::NO_NONCE_GAPS));
3475        assert_eq!(SubPool::Queued, first_in_pool.subpool);
3476
3477        let prev = f.validated(tx.prev());
3478        let InsertOk { updates, replaced_tx, state, move_to, .. } =
3479            pool.insert_tx(prev, on_chain_balance, on_chain_nonce).unwrap();
3480
3481        // updated previous tx
3482        assert_eq!(updates.len(), 1);
3483        assert!(replaced_tx.is_none());
3484        assert!(state.contains(TxState::NO_NONCE_GAPS));
3485        assert_eq!(move_to, SubPool::Pending);
3486
3487        let first_in_pool = pool.get(first.id()).unwrap();
3488        // has non nonce gap
3489        assert!(first_in_pool.state.contains(TxState::NO_NONCE_GAPS));
3490        assert_eq!(SubPool::Pending, first_in_pool.subpool);
3491    }
3492
3493    #[test]
3494    fn insert_previous_blocking() {
3495        let on_chain_balance = U256::from(1_000);
3496        let on_chain_nonce = 0;
3497        let mut f = MockTransactionFactory::default();
3498        let mut pool = AllTransactions::default();
3499        pool.pending_fees.base_fee = pool.minimal_protocol_basefee.checked_add(1).unwrap();
3500        let tx = MockTransaction::eip1559().inc_nonce().inc_limit();
3501        let first = f.validated(tx.clone());
3502
3503        let _res = pool.insert_tx(first.clone(), on_chain_balance, on_chain_nonce);
3504
3505        let first_in_pool = pool.get(first.id()).unwrap();
3506
3507        assert!(tx.get_gas_price() < pool.pending_fees.base_fee as u128);
3508        // has nonce gap
3509        assert!(!first_in_pool.state.contains(TxState::NO_NONCE_GAPS));
3510
3511        let prev = f.validated(tx.prev());
3512        let InsertOk { updates, replaced_tx, state, move_to, .. } =
3513            pool.insert_tx(prev, on_chain_balance, on_chain_nonce).unwrap();
3514
3515        assert!(!state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
3516        // no updates since still in queued pool
3517        assert!(updates.is_empty());
3518        assert!(replaced_tx.is_none());
3519        assert!(state.contains(TxState::NO_NONCE_GAPS));
3520        assert_eq!(move_to, SubPool::BaseFee);
3521
3522        let first_in_pool = pool.get(first.id()).unwrap();
3523        // has non nonce gap
3524        assert!(first_in_pool.state.contains(TxState::NO_NONCE_GAPS));
3525    }
3526
3527    #[test]
3528    fn rejects_spammer() {
3529        let on_chain_balance = U256::from(1_000);
3530        let on_chain_nonce = 0;
3531        let mut f = MockTransactionFactory::default();
3532        let mut pool = AllTransactions::default();
3533
3534        let mut tx = MockTransaction::eip1559();
3535        let unblocked_tx = tx.clone();
3536        for _ in 0..pool.max_account_slots {
3537            tx = tx.next();
3538            pool.insert_tx(f.validated(tx.clone()), on_chain_balance, on_chain_nonce).unwrap();
3539        }
3540
3541        assert_eq!(
3542            pool.max_account_slots,
3543            pool.tx_count(f.ids.sender_id(tx.get_sender()).unwrap())
3544        );
3545
3546        let err =
3547            pool.insert_tx(f.validated(tx.next()), on_chain_balance, on_chain_nonce).unwrap_err();
3548        assert!(matches!(err, InsertErr::ExceededSenderTransactionsCapacity { .. }));
3549
3550        assert!(pool
3551            .insert_tx(f.validated(unblocked_tx), on_chain_balance, on_chain_nonce)
3552            .is_ok());
3553    }
3554
3555    #[test]
3556    fn replace_at_sender_capacity() {
3557        let on_chain_balance = U256::from(1_000);
3558        let on_chain_nonce = 0;
3559        let mut f = MockTransactionFactory::default();
3560        let mut pool = AllTransactions::default();
3561
3562        let mut tx = MockTransaction::eip1559().with_nonce(on_chain_nonce);
3563        pool.insert_tx(f.validated(tx.clone()), on_chain_balance, on_chain_nonce).unwrap();
3564        for _ in 1..pool.max_account_slots {
3565            tx = tx.next();
3566            pool.insert_tx(f.validated(tx.clone()), on_chain_balance, on_chain_nonce).unwrap();
3567        }
3568        let sender = f.ids.sender_id(tx.get_sender()).unwrap();
3569        assert_eq!(pool.tx_count(sender), pool.max_account_slots);
3570
3571        // a fee-bumped replacement of the highest nonce does not change the sender's count
3572        let replacement = f.validated(tx.clone().rng_hash().inc_price_by(tx.get_gas_price()));
3573        let InsertOk { replaced_tx, .. } =
3574            pool.insert_tx(replacement.clone(), on_chain_balance, on_chain_nonce).unwrap();
3575        assert_eq!(replaced_tx.unwrap().0.hash(), tx.hash());
3576        assert!(!pool.contains(tx.hash()));
3577        assert!(pool.contains(replacement.hash()));
3578        assert_eq!(pool.tx_count(sender), pool.max_account_slots);
3579
3580        // an underpriced replacement is still rejected as such
3581        let underpriced = f.validated(tx.clone().rng_hash());
3582        let err = pool.insert_tx(underpriced, on_chain_balance, on_chain_nonce).unwrap_err();
3583        assert!(matches!(err, InsertErr::Underpriced { .. }));
3584
3585        // a new nonce is still over capacity
3586        let err =
3587            pool.insert_tx(f.validated(tx.next()), on_chain_balance, on_chain_nonce).unwrap_err();
3588        assert!(matches!(err, InsertErr::ExceededSenderTransactionsCapacity { .. }));
3589    }
3590
3591    #[test]
3592    fn allow_local_spamming() {
3593        let on_chain_balance = U256::from(1_000);
3594        let on_chain_nonce = 0;
3595        let mut f = MockTransactionFactory::default();
3596        let mut pool = AllTransactions::default();
3597
3598        let mut tx = MockTransaction::eip1559();
3599        for _ in 0..pool.max_account_slots {
3600            tx = tx.next();
3601            pool.insert_tx(
3602                f.validated_with_origin(TransactionOrigin::Local, tx.clone()),
3603                on_chain_balance,
3604                on_chain_nonce,
3605            )
3606            .unwrap();
3607        }
3608
3609        assert_eq!(
3610            pool.max_account_slots,
3611            pool.tx_count(f.ids.sender_id(tx.get_sender()).unwrap())
3612        );
3613
3614        pool.insert_tx(
3615            f.validated_with_origin(TransactionOrigin::Local, tx.next()),
3616            on_chain_balance,
3617            on_chain_nonce,
3618        )
3619        .unwrap();
3620    }
3621
3622    #[test]
3623    fn reject_tx_over_gas_limit() {
3624        let on_chain_balance = U256::from(1_000);
3625        let on_chain_nonce = 0;
3626        let mut f = MockTransactionFactory::default();
3627        let mut pool = AllTransactions::default();
3628
3629        let tx = MockTransaction::eip1559().with_gas_limit(30_000_001);
3630
3631        assert!(matches!(
3632            pool.insert_tx(f.validated(tx), on_chain_balance, on_chain_nonce),
3633            Err(InsertErr::TxGasLimitMoreThanAvailableBlockGas { .. })
3634        ));
3635    }
3636
3637    #[test]
3638    fn test_tx_equal_gas_limit() {
3639        let on_chain_balance = U256::from(1_000);
3640        let on_chain_nonce = 0;
3641        let mut f = MockTransactionFactory::default();
3642        let mut pool = AllTransactions::default();
3643
3644        let tx = MockTransaction::eip1559().with_gas_limit(30_000_000);
3645
3646        let InsertOk { state, .. } =
3647            pool.insert_tx(f.validated(tx), on_chain_balance, on_chain_nonce).unwrap();
3648        assert!(state.contains(TxState::NOT_TOO_MUCH_GAS));
3649    }
3650
3651    #[test]
3652    fn full_update_sender_heuristic() {
3653        let mut pool = AllTransactions::<MockTransaction>::default();
3654        for sender in 0..(FULL_UPDATE_MIN_SENDERS - 1) as u64 {
3655            pool.tx_counter.insert(sender.into(), 1);
3656        }
3657
3658        // Below the pool-size floor, only covering every live sender triggers a full update.
3659        assert!(!pool.should_update_all_senders(250));
3660        assert!(pool.should_update_all_senders(FULL_UPDATE_MIN_SENDERS - 1));
3661
3662        pool.tx_counter.insert((FULL_UPDATE_MIN_SENDERS as u64 - 1).into(), 1);
3663
3664        // At the floor, one quarter of the live senders is the crossover.
3665        assert!(
3666            !pool.should_update_all_senders(FULL_UPDATE_MIN_SENDERS / FULL_UPDATE_SENDER_RATIO - 1)
3667        );
3668        assert!(pool.should_update_all_senders(FULL_UPDATE_MIN_SENDERS / FULL_UPDATE_SENDER_RATIO));
3669        assert!(pool.should_update_all_senders(FULL_UPDATE_MIN_SENDERS + 1));
3670    }
3671
3672    #[test]
3673    fn changed_sender_update_matches_full_update() {
3674        let senders = [
3675            Address::with_last_byte(0x0a),
3676            Address::with_last_byte(0x0b),
3677            Address::with_last_byte(0x0c),
3678        ];
3679        let starting_nonces = [5, 11, 17];
3680
3681        let build_pool = || {
3682            let mut f = MockTransactionFactory::default();
3683            let mut pool = AllTransactions::default();
3684            pool.pending_fees.base_fee = 1;
3685
3686            for (sender, starting_nonce) in senders.into_iter().zip(starting_nonces) {
3687                for nonce in starting_nonce..starting_nonce + 3 {
3688                    let tx = MockTransaction::eip1559()
3689                        .with_sender(sender)
3690                        .with_nonce(nonce)
3691                        .inc_price_by(10)
3692                        .rng_hash();
3693                    pool.insert_tx(f.validated(tx), U256::from(1_000_000), starting_nonce).unwrap();
3694                }
3695            }
3696
3697            // The fee differs from the initial marker, so this takes the all-transactions path.
3698            pool.update(&Default::default());
3699            let sender_ids = senders.map(|sender| f.ids.sender_id(&sender).unwrap());
3700            (pool, sender_ids)
3701        };
3702
3703        let (mut changed_senders_only, sender_ids) = build_pool();
3704        let (mut full_update, full_update_sender_ids) = build_pool();
3705        assert_eq!(sender_ids, full_update_sender_ids);
3706
3707        let mut changed = FxHashMap::default();
3708        changed.insert(
3709            sender_ids[0],
3710            SenderInfo { state_nonce: starting_nonces[0] + 1, balance: U256::from(1_000_000) },
3711        );
3712        changed.insert(
3713            sender_ids[1],
3714            SenderInfo { state_nonce: starting_nonces[1], balance: U256::ZERO },
3715        );
3716
3717        let mut changed_sender_updates = changed_senders_only.update(&changed);
3718        // Force the reference pool through the all-transactions path with the same pending fees.
3719        full_update.last_full_update_fees.base_fee =
3720            full_update.last_full_update_fees.base_fee.saturating_add(1);
3721        let mut full_updates = full_update.update(&changed);
3722
3723        let update_key = |update: &PoolUpdate| {
3724            let destination = match &update.destination {
3725                Destination::Discard => None,
3726                Destination::Pool(pool) => Some(*pool),
3727            };
3728            (update.id, update.current, destination)
3729        };
3730        changed_sender_updates.sort_unstable_by_key(|update| update.id);
3731        full_updates.sort_unstable_by_key(|update| update.id);
3732        assert_eq!(
3733            changed_sender_updates.iter().map(update_key).collect::<Vec<_>>(),
3734            full_updates.iter().map(update_key).collect::<Vec<_>>()
3735        );
3736
3737        let metadata = |pool: &AllTransactions<MockTransaction>| {
3738            pool.txs
3739                .iter()
3740                .map(|(id, tx)| (*id, tx.state, tx.subpool, tx.cumulative_cost))
3741                .collect::<Vec<_>>()
3742        };
3743        assert_eq!(metadata(&changed_senders_only), metadata(&full_update));
3744    }
3745
3746    #[test]
3747    fn update_visits_every_sender_when_the_base_fee_moved() {
3748        let mut f = MockTransactionFactory::default();
3749        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3750
3751        let tx = MockTransaction::eip1559().inc_price_by(10);
3752        let validated = f.validated(tx.clone());
3753        let id = *validated.id();
3754        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
3755
3756        pool.all_transactions.update(&Default::default());
3757        assert!(pool
3758            .all_transactions
3759            .txs
3760            .get(&id)
3761            .unwrap()
3762            .state
3763            .contains(TxState::ENOUGH_FEE_CAP_BLOCK));
3764
3765        // raising the base fee past the tx must still reach it even though no account changed,
3766        // otherwise the fast path would leave a stale fee bit behind
3767        pool.all_transactions.pending_fees.base_fee = (tx.max_fee_per_gas() + 1) as u64;
3768        pool.all_transactions.update(&Default::default());
3769
3770        assert!(
3771            !pool
3772                .all_transactions
3773                .txs
3774                .get(&id)
3775                .unwrap()
3776                .state
3777                .contains(TxState::ENOUGH_FEE_CAP_BLOCK),
3778            "fee change was not applied to an unchanged sender"
3779        );
3780    }
3781
3782    #[test]
3783    fn blob_fee_change_records_full_update() {
3784        let mut pool = AllTransactions::<MockTransaction>::default();
3785        pool.pending_fees.blob_fee += 1;
3786
3787        pool.update(&Default::default());
3788
3789        assert_eq!(pool.last_full_update_fees, pool.pending_fees);
3790    }
3791
3792    #[test]
3793    fn gap_fill_rechecks_descendant_fee_eligibility() {
3794        let mut f = MockTransactionFactory::default();
3795        let mut pool = AllTransactions::default();
3796        let sender = Address::with_last_byte(0x0d);
3797        let balance = U256::MAX;
3798
3799        pool.pending_fees.base_fee = 100;
3800        let descendant = MockTransaction::eip1559()
3801            .with_sender(sender)
3802            .with_nonce(1)
3803            .with_gas_limit(21_000)
3804            .with_max_fee(150)
3805            .with_priority_fee(1)
3806            .rng_hash();
3807        let descendant = f.validated(descendant);
3808        let descendant_id = *descendant.id();
3809        pool.insert_tx(descendant, balance, 0).unwrap();
3810        pool.update(&Default::default());
3811
3812        // The fee increase cannot affect a nonce-gapped transaction yet, but closing its gap must
3813        // evaluate it against the current fee.
3814        pool.pending_fees.base_fee = 200;
3815        pool.update(&Default::default());
3816        assert!(pool.get(&descendant_id).unwrap().state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
3817
3818        let predecessor = MockTransaction::eip1559()
3819            .with_sender(sender)
3820            .with_nonce(0)
3821            .with_gas_limit(21_000)
3822            .with_max_fee(250)
3823            .with_priority_fee(1)
3824            .rng_hash();
3825        let InsertOk { move_to, .. } =
3826            pool.insert_tx(f.validated(predecessor), balance, 0).unwrap();
3827
3828        assert_eq!(move_to, SubPool::Pending);
3829        let descendant = pool.get(&descendant_id).unwrap();
3830        assert_eq!(descendant.subpool, SubPool::BaseFee);
3831        assert!(!descendant.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
3832        assert!(descendant.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
3833    }
3834
3835    #[test]
3836    fn base_fee_update_unparks_all_descendants() {
3837        let mut f = MockTransactionFactory::default();
3838        let mut pool = AllTransactions::default();
3839        let sender = Address::with_last_byte(0x0e);
3840        let mut ids = Vec::new();
3841
3842        pool.pending_fees.base_fee = 200;
3843        for nonce in 0..3 {
3844            let tx = MockTransaction::eip1559()
3845                .with_sender(sender)
3846                .with_nonce(nonce)
3847                .with_gas_limit(21_000)
3848                .with_max_fee(150)
3849                .with_priority_fee(1)
3850                .rng_hash();
3851            let tx = f.validated(tx);
3852            ids.push(*tx.id());
3853            pool.insert_tx(tx, U256::MAX, 0).unwrap();
3854        }
3855
3856        pool.pending_fees.base_fee = 100;
3857        pool.update(&Default::default());
3858
3859        for id in ids {
3860            assert_eq!(pool.get(&id).unwrap().subpool, SubPool::Pending);
3861        }
3862    }
3863
3864    #[test]
3865    fn fee_update_keeps_descendants_of_underpriced_transaction_parked() {
3866        let mut f = MockTransactionFactory::default();
3867        let mut pool = AllTransactions::default();
3868        let sender = Address::with_last_byte(0x10);
3869        let fee_caps = [150, 50, 150];
3870        let mut ids = Vec::new();
3871
3872        pool.pending_fees.base_fee = 200;
3873        for (nonce, fee_cap) in fee_caps.into_iter().enumerate() {
3874            let tx = MockTransaction::eip1559()
3875                .with_sender(sender)
3876                .with_nonce(nonce as u64)
3877                .with_gas_limit(21_000)
3878                .with_max_fee(fee_cap)
3879                .with_priority_fee(1)
3880                .rng_hash();
3881            let tx = f.validated(tx);
3882            ids.push(*tx.id());
3883            pool.insert_tx(tx, U256::MAX, 0).unwrap();
3884        }
3885
3886        pool.pending_fees.base_fee = 100;
3887        pool.update(&Default::default());
3888
3889        assert_eq!(pool.get(&ids[0]).unwrap().subpool, SubPool::Pending);
3890        assert_eq!(pool.get(&ids[1]).unwrap().subpool, SubPool::BaseFee);
3891        assert_eq!(pool.get(&ids[2]).unwrap().subpool, SubPool::Queued);
3892    }
3893
3894    #[test]
3895    fn blob_fee_update_unparks_all_descendants() {
3896        let mut f = MockTransactionFactory::default();
3897        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3898        let sender = Address::with_last_byte(0x0f);
3899        let mut block_info = pool.block_info();
3900        block_info.pending_blob_fee = Some(200);
3901        pool.set_block_info(block_info);
3902
3903        for nonce in 0..3 {
3904            let tx = MockTransaction::eip4844()
3905                .with_sender(sender)
3906                .with_nonce(nonce)
3907                .with_gas_limit(21_000)
3908                .with_max_fee(1_000)
3909                .with_priority_fee(1)
3910                .with_blob_fee(150)
3911                .rng_hash();
3912            pool.add_transaction(f.validated(tx), U256::MAX, 0, None).unwrap();
3913        }
3914        assert_eq!(pool.blob_pool.len(), 3);
3915
3916        block_info.pending_blob_fee = Some(100);
3917        pool.on_canonical_state_change(
3918            block_info,
3919            Vec::new(),
3920            FxHashMap::default(),
3921            PoolUpdateKind::Commit,
3922        );
3923
3924        let nonces = pool.best_transactions().map(|tx| tx.nonce()).collect::<Vec<_>>();
3925        assert_eq!(nonces, vec![0, 1, 2]);
3926    }
3927
3928    #[test]
3929    fn update_basefee_subpools() {
3930        let mut f = MockTransactionFactory::default();
3931        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3932
3933        let tx = MockTransaction::eip1559().inc_price_by(10);
3934        let validated = f.validated(tx.clone());
3935        let id = *validated.id();
3936        pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
3937
3938        assert_eq!(pool.pending_pool.len(), 1);
3939
3940        pool.update_basefee((tx.max_fee_per_gas() + 1) as u64, |_| {});
3941
3942        assert!(pool.pending_pool.is_empty());
3943        assert_eq!(pool.basefee_pool.len(), 1);
3944
3945        assert_eq!(pool.all_transactions.txs.get(&id).unwrap().subpool, SubPool::BaseFee)
3946    }
3947
3948    #[test]
3949    fn update_basefee_subpools_setting_block_info() {
3950        let mut f = MockTransactionFactory::default();
3951        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3952
3953        let tx = MockTransaction::eip1559().inc_price_by(10);
3954        let validated = f.validated(tx.clone());
3955        let id = *validated.id();
3956        pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
3957
3958        assert_eq!(pool.pending_pool.len(), 1);
3959
3960        // use set_block_info for the basefee update
3961        let mut block_info = pool.block_info();
3962        block_info.pending_basefee = (tx.max_fee_per_gas() + 1) as u64;
3963        pool.set_block_info(block_info);
3964
3965        assert!(pool.pending_pool.is_empty());
3966        assert_eq!(pool.basefee_pool.len(), 1);
3967
3968        assert_eq!(pool.all_transactions.txs.get(&id).unwrap().subpool, SubPool::BaseFee)
3969    }
3970
3971    #[test]
3972    fn basefee_decrease_promotes_affordable_and_keeps_unaffordable() {
3973        let mut f = MockTransactionFactory::default();
3974        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
3975
3976        // Create transactions that will be in basefee pool (can't afford initial high fee)
3977        // Use different senders to avoid nonce gap issues
3978        let sender_a = Address::with_last_byte(0x0a);
3979        let sender_b = Address::with_last_byte(0x0b);
3980        let sender_c = Address::with_last_byte(0x0c);
3981
3982        let tx1 = MockTransaction::eip1559()
3983            .set_sender(sender_a)
3984            .set_nonce(0)
3985            .set_max_fee(500)
3986            .inc_limit();
3987        let tx2 = MockTransaction::eip1559()
3988            .set_sender(sender_b)
3989            .set_nonce(0)
3990            .set_max_fee(600)
3991            .inc_limit();
3992        let tx3 = MockTransaction::eip1559()
3993            .set_sender(sender_c)
3994            .set_nonce(0)
3995            .set_max_fee(400)
3996            .inc_limit();
3997
3998        // Set high initial basefee so transactions go to basefee pool
3999        let mut block_info = pool.block_info();
4000        block_info.pending_basefee = 700;
4001        pool.set_block_info(block_info);
4002
4003        let validated1 = f.validated(tx1);
4004        let validated2 = f.validated(tx2);
4005        let validated3 = f.validated(tx3);
4006        let id1 = *validated1.id();
4007        let id2 = *validated2.id();
4008        let id3 = *validated3.id();
4009
4010        // Add transactions - they should go to basefee pool due to high basefee
4011        // All transactions have nonce 0 from different senders, so on_chain_nonce should be 0 for
4012        // all
4013        pool.add_transaction(validated1, U256::from(10_000), 0, None).unwrap();
4014        pool.add_transaction(validated2, U256::from(10_000), 0, None).unwrap();
4015        pool.add_transaction(validated3, U256::from(10_000), 0, None).unwrap();
4016
4017        // Debug: Check where transactions ended up
4018        println!("Basefee pool len: {}", pool.basefee_pool.len());
4019        println!("Pending pool len: {}", pool.pending_pool.len());
4020        println!("tx1 subpool: {:?}", pool.all_transactions.txs.get(&id1).unwrap().subpool);
4021        println!("tx2 subpool: {:?}", pool.all_transactions.txs.get(&id2).unwrap().subpool);
4022        println!("tx3 subpool: {:?}", pool.all_transactions.txs.get(&id3).unwrap().subpool);
4023
4024        // Verify they're in basefee pool
4025        assert_eq!(pool.basefee_pool.len(), 3);
4026        assert_eq!(pool.pending_pool.len(), 0);
4027        assert_eq!(pool.all_transactions.txs.get(&id1).unwrap().subpool, SubPool::BaseFee);
4028        assert_eq!(pool.all_transactions.txs.get(&id2).unwrap().subpool, SubPool::BaseFee);
4029        assert_eq!(pool.all_transactions.txs.get(&id3).unwrap().subpool, SubPool::BaseFee);
4030
4031        // Now decrease basefee to trigger the zero-allocation optimization
4032        let mut block_info = pool.block_info();
4033        block_info.pending_basefee = 450; // tx1 (500) and tx2 (600) can now afford it, tx3 (400)
4034                                          // cannot
4035        pool.set_block_info(block_info);
4036
4037        // Verify the optimization worked correctly:
4038        // - tx1 and tx2 should be promoted to pending (mathematical certainty)
4039        // - tx3 should remain in basefee pool
4040        // - All state transitions should be correct
4041        assert_eq!(pool.basefee_pool.len(), 1);
4042        assert_eq!(pool.pending_pool.len(), 2);
4043
4044        // tx3 should still be in basefee pool (fee 400 < basefee 450)
4045        assert_eq!(pool.all_transactions.txs.get(&id3).unwrap().subpool, SubPool::BaseFee);
4046
4047        // tx1 and tx2 should be in pending pool with correct state bits
4048        let tx1_meta = pool.all_transactions.txs.get(&id1).unwrap();
4049        let tx2_meta = pool.all_transactions.txs.get(&id2).unwrap();
4050        assert_eq!(tx1_meta.subpool, SubPool::Pending);
4051        assert_eq!(tx2_meta.subpool, SubPool::Pending);
4052        assert!(tx1_meta.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
4053        assert!(tx2_meta.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
4054
4055        // Verify that best_transactions returns the promoted transactions
4056        let best: Vec<_> = pool.best_transactions().take(3).collect();
4057        assert_eq!(best.len(), 2); // Only tx1 and tx2 should be returned
4058        assert!(best.iter().any(|tx| tx.id() == &id1));
4059        assert!(best.iter().any(|tx| tx.id() == &id2));
4060    }
4061
4062    #[test]
4063    fn apply_fee_updates_records_promotions_after_basefee_drop() {
4064        let mut f = MockTransactionFactory::default();
4065        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4066
4067        let tx = MockTransaction::eip1559()
4068            .with_gas_limit(21_000)
4069            .with_max_fee(500)
4070            .with_priority_fee(1);
4071        let validated = f.validated(tx);
4072        let id = *validated.id();
4073        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
4074
4075        assert_eq!(pool.pending_pool.len(), 1);
4076
4077        // Raise base fee beyond the transaction's cap so it gets parked in BaseFee pool.
4078        pool.update_basefee(600, |_| {});
4079        assert!(pool.pending_pool.is_empty());
4080        assert_eq!(pool.basefee_pool.len(), 1);
4081
4082        let prev_base_fee = 600;
4083        let prev_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4084
4085        // Simulate the canonical state path updating pending fees before applying promotions.
4086        pool.all_transactions.pending_fees.base_fee = 400;
4087
4088        let mut outcome = UpdateOutcome::default();
4089        pool.apply_fee_updates(prev_base_fee, prev_blob_fee, &mut outcome);
4090
4091        assert_eq!(pool.pending_pool.len(), 1);
4092        assert!(pool.basefee_pool.is_empty());
4093        assert_eq!(outcome.promoted.len(), 1);
4094        assert_eq!(outcome.promoted[0].id(), &id);
4095        assert_eq!(pool.all_transactions.pending_fees.base_fee, 400);
4096        assert_eq!(pool.all_transactions.pending_fees.blob_fee, prev_blob_fee);
4097
4098        let tx_meta = pool.all_transactions.txs.get(&id).unwrap();
4099        assert_eq!(tx_meta.subpool, SubPool::Pending);
4100        assert!(tx_meta.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
4101    }
4102
4103    #[test]
4104    fn update_blob_fee_demotes_and_promotes_when_base_fee_falls() {
4105        let mut f = MockTransactionFactory::default();
4106        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4107
4108        let initial_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4109        let initial_base_fee = 600;
4110        pool.all_transactions.pending_fees.base_fee = initial_base_fee;
4111
4112        let tx_to_demote = MockTransaction::eip4844()
4113            .with_max_fee(700)
4114            .with_priority_fee(1)
4115            .with_blob_fee(initial_blob_fee + 100);
4116        let validated = f.validated(tx_to_demote);
4117        let demoted_id = *validated.id();
4118        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
4119
4120        let tx_to_promote = MockTransaction::eip4844()
4121            .with_max_fee(500)
4122            .with_priority_fee(1)
4123            .with_blob_fee(initial_blob_fee + 300);
4124        let validated = f.validated(tx_to_promote);
4125        let promoted_id = *validated.id();
4126        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
4127
4128        assert_eq!(pool.pending_pool.len(), 1);
4129        assert_eq!(pool.blob_pool.len(), 1);
4130
4131        // The lower base fee makes one transaction affordable while the higher blob fee makes the
4132        // other unaffordable, so the same update must both promote and demote.
4133        let raised_blob_fee = initial_blob_fee + 200;
4134        pool.all_transactions.pending_fees.base_fee = 400;
4135        let mut promoted = Vec::new();
4136        pool.update_blob_fee(raised_blob_fee, Ordering::Less, |tx| promoted.push(*tx.id()));
4137
4138        assert_eq!(pool.pending_pool.len(), 1);
4139        assert_eq!(pool.blob_pool.len(), 1);
4140        assert_eq!(promoted, vec![promoted_id]);
4141
4142        assert_eq!(pool.all_transactions.txs.get(&demoted_id).unwrap().subpool, SubPool::Blob);
4143        assert_eq!(pool.all_transactions.txs.get(&promoted_id).unwrap().subpool, SubPool::Pending);
4144    }
4145
4146    #[test]
4147    fn apply_fee_updates_records_promotions_after_blob_fee_drop() {
4148        let mut f = MockTransactionFactory::default();
4149        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4150
4151        let initial_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4152
4153        let tx = MockTransaction::eip4844().with_blob_fee(initial_blob_fee + 100);
4154        let validated = f.validated(tx.clone());
4155        let id = *validated.id();
4156        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
4157
4158        assert_eq!(pool.pending_pool.len(), 1);
4159
4160        // Raise blob fee beyond the transaction's cap so it gets parked in Blob pool.
4161        let increased_blob_fee = tx.max_fee_per_blob_gas().unwrap() + 200;
4162        pool.update_blob_fee(increased_blob_fee, Ordering::Equal, |_| {});
4163        assert!(pool.pending_pool.is_empty());
4164        assert_eq!(pool.blob_pool.len(), 1);
4165
4166        let prev_base_fee = pool.all_transactions.pending_fees.base_fee;
4167        let prev_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4168
4169        // Simulate the canonical state path updating pending fees before applying promotions.
4170        pool.all_transactions.pending_fees.blob_fee = tx.max_fee_per_blob_gas().unwrap();
4171
4172        let mut outcome = UpdateOutcome::default();
4173        pool.apply_fee_updates(prev_base_fee, prev_blob_fee, &mut outcome);
4174
4175        assert_eq!(pool.pending_pool.len(), 1);
4176        assert!(pool.blob_pool.is_empty());
4177        assert_eq!(outcome.promoted.len(), 1);
4178        assert_eq!(outcome.promoted[0].id(), &id);
4179        assert_eq!(pool.all_transactions.pending_fees.base_fee, prev_base_fee);
4180        assert_eq!(pool.all_transactions.pending_fees.blob_fee, tx.max_fee_per_blob_gas().unwrap());
4181
4182        let tx_meta = pool.all_transactions.txs.get(&id).unwrap();
4183        assert_eq!(tx_meta.subpool, SubPool::Pending);
4184        assert!(tx_meta.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
4185        assert!(tx_meta.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
4186    }
4187
4188    #[test]
4189    fn apply_fee_updates_promotes_blob_after_basefee_drop() {
4190        let mut f = MockTransactionFactory::default();
4191        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4192
4193        let initial_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4194
4195        let tx = MockTransaction::eip4844()
4196            .with_max_fee(500)
4197            .with_priority_fee(1)
4198            .with_blob_fee(initial_blob_fee + 100);
4199        let validated = f.validated(tx);
4200        let id = *validated.id();
4201        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
4202
4203        assert_eq!(pool.pending_pool.len(), 1);
4204
4205        // Raise base fee beyond the transaction's cap so it gets parked in Blob pool.
4206        let high_base_fee = 600;
4207        pool.update_basefee(high_base_fee, |_| {});
4208        assert!(pool.pending_pool.is_empty());
4209        assert_eq!(pool.blob_pool.len(), 1);
4210
4211        let prev_base_fee = high_base_fee;
4212        let prev_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4213
4214        // Simulate applying a lower base fee while keeping blob fee unchanged.
4215        pool.all_transactions.pending_fees.base_fee = 400;
4216
4217        let mut outcome = UpdateOutcome::default();
4218        pool.apply_fee_updates(prev_base_fee, prev_blob_fee, &mut outcome);
4219
4220        assert_eq!(pool.pending_pool.len(), 1);
4221        assert!(pool.blob_pool.is_empty());
4222        assert_eq!(outcome.promoted.len(), 1);
4223        assert_eq!(outcome.promoted[0].id(), &id);
4224        assert_eq!(pool.all_transactions.pending_fees.base_fee, 400);
4225        assert_eq!(pool.all_transactions.pending_fees.blob_fee, prev_blob_fee);
4226
4227        let tx_meta = pool.all_transactions.txs.get(&id).unwrap();
4228        assert_eq!(tx_meta.subpool, SubPool::Pending);
4229        assert!(tx_meta.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
4230        assert!(tx_meta.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
4231    }
4232
4233    #[test]
4234    fn queued_transactions_include_blob_pool() {
4235        let mut f = MockTransactionFactory::default();
4236        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4237
4238        let initial_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4239        let tx = MockTransaction::eip4844()
4240            .with_max_fee(500)
4241            .with_priority_fee(1)
4242            .with_blob_fee(initial_blob_fee + 100);
4243        let validated = f.validated(tx);
4244        let id = *validated.id();
4245        let sender = validated.sender_id();
4246        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
4247
4248        // Raise the base fee beyond the transaction's cap so it gets parked in the blob pool.
4249        pool.update_basefee(600, |_| {});
4250        assert_eq!(pool.blob_pool.len(), 1);
4251
4252        let queued = pool.queued_transactions();
4253        assert_eq!(queued.len(), 1);
4254        assert_eq!(queued[0].id(), &id);
4255
4256        let by_sender = pool.queued_txs_by_sender(sender);
4257        assert_eq!(by_sender.len(), 1);
4258        assert_eq!(by_sender[0].id(), &id);
4259    }
4260
4261    #[test]
4262    fn apply_fee_updates_demotes_after_basefee_rise() {
4263        let mut f = MockTransactionFactory::default();
4264        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4265
4266        let tx = MockTransaction::eip1559()
4267            .with_gas_limit(21_000)
4268            .with_max_fee(400)
4269            .with_priority_fee(1);
4270        let validated = f.validated(tx);
4271        let id = *validated.id();
4272        pool.add_transaction(validated, U256::from(1_000_000), 0, None).unwrap();
4273
4274        assert_eq!(pool.pending_pool.len(), 1);
4275
4276        let prev_base_fee = pool.all_transactions.pending_fees.base_fee;
4277        let prev_blob_fee = pool.all_transactions.pending_fees.blob_fee;
4278
4279        // Simulate canonical path raising the base fee beyond the transaction's cap.
4280        let new_base_fee = prev_base_fee + 1_000;
4281        pool.all_transactions.pending_fees.base_fee = new_base_fee;
4282
4283        let mut outcome = UpdateOutcome::default();
4284        pool.apply_fee_updates(prev_base_fee, prev_blob_fee, &mut outcome);
4285
4286        assert!(pool.pending_pool.is_empty());
4287        assert_eq!(pool.basefee_pool.len(), 1);
4288        assert!(outcome.promoted.is_empty());
4289        assert_eq!(pool.all_transactions.pending_fees.base_fee, new_base_fee);
4290        assert_eq!(pool.all_transactions.pending_fees.blob_fee, prev_blob_fee);
4291
4292        let tx_meta = pool.all_transactions.txs.get(&id).unwrap();
4293        assert_eq!(tx_meta.subpool, SubPool::BaseFee);
4294        assert!(!tx_meta.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK));
4295    }
4296
4297    #[test]
4298    fn get_highest_transaction_by_sender_and_nonce() {
4299        // Set up a mock transaction factory and a new transaction pool.
4300        let mut f = MockTransactionFactory::default();
4301        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4302
4303        // Create a mock transaction and add it to the pool.
4304        let tx = MockTransaction::eip1559();
4305        pool.add_transaction(f.validated(tx.clone()), U256::from(1_000), 0, None).unwrap();
4306
4307        // Create another mock transaction with an incremented price.
4308        let tx1 = tx.inc_price().next();
4309
4310        // Validate the second mock transaction and add it to the pool.
4311        let tx1_validated = f.validated(tx1.clone());
4312        pool.add_transaction(tx1_validated, U256::from(1_000), 0, None).unwrap();
4313
4314        // Ensure that the calculated next nonce for the sender matches the expected value.
4315        assert_eq!(
4316            pool.get_highest_nonce_by_sender(f.ids.sender_id(&tx.sender()).unwrap()),
4317            Some(1)
4318        );
4319
4320        // Retrieve the highest transaction by sender.
4321        let highest_tx = pool
4322            .get_highest_transaction_by_sender(f.ids.sender_id(&tx.sender()).unwrap())
4323            .expect("Failed to retrieve highest transaction");
4324
4325        // Validate that the retrieved highest transaction matches the expected transaction.
4326        assert_eq!(highest_tx.as_ref().transaction, tx1);
4327    }
4328
4329    #[test]
4330    fn get_highest_consecutive_transaction_by_sender() {
4331        // Set up a mock transaction factory and a new transaction pool.
4332        let mut pool = TxPool::new(MockOrdering::default(), PoolConfig::default());
4333        let mut f = MockTransactionFactory::default();
4334
4335        // Create transactions with nonces 0, 1, 2, 4, 5.
4336        let sender = Address::random();
4337        let txs: Vec<_> = vec![0, 1, 2, 4, 5, 8, 9];
4338        for nonce in txs {
4339            let mut mock_tx = MockTransaction::eip1559();
4340            mock_tx.set_sender(sender);
4341            mock_tx.set_nonce(nonce);
4342
4343            let validated_tx = f.validated(mock_tx);
4344            pool.add_transaction(validated_tx, U256::from(1000), 0, None).unwrap();
4345        }
4346
4347        // Get last consecutive transaction
4348        let sender_id = f.ids.sender_id(&sender).unwrap();
4349        let next_tx =
4350            pool.get_highest_consecutive_transaction_by_sender(sender_id.into_transaction_id(0));
4351        assert_eq!(next_tx.map(|tx| tx.nonce()), Some(2), "Expected nonce 2 for on-chain nonce 0");
4352
4353        let next_tx =
4354            pool.get_highest_consecutive_transaction_by_sender(sender_id.into_transaction_id(4));
4355        assert_eq!(next_tx.map(|tx| tx.nonce()), Some(5), "Expected nonce 5 for on-chain nonce 4");
4356
4357        let next_tx =
4358            pool.get_highest_consecutive_transaction_by_sender(sender_id.into_transaction_id(5));
4359        assert_eq!(next_tx.map(|tx| tx.nonce()), Some(5), "Expected nonce 5 for on-chain nonce 5");
4360
4361        // update the tracked nonce
4362        let mut info = SenderInfo::default();
4363        info.update(8, U256::ZERO);
4364        pool.all_transactions.sender_info.insert(sender_id, info);
4365        let next_tx =
4366            pool.get_highest_consecutive_transaction_by_sender(sender_id.into_transaction_id(5));
4367        assert_eq!(next_tx.map(|tx| tx.nonce()), Some(9), "Expected nonce 9 for on-chain nonce 8");
4368    }
4369
4370    #[test]
4371    fn discard_nonce_too_low() {
4372        let mut f = MockTransactionFactory::default();
4373        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4374
4375        let tx = MockTransaction::eip1559().inc_price_by(10);
4376        let validated = f.validated(tx.clone());
4377        let id = *validated.id();
4378        pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
4379
4380        let next = tx.next();
4381        let validated = f.validated(next.clone());
4382        pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
4383
4384        assert_eq!(pool.pending_pool.len(), 2);
4385
4386        let mut changed_senders = HashMap::default();
4387        changed_senders.insert(
4388            id.sender,
4389            SenderInfo { state_nonce: next.nonce(), balance: U256::from(1_000) },
4390        );
4391        let outcome = pool.update_accounts(changed_senders);
4392        assert_eq!(outcome.discarded.len(), 1);
4393        assert_eq!(pool.pending_pool.len(), 1);
4394    }
4395
4396    /// Pool with `enforce_tracked_nonce` enabled.
4397    fn stale_validation_pool() -> TxPool<MockOrdering> {
4398        TxPool::new(
4399            MockOrdering::default(),
4400            PoolConfig { enforce_tracked_nonce: true, ..Default::default() },
4401        )
4402    }
4403
4404    #[test]
4405    fn stale_validation_accepted_by_default() {
4406        let mut f = MockTransactionFactory::default();
4407        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4408
4409        let template = MockTransaction::eip1559();
4410        let first = f.validated(template.clone().with_nonce(0).rng_hash());
4411        let sender = first.sender_id();
4412        pool.add_transaction(first, U256::from(1_000), 0, None).unwrap();
4413
4414        let changed = FxHashMap::from_iter([(
4415            sender,
4416            SenderInfo { state_nonce: 1, balance: U256::from(1_000) },
4417        )]);
4418        let outcome = pool.update_accounts(changed);
4419        assert_eq!(outcome.discarded.len(), 1);
4420        // discarding the sender's last transaction drops its info
4421        assert!(!pool.all_transactions.sender_info.contains_key(&sender));
4422
4423        // the validation snapshot is trusted as is
4424        let stale = f.validated(template.with_nonce(0).rng_hash());
4425        pool.add_transaction(stale, U256::from(1_000), 0, None).unwrap();
4426        assert_eq!(pool.pending_pool.len(), 1);
4427        assert_eq!(pool.all_transactions.sender_info[&sender].state_nonce, 0);
4428    }
4429
4430    #[test]
4431    fn stale_validation_does_not_regress_sender_state() {
4432        let mut f = MockTransactionFactory::default();
4433        let mut pool = stale_validation_pool();
4434
4435        let template = MockTransaction::eip1559();
4436        let first = f.validated(template.clone().with_nonce(0).rng_hash());
4437        let sender = first.sender_id();
4438        pool.add_transaction(first, U256::from(1_000), 0, None).unwrap();
4439
4440        let mut changed_senders = HashMap::default();
4441        changed_senders.insert(sender, SenderInfo { state_nonce: 1, balance: U256::from(1_000) });
4442        let outcome = pool.update_accounts(changed_senders);
4443        assert_eq!(outcome.discarded.len(), 1);
4444        assert_eq!(pool.all_transactions.sender_info[&sender].state_nonce, 1);
4445
4446        // Stale validation for the next nonce remains pending.
4447        let current = f.validated(template.clone().with_nonce(1).rng_hash());
4448        pool.add_transaction(current, U256::from(1_000), 0, None).unwrap();
4449        assert_eq!(pool.pending_pool.len(), 1);
4450        assert_eq!(pool.queued_pool.len(), 0);
4451        assert_eq!(pool.all_transactions.sender_info[&sender].state_nonce, 1);
4452
4453        let stale = f.validated(template.with_nonce(0).rng_hash());
4454        let stale_hash = *stale.hash();
4455        let err = pool.add_transaction(stale, U256::from(1_000), 0, None).unwrap_err();
4456        assert!(matches!(
4457            err.kind,
4458            PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Consensus(
4459                InvalidTransactionError::NonceNotConsistent { tx: 0, state: 1 }
4460            ))
4461        ));
4462        assert!(!pool.contains(&stale_hash));
4463        assert_eq!(pool.all_transactions.sender_info[&sender].state_nonce, 1);
4464    }
4465
4466    #[test]
4467    fn stale_validation_resubmission_after_commit() {
4468        let mut f = MockTransactionFactory::default();
4469        let mut pool = stale_validation_pool();
4470        let block_info = pool.block_info();
4471
4472        let template = MockTransaction::eip1559();
4473        let tx0 = template.clone().with_nonce(0).rng_hash();
4474        let tx1 = template.clone().with_nonce(1).rng_hash();
4475        let first = f.validated(tx0.clone());
4476        let sender = first.sender_id();
4477        pool.add_transaction(first, U256::from(1_000), 0, None).unwrap();
4478        pool.add_transaction(f.validated(tx1.clone()), U256::from(1_000), 0, None).unwrap();
4479        assert_eq!(pool.pending_pool.len(), 2);
4480
4481        // Nonce 0 is mined while resubmissions of both nonces are still being validated.
4482        let changed = FxHashMap::from_iter([(
4483            sender,
4484            SenderInfo { state_nonce: 1, balance: U256::from(1_000) },
4485        )]);
4486        pool.on_canonical_state_change(
4487            block_info,
4488            vec![*tx0.get_hash()],
4489            changed,
4490            PoolUpdateKind::Commit,
4491        );
4492        assert_eq!(pool.pending_pool.len(), 1);
4493
4494        // The resubmitted mined nonce is rejected instead of shadowing nonce 1.
4495        let retry = f.validated(template.with_nonce(0).rng_hash());
4496        let err = pool.add_transaction(retry, U256::from(1_000), 0, None).unwrap_err();
4497        assert!(matches!(
4498            err.kind,
4499            PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Consensus(
4500                InvalidTransactionError::NonceNotConsistent { tx: 0, state: 1 }
4501            ))
4502        ));
4503
4504        // The replacement of the executable nonce is accepted using the tracked nonce.
4505        let replacement = f.validated(tx1.inc_price_by(10).rng_hash());
4506        let added = pool.add_transaction(replacement, U256::from(1_000), 0, None).unwrap();
4507        assert!(added.as_pending().is_some());
4508        assert!(added.replaced().is_some());
4509        assert_eq!(pool.pending_pool.len(), 1);
4510        assert_eq!(pool.all_transactions.sender_info[&sender].state_nonce, 1);
4511        let next =
4512            pool.get_highest_consecutive_transaction_by_sender(sender.into_transaction_id(1));
4513        assert_eq!(next.map(|tx| tx.nonce()), Some(1));
4514    }
4515
4516    #[test]
4517    fn stale_validation_uses_tracked_balance() {
4518        let mut f = MockTransactionFactory::default();
4519        let mut pool = stale_validation_pool();
4520
4521        // each transaction costs 1_500_000
4522        let template = MockTransaction::eip1559().with_gas_price(50).with_gas_limit(30_000);
4523        let first = f.validated(template.clone().with_nonce(0).rng_hash());
4524        let sender = first.sender_id();
4525        pool.add_transaction(first, U256::from(10_000_000), 0, None).unwrap();
4526        assert_eq!(pool.pending_pool.len(), 1);
4527
4528        // The commit mines nonce 0 and drains the balance below the cost of the next transaction.
4529        let changed = FxHashMap::from_iter([(
4530            sender,
4531            SenderInfo { state_nonce: 1, balance: U256::from(1_000) },
4532        )]);
4533        pool.update_accounts(changed);
4534
4535        // The stale snapshot still reports the old balance, the tracked balance applies.
4536        let next = f.validated(template.with_nonce(1).rng_hash());
4537        let id = *next.id();
4538        pool.add_transaction(next, U256::from(10_000_000), 0, None).unwrap();
4539        assert_eq!(pool.pending_pool.len(), 0);
4540        assert_eq!(pool.queued_pool.len(), 1);
4541        let state = pool.all_transactions.get(&id).unwrap().state;
4542        assert!(state.contains(TxState::NO_NONCE_GAPS));
4543        assert!(!state.contains(TxState::ENOUGH_BALANCE));
4544        assert_eq!(pool.all_transactions.sender_info[&sender].balance, U256::from(1_000));
4545    }
4546
4547    #[test]
4548    fn discard_with_large_blob_txs() {
4549        // init tracing
4550        reth_tracing::init_test_tracing();
4551
4552        // this test adds large txs to the parked pool, then attempting to discard worst
4553        let mut f = MockTransactionFactory::default();
4554        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4555        let default_limits = pool.config.blob_limit;
4556
4557        // create a chain of transactions by sender A
4558        // make sure they are all one over half the limit
4559        let a_sender = Address::with_last_byte(0x0a);
4560
4561        // set the base fee of the pool
4562        let mut block_info = pool.block_info();
4563        block_info.pending_blob_fee = Some(100);
4564        block_info.pending_basefee = 100;
4565
4566        // update
4567        pool.set_block_info(block_info);
4568
4569        // 2 txs, that should put the pool over the size limit but not max txs
4570        let a_txs = MockTransactionSet::dependent(a_sender, 0, 2, TxType::Eip4844)
4571            .into_iter()
4572            .map(|mut tx| {
4573                tx.set_size(default_limits.max_size / 2 + 1);
4574                tx.set_max_fee((block_info.pending_basefee - 1).into());
4575                tx
4576            })
4577            .collect::<Vec<_>>();
4578
4579        // add all the transactions to the parked pool
4580        for tx in a_txs {
4581            pool.add_transaction(f.validated(tx), U256::from(1_000), 0, None).unwrap();
4582        }
4583
4584        // truncate the pool, it should remove at least one transaction
4585        let removed = pool.discard_worst();
4586        assert_eq!(removed.len(), 1);
4587    }
4588
4589    #[test]
4590    fn discard_with_parked_large_txs() {
4591        // init tracing
4592        reth_tracing::init_test_tracing();
4593
4594        // this test adds large txs to the parked pool, then attempting to discard worst
4595        let mut f = MockTransactionFactory::default();
4596        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4597        let default_limits = pool.config.queued_limit;
4598
4599        // create a chain of transactions by sender A
4600        // make sure they are all one over half the limit
4601        let a_sender = Address::with_last_byte(0x0a);
4602
4603        // set the base fee of the pool
4604        let pool_base_fee = 100;
4605        pool.update_basefee(pool_base_fee, |_| {});
4606
4607        // 2 txs, that should put the pool over the size limit but not max txs
4608        let a_txs = MockTransactionSet::dependent(a_sender, 0, 3, TxType::Eip1559)
4609            .into_iter()
4610            .map(|mut tx| {
4611                tx.set_size(default_limits.max_size / 2 + 1);
4612                tx.set_max_fee((pool_base_fee - 1).into());
4613                tx
4614            })
4615            .collect::<Vec<_>>();
4616
4617        // add all the transactions to the parked pool
4618        for tx in a_txs {
4619            pool.add_transaction(f.validated(tx), U256::from(1_000), 0, None).unwrap();
4620        }
4621
4622        // truncate the pool, it should remove at least one transaction
4623        let removed = pool.discard_worst();
4624        assert_eq!(removed.len(), 1);
4625    }
4626
4627    #[test]
4628    fn discard_at_capacity() {
4629        let mut f = MockTransactionFactory::default();
4630        let queued_limit = SubPoolLimit::new(1000, usize::MAX);
4631        let mut pool =
4632            TxPool::new(MockOrdering::default(), PoolConfig { queued_limit, ..Default::default() });
4633
4634        // insert a bunch of transactions into the queued pool
4635        for _ in 0..queued_limit.max_txs {
4636            let tx = MockTransaction::eip1559().inc_price_by(10).inc_nonce();
4637            let validated = f.validated(tx);
4638            let _id = *validated.id();
4639            pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
4640        }
4641
4642        let size = pool.size();
4643        assert_eq!(size.queued, queued_limit.max_txs);
4644
4645        for _ in 0..queued_limit.max_txs {
4646            let tx = MockTransaction::eip1559().inc_price_by(10).inc_nonce();
4647            let validated = f.validated(tx);
4648            let _id = *validated.id();
4649            pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
4650
4651            pool.discard_worst();
4652            pool.assert_invariants();
4653            assert!(pool.size().queued <= queued_limit.max_txs);
4654        }
4655    }
4656
4657    #[test]
4658    fn discard_blobs_at_capacity() {
4659        let mut f = MockTransactionFactory::default();
4660        let blob_limit = SubPoolLimit::new(1000, usize::MAX);
4661        let mut pool =
4662            TxPool::new(MockOrdering::default(), PoolConfig { blob_limit, ..Default::default() });
4663        pool.all_transactions.pending_fees.blob_fee = 10000;
4664        // insert a bunch of transactions into the queued pool
4665        for _ in 0..blob_limit.max_txs {
4666            let tx = MockTransaction::eip4844().inc_price_by(100).with_blob_fee(100);
4667            let validated = f.validated(tx);
4668            let _id = *validated.id();
4669            pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
4670        }
4671
4672        let size = pool.size();
4673        assert_eq!(size.blob, blob_limit.max_txs);
4674
4675        for _ in 0..blob_limit.max_txs {
4676            let tx = MockTransaction::eip4844().inc_price_by(100).with_blob_fee(100);
4677            let validated = f.validated(tx);
4678            let _id = *validated.id();
4679            pool.add_transaction(validated, U256::from(1_000), 0, None).unwrap();
4680
4681            pool.discard_worst();
4682            pool.assert_invariants();
4683            assert!(pool.size().blob <= blob_limit.max_txs);
4684        }
4685    }
4686
4687    #[test]
4688    fn reuse_update_buffer_across_pool_operations() {
4689        let mut f = MockTransactionFactory::default();
4690        let mut pool = TxPool::new(
4691            MockOrdering::default(),
4692            PoolConfig { max_account_slots: 128, ..Default::default() },
4693        );
4694        let mut tx = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4695        let first = f.validated(tx.clone());
4696        for _ in 0..80 {
4697            pool.add_transaction(f.validated(tx.clone()), U256::MAX, 0, None).unwrap();
4698            tx = tx.next();
4699        }
4700        assert_eq!(pool.all_transactions.update_buffer.capacity(), 0);
4701
4702        let changed = |balance, state_nonce| {
4703            FxHashMap::from_iter([(first.sender_id(), SenderInfo { balance, state_nonce })])
4704        };
4705        let outcome = pool.update_accounts(changed(U256::ZERO, 0));
4706        assert!(outcome.promoted.is_empty());
4707        assert!(outcome.discarded.is_empty());
4708        assert_eq!(pool.queued_pool.len(), 80);
4709        let capacity = pool.all_transactions.update_buffer.capacity();
4710        assert!(capacity >= 80);
4711        let buffer = pool.all_transactions.update_buffer.as_ptr();
4712
4713        for _ in 0..2 {
4714            let outcome = pool.update_accounts(changed(U256::MAX, 0));
4715            assert_eq!(outcome.promoted.len(), 80);
4716            assert!(outcome.discarded.is_empty());
4717            assert_eq!(pool.pending_pool.len(), 80);
4718
4719            let outcome = pool.update_accounts(FxHashMap::default());
4720            assert!(outcome.promoted.is_empty());
4721            assert!(outcome.discarded.is_empty());
4722
4723            pool.remove_transaction_by_hash(first.hash()).unwrap();
4724            assert_eq!(pool.queued_pool.len(), 79);
4725
4726            // A rejected replacement must leave the reusable allocation available.
4727            let replacement = f.validated(first.transaction.next());
4728            assert!(pool.add_transaction(replacement, U256::MAX, 0, None).is_err());
4729            assert_eq!(pool.all_transactions.update_buffer.as_ptr(), buffer);
4730
4731            let added = pool.add_transaction(first.clone(), U256::MAX, 0, None).unwrap();
4732            let AddedTransaction::Pending(added) = added else { panic!("expected pending") };
4733            assert_eq!(added.promoted.len(), 79);
4734            assert!(added.discarded.is_empty());
4735            assert_eq!(pool.pending_pool.len(), 80);
4736
4737            pool.update_accounts(changed(U256::ZERO, 0));
4738            assert_eq!(pool.queued_pool.len(), 80);
4739            assert!(pool.all_transactions.update_buffer.is_empty());
4740            assert_eq!(pool.all_transactions.update_buffer.capacity(), capacity);
4741            assert_eq!(pool.all_transactions.update_buffer.as_ptr(), buffer);
4742            pool.assert_invariants();
4743        }
4744
4745        let outcome = pool.update_accounts(changed(U256::MAX, 80));
4746        assert_eq!(outcome.discarded.len(), 80);
4747        assert!(outcome.promoted.is_empty());
4748        assert!(pool.is_empty());
4749        assert!(pool.all_transactions.update_buffer.is_empty());
4750        assert_eq!(pool.all_transactions.update_buffer.as_ptr(), buffer);
4751    }
4752
4753    #[test]
4754    fn account_updates_sender_balance() {
4755        let mut on_chain_balance = U256::from(100);
4756        let on_chain_nonce = 0;
4757        let mut f = MockTransactionFactory::default();
4758        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4759
4760        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4761        let tx_1 = tx_0.next();
4762        let tx_2 = tx_1.next();
4763
4764        // Create 3 transactions
4765        let v0 = f.validated(tx_0);
4766        let v1 = f.validated(tx_1);
4767        let v2 = f.validated(tx_2);
4768
4769        let _res =
4770            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4771        let _res = pool.add_transaction(v1, on_chain_balance, on_chain_nonce, None).unwrap();
4772        let _res = pool.add_transaction(v2, on_chain_balance, on_chain_nonce, None).unwrap();
4773
4774        // The sender does not have enough balance to put all txs into pending.
4775        assert_eq!(1, pool.pending_transactions().len());
4776        assert_eq!(2, pool.queued_transactions().len());
4777
4778        // Simulate new block arrival - and chain balance increase.
4779        let mut updated_accounts = HashMap::default();
4780        on_chain_balance = U256::from(300);
4781        updated_accounts.insert(
4782            v0.sender_id(),
4783            SenderInfo { state_nonce: on_chain_nonce, balance: on_chain_balance },
4784        );
4785        pool.update_accounts(updated_accounts.clone());
4786
4787        assert_eq!(3, pool.pending_transactions().len());
4788        assert!(pool.queued_transactions().is_empty());
4789
4790        // Simulate new block arrival - and chain balance decrease.
4791        updated_accounts.entry(v0.sender_id()).and_modify(|v| v.balance = U256::ONE);
4792        pool.update_accounts(updated_accounts);
4793
4794        assert!(pool.pending_transactions().is_empty());
4795        assert_eq!(3, pool.queued_transactions().len());
4796    }
4797
4798    #[test]
4799    fn account_updates_nonce_gap() {
4800        let on_chain_balance = U256::from(10_000);
4801        let mut on_chain_nonce = 0;
4802        let mut f = MockTransactionFactory::default();
4803        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4804
4805        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4806        let tx_1 = tx_0.next();
4807        let tx_2 = tx_1.next();
4808
4809        // Create 3 transactions
4810        let v0 = f.validated(tx_0);
4811        let v1 = f.validated(tx_1);
4812        let v2 = f.validated(tx_2);
4813
4814        // Add first 2 to the pool
4815        let _res =
4816            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4817        let _res = pool.add_transaction(v1, on_chain_balance, on_chain_nonce, None).unwrap();
4818
4819        assert!(pool.queued_transactions().is_empty());
4820        assert_eq!(2, pool.pending_transactions().len());
4821
4822        // Remove first (nonce 0)
4823        pool.remove_transaction_by_hash(v0.hash());
4824
4825        // Now add transaction with nonce 2
4826        let _res = pool.add_transaction(v2, on_chain_balance, on_chain_nonce, None).unwrap();
4827
4828        // v1 and v2 should both be in the queue now.
4829        assert_eq!(2, pool.queued_transactions().len());
4830        assert!(pool.pending_transactions().is_empty());
4831
4832        // Simulate new block arrival - and chain nonce increasing.
4833        let mut updated_accounts = HashMap::default();
4834        on_chain_nonce += 1;
4835        updated_accounts.insert(
4836            v0.sender_id(),
4837            SenderInfo { state_nonce: on_chain_nonce, balance: on_chain_balance },
4838        );
4839        pool.update_accounts(updated_accounts);
4840
4841        // 'pending' now).
4842        assert!(pool.queued_transactions().is_empty());
4843        assert_eq!(2, pool.pending_transactions().len());
4844    }
4845    #[test]
4846    fn test_transaction_removal() {
4847        let on_chain_balance = U256::from(10_000);
4848        let on_chain_nonce = 0;
4849        let mut f = MockTransactionFactory::default();
4850        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4851
4852        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4853        let tx_1 = tx_0.next();
4854
4855        // Create 2 transactions
4856        let v0 = f.validated(tx_0);
4857        let v1 = f.validated(tx_1);
4858
4859        // Add them to the pool
4860        let _res =
4861            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4862        let _res =
4863            pool.add_transaction(v1.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4864
4865        assert_eq!(0, pool.queued_transactions().len());
4866        assert_eq!(2, pool.pending_transactions().len());
4867
4868        // Remove first (nonce 0) - simulating that it was taken to be a part of the block.
4869        pool.remove_transaction(v0.id());
4870        // assert the second transaction is really at the top of the queue
4871        let pool_txs = pool.best_transactions().map(|x| x.id().nonce).collect::<Vec<_>>();
4872        assert_eq!(vec![v1.nonce()], pool_txs);
4873    }
4874    #[test]
4875    fn test_remove_transactions() {
4876        let on_chain_balance = U256::from(10_000);
4877        let on_chain_nonce = 0;
4878        let mut f = MockTransactionFactory::default();
4879        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4880
4881        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4882        let tx_1 = tx_0.next();
4883        let tx_2 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4884        let tx_3 = tx_2.next();
4885
4886        // Create 4 transactions
4887        let v0 = f.validated(tx_0);
4888        let v1 = f.validated(tx_1);
4889        let v2 = f.validated(tx_2);
4890        let v3 = f.validated(tx_3);
4891
4892        // Add them to the pool
4893        let _res =
4894            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4895        let _res =
4896            pool.add_transaction(v1.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4897        let _res =
4898            pool.add_transaction(v2.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4899        let _res =
4900            pool.add_transaction(v3.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4901
4902        assert_eq!(0, pool.queued_transactions().len());
4903        assert_eq!(4, pool.pending_transactions().len());
4904
4905        pool.remove_transactions(vec![*v0.hash(), *v2.hash()]);
4906
4907        assert_eq!(2, pool.queued_transactions().len());
4908        assert!(pool.pending_transactions().is_empty());
4909        assert!(pool.contains(v1.hash()));
4910        assert!(pool.contains(v3.hash()));
4911    }
4912
4913    #[test]
4914    fn test_remove_transactions_middle_pending_hash() {
4915        let on_chain_balance = U256::from(10_000);
4916        let on_chain_nonce = 0;
4917        let mut f = MockTransactionFactory::default();
4918        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4919
4920        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4921        let tx_1 = tx_0.next();
4922        let tx_2 = tx_1.next();
4923        let tx_3 = tx_2.next();
4924
4925        // Create 4 transactions
4926        let v0 = f.validated(tx_0);
4927        let v1 = f.validated(tx_1);
4928        let v2 = f.validated(tx_2);
4929        let v3 = f.validated(tx_3);
4930
4931        // Add them to the pool
4932        let _res = pool.add_transaction(v0, on_chain_balance, on_chain_nonce, None).unwrap();
4933        let _res =
4934            pool.add_transaction(v1.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4935        let _res = pool.add_transaction(v2, on_chain_balance, on_chain_nonce, None).unwrap();
4936        let _res = pool.add_transaction(v3, on_chain_balance, on_chain_nonce, None).unwrap();
4937
4938        assert_eq!(0, pool.queued_transactions().len());
4939        assert_eq!(4, pool.pending_transactions().len());
4940
4941        let mut removed_txs = pool.remove_transactions(vec![*v1.hash()]);
4942        assert_eq!(1, removed_txs.len());
4943
4944        assert_eq!(2, pool.queued_transactions().len());
4945        assert_eq!(1, pool.pending_transactions().len());
4946
4947        // reinsert
4948        let removed_tx = removed_txs.pop().unwrap();
4949        let v1 = f.validated(removed_tx.transaction.clone());
4950        let _res = pool.add_transaction(v1, on_chain_balance, on_chain_nonce, None).unwrap();
4951        assert_eq!(0, pool.queued_transactions().len());
4952        assert_eq!(4, pool.pending_transactions().len());
4953    }
4954
4955    #[test]
4956    fn test_remove_transactions_and_descendants() {
4957        let on_chain_balance = U256::from(10_000);
4958        let on_chain_nonce = 0;
4959        let mut f = MockTransactionFactory::default();
4960        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4961
4962        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4963        let tx_1 = tx_0.next();
4964        let tx_2 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
4965        let tx_3 = tx_2.next();
4966        let tx_4 = tx_3.next();
4967
4968        // Create 5 transactions
4969        let v0 = f.validated(tx_0);
4970        let v1 = f.validated(tx_1);
4971        let v2 = f.validated(tx_2);
4972        let v3 = f.validated(tx_3);
4973        let v4 = f.validated(tx_4);
4974
4975        // Add them to the pool
4976        let _res =
4977            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4978        let _res = pool.add_transaction(v1, on_chain_balance, on_chain_nonce, None).unwrap();
4979        let _res =
4980            pool.add_transaction(v2.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
4981        let _res = pool.add_transaction(v3, on_chain_balance, on_chain_nonce, None).unwrap();
4982        let _res = pool.add_transaction(v4, on_chain_balance, on_chain_nonce, None).unwrap();
4983
4984        assert_eq!(0, pool.queued_transactions().len());
4985        assert_eq!(5, pool.pending_transactions().len());
4986
4987        pool.remove_transactions_and_descendants(vec![*v0.hash(), *v2.hash()]);
4988
4989        assert_eq!(0, pool.queued_transactions().len());
4990        assert_eq!(0, pool.pending_transactions().len());
4991    }
4992    #[test]
4993    fn test_remove_descendants() {
4994        let on_chain_balance = U256::from(10_000);
4995        let on_chain_nonce = 0;
4996        let mut f = MockTransactionFactory::default();
4997        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
4998
4999        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
5000        let tx_1 = tx_0.next();
5001        let tx_2 = tx_1.next();
5002        let tx_3 = tx_2.next();
5003
5004        // Create 4 transactions
5005        let v0 = f.validated(tx_0);
5006        let v1 = f.validated(tx_1);
5007        let v2 = f.validated(tx_2);
5008        let v3 = f.validated(tx_3);
5009
5010        // Add them to the  pool
5011        let _res =
5012            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
5013        let _res = pool.add_transaction(v1, on_chain_balance, on_chain_nonce, None).unwrap();
5014        let _res = pool.add_transaction(v2, on_chain_balance, on_chain_nonce, None).unwrap();
5015        let _res = pool.add_transaction(v3, on_chain_balance, on_chain_nonce, None).unwrap();
5016
5017        assert_eq!(0, pool.queued_transactions().len());
5018        assert_eq!(4, pool.pending_transactions().len());
5019
5020        let mut removed = Vec::new();
5021        pool.remove_transaction(v0.id());
5022        pool.remove_descendants(v0.id(), &mut removed);
5023
5024        assert_eq!(0, pool.queued_transactions().len());
5025        assert_eq!(0, pool.pending_transactions().len());
5026        assert_eq!(3, removed.len());
5027    }
5028    #[test]
5029    fn test_remove_transactions_by_sender() {
5030        let on_chain_balance = U256::from(10_000);
5031        let on_chain_nonce = 0;
5032        let mut f = MockTransactionFactory::default();
5033        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5034
5035        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
5036        let tx_1 = tx_0.next();
5037        let tx_2 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
5038        let tx_3 = tx_2.next();
5039        let tx_4 = tx_3.next();
5040
5041        // Create 5 transactions
5042        let v0 = f.validated(tx_0);
5043        let v1 = f.validated(tx_1);
5044        let v2 = f.validated(tx_2);
5045        let v3 = f.validated(tx_3);
5046        let v4 = f.validated(tx_4);
5047
5048        // Add them to the pool
5049        let _res =
5050            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
5051        let _res =
5052            pool.add_transaction(v1.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
5053        let _res =
5054            pool.add_transaction(v2.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
5055        let _res = pool.add_transaction(v3, on_chain_balance, on_chain_nonce, None).unwrap();
5056        let _res = pool.add_transaction(v4, on_chain_balance, on_chain_nonce, None).unwrap();
5057
5058        assert_eq!(0, pool.queued_transactions().len());
5059        assert_eq!(5, pool.pending_transactions().len());
5060
5061        pool.remove_transactions_by_sender(v2.sender_id());
5062
5063        assert_eq!(0, pool.queued_transactions().len());
5064        assert_eq!(2, pool.pending_transactions().len());
5065        assert!(pool.contains(v0.hash()));
5066        assert!(pool.contains(v1.hash()));
5067    }
5068    #[test]
5069    fn wrong_best_order_of_transactions() {
5070        let on_chain_balance = U256::from(10_000);
5071        let mut on_chain_nonce = 0;
5072        let mut f = MockTransactionFactory::default();
5073        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5074
5075        let tx_0 = MockTransaction::eip1559().set_gas_price(100).inc_limit();
5076        let tx_1 = tx_0.next();
5077        let tx_2 = tx_1.next();
5078        let tx_3 = tx_2.next();
5079
5080        // Create 4 transactions
5081        let v0 = f.validated(tx_0);
5082        let v1 = f.validated(tx_1);
5083        let v2 = f.validated(tx_2);
5084        let v3 = f.validated(tx_3);
5085
5086        // Add first 2 to the pool
5087        let _res =
5088            pool.add_transaction(v0.clone(), on_chain_balance, on_chain_nonce, None).unwrap();
5089        let _res = pool.add_transaction(v1, on_chain_balance, on_chain_nonce, None).unwrap();
5090
5091        assert_eq!(0, pool.queued_transactions().len());
5092        assert_eq!(2, pool.pending_transactions().len());
5093
5094        // Remove first (nonce 0) - simulating that it was taken to be a part of the block.
5095        pool.remove_transaction(v0.id());
5096
5097        // Now add transaction with nonce 2
5098        let _res = pool.add_transaction(v2, on_chain_balance, on_chain_nonce, None).unwrap();
5099
5100        // v2 is in the queue now. v1 is still in 'pending'.
5101        assert_eq!(1, pool.queued_transactions().len());
5102        assert_eq!(1, pool.pending_transactions().len());
5103
5104        // Simulate new block arrival - and chain nonce increasing.
5105        let mut updated_accounts = HashMap::default();
5106        on_chain_nonce += 1;
5107        updated_accounts.insert(
5108            v0.sender_id(),
5109            SenderInfo { state_nonce: on_chain_nonce, balance: on_chain_balance },
5110        );
5111        pool.update_accounts(updated_accounts);
5112
5113        // Transactions are not changed (IMHO - this is a bug, as transaction v2 should be in the
5114        // 'pending' now).
5115        assert_eq!(0, pool.queued_transactions().len());
5116        assert_eq!(2, pool.pending_transactions().len());
5117
5118        // Add transaction v3 - it 'unclogs' everything.
5119        let _res = pool.add_transaction(v3, on_chain_balance, on_chain_nonce, None).unwrap();
5120        assert_eq!(0, pool.queued_transactions().len());
5121        assert_eq!(3, pool.pending_transactions().len());
5122
5123        // It should have returned transactions in order (v1, v2, v3 - as there is nothing blocking
5124        // them).
5125        assert_eq!(
5126            pool.best_transactions().map(|x| x.id().nonce).collect::<Vec<_>>(),
5127            vec![1, 2, 3]
5128        );
5129    }
5130
5131    #[test]
5132    fn test_best_with_attributes() {
5133        let on_chain_balance = U256::MAX;
5134        let on_chain_nonce = 0;
5135        let mut f = MockTransactionFactory::default();
5136        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5137
5138        let base_fee: u128 = 100;
5139        let blob_fee: u128 = 100;
5140
5141        // set base fee and blob fee.
5142        let mut block_info = pool.block_info();
5143        block_info.pending_basefee = base_fee as u64;
5144        block_info.pending_blob_fee = Some(blob_fee);
5145        pool.set_block_info(block_info);
5146
5147        // Insert transactions with varying max_fee_per_gas and max_fee_per_blob_gas.
5148        let tx1 = MockTransaction::eip4844()
5149            .with_sender(Address::with_last_byte(1))
5150            .with_max_fee(base_fee + 10)
5151            .with_blob_fee(blob_fee + 10);
5152        let tx2 = MockTransaction::eip4844()
5153            .with_sender(Address::with_last_byte(2))
5154            .with_max_fee(base_fee + 10)
5155            .with_blob_fee(blob_fee);
5156        let tx3 = MockTransaction::eip4844()
5157            .with_sender(Address::with_last_byte(3))
5158            .with_max_fee(base_fee)
5159            .with_blob_fee(blob_fee + 10);
5160        let tx4 = MockTransaction::eip4844()
5161            .with_sender(Address::with_last_byte(4))
5162            .with_max_fee(base_fee)
5163            .with_blob_fee(blob_fee);
5164        let tx5 = MockTransaction::eip4844()
5165            .with_sender(Address::with_last_byte(5))
5166            .with_max_fee(base_fee)
5167            .with_blob_fee(blob_fee - 10);
5168        let tx6 = MockTransaction::eip4844()
5169            .with_sender(Address::with_last_byte(6))
5170            .with_max_fee(base_fee - 10)
5171            .with_blob_fee(blob_fee);
5172        let tx7 = MockTransaction::eip4844()
5173            .with_sender(Address::with_last_byte(7))
5174            .with_max_fee(base_fee - 10)
5175            .with_blob_fee(blob_fee - 10);
5176
5177        for tx in vec![
5178            tx1.clone(),
5179            tx2.clone(),
5180            tx3.clone(),
5181            tx4.clone(),
5182            tx5.clone(),
5183            tx6.clone(),
5184            tx7.clone(),
5185        ] {
5186            pool.add_transaction(f.validated(tx), on_chain_balance, on_chain_nonce, None).unwrap();
5187        }
5188
5189        let base_fee = base_fee as u64;
5190        let blob_fee = blob_fee as u64;
5191
5192        let cases = vec![
5193            // 1. Base fee increase, blob fee increase
5194            (BestTransactionsAttributes::new(base_fee + 5, Some(blob_fee + 5)), vec![tx1.clone()]),
5195            // 2. Base fee increase, blob fee not change
5196            (
5197                BestTransactionsAttributes::new(base_fee + 5, Some(blob_fee)),
5198                vec![tx1.clone(), tx2.clone()],
5199            ),
5200            // 3. Base fee increase, blob fee decrease
5201            (
5202                BestTransactionsAttributes::new(base_fee + 5, Some(blob_fee - 5)),
5203                vec![tx1.clone(), tx2.clone()],
5204            ),
5205            // 4. Base fee not change, blob fee increase
5206            (
5207                BestTransactionsAttributes::new(base_fee, Some(blob_fee + 5)),
5208                vec![tx1.clone(), tx3.clone()],
5209            ),
5210            // 5. Base fee not change, blob fee not change
5211            (
5212                BestTransactionsAttributes::new(base_fee, Some(blob_fee)),
5213                vec![tx1.clone(), tx2.clone(), tx3.clone(), tx4.clone()],
5214            ),
5215            // 6. Base fee not change, blob fee decrease
5216            (
5217                BestTransactionsAttributes::new(base_fee, Some(blob_fee - 10)),
5218                vec![tx1.clone(), tx2.clone(), tx3.clone(), tx4.clone(), tx5.clone()],
5219            ),
5220            // 7. Base fee decrease, blob fee increase
5221            (
5222                BestTransactionsAttributes::new(base_fee - 5, Some(blob_fee + 5)),
5223                vec![tx1.clone(), tx3.clone()],
5224            ),
5225            // 8. Base fee decrease, blob fee not change
5226            (
5227                BestTransactionsAttributes::new(base_fee - 10, Some(blob_fee)),
5228                vec![tx1.clone(), tx2.clone(), tx3.clone(), tx4.clone(), tx6.clone()],
5229            ),
5230            // 9. Base fee decrease, blob fee decrease
5231            (
5232                BestTransactionsAttributes::new(base_fee - 10, Some(blob_fee - 10)),
5233                vec![tx1, tx2, tx5, tx3, tx4, tx6, tx7],
5234            ),
5235        ];
5236
5237        for (idx, (attribute, expected)) in cases.into_iter().enumerate() {
5238            let mut best = pool.best_transactions_with_attributes(attribute);
5239
5240            for (tx_idx, expected_tx) in expected.into_iter().enumerate() {
5241                let tx = best.next().expect("Transaction should be returned");
5242                assert_eq!(
5243                    tx.transaction,
5244                    expected_tx,
5245                    "Failed tx {} in case {}",
5246                    tx_idx + 1,
5247                    idx + 1
5248                );
5249            }
5250
5251            // No more transactions should be returned
5252            assert!(best.next().is_none());
5253        }
5254    }
5255
5256    #[test]
5257    fn test_pending_ordering() {
5258        let mut f = MockTransactionFactory::default();
5259        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5260
5261        let tx_0 = MockTransaction::eip1559().with_nonce(1).set_gas_price(100).inc_limit();
5262        let tx_1 = tx_0.next();
5263
5264        let v0 = f.validated(tx_0);
5265        let v1 = f.validated(tx_1);
5266
5267        // nonce gap, tx should be queued
5268        pool.add_transaction(v0.clone(), U256::MAX, 0, None).unwrap();
5269        assert_eq!(1, pool.queued_transactions().len());
5270
5271        // nonce gap is closed on-chain, both transactions should be moved to pending
5272        pool.add_transaction(v1, U256::MAX, 1, None).unwrap();
5273
5274        assert_eq!(2, pool.pending_transactions().len());
5275        assert_eq!(0, pool.queued_transactions().len());
5276
5277        assert_eq!(
5278            pool.pending_pool.independent().get(&v0.sender_id()).unwrap().transaction.nonce(),
5279            v0.nonce()
5280        );
5281    }
5282
5283    // <https://github.com/paradigmxyz/reth/issues/12286>
5284    #[test]
5285    fn one_sender_one_independent_transaction() {
5286        let mut on_chain_balance = U256::from(4_999); // only enough for 4 txs
5287        let mut on_chain_nonce = 40;
5288        let mut f = MockTransactionFactory::default();
5289        let mut pool = TxPool::mock();
5290        let mut submitted_txs = Vec::new();
5291
5292        // We use a "template" because we want all txs to have the same sender.
5293        let template =
5294            MockTransaction::eip1559().inc_price().inc_limit().with_value(U256::from(1_001));
5295
5296        // Add 8 txs. Because the balance is only sufficient for 4, so the last 4 will be
5297        // Queued.
5298        for tx_nonce in 40..48 {
5299            let tx = f.validated(template.clone().with_nonce(tx_nonce).rng_hash());
5300            submitted_txs.push(*tx.id());
5301            pool.add_transaction(tx, on_chain_balance, on_chain_nonce, None).unwrap();
5302        }
5303
5304        // A block is mined with two txs (so nonce is changed from 40 to 42).
5305        // Now the balance gets so high that it's enough to execute alltxs.
5306        on_chain_balance = U256::from(999_999);
5307        on_chain_nonce = 42;
5308        pool.remove_transaction(&submitted_txs[0]);
5309        pool.remove_transaction(&submitted_txs[1]);
5310
5311        // Add 4 txs.
5312        for tx_nonce in 48..52 {
5313            pool.add_transaction(
5314                f.validated(template.clone().with_nonce(tx_nonce).rng_hash()),
5315                on_chain_balance,
5316                on_chain_nonce,
5317                None,
5318            )
5319            .unwrap();
5320        }
5321
5322        let best_txs: Vec<_> = pool.pending().best().map(|tx| *tx.id()).collect();
5323        assert_eq!(best_txs.len(), 10); // 8 - 2 + 4 = 10
5324
5325        assert_eq!(pool.pending_pool.independent().len(), 1);
5326    }
5327
5328    #[test]
5329    fn test_insertion_disorder() {
5330        let mut f = MockTransactionFactory::default();
5331        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5332
5333        let sender = address!("0x1234567890123456789012345678901234567890");
5334        let tx0 = f.validated_arc(
5335            MockTransaction::legacy().with_sender(sender).with_nonce(0).with_gas_price(10),
5336        );
5337        let tx1 = f.validated_arc(
5338            MockTransaction::eip1559()
5339                .with_sender(sender)
5340                .with_nonce(1)
5341                .with_gas_limit(1000)
5342                .with_gas_price(10),
5343        );
5344        let tx2 = f.validated_arc(
5345            MockTransaction::legacy().with_sender(sender).with_nonce(2).with_gas_price(10),
5346        );
5347        let tx3 = f.validated_arc(
5348            MockTransaction::legacy().with_sender(sender).with_nonce(3).with_gas_price(10),
5349        );
5350
5351        // tx0 should be put in the pending subpool
5352        pool.add_transaction((*tx0).clone(), U256::from(1000), 0, None).unwrap();
5353        let mut best = pool.best_transactions();
5354        let t0 = best.next().expect("tx0 should be put in the pending subpool");
5355        assert_eq!(t0.id(), tx0.id());
5356        // tx1 should be put in the queued subpool due to insufficient sender balance
5357        pool.add_transaction((*tx1).clone(), U256::from(1000), 0, None).unwrap();
5358        let mut best = pool.best_transactions();
5359        let t0 = best.next().expect("tx0 should be put in the pending subpool");
5360        assert_eq!(t0.id(), tx0.id());
5361        assert!(best.next().is_none());
5362
5363        // tx2 should be put in the pending subpool, and tx1 should be promoted to pending
5364        pool.add_transaction((*tx2).clone(), U256::MAX, 0, None).unwrap();
5365
5366        let mut best = pool.best_transactions();
5367
5368        let t0 = best.next().expect("tx0 should be put in the pending subpool");
5369        let t1 = best.next().expect("tx1 should be put in the pending subpool");
5370        let t2 = best.next().expect("tx2 should be put in the pending subpool");
5371        assert_eq!(t0.id(), tx0.id());
5372        assert_eq!(t1.id(), tx1.id());
5373        assert_eq!(t2.id(), tx2.id());
5374
5375        // tx3 should be put in the pending subpool,
5376        pool.add_transaction((*tx3).clone(), U256::MAX, 0, None).unwrap();
5377        let mut best = pool.best_transactions();
5378        let t0 = best.next().expect("tx0 should be put in the pending subpool");
5379        let t1 = best.next().expect("tx1 should be put in the pending subpool");
5380        let t2 = best.next().expect("tx2 should be put in the pending subpool");
5381        let t3 = best.next().expect("tx3 should be put in the pending subpool");
5382        assert_eq!(t0.id(), tx0.id());
5383        assert_eq!(t1.id(), tx1.id());
5384        assert_eq!(t2.id(), tx2.id());
5385        assert_eq!(t3.id(), tx3.id());
5386    }
5387
5388    #[test]
5389    fn test_non_4844_blob_fee_bit_invariant() {
5390        let mut f = MockTransactionFactory::default();
5391        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5392
5393        let non_4844_tx = MockTransaction::eip1559().set_max_fee(200).inc_limit();
5394        let validated = f.validated(non_4844_tx.clone());
5395
5396        assert!(!non_4844_tx.is_eip4844());
5397        pool.add_transaction(validated.clone(), U256::from(10_000), 0, None).unwrap();
5398
5399        // Core invariant: Non-4844 transactions must ALWAYS have ENOUGH_BLOB_FEE_CAP_BLOCK bit
5400        let tx_meta = pool.all_transactions.txs.get(validated.id()).unwrap();
5401        assert!(tx_meta.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
5402        assert_eq!(tx_meta.subpool, SubPool::Pending);
5403    }
5404
5405    #[test]
5406    fn test_blob_fee_enforcement_only_applies_to_eip4844() {
5407        let mut f = MockTransactionFactory::default();
5408        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5409
5410        // Set blob fee higher than EIP-4844 tx can afford
5411        let mut block_info = pool.block_info();
5412        block_info.pending_blob_fee = Some(160);
5413        block_info.pending_basefee = 100;
5414        pool.set_block_info(block_info);
5415
5416        let eip4844_tx = MockTransaction::eip4844()
5417            .with_sender(Address::with_last_byte(0x0a))
5418            .with_max_fee(200)
5419            .with_blob_fee(150) // Less than block blob fee (160)
5420            .inc_limit();
5421
5422        let non_4844_tx = MockTransaction::eip1559()
5423            .with_sender(Address::with_last_byte(0x0b))
5424            .set_max_fee(200)
5425            .inc_limit();
5426
5427        let validated_4844 = f.validated(eip4844_tx);
5428        let validated_non_4844 = f.validated(non_4844_tx);
5429
5430        pool.add_transaction(validated_4844.clone(), U256::from(10_000), 0, None).unwrap();
5431        pool.add_transaction(validated_non_4844.clone(), U256::from(10_000), 0, None).unwrap();
5432
5433        let tx_4844_meta = pool.all_transactions.txs.get(validated_4844.id()).unwrap();
5434        let tx_non_4844_meta = pool.all_transactions.txs.get(validated_non_4844.id()).unwrap();
5435
5436        // EIP-4844: blob fee enforcement applies - insufficient blob fee removes bit
5437        assert!(!tx_4844_meta.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
5438        assert_eq!(tx_4844_meta.subpool, SubPool::Blob);
5439
5440        // Non-4844: blob fee enforcement does NOT apply - bit always remains true
5441        assert!(tx_non_4844_meta.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK));
5442        assert_eq!(tx_non_4844_meta.subpool, SubPool::Pending);
5443    }
5444
5445    #[test]
5446    fn test_basefee_decrease_preserves_non_4844_blob_fee_bit() {
5447        let mut f = MockTransactionFactory::default();
5448        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5449
5450        // Create non-4844 transaction with fee that initially can't afford high basefee
5451        let non_4844_tx = MockTransaction::eip1559()
5452            .with_sender(Address::with_last_byte(0x0a))
5453            .set_max_fee(500) // Can't afford basefee of 600
5454            .inc_limit();
5455
5456        // Set high basefee so transaction goes to BaseFee pool initially
5457        pool.update_basefee(600, |_| {});
5458
5459        let validated = f.validated(non_4844_tx);
5460        let tx_id = *validated.id();
5461        pool.add_transaction(validated, U256::from(10_000), 0, None).unwrap();
5462
5463        // Initially should be in BaseFee pool but STILL have blob fee bit (critical invariant)
5464        let tx_meta = pool.all_transactions.txs.get(&tx_id).unwrap();
5465        assert_eq!(tx_meta.subpool, SubPool::BaseFee);
5466        assert!(
5467            tx_meta.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK),
5468            "Non-4844 tx in BaseFee pool must retain ENOUGH_BLOB_FEE_CAP_BLOCK bit"
5469        );
5470
5471        // Decrease basefee - transaction should be promoted to Pending
5472        // This is where PR #18215 bug would manifest: blob fee bit incorrectly removed
5473        pool.update_basefee(400, |_| {});
5474
5475        // After basefee decrease: should be promoted to Pending with blob fee bit preserved
5476        let tx_meta = pool.all_transactions.txs.get(&tx_id).unwrap();
5477        assert_eq!(
5478            tx_meta.subpool,
5479            SubPool::Pending,
5480            "Non-4844 tx should be promoted from BaseFee to Pending after basefee decrease"
5481        );
5482        assert!(
5483            tx_meta.state.contains(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK),
5484            "Non-4844 tx must NEVER lose ENOUGH_BLOB_FEE_CAP_BLOCK bit during basefee promotion"
5485        );
5486        assert!(
5487            tx_meta.state.contains(TxState::ENOUGH_FEE_CAP_BLOCK),
5488            "Non-4844 tx should gain ENOUGH_FEE_CAP_BLOCK bit after basefee decrease"
5489        );
5490    }
5491
5492    /// Test for <https://github.com/paradigmxyz/reth/issues/17701>
5493    ///
5494    /// When a new transaction is added and its `updates` contain a same-sender transaction with
5495    /// a lower nonce, the lower-nonce tx must be added to the pending subpool *before* the
5496    /// higher-nonce tx. Otherwise, live `BestTransactions` iterators receive them out of order.
5497    #[test]
5498    fn best_transactions_nonce_order_on_balance_unlock() {
5499        let mut f = MockTransactionFactory::default();
5500        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5501
5502        let sender = Address::random();
5503        let on_chain_balance = U256::from(10_000);
5504
5505        // tx0: nonce 0, cheap — will go straight to pending
5506        let tx0 = MockTransaction::eip1559().with_sender(sender).set_gas_price(100).inc_limit();
5507        // tx1: nonce 1, very expensive — cumulative cost (tx0 + tx1) will exceed balance
5508        let tx1 = tx0.next().inc_limit().with_value(on_chain_balance);
5509        // tx2: nonce 2
5510        let tx2 = tx1.next().inc_limit().with_value(U256::ZERO);
5511
5512        let v0 = f.validated(tx0);
5513        let v1 = f.validated(tx1);
5514        let v2 = f.validated(tx2);
5515
5516        // Add tx0 with limited balance — goes to pending (tx0 cost is small: 1 * 100 = 100)
5517        pool.add_transaction(v0, on_chain_balance, 0, None).unwrap();
5518
5519        // Create a live BestTransactions iterator that will receive new pending txs
5520        let mut best = pool.best_transactions();
5521
5522        // Drain tx0 from the iterator
5523        let first = best.next().expect("should yield tx0");
5524        assert_eq!(first.id().nonce, 0);
5525
5526        // Add tx1 with the same limited balance — cumulative cost exceeds balance, goes to
5527        // queued
5528        pool.add_transaction(v1, on_chain_balance, 0, None).unwrap();
5529
5530        // tx1 should be queued, nothing new in best
5531        assert!(best.next().is_none(), "tx1 should be queued, not pending");
5532
5533        // Now add tx2 with U256::MAX balance — tx2 goes to pending AND tx1 gets promoted.
5534        // The bug: tx2 was added to pending *before* tx1, so BestTransactions yielded tx2
5535        // first, violating nonce ordering.
5536        pool.add_transaction(v2, U256::MAX, 0, None).unwrap();
5537
5538        let t1 = best.next().expect("should yield a transaction");
5539        let t2 = best.next().expect("should yield a transaction");
5540
5541        // Correct order: tx1 (nonce 1) before tx2 (nonce 2)
5542        assert_eq!(
5543            t1.id().nonce,
5544            1,
5545            "first yielded tx should be nonce 1, got nonce {}",
5546            t1.id().nonce
5547        );
5548        assert_eq!(
5549            t2.id().nonce,
5550            2,
5551            "second yielded tx should be nonce 2, got nonce {}",
5552            t2.id().nonce
5553        );
5554    }
5555
5556    /// Gap-fill scenario: inserting a low-nonce transaction promotes a queued higher-nonce
5557    /// transaction. The new (lower-nonce) tx must appear before the promoted (higher-nonce)
5558    /// tx in the `BestTransactions` iterator.
5559    #[test]
5560    fn best_transactions_nonce_order_on_gap_fill() {
5561        let mut f = MockTransactionFactory::default();
5562        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5563
5564        let sender = Address::random();
5565        let balance = U256::MAX;
5566
5567        // tx0: nonce 0
5568        let tx0 = MockTransaction::eip1559().with_sender(sender).set_gas_price(100).inc_limit();
5569        // tx1: nonce 1
5570        let tx1 = tx0.next().inc_limit();
5571
5572        let v0 = f.validated(tx0);
5573        let v1 = f.validated(tx1);
5574
5575        // Add tx1 first — goes to queued because nonce 0 is missing (nonce gap)
5576        pool.add_transaction(v1, balance, 0, None).unwrap();
5577
5578        // Create a live BestTransactions iterator (currently empty — nothing pending)
5579        let mut best = pool.best_transactions();
5580        assert!(best.next().is_none(), "pool should have no pending txs yet");
5581
5582        // Add tx0 — fills the gap, tx1 gets promoted
5583        pool.add_transaction(v0, balance, 0, None).unwrap();
5584
5585        let t0 = best.next().expect("should yield a transaction");
5586        let t1 = best.next().expect("should yield a transaction");
5587
5588        assert_eq!(t0.id().nonce, 0, "first yielded tx should be nonce 0, got {}", t0.id().nonce);
5589        assert_eq!(t1.id().nonce, 1, "second yielded tx should be nonce 1, got {}", t1.id().nonce);
5590    }
5591
5592    /// Mixed scenario: inserting a mid-nonce transaction promotes both a lower-nonce tx
5593    /// (via balance update) and a higher-nonce tx (via gap fill). All three must appear
5594    /// in nonce order in `BestTransactions`.
5595    #[test]
5596    fn best_transactions_nonce_order_mixed_promotions() {
5597        let mut f = MockTransactionFactory::default();
5598        let mut pool = TxPool::new(MockOrdering::default(), Default::default());
5599
5600        let sender = Address::random();
5601        let low_balance = U256::from(10_000);
5602
5603        // tx0: nonce 0, cheap
5604        let tx0 = MockTransaction::eip1559().with_sender(sender).set_gas_price(100).inc_limit();
5605        // tx1: nonce 1, very expensive — will exceed balance
5606        let tx1 = tx0.next().inc_limit().with_value(low_balance);
5607        // tx2: nonce 2
5608        let tx2 = tx1.next().inc_limit().with_value(U256::ZERO);
5609        // tx3: nonce 3
5610        let tx3 = tx2.next().inc_limit().with_value(U256::ZERO);
5611
5612        let v0 = f.validated(tx0);
5613        let v1 = f.validated(tx1);
5614        let v2 = f.validated(tx2);
5615        let v3 = f.validated(tx3);
5616
5617        // Add tx0 — goes to pending
5618        pool.add_transaction(v0, low_balance, 0, None).unwrap();
5619
5620        // Add tx1 — queued (cumulative cost exceeds balance)
5621        pool.add_transaction(v1, low_balance, 0, None).unwrap();
5622
5623        // Add tx3 — queued (nonce gap: tx2 is missing)
5624        pool.add_transaction(v3, low_balance, 0, None).unwrap();
5625
5626        let mut best = pool.best_transactions();
5627
5628        // Drain tx0
5629        let first = best.next().expect("should yield tx0");
5630        assert_eq!(first.id().nonce, 0);
5631        assert!(best.next().is_none(), "only tx0 should be pending");
5632
5633        // Add tx2 with U256::MAX balance — this should:
5634        //  - promote tx1 (lower-nonce, was queued due to balance)
5635        //  - add tx2 itself to pending
5636        //  - promote tx3 (higher-nonce, was queued due to nonce gap)
5637        pool.add_transaction(v2, U256::MAX, 0, None).unwrap();
5638
5639        let t1 = best.next().expect("should yield nonce 1");
5640        let t2 = best.next().expect("should yield nonce 2");
5641        let t3 = best.next().expect("should yield nonce 3");
5642
5643        assert_eq!(t1.id().nonce, 1, "expected nonce 1, got {}", t1.id().nonce);
5644        assert_eq!(t2.id().nonce, 2, "expected nonce 2, got {}", t2.id().nonce);
5645        assert_eq!(t3.id().nonce, 3, "expected nonce 3, got {}", t3.id().nonce);
5646    }
5647}