reth_transaction_pool/pool/
pending.rs

1use crate::{
2    identifier::{SenderId, TransactionId},
3    pool::{
4        best::{BestTransactions, BestTransactionsWithFees},
5        size::SizeTracker,
6    },
7    Priority, SubPoolLimit, TransactionOrdering, ValidPoolTransaction,
8};
9use rustc_hash::FxHashMap;
10use std::{
11    cmp::Ordering,
12    collections::{hash_map::Entry, BTreeMap},
13    ops::Bound::Unbounded,
14    sync::Arc,
15};
16use tokio::sync::broadcast;
17
18/// A pool of validated and gapless transactions that are ready to be executed on the current state
19/// and are waiting to be included in a block.
20///
21/// This pool distinguishes between `independent` transactions and pending transactions. A
22/// transaction is `independent`, if it is in the pending pool, and it has the current on chain
23/// nonce of the sender. Meaning `independent` transactions can be executed right away, other
24/// pending transactions depend on at least one `independent` transaction.
25///
26/// Once an `independent` transaction was executed it *unlocks* the next nonce, if this transaction
27/// is also pending, then this will be moved to the `independent` queue.
28#[derive(Debug, Clone)]
29pub struct PendingPool<T: TransactionOrdering> {
30    /// How to order transactions.
31    ordering: T,
32    /// Keeps track of transactions inserted in the pool.
33    ///
34    /// This way we can determine when transactions were submitted to the pool.
35    submission_id: u64,
36    /// _All_ Transactions that are currently inside the pool grouped by their identifier.
37    by_id: BTreeMap<TransactionId, PendingTransaction<T>>,
38    /// The highest nonce transactions for each sender - like the `independent` set, but the
39    /// highest instead of lowest nonce.
40    highest_nonces: FxHashMap<SenderId, PendingTransaction<T>>,
41    /// Independent transactions that can be included directly and don't require other
42    /// transactions.
43    independent_transactions: FxHashMap<SenderId, PendingTransaction<T>>,
44    /// Keeps track of the size of this pool.
45    ///
46    /// See also [`PoolTransaction::size`](crate::traits::PoolTransaction::size).
47    size_of: SizeTracker,
48    /// Used to broadcast new transactions that have been added to the `PendingPool` to existing
49    /// `static_files` of this pool.
50    new_transaction_notifier: broadcast::Sender<PendingTransaction<T>>,
51}
52
53// === impl PendingPool ===
54
55impl<T: TransactionOrdering> PendingPool<T> {
56    /// Create a new pool instance.
57    pub fn new(ordering: T) -> Self {
58        let (new_transaction_notifier, _) = broadcast::channel(200);
59        Self {
60            ordering,
61            submission_id: 0,
62            by_id: Default::default(),
63            independent_transactions: Default::default(),
64            highest_nonces: Default::default(),
65            size_of: Default::default(),
66            new_transaction_notifier,
67        }
68    }
69
70    /// Clear all transactions from the pool without resetting other values.
71    /// Used for atomic reordering during basefee update.
72    ///
73    /// # Returns
74    ///
75    /// Returns all transactions by id.
76    fn clear_transactions(&mut self) -> BTreeMap<TransactionId, PendingTransaction<T>> {
77        self.independent_transactions.clear();
78        self.highest_nonces.clear();
79        self.size_of.reset();
80        std::mem::take(&mut self.by_id)
81    }
82
83    /// Returns an iterator over all transactions that are _currently_ ready.
84    ///
85    /// 1. The iterator _always_ returns transactions in order: it never returns a transaction with
86    ///    an unsatisfied dependency and only returns them if dependency transaction were yielded
87    ///    previously. In other words: the nonces of transactions with the same sender will _always_
88    ///    increase by exactly 1.
89    ///
90    /// The order of transactions which satisfy (1.) is determined by their computed priority: a
91    /// transaction with a higher priority is returned before a transaction with a lower priority.
92    ///
93    /// If two transactions have the same priority score, then the transactions which spent more
94    /// time in pool (were added earlier) are returned first.
95    ///
96    /// NOTE: while this iterator returns transaction that pool considers valid at this point, they
97    /// could potentially be become invalid at point of execution. Therefore, this iterator
98    /// provides a way to mark transactions that the consumer of this iterator considers invalid. In
99    /// which case the transaction's subgraph is also automatically marked invalid, See (1.).
100    /// Invalid transactions are skipped.
101    pub(crate) fn best(&self) -> BestTransactions<T> {
102        BestTransactions {
103            all: self.by_id.clone(),
104            independent: self.independent_transactions.values().cloned().collect(),
105            invalid: Default::default(),
106            new_transaction_receiver: Some(self.new_transaction_notifier.subscribe()),
107            skip_blobs: false,
108        }
109    }
110
111    /// Same as `best` but only returns transactions that satisfy the given basefee and blobfee.
112    pub(crate) fn best_with_basefee_and_blobfee(
113        &self,
114        base_fee: u64,
115        base_fee_per_blob_gas: u64,
116    ) -> BestTransactionsWithFees<T> {
117        BestTransactionsWithFees { best: self.best(), base_fee, base_fee_per_blob_gas }
118    }
119
120    /// Same as `best` but also includes the given unlocked transactions.
121    ///
122    /// This mimics the [`Self::add_transaction`] method, but does not insert the transactions into
123    /// pool but only into the returned iterator.
124    ///
125    /// Note: this does not insert the unlocked transactions into the pool.
126    ///
127    /// # Panics
128    ///
129    /// if the transaction is already included
130    pub(crate) fn best_with_unlocked(
131        &self,
132        unlocked: Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
133        base_fee: u64,
134    ) -> BestTransactions<T> {
135        let mut best = self.best();
136        let mut submission_id = self.submission_id;
137        for tx in unlocked {
138            submission_id += 1;
139            debug_assert!(!best.all.contains_key(tx.id()), "transaction already included");
140            let priority = self.ordering.priority(&tx.transaction, base_fee);
141            let tx_id = *tx.id();
142            let transaction = PendingTransaction { submission_id, transaction: tx, priority };
143            if best.ancestor(&tx_id).is_none() {
144                best.independent.insert(transaction.clone());
145            }
146            best.all.insert(tx_id, transaction);
147        }
148
149        best
150    }
151
152    /// Returns an iterator over all transactions in the pool
153    pub(crate) fn all(
154        &self,
155    ) -> impl Iterator<Item = Arc<ValidPoolTransaction<T::Transaction>>> + '_ {
156        self.by_id.values().map(|tx| tx.transaction.clone())
157    }
158
159    /// Updates the pool with the new blob fee. Removes
160    /// from the subpool all transactions and their dependents that no longer satisfy the given
161    /// blob fee (`tx.max_blob_fee < blob_fee`).
162    ///
163    /// Note: the transactions are not returned in a particular order.
164    ///
165    /// # Returns
166    ///
167    /// Removed transactions that no longer satisfy the blob fee.
168    pub(crate) fn update_blob_fee(
169        &mut self,
170        blob_fee: u128,
171    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
172        // Create a collection for removed transactions.
173        let mut removed = Vec::new();
174
175        // Drain and iterate over all transactions.
176        let mut transactions_iter = self.clear_transactions().into_iter().peekable();
177        while let Some((id, tx)) = transactions_iter.next() {
178            if tx.transaction.max_fee_per_blob_gas() < Some(blob_fee) {
179                // Add this tx to the removed collection since it no longer satisfies the blob fee
180                // condition. Decrease the total pool size.
181                removed.push(Arc::clone(&tx.transaction));
182
183                // Remove all dependent transactions.
184                'this: while let Some((next_id, next_tx)) = transactions_iter.peek() {
185                    if next_id.sender != id.sender {
186                        break 'this
187                    }
188                    removed.push(Arc::clone(&next_tx.transaction));
189                    transactions_iter.next();
190                }
191            } else {
192                self.size_of += tx.transaction.size();
193                self.update_independents_and_highest_nonces(&tx);
194                self.by_id.insert(id, tx);
195            }
196        }
197
198        removed
199    }
200
201    /// Updates the pool with the new base fee. Reorders transactions by new priorities. Removes
202    /// from the subpool all transactions and their dependents that no longer satisfy the given
203    /// base fee (`tx.fee < base_fee`).
204    ///
205    /// Note: the transactions are not returned in a particular order.
206    ///
207    /// # Returns
208    ///
209    /// Removed transactions that no longer satisfy the base fee.
210    pub(crate) fn update_base_fee(
211        &mut self,
212        base_fee: u64,
213    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
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        while let Some((id, mut tx)) = transactions_iter.next() {
220            if tx.transaction.max_fee_per_gas() < base_fee as u128 {
221                // Add this tx to the removed collection since it no longer satisfies the base fee
222                // condition. Decrease the total pool size.
223                removed.push(Arc::clone(&tx.transaction));
224
225                // Remove all dependent transactions.
226                'this: while let Some((next_id, next_tx)) = transactions_iter.peek() {
227                    if next_id.sender != id.sender {
228                        break 'this
229                    }
230                    removed.push(Arc::clone(&next_tx.transaction));
231                    transactions_iter.next();
232                }
233            } else {
234                // Re-insert the transaction with new priority.
235                tx.priority = self.ordering.priority(&tx.transaction.transaction, base_fee);
236
237                self.size_of += tx.transaction.size();
238                self.update_independents_and_highest_nonces(&tx);
239                self.by_id.insert(id, tx);
240            }
241        }
242
243        removed
244    }
245
246    /// Updates the independent transaction and highest nonces set, assuming the given transaction
247    /// is being _added_ to the pool.
248    fn update_independents_and_highest_nonces(&mut self, tx: &PendingTransaction<T>) {
249        match self.highest_nonces.entry(tx.transaction.sender_id()) {
250            Entry::Occupied(mut entry) => {
251                if entry.get().transaction.nonce() < tx.transaction.nonce() {
252                    *entry.get_mut() = tx.clone();
253                }
254            }
255            Entry::Vacant(entry) => {
256                entry.insert(tx.clone());
257            }
258        }
259        match self.independent_transactions.entry(tx.transaction.sender_id()) {
260            Entry::Occupied(mut entry) => {
261                if entry.get().transaction.nonce() > tx.transaction.nonce() {
262                    *entry.get_mut() = tx.clone();
263                }
264            }
265            Entry::Vacant(entry) => {
266                entry.insert(tx.clone());
267            }
268        }
269    }
270
271    /// Returns the ancestor the given transaction, the transaction with `nonce - 1`.
272    ///
273    /// Note: for a transaction with nonce higher than the current on chain nonce this will always
274    /// return an ancestor since all transaction in this pool are gapless.
275    fn ancestor(&self, id: &TransactionId) -> Option<&PendingTransaction<T>> {
276        self.get(&id.unchecked_ancestor()?)
277    }
278
279    /// Adds a new transactions to the pending queue.
280    ///
281    /// # Panics
282    ///
283    /// if the transaction is already included
284    pub fn add_transaction(
285        &mut self,
286        tx: Arc<ValidPoolTransaction<T::Transaction>>,
287        base_fee: u64,
288    ) {
289        assert!(
290            !self.contains(tx.id()),
291            "transaction already included {:?}",
292            self.get(tx.id()).unwrap().transaction
293        );
294
295        // keep track of size
296        self.size_of += tx.size();
297
298        let tx_id = *tx.id();
299
300        let submission_id = self.next_id();
301        let priority = self.ordering.priority(&tx.transaction, base_fee);
302        let tx = PendingTransaction { submission_id, transaction: tx, priority };
303
304        self.update_independents_and_highest_nonces(&tx);
305
306        // send the new transaction to any existing pendingpool static file iterators
307        if self.new_transaction_notifier.receiver_count() > 0 {
308            let _ = self.new_transaction_notifier.send(tx.clone());
309        }
310
311        self.by_id.insert(tx_id, tx);
312    }
313
314    /// Removes the transaction from the pool.
315    ///
316    /// Note: If the transaction has a descendant transaction
317    /// it will advance it to the best queue.
318    pub(crate) fn remove_transaction(
319        &mut self,
320        id: &TransactionId,
321    ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
322        if let Some(lowest) = self.independent_transactions.get(&id.sender) {
323            if lowest.transaction.nonce() == id.nonce {
324                self.independent_transactions.remove(&id.sender);
325                // mark the next as independent if it exists
326                if let Some(unlocked) = self.get(&id.descendant()) {
327                    self.independent_transactions.insert(id.sender, unlocked.clone());
328                }
329            }
330        }
331
332        let tx = self.by_id.remove(id)?;
333        self.size_of -= tx.transaction.size();
334
335        if let Some(highest) = self.highest_nonces.get(&id.sender) {
336            if highest.transaction.nonce() == id.nonce {
337                self.highest_nonces.remove(&id.sender);
338            }
339            if let Some(ancestor) = self.ancestor(id) {
340                self.highest_nonces.insert(id.sender, ancestor.clone());
341            }
342        }
343        Some(tx.transaction)
344    }
345
346    fn next_id(&mut self) -> u64 {
347        let id = self.submission_id;
348        self.submission_id = self.submission_id.wrapping_add(1);
349        id
350    }
351
352    /// Traverses the pool, starting at the highest nonce set, removing the transactions which
353    /// would put the pool under the specified limits.
354    ///
355    /// This attempts to remove transactions by roughly the same amount for each sender. This is
356    /// done by removing the highest-nonce transactions for each sender.
357    ///
358    /// If the `remove_locals` flag is unset, transactions will be removed per-sender until a
359    /// local transaction is the highest nonce transaction for that sender. If all senders have a
360    /// local highest-nonce transaction, the pool will not be truncated further.
361    ///
362    /// Otherwise, if the `remove_locals` flag is set, transactions will be removed per-sender
363    /// until the pool is under the given limits.
364    ///
365    /// Any removed transactions will be added to the `end_removed` vector.
366    pub fn remove_to_limit(
367        &mut self,
368        limit: &SubPoolLimit,
369        remove_locals: bool,
370        end_removed: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
371    ) {
372        // This serves as a termination condition for the loop - it represents the number of
373        // _valid_ unique senders that might have descendants in the pool.
374        //
375        // If `remove_locals` is false, a value of zero means that there are no non-local txs in the
376        // pool that can be removed.
377        //
378        // If `remove_locals` is true, a value of zero means that there are no txs in the pool that
379        // can be removed.
380        let mut non_local_senders = self.highest_nonces.len();
381
382        // keep track of unique senders from previous iterations, to understand how many unique
383        // senders were removed in the last iteration
384        let mut unique_senders = self.highest_nonces.len();
385
386        // keep track of transactions to remove and how many have been removed so far
387        let original_length = self.len();
388        let mut removed = Vec::new();
389        let mut total_removed = 0;
390
391        // track total `size` of transactions to remove
392        let original_size = self.size();
393        let mut total_size = 0;
394
395        loop {
396            // check how many unique senders were removed last iteration
397            let unique_removed = unique_senders - self.highest_nonces.len();
398
399            // the new number of unique senders
400            unique_senders = self.highest_nonces.len();
401            non_local_senders -= unique_removed;
402
403            // we can reuse the temp array
404            removed.clear();
405
406            // we prefer removing transactions with lower ordering
407            let mut worst_transactions = self.highest_nonces.values().collect::<Vec<_>>();
408            worst_transactions.sort();
409
410            // loop through the highest nonces set, removing transactions until we reach the limit
411            for tx in worst_transactions {
412                // return early if the pool is under limits
413                if !limit.is_exceeded(original_length - total_removed, original_size - total_size) ||
414                    non_local_senders == 0
415                {
416                    // need to remove remaining transactions before exiting
417                    for id in &removed {
418                        if let Some(tx) = self.remove_transaction(id) {
419                            end_removed.push(tx);
420                        }
421                    }
422
423                    return
424                }
425
426                if !remove_locals && tx.transaction.is_local() {
427                    non_local_senders -= 1;
428                    continue
429                }
430
431                total_size += tx.transaction.size();
432                total_removed += 1;
433                removed.push(*tx.transaction.id());
434            }
435
436            // remove the transactions from this iteration
437            for id in &removed {
438                if let Some(tx) = self.remove_transaction(id) {
439                    end_removed.push(tx);
440                }
441            }
442
443            // return if either the pool is under limits or there are no more _eligible_
444            // transactions to remove
445            if !self.exceeds(limit) || non_local_senders == 0 {
446                return
447            }
448        }
449    }
450
451    /// Truncates the pool to the given [`SubPoolLimit`], removing transactions until the subpool
452    /// limits are met.
453    ///
454    /// This attempts to remove transactions by roughly the same amount for each sender. For more
455    /// information on this exact process see docs for
456    /// [`remove_to_limit`](PendingPool::remove_to_limit).
457    ///
458    /// This first truncates all of the non-local transactions in the pool. If the subpool is still
459    /// not under the limit, this truncates the entire pool, including non-local transactions. The
460    /// removed transactions are returned.
461    pub fn truncate_pool(
462        &mut self,
463        limit: SubPoolLimit,
464    ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
465        let mut removed = Vec::new();
466        // return early if the pool is already under the limits
467        if !self.exceeds(&limit) {
468            return removed
469        }
470
471        // first truncate only non-local transactions, returning if the pool end up under the limit
472        self.remove_to_limit(&limit, false, &mut removed);
473        if !self.exceeds(&limit) {
474            return removed
475        }
476
477        // now repeat for local transactions, since local transactions must be removed now for the
478        // pool to be under the limit
479        self.remove_to_limit(&limit, true, &mut removed);
480
481        removed
482    }
483
484    /// Returns true if the pool exceeds the given limit
485    #[inline]
486    pub(crate) fn exceeds(&self, limit: &SubPoolLimit) -> bool {
487        limit.is_exceeded(self.len(), self.size())
488    }
489
490    /// The reported size of all transactions in this pool.
491    pub(crate) fn size(&self) -> usize {
492        self.size_of.into()
493    }
494
495    /// Number of transactions in the entire pool
496    pub(crate) fn len(&self) -> usize {
497        self.by_id.len()
498    }
499
500    /// Whether the pool is empty
501    #[cfg(test)]
502    pub(crate) fn is_empty(&self) -> bool {
503        self.by_id.is_empty()
504    }
505
506    /// Returns `true` if the transaction with the given id is already included in this pool.
507    pub(crate) fn contains(&self, id: &TransactionId) -> bool {
508        self.by_id.contains_key(id)
509    }
510
511    /// Get transactions by sender
512    pub(crate) fn get_txs_by_sender(&self, sender: SenderId) -> Vec<TransactionId> {
513        self.by_id
514            .range((sender.start_bound(), Unbounded))
515            .take_while(move |(other, _)| sender == other.sender)
516            .map(|(tx_id, _)| *tx_id)
517            .collect()
518    }
519
520    /// Retrieves a transaction with the given ID from the pool, if it exists.
521    fn get(&self, id: &TransactionId) -> Option<&PendingTransaction<T>> {
522        self.by_id.get(id)
523    }
524
525    /// Returns a reference to the independent transactions in the pool
526    #[cfg(test)]
527    pub(crate) const fn independent(&self) -> &FxHashMap<SenderId, PendingTransaction<T>> {
528        &self.independent_transactions
529    }
530
531    /// Asserts that the bijection between `by_id` and `all` is valid.
532    #[cfg(any(test, feature = "test-utils"))]
533    pub(crate) fn assert_invariants(&self) {
534        assert!(
535            self.independent_transactions.len() <= self.by_id.len(),
536            "independent.len() > all.len()"
537        );
538        assert!(
539            self.highest_nonces.len() <= self.by_id.len(),
540            "independent_descendants.len() > all.len()"
541        );
542        assert_eq!(
543            self.highest_nonces.len(),
544            self.independent_transactions.len(),
545            "independent.len() = independent_descendants.len()"
546        );
547    }
548}
549
550/// A transaction that is ready to be included in a block.
551#[derive(Debug)]
552pub(crate) struct PendingTransaction<T: TransactionOrdering> {
553    /// Identifier that tags when transaction was submitted in the pool.
554    pub(crate) submission_id: u64,
555    /// Actual transaction.
556    pub(crate) transaction: Arc<ValidPoolTransaction<T::Transaction>>,
557    /// The priority value assigned by the used `Ordering` function.
558    pub(crate) priority: Priority<T::PriorityValue>,
559}
560
561impl<T: TransactionOrdering> PendingTransaction<T> {
562    /// The next transaction of the sender: `nonce + 1`
563    pub(crate) fn unlocks(&self) -> TransactionId {
564        self.transaction.transaction_id.descendant()
565    }
566}
567
568impl<T: TransactionOrdering> Clone for PendingTransaction<T> {
569    fn clone(&self) -> Self {
570        Self {
571            submission_id: self.submission_id,
572            transaction: Arc::clone(&self.transaction),
573            priority: self.priority.clone(),
574        }
575    }
576}
577
578impl<T: TransactionOrdering> Eq for PendingTransaction<T> {}
579
580impl<T: TransactionOrdering> PartialEq<Self> for PendingTransaction<T> {
581    fn eq(&self, other: &Self) -> bool {
582        self.cmp(other) == Ordering::Equal
583    }
584}
585
586impl<T: TransactionOrdering> PartialOrd<Self> for PendingTransaction<T> {
587    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
588        Some(self.cmp(other))
589    }
590}
591
592impl<T: TransactionOrdering> Ord for PendingTransaction<T> {
593    fn cmp(&self, other: &Self) -> Ordering {
594        // This compares by `priority` and only if two tx have the exact same priority this compares
595        // the unique `submission_id`. This ensures that transactions with same priority are not
596        // equal, so they're not replaced in the set
597        self.priority
598            .cmp(&other.priority)
599            .then_with(|| other.submission_id.cmp(&self.submission_id))
600    }
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606    use crate::{
607        test_utils::{MockOrdering, MockTransaction, MockTransactionFactory, MockTransactionSet},
608        PoolTransaction,
609    };
610    use alloy_primitives::address;
611    use reth_primitives::TxType;
612    use std::collections::HashSet;
613
614    #[test]
615    fn test_enforce_basefee() {
616        let mut f = MockTransactionFactory::default();
617        let mut pool = PendingPool::new(MockOrdering::default());
618        let tx = f.validated_arc(MockTransaction::eip1559().inc_price());
619        pool.add_transaction(tx.clone(), 0);
620
621        assert!(pool.contains(tx.id()));
622        assert_eq!(pool.len(), 1);
623
624        let removed = pool.update_base_fee(0);
625        assert!(removed.is_empty());
626
627        let removed = pool.update_base_fee((tx.max_fee_per_gas() + 1) as u64);
628        assert_eq!(removed.len(), 1);
629        assert!(pool.is_empty());
630    }
631
632    #[test]
633    fn test_enforce_basefee_descendant() {
634        let mut f = MockTransactionFactory::default();
635        let mut pool = PendingPool::new(MockOrdering::default());
636        let t = MockTransaction::eip1559().inc_price_by(10);
637        let root_tx = f.validated_arc(t.clone());
638        pool.add_transaction(root_tx.clone(), 0);
639
640        let descendant_tx = f.validated_arc(t.inc_nonce().decr_price());
641        pool.add_transaction(descendant_tx.clone(), 0);
642
643        assert!(pool.contains(root_tx.id()));
644        assert!(pool.contains(descendant_tx.id()));
645        assert_eq!(pool.len(), 2);
646
647        assert_eq!(pool.independent_transactions.len(), 1);
648        assert_eq!(pool.highest_nonces.len(), 1);
649
650        let removed = pool.update_base_fee(0);
651        assert!(removed.is_empty());
652
653        // two dependent tx in the pool with decreasing fee
654
655        {
656            let mut pool2 = pool.clone();
657            let removed = pool2.update_base_fee((descendant_tx.max_fee_per_gas() + 1) as u64);
658            assert_eq!(removed.len(), 1);
659            assert_eq!(pool2.len(), 1);
660            // descendant got popped
661            assert!(pool2.contains(root_tx.id()));
662            assert!(!pool2.contains(descendant_tx.id()));
663        }
664
665        // remove root transaction via fee
666        let removed = pool.update_base_fee((root_tx.max_fee_per_gas() + 1) as u64);
667        assert_eq!(removed.len(), 2);
668        assert!(pool.is_empty());
669        pool.assert_invariants();
670    }
671
672    #[test]
673    fn evict_worst() {
674        let mut f = MockTransactionFactory::default();
675        let mut pool = PendingPool::new(MockOrdering::default());
676
677        let t = MockTransaction::eip1559();
678        pool.add_transaction(f.validated_arc(t.clone()), 0);
679
680        let t2 = MockTransaction::eip1559().inc_price_by(10);
681        pool.add_transaction(f.validated_arc(t2), 0);
682
683        // First transaction should be evicted.
684        assert_eq!(
685            pool.highest_nonces.values().min().map(|tx| *tx.transaction.hash()),
686            Some(*t.hash())
687        );
688
689        // truncate pool with max size = 1, ensure it's the same transaction
690        let removed = pool.truncate_pool(SubPoolLimit { max_txs: 1, max_size: usize::MAX });
691        assert_eq!(removed.len(), 1);
692        assert_eq!(removed[0].hash(), t.hash());
693    }
694
695    #[test]
696    fn correct_independent_descendants() {
697        // this test ensures that we set the right highest nonces set for each sender
698        let mut f = MockTransactionFactory::default();
699        let mut pool = PendingPool::new(MockOrdering::default());
700
701        let a_sender = address!("000000000000000000000000000000000000000a");
702        let b_sender = address!("000000000000000000000000000000000000000b");
703        let c_sender = address!("000000000000000000000000000000000000000c");
704        let d_sender = address!("000000000000000000000000000000000000000d");
705
706        // create a chain of transactions by sender A, B, C
707        let mut tx_set =
708            MockTransactionSet::dependent(a_sender, 0, 4, reth_primitives::TxType::Eip1559);
709        let a = tx_set.clone().into_vec();
710
711        let b = MockTransactionSet::dependent(b_sender, 0, 3, reth_primitives::TxType::Eip1559)
712            .into_vec();
713        tx_set.extend(b.clone());
714
715        // C has the same number of txs as B
716        let c = MockTransactionSet::dependent(c_sender, 0, 3, reth_primitives::TxType::Eip1559)
717            .into_vec();
718        tx_set.extend(c.clone());
719
720        let d = MockTransactionSet::dependent(d_sender, 0, 1, reth_primitives::TxType::Eip1559)
721            .into_vec();
722        tx_set.extend(d.clone());
723
724        // add all the transactions to the pool
725        let all_txs = tx_set.into_vec();
726        for tx in all_txs {
727            pool.add_transaction(f.validated_arc(tx), 0);
728        }
729
730        pool.assert_invariants();
731
732        // the independent set is the roots of each of these tx chains, these are the highest
733        // nonces for each sender
734        let expected_highest_nonces = vec![d[0].clone(), c[2].clone(), b[2].clone(), a[3].clone()]
735            .iter()
736            .map(|tx| (tx.sender(), tx.nonce()))
737            .collect::<HashSet<_>>();
738        let actual_highest_nonces = pool
739            .highest_nonces
740            .values()
741            .map(|tx| (tx.transaction.sender(), tx.transaction.nonce()))
742            .collect::<HashSet<_>>();
743        assert_eq!(expected_highest_nonces, actual_highest_nonces);
744        pool.assert_invariants();
745    }
746
747    #[test]
748    fn truncate_by_sender() {
749        // This test ensures that transactions are removed from the pending pool by sender.
750        let mut f = MockTransactionFactory::default();
751        let mut pool = PendingPool::new(MockOrdering::default());
752
753        // Addresses for simulated senders A, B, C, and D.
754        let a = address!("000000000000000000000000000000000000000a");
755        let b = address!("000000000000000000000000000000000000000b");
756        let c = address!("000000000000000000000000000000000000000c");
757        let d = address!("000000000000000000000000000000000000000d");
758
759        // Create transaction chains for senders A, B, C, and D.
760        let a_txs = MockTransactionSet::sequential_transactions_by_sender(a, 4, TxType::Eip1559);
761        let b_txs = MockTransactionSet::sequential_transactions_by_sender(b, 3, TxType::Eip1559);
762        let c_txs = MockTransactionSet::sequential_transactions_by_sender(c, 3, TxType::Eip1559);
763        let d_txs = MockTransactionSet::sequential_transactions_by_sender(d, 1, TxType::Eip1559);
764
765        // Set up expected pending transactions.
766        let expected_pending = vec![
767            a_txs.transactions[0].clone(),
768            b_txs.transactions[0].clone(),
769            c_txs.transactions[0].clone(),
770            a_txs.transactions[1].clone(),
771        ]
772        .into_iter()
773        .map(|tx| (tx.sender(), tx.nonce()))
774        .collect::<HashSet<_>>();
775
776        // Set up expected removed transactions.
777        let expected_removed = vec![
778            d_txs.transactions[0].clone(),
779            c_txs.transactions[2].clone(),
780            b_txs.transactions[2].clone(),
781            a_txs.transactions[3].clone(),
782            c_txs.transactions[1].clone(),
783            b_txs.transactions[1].clone(),
784            a_txs.transactions[2].clone(),
785        ]
786        .into_iter()
787        .map(|tx| (tx.sender(), tx.nonce()))
788        .collect::<HashSet<_>>();
789
790        // Consolidate all transactions into a single vector.
791        let all_txs =
792            [a_txs.into_vec(), b_txs.into_vec(), c_txs.into_vec(), d_txs.into_vec()].concat();
793
794        // Add all the transactions to the pool.
795        for tx in all_txs {
796            pool.add_transaction(f.validated_arc(tx), 0);
797        }
798
799        // Sanity check, ensuring everything is consistent.
800        pool.assert_invariants();
801
802        // Define the maximum total transactions to be 4, removing transactions for each sender.
803        // Expected order of removal:
804        // * d1, c3, b3, a4
805        // * c2, b2, a3
806        //
807        // Remaining transactions:
808        // * a1, a2
809        // * b1
810        // * c1
811        let pool_limit = SubPoolLimit { max_txs: 4, max_size: usize::MAX };
812
813        // Truncate the pool based on the defined limit.
814        let removed = pool.truncate_pool(pool_limit);
815        pool.assert_invariants();
816        assert_eq!(removed.len(), expected_removed.len());
817
818        // Get the set of removed transactions and compare with the expected set.
819        let removed =
820            removed.into_iter().map(|tx| (tx.sender(), tx.nonce())).collect::<HashSet<_>>();
821        assert_eq!(removed, expected_removed);
822
823        // Retrieve the current pending transactions after truncation.
824        let pending = pool.all().collect::<Vec<_>>();
825        assert_eq!(pending.len(), expected_pending.len());
826
827        // Get the set of pending transactions and compare with the expected set.
828        let pending =
829            pending.into_iter().map(|tx| (tx.sender(), tx.nonce())).collect::<HashSet<_>>();
830        assert_eq!(pending, expected_pending);
831    }
832
833    // <https://github.com/paradigmxyz/reth/issues/12340>
834    #[test]
835    fn test_eligible_updates_promoted() {
836        let mut pool = PendingPool::new(MockOrdering::default());
837        let mut f = MockTransactionFactory::default();
838
839        let num_senders = 10;
840
841        let first_txs: Vec<_> = (0..num_senders) //
842            .map(|_| MockTransaction::eip1559())
843            .collect();
844        let second_txs: Vec<_> =
845            first_txs.iter().map(|tx| tx.clone().rng_hash().inc_nonce()).collect();
846
847        for tx in first_txs {
848            let valid_tx = f.validated(tx);
849            pool.add_transaction(Arc::new(valid_tx), 0);
850        }
851
852        let mut best = pool.best();
853
854        for _ in 0..num_senders {
855            if let Some(tx) = best.next() {
856                assert_eq!(tx.nonce(), 0);
857            } else {
858                panic!("cannot read one of first_txs");
859            }
860        }
861
862        for tx in second_txs {
863            let valid_tx = f.validated(tx);
864            pool.add_transaction(Arc::new(valid_tx), 0);
865        }
866
867        for _ in 0..num_senders {
868            if let Some(tx) = best.next() {
869                assert_eq!(tx.nonce(), 1);
870            } else {
871                panic!("cannot read one of second_txs");
872            }
873        }
874    }
875
876    #[test]
877    fn test_empty_pool_behavior() {
878        let mut pool = PendingPool::<MockOrdering>::new(MockOrdering::default());
879
880        // Ensure the pool is empty
881        assert!(pool.is_empty());
882        assert_eq!(pool.len(), 0);
883        assert_eq!(pool.size(), 0);
884
885        // Verify that attempting to truncate an empty pool does not panic and returns an empty vec
886        let removed = pool.truncate_pool(SubPoolLimit { max_txs: 10, max_size: 1000 });
887        assert!(removed.is_empty());
888
889        // Verify that retrieving transactions from an empty pool yields nothing
890        let all_txs: Vec<_> = pool.all().collect();
891        assert!(all_txs.is_empty());
892    }
893
894    #[test]
895    fn test_add_remove_transaction() {
896        let mut f = MockTransactionFactory::default();
897        let mut pool = PendingPool::new(MockOrdering::default());
898
899        // Add a transaction and check if it's in the pool
900        let tx = f.validated_arc(MockTransaction::eip1559());
901        pool.add_transaction(tx.clone(), 0);
902        assert!(pool.contains(tx.id()));
903        assert_eq!(pool.len(), 1);
904
905        // Remove the transaction and ensure it's no longer in the pool
906        let removed_tx = pool.remove_transaction(tx.id()).unwrap();
907        assert_eq!(removed_tx.id(), tx.id());
908        assert!(!pool.contains(tx.id()));
909        assert_eq!(pool.len(), 0);
910    }
911
912    #[test]
913    fn test_reorder_on_basefee_update() {
914        let mut f = MockTransactionFactory::default();
915        let mut pool = PendingPool::new(MockOrdering::default());
916
917        // Add two transactions with different fees
918        let tx1 = f.validated_arc(MockTransaction::eip1559().inc_price());
919        let tx2 = f.validated_arc(MockTransaction::eip1559().inc_price_by(20));
920        pool.add_transaction(tx1.clone(), 0);
921        pool.add_transaction(tx2.clone(), 0);
922
923        // Ensure the transactions are in the correct order
924        let mut best = pool.best();
925        assert_eq!(best.next().unwrap().hash(), tx2.hash());
926        assert_eq!(best.next().unwrap().hash(), tx1.hash());
927
928        // Update the base fee to a value higher than tx1's fee, causing it to be removed
929        let removed = pool.update_base_fee((tx1.max_fee_per_gas() + 1) as u64);
930        assert_eq!(removed.len(), 1);
931        assert_eq!(removed[0].hash(), tx1.hash());
932
933        // Verify that only tx2 remains in the pool
934        assert_eq!(pool.len(), 1);
935        assert!(pool.contains(tx2.id()));
936        assert!(!pool.contains(tx1.id()));
937    }
938
939    #[test]
940    #[should_panic(expected = "transaction already included")]
941    fn test_handle_duplicates() {
942        let mut f = MockTransactionFactory::default();
943        let mut pool = PendingPool::new(MockOrdering::default());
944
945        // Add the same transaction twice and ensure it only appears once
946        let tx = f.validated_arc(MockTransaction::eip1559());
947        pool.add_transaction(tx.clone(), 0);
948        assert!(pool.contains(tx.id()));
949        assert_eq!(pool.len(), 1);
950
951        // Attempt to add the same transaction again, which should be ignored
952        pool.add_transaction(tx, 0);
953    }
954
955    #[test]
956    fn test_update_blob_fee() {
957        let mut f = MockTransactionFactory::default();
958        let mut pool = PendingPool::new(MockOrdering::default());
959
960        // Add transactions with varying blob fees
961        let tx1 = f.validated_arc(MockTransaction::eip4844().set_blob_fee(50).clone());
962        let tx2 = f.validated_arc(MockTransaction::eip4844().set_blob_fee(150).clone());
963        pool.add_transaction(tx1.clone(), 0);
964        pool.add_transaction(tx2.clone(), 0);
965
966        // Update the blob fee to a value that causes tx1 to be removed
967        let removed = pool.update_blob_fee(100);
968        assert_eq!(removed.len(), 1);
969        assert_eq!(removed[0].hash(), tx1.hash());
970
971        // Verify that only tx2 remains in the pool
972        assert!(pool.contains(tx2.id()));
973        assert!(!pool.contains(tx1.id()));
974    }
975}