1use 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#[derive(Debug, Clone)]
33pub struct PendingPool<T: TransactionOrdering> {
34 ordering: T,
36 submission_id: u64,
40 by_id: OrdMap<TransactionId, PendingTransaction<T>>,
42 highest_nonces: FxHashMap<SenderId, PendingTransaction<T>>,
45 highest_nonces_by_priority: Option<HighestNoncesByPriority<T>>,
53 independent_transactions: FxHashMap<SenderId, PendingTransaction<T>>,
56 size_of: SizeTracker,
60 new_transaction_notifier: broadcast::Sender<PendingTransaction<T>>,
63 local_transactions_config: Arc<LocalTransactionConfig>,
65}
66
67impl<T: TransactionOrdering> PendingPool<T> {
70 pub fn new(ordering: T) -> Self {
72 Self::with_buffer(ordering, 200)
73 }
74
75 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 pub fn with_local_transactions_config(mut self, config: Arc<LocalTransactionConfig>) -> Self {
95 self.local_transactions_config = config;
96 self.clear_highest_nonces_by_priority();
98 self
99 }
100
101 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 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 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 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 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 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 if !self.by_id.values().any(priced_out) {
211 return Vec::new()
212 }
213
214 let mut removed = Vec::new();
216
217 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 removed.push(Arc::clone(&tx.transaction));
226
227 '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 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 pub(crate) fn update_base_fee(
261 &mut self,
262 base_fee: u64,
263 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
264 let mut removed = Vec::new();
266
267 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 removed.push(Arc::clone(&tx.transaction));
276
277 '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 tx.priority = self.ordering.priority(&tx.transaction.transaction, base_fee);
289
290 self.size_of += tx.transaction.size();
291 if highest.is_none() {
292 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 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 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 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 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 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 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 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 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 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 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 let original_length = self.len();
483 let mut removed = Vec::new();
484 let mut total_removed = 0;
485
486 let original_size = self.size();
488 let mut total_size = 0;
489
490 loop {
491 removed.clear();
493
494 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 if worst_transactions.peek().is_none() {
509 return
510 }
511
512 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 let removal_candidates = excess_txs.max(excess_size_txs).max(1);
523
524 for tx in worst_transactions.take(removal_candidates) {
526 if !limit.is_exceeded(original_length - total_removed, original_size - total_size) {
528 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 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 pub fn truncate_pool(
568 &mut self,
569 limit: SubPoolLimit,
570 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
571 let mut removed = Vec::new();
572 if !self.exceeds(&limit) {
574 return removed
575 }
576
577 self.remove_to_limit(&limit, false, &mut removed);
579 if !self.exceeds(&limit) {
580 return removed
581 }
582
583 self.remove_to_limit(&limit, true, &mut removed);
586
587 removed
588 }
589
590 pub(crate) fn clear_highest_nonces_by_priority(&mut self) {
597 self.highest_nonces_by_priority = None;
598 }
599
600 #[inline]
602 pub(crate) fn exceeds(&self, limit: &SubPoolLimit) -> bool {
603 limit.is_exceeded(self.len(), self.size())
604 }
605
606 pub(crate) fn size(&self) -> usize {
608 self.size_of.into()
609 }
610
611 pub(crate) fn len(&self) -> usize {
613 self.by_id.len()
614 }
615
616 pub const fn by_id(&self) -> &OrdMap<TransactionId, PendingTransaction<T>> {
618 &self.by_id
619 }
620
621 pub const fn independent_transactions(&self) -> &FxHashMap<SenderId, PendingTransaction<T>> {
623 &self.independent_transactions
624 }
625
626 pub fn new_transaction_receiver(&self) -> broadcast::Receiver<PendingTransaction<T>> {
628 self.new_transaction_notifier.subscribe()
629 }
630
631 #[cfg(test)]
633 pub(crate) fn is_empty(&self) -> bool {
634 self.by_id.is_empty()
635 }
636
637 pub(crate) fn contains(&self, id: &TransactionId) -> bool {
639 self.by_id.contains_key(id)
640 }
641
642 pub(crate) fn get_txs_by_sender(&self, sender: SenderId) -> Vec<TransactionId> {
644 self.iter_txs_by_sender(sender).copied().collect()
645 }
646
647 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 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 fn get(&self, id: &TransactionId) -> Option<&PendingTransaction<T>> {
672 self.by_id.get(id)
673 }
674
675 #[cfg(test)]
677 pub(crate) const fn independent(&self) -> &FxHashMap<SenderId, PendingTransaction<T>> {
678 &self.independent_transactions
679 }
680
681 #[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#[derive(Debug)]
757pub struct PendingTransaction<T: TransactionOrdering> {
758 pub submission_id: u64,
760 pub transaction: Arc<ValidPoolTransaction<T::Transaction>>,
762 pub priority: Priority<T::PriorityValue>,
764}
765
766impl<T: TransactionOrdering> PendingTransaction<T> {
767 pub fn unlocks(&self) -> TransactionId {
769 self.transaction.transaction_id.descendant()
770 }
771
772 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 self.priority
809 .cmp(&other.priority)
810 .then_with(|| other.submission_id.cmp(&self.submission_id))
811 }
812}
813
814#[derive(Debug, Clone)]
820struct HighestNoncesByPriority<T: TransactionOrdering> {
821 non_local: BTreeSet<PendingTransaction<T>>,
823 local: BTreeSet<PendingTransaction<T>>,
825}
826
827impl<T: TransactionOrdering> HighestNoncesByPriority<T> {
828 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 Self { non_local: non_local.into_iter().collect(), local: local.into_iter().collect() }
837 }
838
839 fn insert(&mut self, tx: PendingTransaction<T>, config: &LocalTransactionConfig) {
841 self.set_mut(&tx, config).insert(tx);
842 }
843
844 fn remove(&mut self, tx: &PendingTransaction<T>, config: &LocalTransactionConfig) {
846 self.set_mut(tx, config).remove(tx);
847 }
848
849 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 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
873struct 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 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 {
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 assert!(pool2.contains(root_tx.id()));
957 assert!(!pool2.contains(descendant_tx.id()));
958 }
959
960 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 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 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 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 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 assert_eq!(
1033 pool.highest_nonces.values().min().map(|tx| *tx.transaction.hash()),
1034 Some(*t.hash())
1035 );
1036
1037 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 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 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 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 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 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 let mut f = MockTransactionFactory::default();
1095 let mut pool = PendingPool::new(MockOrdering::default());
1096
1097 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 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 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 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 let all_txs =
1136 [a_txs.into_vec(), b_txs.into_vec(), c_txs.into_vec(), d_txs.into_vec()].concat();
1137
1138 for tx in all_txs {
1140 pool.add_transaction(f.validated_arc(tx), 0);
1141 }
1142
1143 pool.assert_invariants();
1145
1146 let pool_limit = SubPoolLimit { max_txs: 4, max_size: usize::MAX };
1156
1157 let removed = pool.truncate_pool(pool_limit);
1159 pool.assert_invariants();
1160 assert_eq!(removed.len(), expected_removed.len());
1161
1162 let removed = removed.into_iter().map(|tx| (tx.sender(), tx.nonce())).collect::<Vec<_>>();
1164 assert_eq!(removed, expected_removed);
1165
1166 let pending = pool.all().collect::<Vec<_>>();
1168 assert_eq!(pending.len(), expected_pending.len());
1169
1170 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 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 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 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 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 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 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 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 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 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 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 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 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 let removed = pool.truncate_pool(limit(2));
1382 assert_eq!(removed.len(), 1);
1383 assert_eq!(removed[0].id(), b0.id());
1384
1385 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 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 let removed = pool.truncate_pool(limit(2));
1422 pool.assert_invariants();
1423 assert_eq!(removed[0].id(), b0.id());
1424
1425 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 #[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) .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 assert!(pool.is_empty());
1486 assert_eq!(pool.len(), 0);
1487 assert_eq!(pool.size(), 0);
1488
1489 let removed = pool.truncate_pool(SubPoolLimit { max_txs: 10, max_size: 1000 });
1491 assert!(removed.is_empty());
1492
1493 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 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 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 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 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 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 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 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 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 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 let removed = pool.update_blob_fee(100);
1572 assert_eq!(removed.len(), 1);
1573 assert_eq!(removed[0].hash(), tx1.hash());
1574
1575 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 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 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 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 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 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 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 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}