Skip to main content

reth_transaction_pool/pool/
pending.rs

1//! Pending transactions
2
3use crate::{
4    identifier::{SenderId, TransactionId},
5    pool::{
6        best::{BestTransactions, BestTransactionsWithFees},
7        size::SizeTracker,
8    },
9    LocalTransactionConfig, Priority, SubPoolLimit, TransactionOrdering, ValidPoolTransaction,
10};
11use imbl::OrdMap;
12use rustc_hash::FxHashMap;
13use std::{
14    cmp::Ordering,
15    collections::{btree_set, hash_map::Entry, BTreeSet},
16    iter::Peekable,
17    ops::Bound::{Excluded, Included, Unbounded},
18    sync::Arc,
19};
20use tokio::sync::broadcast;
21
22/// A pool of validated and gapless transactions that are ready to be executed on the current state
23/// and are waiting to be included in a block.
24///
25/// This pool distinguishes between `independent` transactions and pending transactions. A
26/// transaction is `independent`, if it is in the pending pool, and it has the current on chain
27/// nonce of the sender. Meaning `independent` transactions can be executed right away, other
28/// pending transactions depend on at least one `independent` transaction.
29///
30/// Once an `independent` transaction was executed it *unlocks* the next nonce, if this transaction
31/// is also pending, then this will be moved to the `independent` queue.
32#[derive(Debug, Clone)]
33pub struct PendingPool<T: TransactionOrdering> {
34    /// How to order transactions.
35    ordering: T,
36    /// Keeps track of transactions inserted in the pool.
37    ///
38    /// This way we can determine when transactions were submitted to the pool.
39    submission_id: u64,
40    /// _All_ Transactions that are currently inside the pool grouped by their identifier.
41    by_id: OrdMap<TransactionId, PendingTransaction<T>>,
42    /// The highest nonce transactions for each sender - like the `independent` set, but the
43    /// highest instead of lowest nonce.
44    highest_nonces: FxHashMap<SenderId, PendingTransaction<T>>,
45    /// The values of `highest_nonces`, ordered from worst to best.
46    ///
47    /// This is the order in which [`Self::remove_to_limit`] removes transactions. `None` means
48    /// that it is not built. [`Self::remove_to_limit`] builds it and every later change of
49    /// `highest_nonces` updates it. A fee update that rebuilds the pool drops it, and so does
50    /// [`Self::clear_highest_nonces_by_priority`]. A pool that stays within its limit never
51    /// builds it.
52    highest_nonces_by_priority: Option<HighestNoncesByPriority<T>>,
53    /// Independent transactions that can be included directly and don't require other
54    /// transactions.
55    independent_transactions: FxHashMap<SenderId, PendingTransaction<T>>,
56    /// Keeps track of the size of this pool.
57    ///
58    /// See also [`reth_primitives_traits::InMemorySize::size`].
59    size_of: SizeTracker,
60    /// Used to broadcast new transactions that have been added to the `PendingPool` to existing
61    /// `static_files` of this pool.
62    new_transaction_notifier: broadcast::Sender<PendingTransaction<T>>,
63    /// Which transactions count as local, which `truncate_pool` removes last.
64    local_transactions_config: Arc<LocalTransactionConfig>,
65}
66
67// === impl PendingPool ===
68
69impl<T: TransactionOrdering> PendingPool<T> {
70    /// Create a new pending pool instance.
71    pub fn new(ordering: T) -> Self {
72        Self::with_buffer(ordering, 200)
73    }
74
75    /// Create a new pool instance with the given buffer capacity.
76    pub fn with_buffer(ordering: T, buffer_capacity: usize) -> Self {
77        let (new_transaction_notifier, _) = broadcast::channel(buffer_capacity);
78        Self {
79            ordering,
80            submission_id: 0,
81            by_id: Default::default(),
82            independent_transactions: Default::default(),
83            highest_nonces: Default::default(),
84            highest_nonces_by_priority: Default::default(),
85            size_of: Default::default(),
86            new_transaction_notifier,
87            local_transactions_config: Default::default(),
88        }
89    }
90
91    /// Sets which transactions are local and removed last by [`Self::truncate_pool`].
92    ///
93    /// By default, only transactions with a local origin are.
94    pub fn with_local_transactions_config(mut self, config: Arc<LocalTransactionConfig>) -> Self {
95        self.local_transactions_config = config;
96        // The eviction order splits transactions by the old config.
97        self.clear_highest_nonces_by_priority();
98        self
99    }
100
101    /// Clear all transactions from the pool without resetting other values.
102    /// Used for atomic reordering during basefee update.
103    ///
104    /// # Returns
105    ///
106    /// Returns all transactions by id.
107    fn clear_transactions(&mut self) -> OrdMap<TransactionId, PendingTransaction<T>> {
108        self.independent_transactions.clear();
109        self.highest_nonces.clear();
110        self.highest_nonces_by_priority = None;
111        self.size_of.reset();
112        std::mem::take(&mut self.by_id)
113    }
114
115    /// Returns an iterator over all transactions that are _currently_ ready.
116    ///
117    /// 1. The iterator _always_ returns transactions in order: it never returns a transaction with
118    ///    an unsatisfied dependency and only returns them if dependency transaction were yielded
119    ///    previously. In other words: the nonces of transactions with the same sender will _always_
120    ///    increase by exactly 1.
121    ///
122    /// The order of transactions which satisfy (1.) is determined by their computed priority: a
123    /// transaction with a higher priority is returned before a transaction with a lower priority.
124    ///
125    /// If two transactions have the same priority score, then the transactions which spent more
126    /// time in pool (were added earlier) are returned first.
127    ///
128    /// NOTE: while this iterator returns transaction that pool considers valid at this point, they
129    /// could potentially become invalid at point of execution. Therefore, this iterator
130    /// provides a way to mark transactions that the consumer of this iterator considers invalid. In
131    /// which case the transaction's subgraph is also automatically marked invalid, See (1.).
132    /// Invalid transactions are skipped.
133    pub fn best(&self) -> BestTransactions<T> {
134        BestTransactions {
135            all: self.by_id.clone(),
136            independent: self.independent_transactions.values().cloned().collect(),
137            invalid: Default::default(),
138            new_transaction_receiver: Some(self.new_transaction_notifier.subscribe()),
139            last_priority: None,
140            skip_blobs: false,
141            allow_updates_out_of_order: false,
142        }
143    }
144
145    /// Same as `best` but only returns transactions that satisfy the given basefee and blobfee.
146    pub(crate) fn best_with_basefee_and_blobfee(
147        &self,
148        base_fee: u64,
149        base_fee_per_blob_gas: u64,
150    ) -> BestTransactionsWithFees<T> {
151        BestTransactionsWithFees { best: self.best(), base_fee, base_fee_per_blob_gas }
152    }
153
154    /// Same as `best` but also includes the given unlocked transactions.
155    ///
156    /// This mimics the [`Self::add_transaction`] method, but does not insert the transactions into
157    /// pool but only into the returned iterator.
158    ///
159    /// Note: this does not insert the unlocked transactions into the pool.
160    ///
161    /// # Panics
162    ///
163    /// if the transaction is already included
164    pub(crate) fn best_with_unlocked_and_attributes(
165        &self,
166        unlocked: Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
167        base_fee: u64,
168        base_fee_per_blob_gas: u64,
169    ) -> BestTransactionsWithFees<T> {
170        let mut best = self.best();
171        for (submission_id, tx) in (self.submission_id + 1..).zip(unlocked) {
172            debug_assert!(!best.all.contains_key(tx.id()), "transaction already included");
173            let priority = self.ordering.priority(&tx.transaction, base_fee);
174            let tx_id = *tx.id();
175            let transaction = PendingTransaction { submission_id, transaction: tx, priority };
176            if best.ancestor(&tx_id).is_none() {
177                best.independent.insert(transaction.clone());
178            }
179            best.all.insert(tx_id, transaction);
180        }
181
182        BestTransactionsWithFees { best, base_fee, base_fee_per_blob_gas }
183    }
184
185    /// Returns an iterator over all transactions in the pool
186    pub(crate) fn all(
187        &self,
188    ) -> impl ExactSizeIterator<Item = Arc<ValidPoolTransaction<T::Transaction>>> + '_ {
189        self.by_id.values().map(|tx| tx.transaction.clone())
190    }
191
192    /// Updates the pool with the new blob fee. Removes
193    /// from the subpool all transactions and their dependents that no longer satisfy the given
194    /// blob fee (`tx.max_blob_fee < blob_fee`).
195    ///
196    /// Note: the transactions are not returned in a particular order.
197    ///
198    /// # Returns
199    ///
200    /// Removed transactions that no longer satisfy the blob fee.
201    pub(crate) fn update_blob_fee(
202        &mut self,
203        blob_fee: u128,
204    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
205        let priced_out = |tx: &PendingTransaction<T>| {
206            tx.transaction.is_eip4844() && tx.transaction.max_fee_per_blob_gas() < Some(blob_fee)
207        };
208        // The blob fee does not order the pool, so the pool only changes if a transaction no
209        // longer satisfies the fee.
210        if !self.by_id.values().any(priced_out) {
211            return Vec::new()
212        }
213
214        // Create a collection for removed transactions.
215        let mut removed = Vec::new();
216
217        // Drain and iterate over all transactions.
218        let mut transactions_iter = self.clear_transactions().into_iter().peekable();
219        let mut highest: Option<TransactionId> = None;
220        while let Some((id, tx)) = transactions_iter.next() {
221            self.flush_highest_nonce(&mut highest, Some(id.sender));
222            if priced_out(&tx) {
223                // Add this tx to the removed collection since it no longer satisfies the blob fee
224                // condition. Decrease the total pool size.
225                removed.push(Arc::clone(&tx.transaction));
226
227                // Remove all dependent transactions. Draining the rest of the sender here is what
228                // keeps the tracked `highest` correct, see `flush_highest_nonce`.
229                'this: while let Some((next_id, next_tx)) = transactions_iter.peek() {
230                    if next_id.sender != id.sender {
231                        break 'this
232                    }
233                    removed.push(Arc::clone(&next_tx.transaction));
234                    transactions_iter.next();
235                }
236            } else {
237                self.size_of += tx.transaction.size();
238                if highest.is_none() {
239                    // first kept transaction of this sender, hence the independent one
240                    self.independent_transactions.insert(id.sender, tx.clone());
241                }
242                highest = Some(id);
243                self.by_id.insert(id, tx);
244            }
245        }
246        self.flush_highest_nonce(&mut highest, None);
247
248        removed
249    }
250
251    /// Updates the pool with the new base fee. Reorders transactions by new priorities. Removes
252    /// from the subpool all transactions and their dependents that no longer satisfy the given
253    /// base fee (`tx.fee < base_fee`).
254    ///
255    /// Note: the transactions are not returned in a particular order.
256    ///
257    /// # Returns
258    ///
259    /// Removed transactions that no longer satisfy the base fee.
260    pub(crate) fn update_base_fee(
261        &mut self,
262        base_fee: u64,
263    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
264        // Create a collection for removed transactions.
265        let mut removed = Vec::new();
266
267        // Drain and iterate over all transactions.
268        let mut transactions_iter = self.clear_transactions().into_iter().peekable();
269        let mut highest: Option<TransactionId> = None;
270        while let Some((id, mut tx)) = transactions_iter.next() {
271            self.flush_highest_nonce(&mut highest, Some(id.sender));
272            if tx.transaction.max_fee_per_gas() < base_fee as u128 {
273                // Add this tx to the removed collection since it no longer satisfies the base fee
274                // condition. Decrease the total pool size.
275                removed.push(Arc::clone(&tx.transaction));
276
277                // Remove all dependent transactions. Draining the rest of the sender here is what
278                // keeps the tracked `highest` correct, see `flush_highest_nonce`.
279                'this: while let Some((next_id, next_tx)) = transactions_iter.peek() {
280                    if next_id.sender != id.sender {
281                        break 'this
282                    }
283                    removed.push(Arc::clone(&next_tx.transaction));
284                    transactions_iter.next();
285                }
286            } else {
287                // Re-insert the transaction with new priority.
288                tx.priority = self.ordering.priority(&tx.transaction.transaction, base_fee);
289
290                self.size_of += tx.transaction.size();
291                if highest.is_none() {
292                    // first kept transaction of this sender, hence the independent one
293                    self.independent_transactions.insert(id.sender, tx.clone());
294                }
295                highest = Some(id);
296                self.by_id.insert(id, tx);
297            }
298        }
299        self.flush_highest_nonce(&mut highest, None);
300
301        removed
302    }
303
304    /// Writes the transaction tracked by a rebuild loop (`update_base_fee`, `update_blob_fee`) to
305    /// `highest_nonces` if the loop has moved on to `next_sender`.
306    ///
307    /// The pool is drained in ascending `(sender, nonce)` order, so the highest kept nonce of a
308    /// sender is only known once the drain reaches the next sender or the end of the pool. This
309    /// relies on the loops removing all remaining transactions of a sender once one of them no
310    /// longer satisfies the fee, otherwise the tracked transaction would not be the highest kept
311    /// one.
312    fn flush_highest_nonce(
313        &mut self,
314        tracked: &mut Option<TransactionId>,
315        next_sender: Option<SenderId>,
316    ) {
317        if let Some(id) = tracked.take_if(|id| Some(id.sender) != next_sender) &&
318            let Some(tx) = self.by_id.get(&id).cloned()
319        {
320            self.highest_nonces.insert(id.sender, tx);
321        }
322    }
323
324    /// Updates the independent transaction and highest nonces set, assuming the given transaction
325    /// is being _added_ to the pool.
326    fn update_independents_and_highest_nonces(&mut self, tx: &PendingTransaction<T>) {
327        match self.highest_nonces.entry(tx.transaction.sender_id()) {
328            Entry::Occupied(mut entry) => {
329                if entry.get().transaction.nonce() < tx.transaction.nonce() {
330                    if let Some(index) = &mut self.highest_nonces_by_priority {
331                        index.remove(entry.get(), &self.local_transactions_config);
332                        index.insert(tx.clone(), &self.local_transactions_config);
333                    }
334                    *entry.get_mut() = tx.clone();
335                }
336            }
337            Entry::Vacant(entry) => {
338                if let Some(index) = &mut self.highest_nonces_by_priority {
339                    index.insert(tx.clone(), &self.local_transactions_config);
340                }
341                entry.insert(tx.clone());
342            }
343        }
344        match self.independent_transactions.entry(tx.transaction.sender_id()) {
345            Entry::Occupied(mut entry) => {
346                if entry.get().transaction.nonce() > tx.transaction.nonce() {
347                    *entry.get_mut() = tx.clone();
348                }
349            }
350            Entry::Vacant(entry) => {
351                entry.insert(tx.clone());
352            }
353        }
354    }
355
356    /// Adds a new transactions to the pending queue.
357    ///
358    /// # Panics
359    ///
360    /// if the transaction is already included
361    pub fn add_transaction(
362        &mut self,
363        tx: Arc<ValidPoolTransaction<T::Transaction>>,
364        base_fee: u64,
365    ) {
366        debug_assert!(
367            !self.contains(tx.id()),
368            "transaction already included {:?}",
369            self.get(tx.id()).unwrap().transaction
370        );
371
372        // keep track of size
373        self.size_of += tx.size();
374
375        let tx_id = *tx.id();
376
377        let submission_id = self.next_id();
378        let priority = self.ordering.priority(&tx.transaction, base_fee);
379        let tx = PendingTransaction { submission_id, transaction: tx, priority };
380
381        self.update_independents_and_highest_nonces(&tx);
382
383        // send the new transaction to any existing pendingpool static file iterators
384        if self.new_transaction_notifier.receiver_count() > 0 {
385            let _ = self.new_transaction_notifier.send(tx.clone());
386        }
387
388        self.by_id.insert(tx_id, tx);
389    }
390
391    /// Removes the transaction from the pool.
392    ///
393    /// Note: If the sender has a transaction with a higher nonce, the lowest of them advances to
394    /// the best queue.
395    pub(crate) fn remove_transaction(
396        &mut self,
397        id: &TransactionId,
398    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
399        if let Some(lowest) = self.independent_transactions.get(&id.sender) &&
400            lowest.transaction.nonce() == id.nonce
401        {
402            self.independent_transactions.remove(&id.sender);
403            // Mark the sender's next transaction as independent. It need not be the descendant: a
404            // canonical update can prune a mined nonce before it discards the stale lower one.
405            if let Some((_, unlocked)) = self
406                .by_id
407                .range((Excluded(*id), Included(TransactionId::new(id.sender, u64::MAX))))
408                .next()
409            {
410                self.independent_transactions.insert(id.sender, unlocked.clone());
411            }
412        }
413
414        let tx = self.by_id.remove(id)?;
415        self.size_of -= tx.transaction.size();
416
417        match self.highest_nonces.entry(id.sender) {
418            Entry::Occupied(mut entry) => {
419                if entry.get().transaction.nonce() == id.nonce {
420                    if let Some(index) = &mut self.highest_nonces_by_priority {
421                        index.remove(entry.get(), &self.local_transactions_config);
422                    }
423                    // we just removed the tx with the highest nonce for this sender, find the
424                    // highest remaining tx from that sender
425                    if let Some((_, new_highest)) = self
426                        .by_id
427                        .range((
428                            id.sender.start_bound(),
429                            Included(TransactionId::new(id.sender, u64::MAX)),
430                        ))
431                        .next_back()
432                    {
433                        // insert the new highest nonce for this sender
434                        if let Some(index) = &mut self.highest_nonces_by_priority {
435                            index.insert(new_highest.clone(), &self.local_transactions_config);
436                        }
437                        entry.insert(new_highest.clone());
438                    } else {
439                        entry.remove();
440                    }
441                }
442            }
443            Entry::Vacant(_) => {
444                debug_assert!(
445                    false,
446                    "removed transaction without a tracked highest nonce {:?}",
447                    id
448                );
449            }
450        }
451
452        Some(tx.transaction)
453    }
454
455    const fn next_id(&mut self) -> u64 {
456        let id = self.submission_id;
457        self.submission_id = self.submission_id.wrapping_add(1);
458        id
459    }
460
461    /// Traverses the pool, starting at the highest nonce set, removing the transactions which
462    /// would put the pool under the specified limits.
463    ///
464    /// This attempts to remove transactions by roughly the same amount for each sender. This is
465    /// done by removing the highest-nonce transactions for each sender.
466    ///
467    /// If the `remove_locals` flag is unset, transactions will be removed per-sender until a
468    /// local transaction is the highest nonce transaction for that sender. If all senders have a
469    /// local highest-nonce transaction, the pool will not be truncated further.
470    ///
471    /// Otherwise, if the `remove_locals` flag is set, transactions will be removed per-sender
472    /// until the pool is under the given limits.
473    ///
474    /// Any removed transactions will be added to the `end_removed` vector.
475    pub fn remove_to_limit(
476        &mut self,
477        limit: &SubPoolLimit,
478        remove_locals: bool,
479        end_removed: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
480    ) {
481        // keep track of transactions to remove and how many have been removed so far
482        let original_length = self.len();
483        let mut removed = Vec::new();
484        let mut total_removed = 0;
485
486        // track total `size` of transactions to remove
487        let original_size = self.size();
488        let mut total_size = 0;
489
490        loop {
491            // we can reuse the temp array
492            removed.clear();
493
494            // We prefer removing transactions with lower ordering. The first pass builds the
495            // index if it is not built.
496            let mut worst_transactions = self
497                .highest_nonces_by_priority
498                .get_or_insert_with(|| {
499                    HighestNoncesByPriority::new(
500                        self.highest_nonces.values().cloned(),
501                        &self.local_transactions_config,
502                    )
503                })
504                .iter(remove_locals)
505                .peekable();
506
507            // no eligible transactions left to remove
508            if worst_transactions.peek().is_none() {
509                return
510            }
511
512            // Each pass removes at most one transaction per sender (its highest nonce), so only
513            // the worst few senders can be relevant in this pass. The estimate may fall short for
514            // size-based limits, in which case the outer loop runs another pass.
515            let current_len = original_length - total_removed;
516            let current_size = original_size - total_size;
517            let excess_txs = current_len.saturating_sub(limit.max_txs);
518            let avg_tx_size = (current_size / current_len.max(1)).max(1);
519            let excess_size_txs = current_size.saturating_sub(limit.max_size).div_ceil(avg_tx_size);
520            // Number of worst senders to consider for removal in this pass: enough to cover the
521            // count and (estimated) size excess.
522            let removal_candidates = excess_txs.max(excess_size_txs).max(1);
523
524            // loop through the highest nonces set, removing transactions until we reach the limit
525            for tx in worst_transactions.take(removal_candidates) {
526                // return early if the pool is under limits
527                if !limit.is_exceeded(original_length - total_removed, original_size - total_size) {
528                    // need to remove remaining transactions before exiting
529                    for id in &removed {
530                        if let Some(tx) = self.remove_transaction(id) {
531                            end_removed.push(tx);
532                        }
533                    }
534
535                    return
536                }
537
538                total_size += tx.transaction.size();
539                total_removed += 1;
540                removed.push(*tx.transaction.id());
541            }
542
543            // remove the transactions from this iteration
544            for id in &removed {
545                if let Some(tx) = self.remove_transaction(id) {
546                    end_removed.push(tx);
547                }
548            }
549
550            if !self.exceeds(limit) {
551                return
552            }
553        }
554    }
555
556    /// Truncates the pool to the given [`SubPoolLimit`], removing transactions until the subpool
557    /// limits are met.
558    ///
559    /// This attempts to remove transactions by roughly the same amount for each sender. For more
560    /// information on this exact process see docs for
561    /// [`remove_to_limit`](PendingPool::remove_to_limit).
562    ///
563    /// This first truncates all of the non-local transactions in the pool, as decided by the
564    /// configured [`LocalTransactionConfig`]. If the subpool is still not under the limit, this
565    /// truncates the entire pool, including local transactions. The removed transactions are
566    /// returned.
567    pub fn truncate_pool(
568        &mut self,
569        limit: SubPoolLimit,
570    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
571        let mut removed = Vec::new();
572        // return early if the pool is already under the limits
573        if !self.exceeds(&limit) {
574            return removed
575        }
576
577        // first truncate only non-local transactions, returning if the pool end up under the limit
578        self.remove_to_limit(&limit, false, &mut removed);
579        if !self.exceeds(&limit) {
580            return removed
581        }
582
583        // now repeat for local transactions, since local transactions must be removed now for the
584        // pool to be under the limit
585        self.remove_to_limit(&limit, true, &mut removed);
586
587        removed
588    }
589
590    /// Drops `highest_nonces_by_priority`. The next call of [`Self::remove_to_limit`] builds it
591    /// again.
592    ///
593    /// Call this before an update that changes many transactions and does not evict, such as a
594    /// block update. Building the order once is cheaper than keeping it up to date through such
595    /// an update.
596    pub(crate) fn clear_highest_nonces_by_priority(&mut self) {
597        self.highest_nonces_by_priority = None;
598    }
599
600    /// Returns true if the pool exceeds the given limit
601    #[inline]
602    pub(crate) fn exceeds(&self, limit: &SubPoolLimit) -> bool {
603        limit.is_exceeded(self.len(), self.size())
604    }
605
606    /// The reported size of all transactions in this pool.
607    pub(crate) fn size(&self) -> usize {
608        self.size_of.into()
609    }
610
611    /// Number of transactions in the entire pool
612    pub(crate) fn len(&self) -> usize {
613        self.by_id.len()
614    }
615
616    /// All transactions grouped by id
617    pub const fn by_id(&self) -> &OrdMap<TransactionId, PendingTransaction<T>> {
618        &self.by_id
619    }
620
621    /// Independent transactions
622    pub const fn independent_transactions(&self) -> &FxHashMap<SenderId, PendingTransaction<T>> {
623        &self.independent_transactions
624    }
625
626    /// Subscribes to new transactions
627    pub fn new_transaction_receiver(&self) -> broadcast::Receiver<PendingTransaction<T>> {
628        self.new_transaction_notifier.subscribe()
629    }
630
631    /// Whether the pool is empty
632    #[cfg(test)]
633    pub(crate) fn is_empty(&self) -> bool {
634        self.by_id.is_empty()
635    }
636
637    /// Returns `true` if the transaction with the given id is already included in this pool.
638    pub(crate) fn contains(&self, id: &TransactionId) -> bool {
639        self.by_id.contains_key(id)
640    }
641
642    /// Get transactions by sender
643    pub(crate) fn get_txs_by_sender(&self, sender: SenderId) -> Vec<TransactionId> {
644        self.iter_txs_by_sender(sender).copied().collect()
645    }
646
647    /// Returns an iterator over all transaction with the sender id
648    pub(crate) fn iter_txs_by_sender(
649        &self,
650        sender: SenderId,
651    ) -> impl Iterator<Item = &TransactionId> + '_ {
652        self.by_id
653            .range((sender.start_bound(), Unbounded))
654            .take_while(move |(other, _)| sender == other.sender)
655            .map(|(tx_id, _)| tx_id)
656    }
657
658    /// Returns an iterator over all transactions for the given sender, using a `BTree` range
659    /// query.
660    pub(crate) fn txs_by_sender(
661        &self,
662        sender: SenderId,
663    ) -> impl Iterator<Item = Arc<ValidPoolTransaction<T::Transaction>>> + '_ {
664        self.by_id
665            .range((sender.start_bound(), Unbounded))
666            .take_while(move |(other, _)| sender == other.sender)
667            .map(|(_, tx)| tx.transaction.clone())
668    }
669
670    /// Retrieves a transaction with the given ID from the pool, if it exists.
671    fn get(&self, id: &TransactionId) -> Option<&PendingTransaction<T>> {
672        self.by_id.get(id)
673    }
674
675    /// Returns a reference to the independent transactions in the pool
676    #[cfg(test)]
677    pub(crate) const fn independent(&self) -> &FxHashMap<SenderId, PendingTransaction<T>> {
678        &self.independent_transactions
679    }
680
681    /// Asserts that the per-sender side maps are consistent with `by_id`.
682    ///
683    /// Every sender in `by_id` must be tracked with its lowest nonce transaction in
684    /// `independent_transactions` and its highest nonce transaction in `highest_nonces`, no other
685    /// sender may be tracked, `highest_nonces_by_priority` must hold exactly the values of
686    /// `highest_nonces` if it is built, each in the set of its local policy, and the tracked size
687    /// must match the size of all transactions.
688    #[cfg(any(test, feature = "test-utils"))]
689    pub(crate) fn assert_invariants(&self) {
690        let mut senders = 0;
691        let mut txs = self.by_id.iter().peekable();
692        while let Some((lowest_id, lowest)) = txs.next() {
693            let sender = lowest_id.sender;
694            senders += 1;
695
696            let mut highest = lowest;
697            while let Some((_, tx)) = txs.next_if(|(id, _)| id.sender == sender) {
698                highest = tx;
699            }
700
701            let independent = self
702                .independent_transactions
703                .get(&sender)
704                .unwrap_or_else(|| panic!("no independent transaction tracked for {sender:?}"));
705            assert_eq!(
706                independent, lowest,
707                "independent transaction of {sender:?} does not match its lowest nonce pool entry"
708            );
709            let tracked_highest = self
710                .highest_nonces
711                .get(&sender)
712                .unwrap_or_else(|| panic!("no highest nonce tracked for {sender:?}"));
713            assert_eq!(
714                tracked_highest, highest,
715                "highest nonce of {sender:?} does not match its highest nonce pool entry"
716            );
717            if let Some(index) = &self.highest_nonces_by_priority {
718                let by_priority = if tracked_highest.is_local(&self.local_transactions_config) {
719                    &index.local
720                } else {
721                    &index.non_local
722                };
723                assert!(
724                    by_priority.contains(tracked_highest),
725                    "highest nonce of {sender:?} is not tracked in highest_nonces_by_priority"
726                );
727            }
728        }
729
730        assert_eq!(
731            self.independent_transactions.len(),
732            senders,
733            "independent_transactions tracks senders without transactions"
734        );
735        assert_eq!(
736            self.highest_nonces.len(),
737            senders,
738            "highest_nonces tracks senders without transactions"
739        );
740        if let Some(index) = &self.highest_nonces_by_priority {
741            assert_eq!(
742                index.non_local.len() + index.local.len(),
743                senders,
744                "highest_nonces_by_priority tracks transactions that are not a highest nonce"
745            );
746        }
747        assert_eq!(
748            self.size(),
749            self.by_id.values().map(|tx| tx.transaction.size()).sum::<usize>(),
750            "size_of does not match the size of all transactions"
751        );
752    }
753}
754
755/// A transaction that is ready to be included in a block.
756#[derive(Debug)]
757pub struct PendingTransaction<T: TransactionOrdering> {
758    /// Identifier that tags when transaction was submitted in the pool.
759    pub submission_id: u64,
760    /// Actual transaction.
761    pub transaction: Arc<ValidPoolTransaction<T::Transaction>>,
762    /// The priority value assigned by the used `Ordering` function.
763    pub priority: Priority<T::PriorityValue>,
764}
765
766impl<T: TransactionOrdering> PendingTransaction<T> {
767    /// The next transaction of the sender: `nonce + 1`
768    pub fn unlocks(&self) -> TransactionId {
769        self.transaction.transaction_id.descendant()
770    }
771
772    /// Whether `config` treats the transaction as local, including its local addresses and
773    /// `no_exemptions`.
774    fn is_local(&self, config: &LocalTransactionConfig) -> bool {
775        config.is_local(self.transaction.origin, self.transaction.sender_ref())
776    }
777}
778
779impl<T: TransactionOrdering> Clone for PendingTransaction<T> {
780    fn clone(&self) -> Self {
781        Self {
782            submission_id: self.submission_id,
783            transaction: Arc::clone(&self.transaction),
784            priority: self.priority.clone(),
785        }
786    }
787}
788
789impl<T: TransactionOrdering> Eq for PendingTransaction<T> {}
790
791impl<T: TransactionOrdering> PartialEq<Self> for PendingTransaction<T> {
792    fn eq(&self, other: &Self) -> bool {
793        self.cmp(other) == Ordering::Equal
794    }
795}
796
797impl<T: TransactionOrdering> PartialOrd<Self> for PendingTransaction<T> {
798    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
799        Some(self.cmp(other))
800    }
801}
802
803impl<T: TransactionOrdering> Ord for PendingTransaction<T> {
804    fn cmp(&self, other: &Self) -> Ordering {
805        // This compares by `priority` and only if two tx have the exact same priority this compares
806        // the unique `submission_id`. This ensures that transactions with same priority are not
807        // equal, so they're not replaced in the set
808        self.priority
809            .cmp(&other.priority)
810            .then_with(|| other.submission_id.cmp(&self.submission_id))
811    }
812}
813
814/// The highest nonce transaction of each sender in a [`PendingPool`], ordered from worst to best.
815///
816/// Local transactions are kept in their own set, so that an iteration without them never visits
817/// them. The local policy decides which set holds a transaction, and changing it drops the index,
818/// so a transaction is always looked up in the set it was inserted into.
819#[derive(Debug, Clone)]
820struct HighestNoncesByPriority<T: TransactionOrdering> {
821    /// The transactions that are not local.
822    non_local: BTreeSet<PendingTransaction<T>>,
823    /// The local transactions.
824    local: BTreeSet<PendingTransaction<T>>,
825}
826
827impl<T: TransactionOrdering> HighestNoncesByPriority<T> {
828    /// Sorts the transactions into the local and non-local sets of `config`.
829    fn new(
830        txs: impl Iterator<Item = PendingTransaction<T>>,
831        config: &LocalTransactionConfig,
832    ) -> Self {
833        let (local, non_local) = txs.partition::<Vec<_>, _>(|tx| tx.is_local(config));
834        // Partitioning into the sets directly would insert one transaction at a time. Collecting
835        // a `Vec` sorts it once.
836        Self { non_local: non_local.into_iter().collect(), local: local.into_iter().collect() }
837    }
838
839    /// Inserts the transaction into its set.
840    fn insert(&mut self, tx: PendingTransaction<T>, config: &LocalTransactionConfig) {
841        self.set_mut(&tx, config).insert(tx);
842    }
843
844    /// Removes the transaction from its set.
845    fn remove(&mut self, tx: &PendingTransaction<T>, config: &LocalTransactionConfig) {
846        self.set_mut(tx, config).remove(tx);
847    }
848
849    /// Returns the transactions from worst to best, with the local transactions only if
850    /// `include_locals` is set.
851    fn iter(&self, include_locals: bool) -> HighestNoncesByPriorityIter<'_, T> {
852        let local = if include_locals { self.local.iter() } else { btree_set::Iter::default() };
853        HighestNoncesByPriorityIter {
854            non_local: self.non_local.iter().peekable(),
855            local: local.peekable(),
856        }
857    }
858
859    /// Returns the set that holds the given transaction.
860    fn set_mut(
861        &mut self,
862        tx: &PendingTransaction<T>,
863        config: &LocalTransactionConfig,
864    ) -> &mut BTreeSet<PendingTransaction<T>> {
865        if tx.is_local(config) {
866            &mut self.local
867        } else {
868            &mut self.non_local
869        }
870    }
871}
872
873/// An iterator over the transactions of a [`HighestNoncesByPriority`], from worst to best.
874///
875/// This is a named type because [`PendingPool::remove_to_limit`] removes transactions while its
876/// iterator is in scope, and the borrow checker assumes that an `impl Iterator` has a destructor.
877struct HighestNoncesByPriorityIter<'a, T: TransactionOrdering> {
878    non_local: Peekable<btree_set::Iter<'a, PendingTransaction<T>>>,
879    local: Peekable<btree_set::Iter<'a, PendingTransaction<T>>>,
880}
881
882impl<'a, T: TransactionOrdering> Iterator for HighestNoncesByPriorityIter<'a, T> {
883    type Item = &'a PendingTransaction<T>;
884
885    fn next(&mut self) -> Option<Self::Item> {
886        // No two transactions compare equal, so the merged order is unique.
887        match (self.non_local.peek(), self.local.peek()) {
888            (Some(non_local), Some(local)) if local < non_local => self.local.next(),
889            (Some(_), _) => self.non_local.next(),
890            (None, _) => self.local.next(),
891        }
892    }
893}
894
895#[cfg(test)]
896mod tests {
897
898    use super::*;
899    use crate::{
900        test_utils::{
901            MockOrdering, MockTransaction, MockTransactionFactory, MockTransactionSet, MockValidTx,
902        },
903        PoolTransaction, TransactionOrigin,
904    };
905    use alloy_consensus::{Transaction, TxType};
906    use alloy_primitives::Address;
907    use std::collections::HashSet;
908
909    #[test]
910    fn test_enforce_basefee() {
911        let mut f = MockTransactionFactory::default();
912        let mut pool = PendingPool::new(MockOrdering::default());
913        let tx = f.validated_arc(MockTransaction::eip1559().inc_price());
914        pool.add_transaction(tx.clone(), 0);
915
916        assert!(pool.contains(tx.id()));
917        assert_eq!(pool.len(), 1);
918
919        let removed = pool.update_base_fee(0);
920        assert!(removed.is_empty());
921
922        let removed = pool.update_base_fee((tx.max_fee_per_gas() + 1) as u64);
923        assert_eq!(removed.len(), 1);
924        assert!(pool.is_empty());
925    }
926
927    #[test]
928    fn test_enforce_basefee_descendant() {
929        let mut f = MockTransactionFactory::default();
930        let mut pool = PendingPool::new(MockOrdering::default());
931        let t = MockTransaction::eip1559().inc_price_by(10);
932        let root_tx = f.validated_arc(t.clone());
933        pool.add_transaction(root_tx.clone(), 0);
934
935        let descendant_tx = f.validated_arc(t.inc_nonce().decr_price());
936        pool.add_transaction(descendant_tx.clone(), 0);
937
938        assert!(pool.contains(root_tx.id()));
939        assert!(pool.contains(descendant_tx.id()));
940        assert_eq!(pool.len(), 2);
941
942        assert_eq!(pool.independent_transactions.len(), 1);
943        assert_eq!(pool.highest_nonces.len(), 1);
944
945        let removed = pool.update_base_fee(0);
946        assert!(removed.is_empty());
947
948        // two dependent tx in the pool with decreasing fee
949
950        {
951            let mut pool2 = pool.clone();
952            let removed = pool2.update_base_fee((descendant_tx.max_fee_per_gas() + 1) as u64);
953            assert_eq!(removed.len(), 1);
954            assert_eq!(pool2.len(), 1);
955            // descendant got popped
956            assert!(pool2.contains(root_tx.id()));
957            assert!(!pool2.contains(descendant_tx.id()));
958        }
959
960        // remove root transaction via fee
961        let removed = pool.update_base_fee((root_tx.max_fee_per_gas() + 1) as u64);
962        assert_eq!(removed.len(), 2);
963        assert!(pool.is_empty());
964        pool.assert_invariants();
965    }
966
967    #[test]
968    fn test_enforce_basefee_tracks_highest_nonce_of_partially_removed_sender() {
969        let mut f = MockTransactionFactory::default();
970        let mut pool = PendingPool::new(MockOrdering::default());
971
972        // sender a keeps its first transaction but its descendant is priced out
973        let a = MockTransaction::eip1559().inc_price_by(20);
974        let a0 = f.validated_arc(a.clone());
975        let a1 = f.validated_arc(a.inc_nonce().rng_hash().decr_price_by(15));
976        // sender b keeps both of its transactions
977        let b = MockTransaction::eip1559().inc_price_by(20);
978        let b0 = f.validated_arc(b.clone());
979        let b1 = f.validated_arc(b.inc_nonce().rng_hash());
980
981        for tx in [&a0, &a1, &b0, &b1] {
982            pool.add_transaction(tx.clone(), 0);
983        }
984
985        let removed = pool.update_base_fee((a1.max_fee_per_gas() + 1) as u64);
986        assert_eq!(removed.len(), 1);
987        assert_eq!(removed[0].hash(), a1.hash());
988
989        pool.assert_invariants();
990        assert_eq!(pool.highest_nonces[&a0.sender_id()].transaction.nonce(), a0.nonce());
991        assert_eq!(pool.independent_transactions[&a0.sender_id()].transaction.nonce(), a0.nonce());
992        assert_eq!(pool.highest_nonces[&b1.sender_id()].transaction.nonce(), b1.nonce());
993        assert_eq!(pool.independent_transactions[&b0.sender_id()].transaction.nonce(), b0.nonce());
994    }
995
996    #[test]
997    fn test_enforce_blobfee_tracks_highest_nonce_of_partially_removed_sender() {
998        let mut f = MockTransactionFactory::default();
999        let mut pool = PendingPool::new(MockOrdering::default());
1000
1001        // sender a keeps its first transaction but its descendant is priced out
1002        let a = MockTransaction::eip4844().with_blob_fee(150);
1003        let a0 = f.validated_arc(a.clone());
1004        let a1 = f.validated_arc(a.inc_nonce().rng_hash().with_blob_fee(50));
1005        // sender b keeps both of its transactions
1006        let b = MockTransaction::eip4844().with_blob_fee(150);
1007        let b0 = f.validated_arc(b.clone());
1008        let b1 = f.validated_arc(b.inc_nonce().rng_hash());
1009
1010        for tx in [&a0, &a1, &b0, &b1] {
1011            pool.add_transaction(tx.clone(), 0);
1012        }
1013
1014        let removed = pool.update_blob_fee(100);
1015        assert_eq!(removed.len(), 1);
1016        assert_eq!(removed[0].hash(), a1.hash());
1017        pool.assert_invariants();
1018    }
1019
1020    #[test]
1021    fn evict_worst() {
1022        let mut f = MockTransactionFactory::default();
1023        let mut pool = PendingPool::new(MockOrdering::default());
1024
1025        let t = MockTransaction::eip1559();
1026        pool.add_transaction(f.validated_arc(t.clone()), 0);
1027
1028        let t2 = MockTransaction::eip1559().inc_price_by(10);
1029        pool.add_transaction(f.validated_arc(t2), 0);
1030
1031        // First transaction should be evicted.
1032        assert_eq!(
1033            pool.highest_nonces.values().min().map(|tx| *tx.transaction.hash()),
1034            Some(*t.hash())
1035        );
1036
1037        // truncate pool with max size = 1, ensure it's the same transaction
1038        let removed = pool.truncate_pool(SubPoolLimit { max_txs: 1, max_size: usize::MAX });
1039        assert_eq!(removed.len(), 1);
1040        assert_eq!(removed[0].hash(), t.hash());
1041    }
1042
1043    #[test]
1044    fn correct_independent_descendants() {
1045        // this test ensures that we set the right highest nonces set for each sender
1046        let mut f = MockTransactionFactory::default();
1047        let mut pool = PendingPool::new(MockOrdering::default());
1048
1049        let a_sender = Address::with_last_byte(0x0a);
1050        let b_sender = Address::with_last_byte(0x0b);
1051        let c_sender = Address::with_last_byte(0x0c);
1052        let d_sender = Address::with_last_byte(0x0d);
1053
1054        // create a chain of transactions by sender A, B, C
1055        let mut tx_set = MockTransactionSet::dependent(a_sender, 0, 4, TxType::Eip1559);
1056        let a = tx_set.clone().into_vec();
1057
1058        let b = MockTransactionSet::dependent(b_sender, 0, 3, TxType::Eip1559).into_vec();
1059        tx_set.extend(b.clone());
1060
1061        // C has the same number of txs as B
1062        let c = MockTransactionSet::dependent(c_sender, 0, 3, TxType::Eip1559).into_vec();
1063        tx_set.extend(c.clone());
1064
1065        let d = MockTransactionSet::dependent(d_sender, 0, 1, TxType::Eip1559).into_vec();
1066        tx_set.extend(d.clone());
1067
1068        // add all the transactions to the pool
1069        let all_txs = tx_set.into_vec();
1070        for tx in all_txs {
1071            pool.add_transaction(f.validated_arc(tx), 0);
1072        }
1073
1074        pool.assert_invariants();
1075
1076        // the independent set is the roots of each of these tx chains, these are the highest
1077        // nonces for each sender
1078        let expected_highest_nonces = [d[0].clone(), c[2].clone(), b[2].clone(), a[3].clone()]
1079            .iter()
1080            .map(|tx| (tx.sender(), tx.nonce()))
1081            .collect::<HashSet<_>>();
1082        let actual_highest_nonces = pool
1083            .highest_nonces
1084            .values()
1085            .map(|tx| (tx.transaction.sender(), tx.transaction.nonce()))
1086            .collect::<HashSet<_>>();
1087        assert_eq!(expected_highest_nonces, actual_highest_nonces);
1088        pool.assert_invariants();
1089    }
1090
1091    #[test]
1092    fn truncate_by_sender() {
1093        // This test ensures that transactions are removed from the pending pool by sender.
1094        let mut f = MockTransactionFactory::default();
1095        let mut pool = PendingPool::new(MockOrdering::default());
1096
1097        // Addresses for simulated senders A, B, C, and D.
1098        let a = Address::with_last_byte(0x0a);
1099        let b = Address::with_last_byte(0x0b);
1100        let c = Address::with_last_byte(0x0c);
1101        let d = Address::with_last_byte(0x0d);
1102
1103        // Create transaction chains for senders A, B, C, and D.
1104        let a_txs = MockTransactionSet::sequential_transactions_by_sender(a, 4, TxType::Eip1559);
1105        let b_txs = MockTransactionSet::sequential_transactions_by_sender(b, 3, TxType::Eip1559);
1106        let c_txs = MockTransactionSet::sequential_transactions_by_sender(c, 3, TxType::Eip1559);
1107        let d_txs = MockTransactionSet::sequential_transactions_by_sender(d, 1, TxType::Eip1559);
1108
1109        // Set up expected pending transactions.
1110        let expected_pending = vec![
1111            a_txs.transactions[0].clone(),
1112            b_txs.transactions[0].clone(),
1113            c_txs.transactions[0].clone(),
1114            a_txs.transactions[1].clone(),
1115        ]
1116        .into_iter()
1117        .map(|tx| (tx.sender(), tx.nonce()))
1118        .collect::<HashSet<_>>();
1119
1120        // Set up expected removed transactions, in the order of removal.
1121        let expected_removed = vec![
1122            d_txs.transactions[0].clone(),
1123            c_txs.transactions[2].clone(),
1124            b_txs.transactions[2].clone(),
1125            a_txs.transactions[3].clone(),
1126            c_txs.transactions[1].clone(),
1127            b_txs.transactions[1].clone(),
1128            a_txs.transactions[2].clone(),
1129        ]
1130        .into_iter()
1131        .map(|tx| (tx.sender(), tx.nonce()))
1132        .collect::<Vec<_>>();
1133
1134        // Consolidate all transactions into a single vector.
1135        let all_txs =
1136            [a_txs.into_vec(), b_txs.into_vec(), c_txs.into_vec(), d_txs.into_vec()].concat();
1137
1138        // Add all the transactions to the pool.
1139        for tx in all_txs {
1140            pool.add_transaction(f.validated_arc(tx), 0);
1141        }
1142
1143        // Sanity check, ensuring everything is consistent.
1144        pool.assert_invariants();
1145
1146        // Define the maximum total transactions to be 4, removing transactions for each sender.
1147        // Expected order of removal:
1148        // * d1, c3, b3, a4
1149        // * c2, b2, a3
1150        //
1151        // Remaining transactions:
1152        // * a1, a2
1153        // * b1
1154        // * c1
1155        let pool_limit = SubPoolLimit { max_txs: 4, max_size: usize::MAX };
1156
1157        // Truncate the pool based on the defined limit.
1158        let removed = pool.truncate_pool(pool_limit);
1159        pool.assert_invariants();
1160        assert_eq!(removed.len(), expected_removed.len());
1161
1162        // Get the removed transactions and compare with the expected order of removal.
1163        let removed = removed.into_iter().map(|tx| (tx.sender(), tx.nonce())).collect::<Vec<_>>();
1164        assert_eq!(removed, expected_removed);
1165
1166        // Retrieve the current pending transactions after truncation.
1167        let pending = pool.all().collect::<Vec<_>>();
1168        assert_eq!(pending.len(), expected_pending.len());
1169
1170        // Get the set of pending transactions and compare with the expected set.
1171        let pending =
1172            pending.into_iter().map(|tx| (tx.sender(), tx.nonce())).collect::<HashSet<_>>();
1173        assert_eq!(pending, expected_pending);
1174    }
1175
1176    #[test]
1177    fn truncate_by_size() {
1178        let mut f = MockTransactionFactory::default();
1179        let mut pool = PendingPool::new(MockOrdering::default());
1180
1181        // Sender a ranks below senders b and c. Its first tx is large and its second tx is small.
1182        let a = MockTransaction::eip1559().with_size(100);
1183        let a0 = f.validated_arc(a.clone());
1184        let a1 = f.validated_arc(a.inc_nonce().rng_hash().with_size(1));
1185        let b0 = f.validated_arc(MockTransaction::eip1559().inc_price_by(10).with_size(1));
1186        let c0 = f.validated_arc(MockTransaction::eip1559().inc_price_by(20).with_size(1));
1187        for tx in [&a0, &a1, &b0, &c0] {
1188            pool.add_transaction(tx.clone(), 0);
1189        }
1190        pool.assert_invariants();
1191
1192        // The size excess is below the average tx size, so each pass removes one tx. The first
1193        // pass removes a1, which does not free enough, and the second pass removes a0.
1194        let removed = pool.truncate_pool(SubPoolLimit { max_txs: usize::MAX, max_size: 101 });
1195        pool.assert_invariants();
1196
1197        assert_eq!(removed.len(), 2);
1198        assert_eq!(removed[0].hash(), a1.hash());
1199        assert_eq!(removed[1].hash(), a0.hash());
1200        assert_eq!(pool.size(), 2);
1201    }
1202
1203    #[test]
1204    fn truncate_skips_local_heads_ranked_below_non_local() {
1205        let mut f = MockTransactionFactory::default();
1206        let mut pool = PendingPool::new(MockOrdering::default());
1207
1208        // many local senders that rank below every non-local sender
1209        let num_locals = 3_000;
1210        for _ in 0..num_locals {
1211            let tx = f.validated_with_origin(TransactionOrigin::Local, MockTransaction::eip1559());
1212            pool.add_transaction(Arc::new(tx), 0);
1213        }
1214
1215        let non_locals: Vec<_> = (1..=3u128)
1216            .map(|i| {
1217                let tx = f.validated_arc(MockTransaction::eip1559().inc_price_by(10 * i));
1218                pool.add_transaction(tx.clone(), 0);
1219                tx
1220            })
1221            .collect();
1222        pool.assert_invariants();
1223
1224        let removed =
1225            pool.truncate_pool(SubPoolLimit { max_txs: num_locals + 2, max_size: usize::MAX });
1226        pool.assert_invariants();
1227
1228        assert_eq!(removed.len(), 1);
1229        assert_eq!(removed[0].hash(), non_locals[0].hash());
1230        assert_eq!(pool.len(), num_locals + 2);
1231    }
1232
1233    #[test]
1234    fn truncate_removes_non_local_head_above_local_tx() {
1235        let mut f = MockTransactionFactory::default();
1236        let mut pool = PendingPool::new(MockOrdering::default());
1237
1238        // the sender's highest nonce tx is non-local, so it is removed even though a local tx
1239        // of the same sender stays behind
1240        let local = MockTransaction::eip1559();
1241        let local_tx = f.validated_with_origin(TransactionOrigin::Local, local.clone());
1242        let head_tx = f.validated_arc(local.inc_nonce().rng_hash());
1243        pool.add_transaction(Arc::new(local_tx), 0);
1244        pool.add_transaction(head_tx.clone(), 0);
1245
1246        let removed = pool.truncate_pool(SubPoolLimit { max_txs: 1, max_size: usize::MAX });
1247        pool.assert_invariants();
1248
1249        assert_eq!(removed.len(), 1);
1250        assert_eq!(removed[0].hash(), head_tx.hash());
1251        assert_eq!(pool.len(), 1);
1252    }
1253
1254    #[test]
1255    fn remove_to_limit_merges_local_and_non_local_heads() {
1256        let mut f = MockTransactionFactory::default();
1257        let mut pool = PendingPool::new(MockOrdering::default());
1258
1259        // The highest nonce txs rank a1 (local), m1 (local), b0 (non-local), c0 (local). Once a1
1260        // and m1 are removed, the non-local m0 ranks below the local a0.
1261        let a = MockTransaction::eip1559();
1262        let m = MockTransaction::eip1559();
1263        let [a0, a1, m0, m1, b0, c0] = [
1264            (TransactionOrigin::Local, a.clone().with_gas_price(40)),
1265            (TransactionOrigin::Local, a.inc_nonce().rng_hash().with_gas_price(10)),
1266            (TransactionOrigin::External, m.clone().with_gas_price(25)),
1267            (TransactionOrigin::Local, m.inc_nonce().rng_hash().with_gas_price(20)),
1268            (TransactionOrigin::External, MockTransaction::eip1559().with_gas_price(30)),
1269            (TransactionOrigin::Local, MockTransaction::eip1559().with_gas_price(50)),
1270        ]
1271        .map(|(origin, tx)| {
1272            let tx = Arc::new(f.validated_with_origin(origin, tx));
1273            pool.add_transaction(tx.clone(), 0);
1274            tx
1275        });
1276        pool.assert_invariants();
1277
1278        let limit = SubPoolLimit { max_txs: 1, max_size: usize::MAX };
1279        let mut removed = Vec::new();
1280        pool.remove_to_limit(&limit, true, &mut removed);
1281        pool.assert_invariants();
1282
1283        // The first pass removes the four highest nonce txs. The second pass removes m0.
1284        let removed = removed.iter().map(|tx| *tx.id()).collect::<Vec<_>>();
1285        assert_eq!(removed, [a1, m1, b0, c0, m0].map(|tx| *tx.id()));
1286        assert!(pool.contains(a0.id()));
1287        assert_eq!(pool.len(), 1);
1288    }
1289
1290    #[test]
1291    fn truncate_follows_updates_of_highest_nonces() {
1292        let mut f = MockTransactionFactory::default();
1293        let mut pool = PendingPool::new(MockOrdering::default());
1294        let limit = |max_txs| SubPoolLimit { max_txs, max_size: usize::MAX };
1295        let mock = |max_fee, priority_fee| {
1296            MockTransaction::eip1559().with_max_fee(max_fee).with_priority_fee(priority_fee)
1297        };
1298        let next = |tx: &MockValidTx, priority_fee| {
1299            tx.transaction.clone().inc_nonce().rng_hash().with_priority_fee(priority_fee)
1300        };
1301
1302        let a0 = f.validated_arc(mock(100, 50));
1303        let a1 = f.validated_arc(next(&a0, 40));
1304        let b0 = f.validated_arc(mock(100, 30));
1305        let c0 = f.validated_arc(mock(100, 10));
1306        for tx in [&a0, &a1, &b0, &c0] {
1307            pool.add_transaction(tx.clone(), 0);
1308        }
1309
1310        // The first truncation builds `highest_nonces_by_priority`.
1311        let removed = pool.truncate_pool(limit(3));
1312        pool.assert_invariants();
1313        assert_eq!(removed.len(), 1);
1314        assert_eq!(removed[0].id(), c0.id());
1315
1316        // Add a new sender and the next nonce of a sender. Remove one highest nonce tx that has
1317        // a lower nonce tx below it and one that has none.
1318        let d0 = f.validated_arc(mock(100, 20));
1319        let b1 = f.validated_arc(next(&b0, 15));
1320        let e0 = f.validated_arc(mock(100, 5));
1321        for tx in [&d0, &b1, &e0] {
1322            pool.add_transaction(tx.clone(), 0);
1323            pool.assert_invariants();
1324        }
1325        for tx in [&a1, &e0] {
1326            pool.remove_transaction(tx.id());
1327            pool.assert_invariants();
1328        }
1329
1330        // The highest nonce txs now rank b1, d0, a0.
1331        let removed = pool.truncate_pool(limit(2));
1332        pool.assert_invariants();
1333        let removed = removed.iter().map(|tx| *tx.id()).collect::<Vec<_>>();
1334        assert_eq!(removed, [*b1.id(), *d0.id()]);
1335
1336        // The fee update removes h0 and moves g0 below b0.
1337        let g0 = f.validated_arc(mock(40, 40));
1338        let h0 = f.validated_arc(mock(12, 12));
1339        for tx in [&g0, &h0] {
1340            pool.add_transaction(tx.clone(), 0);
1341        }
1342        let removed = pool.update_base_fee(20);
1343        pool.assert_invariants();
1344        assert_eq!(removed.len(), 1);
1345        assert_eq!(removed[0].id(), h0.id());
1346
1347        let removed = pool.truncate_pool(limit(2));
1348        pool.assert_invariants();
1349        assert_eq!(removed.len(), 1);
1350        assert_eq!(removed[0].id(), g0.id());
1351
1352        // Changes made while the order is dropped are part of the next build.
1353        pool.clear_highest_nonces_by_priority();
1354        let i0 = f.validated_arc(mock(100, 5));
1355        pool.add_transaction(i0.clone(), 20);
1356        pool.assert_invariants();
1357        let removed = pool.truncate_pool(limit(2));
1358        pool.assert_invariants();
1359        assert_eq!(removed.len(), 1);
1360        assert_eq!(removed[0].id(), i0.id());
1361    }
1362
1363    #[test]
1364    fn local_config_change_rebuilds_eviction_order() {
1365        let mut f = MockTransactionFactory::default();
1366        let mut pool = PendingPool::new(MockOrdering::default());
1367        let limit = |max_txs| SubPoolLimit { max_txs, max_size: usize::MAX };
1368
1369        // The local tx pays the lowest price.
1370        let local = Arc::new(f.validated_with_origin(
1371            TransactionOrigin::Local,
1372            MockTransaction::eip1559().with_gas_price(10),
1373        ));
1374        let [b0, c0] =
1375            [20, 30].map(|price| f.validated_arc(MockTransaction::eip1559().with_gas_price(price)));
1376        for tx in [&local, &b0, &c0] {
1377            pool.add_transaction(tx.clone(), 0);
1378        }
1379
1380        // The first truncation builds the order with the local tx exempt.
1381        let removed = pool.truncate_pool(limit(2));
1382        assert_eq!(removed.len(), 1);
1383        assert_eq!(removed[0].id(), b0.id());
1384
1385        // Without exemptions, the local tx is the worst.
1386        let mut pool = pool.with_local_transactions_config(Arc::new(LocalTransactionConfig {
1387            no_exemptions: true,
1388            ..Default::default()
1389        }));
1390        pool.assert_invariants();
1391        let removed = pool.truncate_pool(limit(1));
1392        pool.assert_invariants();
1393        assert_eq!(removed.len(), 1);
1394        assert_eq!(removed[0].id(), local.id());
1395    }
1396
1397    #[test]
1398    fn built_eviction_order_follows_local_addresses() {
1399        let mut f = MockTransactionFactory::default();
1400        let limit = |max_txs| SubPoolLimit { max_txs, max_size: usize::MAX };
1401
1402        // Both senders are local by address only and pay the lowest price.
1403        let l = MockTransaction::eip1559().with_gas_price(10);
1404        let m = MockTransaction::eip1559().with_gas_price(10);
1405        let mut pool = PendingPool::new(MockOrdering::default()).with_local_transactions_config(
1406            Arc::new(LocalTransactionConfig {
1407                local_addresses: [l.sender(), m.sender()].into_iter().collect(),
1408                ..Default::default()
1409            }),
1410        );
1411        let l0 = f.validated_arc(l.clone());
1412        let l1 = f.validated_arc(l.inc_nonce().rng_hash());
1413        let m0 = f.validated_arc(m);
1414        let [b0, c0] =
1415            [20, 30].map(|price| f.validated_arc(MockTransaction::eip1559().with_gas_price(price)));
1416        for tx in [&l0, &b0, &c0] {
1417            pool.add_transaction(tx.clone(), 0);
1418        }
1419
1420        // The first truncation builds the order.
1421        let removed = pool.truncate_pool(limit(2));
1422        pool.assert_invariants();
1423        assert_eq!(removed[0].id(), b0.id());
1424
1425        // Every later change of a sender's highest nonce keeps it in the local set.
1426        pool.add_transaction(l1.clone(), 0);
1427        pool.assert_invariants();
1428        pool.add_transaction(m0, 0);
1429        pool.assert_invariants();
1430        pool.remove_transaction(l1.id());
1431        pool.assert_invariants();
1432        let removed = pool.truncate_pool(limit(2));
1433        pool.assert_invariants();
1434        assert_eq!(removed[0].id(), c0.id());
1435    }
1436
1437    // <https://github.com/paradigmxyz/reth/issues/12340>
1438    #[test]
1439    fn test_eligible_updates_promoted() {
1440        let mut pool = PendingPool::new(MockOrdering::default());
1441        let mut f = MockTransactionFactory::default();
1442
1443        let num_senders = 10;
1444
1445        let first_txs: Vec<_> = (0..num_senders) //
1446            .map(|_| MockTransaction::eip1559())
1447            .collect();
1448        let second_txs: Vec<_> =
1449            first_txs.iter().map(|tx| tx.clone().rng_hash().inc_nonce()).collect();
1450
1451        for tx in first_txs {
1452            let valid_tx = f.validated(tx);
1453            pool.add_transaction(Arc::new(valid_tx), 0);
1454        }
1455
1456        let mut best = pool.best();
1457
1458        for _ in 0..num_senders {
1459            if let Some(tx) = best.next() {
1460                assert_eq!(tx.nonce(), 0);
1461            } else {
1462                panic!("cannot read one of first_txs");
1463            }
1464        }
1465
1466        for tx in second_txs {
1467            let valid_tx = f.validated(tx);
1468            pool.add_transaction(Arc::new(valid_tx), 0);
1469        }
1470
1471        for _ in 0..num_senders {
1472            if let Some(tx) = best.next() {
1473                assert_eq!(tx.nonce(), 1);
1474            } else {
1475                panic!("cannot read one of second_txs");
1476            }
1477        }
1478    }
1479
1480    #[test]
1481    fn test_empty_pool_behavior() {
1482        let mut pool = PendingPool::<MockOrdering>::new(MockOrdering::default());
1483
1484        // Ensure the pool is empty
1485        assert!(pool.is_empty());
1486        assert_eq!(pool.len(), 0);
1487        assert_eq!(pool.size(), 0);
1488
1489        // Verify that attempting to truncate an empty pool does not panic and returns an empty vec
1490        let removed = pool.truncate_pool(SubPoolLimit { max_txs: 10, max_size: 1000 });
1491        assert!(removed.is_empty());
1492
1493        // Verify that retrieving transactions from an empty pool yields nothing
1494        assert!(pool.all().next().is_none());
1495    }
1496
1497    #[test]
1498    fn test_add_remove_transaction() {
1499        let mut f = MockTransactionFactory::default();
1500        let mut pool = PendingPool::new(MockOrdering::default());
1501
1502        // Add a transaction and check if it's in the pool
1503        let tx = f.validated_arc(MockTransaction::eip1559());
1504        pool.add_transaction(tx.clone(), 0);
1505        assert!(pool.contains(tx.id()));
1506        assert_eq!(pool.len(), 1);
1507
1508        // Remove the transaction and ensure it's no longer in the pool
1509        let removed_tx = pool.remove_transaction(tx.id()).unwrap();
1510        assert_eq!(removed_tx.id(), tx.id());
1511        assert!(!pool.contains(tx.id()));
1512        assert_eq!(pool.len(), 0);
1513    }
1514
1515    #[test]
1516    fn test_reorder_on_basefee_update() {
1517        let mut f = MockTransactionFactory::default();
1518        let mut pool = PendingPool::new(MockOrdering::default());
1519
1520        // Add two transactions with different fees
1521        let tx1 = f.validated_arc(MockTransaction::eip1559().inc_price());
1522        let tx2 = f.validated_arc(MockTransaction::eip1559().inc_price_by(20));
1523        pool.add_transaction(tx1.clone(), 0);
1524        pool.add_transaction(tx2.clone(), 0);
1525
1526        // Ensure the transactions are in the correct order
1527        let mut best = pool.best();
1528        assert_eq!(best.next().unwrap().hash(), tx2.hash());
1529        assert_eq!(best.next().unwrap().hash(), tx1.hash());
1530
1531        // Update the base fee to a value higher than tx1's fee, causing it to be removed
1532        let removed = pool.update_base_fee((tx1.max_fee_per_gas() + 1) as u64);
1533        assert_eq!(removed.len(), 1);
1534        assert_eq!(removed[0].hash(), tx1.hash());
1535
1536        // Verify that only tx2 remains in the pool
1537        assert_eq!(pool.len(), 1);
1538        assert!(pool.contains(tx2.id()));
1539        assert!(!pool.contains(tx1.id()));
1540    }
1541
1542    #[test]
1543    #[cfg(debug_assertions)]
1544    #[should_panic(expected = "transaction already included")]
1545    fn test_handle_duplicates() {
1546        let mut f = MockTransactionFactory::default();
1547        let mut pool = PendingPool::new(MockOrdering::default());
1548
1549        // Add the same transaction twice and ensure it only appears once
1550        let tx = f.validated_arc(MockTransaction::eip1559());
1551        pool.add_transaction(tx.clone(), 0);
1552        assert!(pool.contains(tx.id()));
1553        assert_eq!(pool.len(), 1);
1554
1555        // Attempt to add the same transaction again, which should be ignored
1556        pool.add_transaction(tx, 0);
1557    }
1558
1559    #[test]
1560    fn test_update_blob_fee() {
1561        let mut f = MockTransactionFactory::default();
1562        let mut pool = PendingPool::new(MockOrdering::default());
1563
1564        // Add transactions with varying blob fees
1565        let tx1 = f.validated_arc(MockTransaction::eip4844().set_blob_fee(50).clone());
1566        let tx2 = f.validated_arc(MockTransaction::eip4844().set_blob_fee(150).clone());
1567        pool.add_transaction(tx1.clone(), 0);
1568        pool.add_transaction(tx2.clone(), 0);
1569
1570        // Update the blob fee to a value that causes tx1 to be removed
1571        let removed = pool.update_blob_fee(100);
1572        assert_eq!(removed.len(), 1);
1573        assert_eq!(removed[0].hash(), tx1.hash());
1574
1575        // Verify that only tx2 remains in the pool
1576        assert!(pool.contains(tx2.id()));
1577        assert!(!pool.contains(tx1.id()));
1578    }
1579
1580    #[test]
1581    fn removing_the_lowest_nonce_past_a_gap_keeps_the_next_one_independent() {
1582        let mut f = MockTransactionFactory::default();
1583        let mut pool = PendingPool::new(MockOrdering::default());
1584
1585        let t0 = MockTransaction::eip1559();
1586        let t1 = t0.next();
1587        let t2 = t1.next();
1588        let [v0, v1, v2] = [t0, t1, t2].map(|tx| f.validated_arc(tx));
1589        for tx in [&v0, &v1, &v2] {
1590            pool.add_transaction(tx.clone(), 0);
1591        }
1592
1593        // A canonical update prunes the mined nonce 1 before it discards the stale nonce 0.
1594        pool.remove_transaction(v1.id());
1595        pool.remove_transaction(v0.id());
1596        pool.assert_invariants();
1597        assert_eq!(pool.best().next().map(|tx| *tx.id()), Some(*v2.id()));
1598    }
1599
1600    #[test]
1601    fn update_blob_fee_keeps_transactions_that_satisfy_the_fee() {
1602        let mut f = MockTransactionFactory::default();
1603        let mut pool = PendingPool::new(MockOrdering::default());
1604
1605        let blob = f.validated_arc(MockTransaction::eip4844().with_blob_fee(150));
1606        // A transaction without blobs has no blob fee to compare.
1607        let plain = f.validated_arc(MockTransaction::eip1559());
1608        for tx in [&blob, &plain] {
1609            pool.add_transaction(tx.clone(), 0);
1610        }
1611
1612        assert!(pool.update_blob_fee(100).is_empty());
1613        assert_eq!(pool.len(), 2);
1614        pool.assert_invariants();
1615    }
1616
1617    #[test]
1618    fn local_senders_tracking() {
1619        let mut f = MockTransactionFactory::default();
1620        let mut pool = PendingPool::new(MockOrdering::default());
1621
1622        // Addresses for simulated senders A, B, C
1623        let a = Address::with_last_byte(0x0a);
1624        let b = Address::with_last_byte(0x0b);
1625        let c = Address::with_last_byte(0x0c);
1626
1627        // sender A (local) - 11+ transactions (large enough to keep limit exceeded)
1628        // sender B (external) - 2 transactions
1629        // sender C (external) - 2 transactions
1630
1631        // Create transaction chains for senders A, B, C
1632        let a_txs = MockTransactionSet::sequential_transactions_by_sender(a, 11, TxType::Eip1559);
1633        let b_txs = MockTransactionSet::sequential_transactions_by_sender(b, 2, TxType::Eip1559);
1634        let c_txs = MockTransactionSet::sequential_transactions_by_sender(c, 2, TxType::Eip1559);
1635
1636        // create local txs for sender A
1637        for tx in a_txs.into_vec() {
1638            let final_tx = Arc::new(f.validated_with_origin(crate::TransactionOrigin::Local, tx));
1639
1640            pool.add_transaction(final_tx, 0);
1641        }
1642
1643        // create external txs for senders B and C
1644        let remaining_txs = [b_txs.into_vec(), c_txs.into_vec()].concat();
1645        for tx in remaining_txs {
1646            let final_tx = f.validated_arc(tx);
1647
1648            pool.add_transaction(final_tx, 0);
1649        }
1650
1651        // Sanity check, ensuring everything is consistent.
1652        pool.assert_invariants();
1653
1654        let pool_limit = SubPoolLimit { max_txs: 10, max_size: usize::MAX };
1655        pool.truncate_pool(pool_limit);
1656
1657        let sender_a = f.ids.sender_id(&a).unwrap();
1658        let sender_b = f.ids.sender_id(&b).unwrap();
1659        let sender_c = f.ids.sender_id(&c).unwrap();
1660
1661        assert_eq!(pool.get_txs_by_sender(sender_a).len(), 10);
1662        assert!(pool.get_txs_by_sender(sender_b).is_empty());
1663        assert!(pool.get_txs_by_sender(sender_c).is_empty());
1664    }
1665
1666    #[test]
1667    fn test_remove_non_highest_keeps_highest() {
1668        let mut f = MockTransactionFactory::default();
1669        let mut pool = PendingPool::new(MockOrdering::default());
1670        let sender = Address::with_last_byte(0xaa);
1671        let txs = MockTransactionSet::dependent(sender, 0, 3, TxType::Eip1559).into_vec();
1672        for tx in txs {
1673            pool.add_transaction(f.validated_arc(tx), 0);
1674        }
1675        pool.assert_invariants();
1676        let sender_id = f.ids.sender_id(&sender).unwrap();
1677        let mid_id = TransactionId::new(sender_id, 1);
1678        let _ = pool.remove_transaction(&mid_id);
1679        let highest = pool.highest_nonces.get(&sender_id).unwrap();
1680        assert_eq!(highest.transaction.nonce(), 2);
1681        pool.assert_invariants();
1682    }
1683
1684    #[test]
1685    fn test_cascade_removal_recomputes_highest() {
1686        let mut f = MockTransactionFactory::default();
1687        let mut pool = PendingPool::new(MockOrdering::default());
1688        let sender = Address::with_last_byte(0xbb);
1689        let txs = MockTransactionSet::dependent(sender, 0, 4, TxType::Eip1559).into_vec();
1690        for tx in txs {
1691            pool.add_transaction(f.validated_arc(tx), 0);
1692        }
1693        pool.assert_invariants();
1694        let sender_id = f.ids.sender_id(&sender).unwrap();
1695        let id3 = TransactionId::new(sender_id, 3);
1696        let _ = pool.remove_transaction(&id3);
1697        let highest = pool.highest_nonces.get(&sender_id).unwrap();
1698        assert_eq!(highest.transaction.nonce(), 2);
1699        let id2 = TransactionId::new(sender_id, 2);
1700        let _ = pool.remove_transaction(&id2);
1701        let highest = pool.highest_nonces.get(&sender_id).unwrap();
1702        assert_eq!(highest.transaction.nonce(), 1);
1703        pool.assert_invariants();
1704    }
1705
1706    #[test]
1707    fn test_remove_only_tx_clears_highest() {
1708        let mut f = MockTransactionFactory::default();
1709        let mut pool = PendingPool::new(MockOrdering::default());
1710        let sender = Address::with_last_byte(0xcc);
1711        let txs = MockTransactionSet::dependent(sender, 0, 1, TxType::Eip1559).into_vec();
1712        for tx in txs {
1713            pool.add_transaction(f.validated_arc(tx), 0);
1714        }
1715        pool.assert_invariants();
1716        let sender_id = f.ids.sender_id(&sender).unwrap();
1717        let id0 = TransactionId::new(sender_id, 0);
1718        let _ = pool.remove_transaction(&id0);
1719        assert!(!pool.highest_nonces.contains_key(&sender_id));
1720        pool.assert_invariants();
1721    }
1722}