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