1use crate::{
69 blobstore::{BlobStore, PooledBlobSidecar},
70 error::{PoolError, PoolErrorKind, PoolResult},
71 identifier::{SenderId, SenderIdentifiers, TransactionId},
72 metrics::BlobStoreMetrics,
73 pool::{
74 listener::{
75 BlobTransactionSidecarListener, PendingTransactionHashListener, PoolEventBroadcast,
76 TransactionListener,
77 },
78 state::SubPool,
79 txpool::{SenderInfo, TxPool},
80 update::UpdateOutcome,
81 },
82 traits::{
83 AllPoolTransactions, BestTransactionsAttributes, BlockInfo, GetPooledTransactionLimit,
84 NewBlobSidecar, PoolSize, PoolTransaction, PropagatedTransactions, TransactionOrigin,
85 },
86 validate::{TransactionValidationOutcome, ValidPoolTransaction, ValidTransaction},
87 CanonicalStateUpdate, EthPoolTransaction, PoolConfig, TransactionOrdering,
88 TransactionValidator,
89};
90
91use alloy_primitives::{
92 map::{AddressSet, B256Set},
93 Address, TxHash, B256,
94};
95use parking_lot::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
96use reth_eth_wire_types::HandleMempoolData;
97use reth_execution_types::ChangedAccount;
98
99use alloy_eips::{eip7594::BlobTransactionSidecarVariant, Typed2718};
100use reth_primitives_traits::Recovered;
101use rustc_hash::FxHashMap;
102use std::{
103 fmt,
104 sync::{
105 atomic::{AtomicBool, Ordering},
106 Arc,
107 },
108 time::Instant,
109};
110use tokio::sync::mpsc;
111use tracing::{debug, trace, warn};
112mod events;
113pub use best::{BestTransactionFilter, BestTransactionsWithPrioritizedSenders};
114pub use blob::{blob_tx_priority, fee_delta, BlobOrd, BlobTransactions};
115pub use events::{FullTransactionEvent, NewTransactionEvent, TransactionEvent};
116pub use listener::{AllTransactionsEvents, TransactionEvents, TransactionListenerKind};
117pub use parked::{BasefeeOrd, ParkedOrd, ParkedPool, QueuedOrd};
118pub use pending::PendingPool;
119
120mod best;
121pub use best::BestTransactions;
122
123mod blob;
124pub mod listener;
125mod parked;
126pub mod pending;
127pub mod size;
128pub(crate) mod state;
129pub mod txpool;
130mod update;
131
132pub const PENDING_TX_LISTENER_BUFFER_SIZE: usize = 2048;
134pub const NEW_TX_LISTENER_BUFFER_SIZE: usize = 1024;
136
137const BLOB_SIDECAR_LISTENER_BUFFER_SIZE: usize = 512;
138
139pub struct PoolInner<V, T, S>
141where
142 T: TransactionOrdering,
143{
144 identifiers: RwLock<SenderIdentifiers>,
146 validator: V,
148 blob_store: S,
150 pool: RwLock<TxPool<T>>,
152 config: PoolConfig,
154 event_listener: RwLock<PoolEventBroadcast<T::Transaction>>,
156 has_event_listeners: AtomicBool,
158 pending_transaction_listener: RwLock<Vec<PendingTransactionHashListener>>,
160 transaction_listener: RwLock<Vec<TransactionListener<T::Transaction>>>,
162 blob_transaction_sidecar_listener: Mutex<Vec<BlobTransactionSidecarListener>>,
164 blob_store_metrics: BlobStoreMetrics,
166}
167
168impl<V, T, S> PoolInner<V, T, S>
171where
172 V: TransactionValidator,
173 T: TransactionOrdering<Transaction = <V as TransactionValidator>::Transaction>,
174 S: BlobStore,
175{
176 pub fn new(validator: V, ordering: T, blob_store: S, config: PoolConfig) -> Self {
178 Self {
179 identifiers: Default::default(),
180 validator,
181 event_listener: Default::default(),
182 has_event_listeners: AtomicBool::new(false),
183 pool: RwLock::new(TxPool::new(ordering, config.clone())),
184 pending_transaction_listener: Default::default(),
185 transaction_listener: Default::default(),
186 blob_transaction_sidecar_listener: Default::default(),
187 config,
188 blob_store,
189 blob_store_metrics: Default::default(),
190 }
191 }
192
193 pub const fn blob_store(&self) -> &S {
195 &self.blob_store
196 }
197
198 pub fn size(&self) -> PoolSize {
200 self.get_pool_data().size()
201 }
202
203 pub fn block_info(&self) -> BlockInfo {
205 self.get_pool_data().block_info()
206 }
207 pub fn set_block_info(&self, info: BlockInfo) {
212 let outcome = self.pool.write().set_block_info(info);
213
214 self.notify_on_transaction_updates(outcome.promoted, outcome.discarded);
216 }
217
218 pub fn get_sender_id(&self, addr: Address) -> SenderId {
225 self.identifiers.write().sender_id_or_create(addr)
226 }
227
228 pub fn sender_id(&self, addr: &Address) -> Option<SenderId> {
233 self.identifiers.read().sender_id(addr)
234 }
235
236 pub fn get_sender_ids(&self, addrs: impl IntoIterator<Item = Address>) -> Vec<SenderId> {
238 self.identifiers.write().sender_ids_or_create(addrs)
239 }
240
241 pub fn unique_senders(&self) -> AddressSet {
243 self.get_pool_data().unique_senders()
244 }
245
246 fn changed_senders(
249 &self,
250 accs: impl Iterator<Item = ChangedAccount>,
251 ) -> FxHashMap<SenderId, SenderInfo> {
252 let identifiers = self.identifiers.read();
253 accs.into_iter()
254 .filter_map(|acc| {
255 let ChangedAccount { address, nonce, balance } = acc;
256 let sender_id = identifiers.sender_id(&address)?;
257 Some((sender_id, SenderInfo { state_nonce: nonce, balance }))
258 })
259 .collect()
260 }
261
262 pub const fn config(&self) -> &PoolConfig {
264 &self.config
265 }
266
267 pub const fn validator(&self) -> &V {
269 &self.validator
270 }
271
272 pub fn add_pending_listener(&self, kind: TransactionListenerKind) -> mpsc::Receiver<TxHash> {
275 let (sender, rx) = mpsc::channel(self.config.pending_tx_listener_buffer_size);
276 let listener = PendingTransactionHashListener { sender, kind };
277
278 let mut listeners = self.pending_transaction_listener.write();
279 listeners.retain(|l| !l.sender.is_closed());
281 listeners.push(listener);
282
283 rx
284 }
285
286 pub fn add_new_transaction_listener(
288 &self,
289 kind: TransactionListenerKind,
290 ) -> mpsc::Receiver<NewTransactionEvent<T::Transaction>> {
291 let (sender, rx) = mpsc::channel(self.config.new_tx_listener_buffer_size);
292 let listener = TransactionListener { sender, kind };
293
294 let mut listeners = self.transaction_listener.write();
295 listeners.retain(|l| !l.sender.is_closed());
297 listeners.push(listener);
298
299 rx
300 }
301 pub fn add_blob_sidecar_listener(&self) -> mpsc::Receiver<NewBlobSidecar> {
304 let (sender, rx) = mpsc::channel(BLOB_SIDECAR_LISTENER_BUFFER_SIZE);
305 let listener = BlobTransactionSidecarListener { sender };
306 self.blob_transaction_sidecar_listener.lock().push(listener);
307 rx
308 }
309
310 pub fn add_transaction_event_listener(&self, tx_hash: TxHash) -> Option<TransactionEvents> {
313 if !self.get_pool_data().contains(&tx_hash) {
314 return None
315 }
316 Some(self.subscribe_transaction_events(tx_hash))
317 }
318
319 pub fn subscribe_transaction_events(&self, tx_hash: TxHash) -> TransactionEvents {
327 let events = self.event_listener.write().subscribe(tx_hash);
328 self.mark_event_listener_installed();
329 events
330 }
331
332 pub fn add_all_transactions_event_listener(&self) -> AllTransactionsEvents<T::Transaction> {
334 let mut listener = self.event_listener.write();
335 let events = listener.subscribe_all();
336 self.mark_event_listener_installed();
337 events
338 }
339
340 #[inline]
341 fn has_event_listeners(&self) -> bool {
342 self.has_event_listeners.load(Ordering::Relaxed)
343 }
344
345 #[inline]
346 fn mark_event_listener_installed(&self) {
347 self.has_event_listeners.store(true, Ordering::Relaxed);
348 }
349
350 #[inline]
351 fn update_event_listener_state(&self, listener: &PoolEventBroadcast<T::Transaction>) {
352 if listener.is_empty() {
353 self.has_event_listeners.store(false, Ordering::Relaxed);
354 }
355 }
356
357 #[inline]
358 fn with_event_listener<F>(&self, emit: F)
359 where
360 F: FnOnce(&mut PoolEventBroadcast<T::Transaction>),
361 {
362 if !self.has_event_listeners() {
363 return
364 }
365 let mut listener = self.event_listener.write();
366 if !listener.is_empty() {
367 emit(&mut listener);
368 }
369 self.update_event_listener_state(&listener);
370 }
371
372 pub fn get_pool_data(&self) -> RwLockReadGuard<'_, TxPool<T>> {
374 self.pool.read()
375 }
376
377 pub fn pooled_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
379 let mut out = Vec::new();
380 self.append_pooled_transactions(&mut out);
381 out
382 }
383
384 pub fn pooled_transactions_hashes(&self) -> Vec<TxHash> {
386 let mut out = Vec::new();
387 self.append_pooled_transactions_hashes(&mut out);
388 out
389 }
390
391 pub fn pooled_transactions_max(
393 &self,
394 max: usize,
395 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
396 if max == 0 {
397 return Vec::new()
398 }
399
400 let pool = self.get_pool_data();
401 let mut out = Vec::with_capacity(max.min(pool.all().len()));
402 out.extend(pool.all().transactions_iter().filter(|tx| tx.propagate).take(max).cloned());
403 out
404 }
405
406 pub fn append_pooled_transactions(
408 &self,
409 out: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
410 ) {
411 out.extend(
412 self.get_pool_data().all().transactions_iter().filter(|tx| tx.propagate).cloned(),
413 );
414 }
415
416 pub fn append_pooled_transaction_elements(
419 &self,
420 tx_hashes: &[TxHash],
421 limit: GetPooledTransactionLimit,
422 out: &mut Vec<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>,
423 ) where
424 <V as TransactionValidator>::Transaction: EthPoolTransaction,
425 {
426 let transactions = self.get_all_propagatable(tx_hashes);
427 let mut size = 0;
428 for transaction in transactions {
429 let encoded_len = transaction.encoded_length();
430 let Some(pooled) = self.to_pooled_transaction(transaction) else {
431 continue;
432 };
433
434 size += encoded_len;
435 out.push(pooled.into_inner());
436
437 if limit.exceeds(size) {
438 break
439 }
440 }
441 }
442
443 pub fn append_pooled_transactions_hashes(&self, out: &mut Vec<TxHash>) {
446 out.extend(
447 self.get_pool_data()
448 .all()
449 .transactions_iter()
450 .filter(|tx| tx.propagate)
451 .map(|tx| *tx.hash()),
452 );
453 }
454
455 pub fn append_pooled_transactions_max(
458 &self,
459 max: usize,
460 out: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
461 ) {
462 out.extend(
463 self.get_pool_data()
464 .all()
465 .transactions_iter()
466 .filter(|tx| tx.propagate)
467 .take(max)
468 .cloned(),
469 );
470 }
471
472 pub fn pooled_transactions_hashes_max(&self, max: usize) -> Vec<TxHash> {
474 if max == 0 {
475 return Vec::new();
476 }
477
478 let pool = self.get_pool_data();
479 let mut out = Vec::with_capacity(max.min(pool.all().len()));
480 out.extend(
481 pool.all().transactions_iter().filter(|tx| tx.propagate).take(max).map(|tx| *tx.hash()),
482 );
483 out
484 }
485
486 fn to_pooled_transaction(
491 &self,
492 transaction: Arc<ValidPoolTransaction<T::Transaction>>,
493 ) -> Option<Recovered<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>>
494 where
495 <V as TransactionValidator>::Transaction: EthPoolTransaction,
496 {
497 if transaction.is_eip4844() {
498 let sidecar = self.blob_store.get(*transaction.hash()).ok()??;
499 transaction.transaction.clone().try_into_pooled_eip4844(sidecar)
500 } else {
501 transaction
502 .transaction
503 .clone_into_pooled()
504 .inspect_err(|err| {
505 debug!(
506 target: "txpool", %err,
507 "failed to convert transaction to pooled element; skipping",
508 );
509 })
510 .ok()
511 }
512 }
513
514 pub fn get_pooled_transaction_elements(
517 &self,
518 tx_hashes: Vec<TxHash>,
519 limit: GetPooledTransactionLimit,
520 ) -> Vec<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>
521 where
522 <V as TransactionValidator>::Transaction: EthPoolTransaction,
523 {
524 let mut elements = Vec::new();
525 self.append_pooled_transaction_elements(&tx_hashes, limit, &mut elements);
526 elements.shrink_to_fit();
527 elements
528 }
529
530 pub fn get_pooled_transaction_element(
532 &self,
533 tx_hash: TxHash,
534 ) -> Option<Recovered<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>>
535 where
536 <V as TransactionValidator>::Transaction: EthPoolTransaction,
537 {
538 self.get(&tx_hash).and_then(|tx| self.to_pooled_transaction(tx))
539 }
540
541 pub fn on_canonical_state_change(&self, update: CanonicalStateUpdate<'_, V::Block>) {
543 trace!(target: "txpool", ?update, "updating pool on canonical state change");
544
545 let block_info = update.block_info();
546 let CanonicalStateUpdate {
547 new_tip, changed_accounts, mined_transactions, update_kind, ..
548 } = update;
549 self.validator.on_new_head_block(new_tip);
550
551 let changed_senders = self.changed_senders(changed_accounts.into_iter());
552
553 let outcome = self.pool.write().on_canonical_state_change(
555 block_info,
556 mined_transactions,
557 changed_senders,
558 update_kind,
559 );
560
561 self.delete_discarded_blobs(outcome.discarded.iter());
563
564 self.notify_on_new_state(outcome);
566 }
567
568 pub fn update_accounts(&self, accounts: Vec<ChangedAccount>) {
574 let changed_senders = self.changed_senders(accounts.into_iter());
575 let UpdateOutcome { promoted, discarded } =
576 self.pool.write().update_accounts(changed_senders);
577
578 self.notify_on_transaction_updates(promoted, discarded);
579 }
580
581 fn add_transaction(
589 &self,
590 pool: &mut RwLockWriteGuard<'_, TxPool<T>>,
591 origin: TransactionOrigin,
592 tx: TransactionValidationOutcome<T::Transaction>,
593 timestamp: Instant,
594 ) -> (PoolResult<AddedTransactionOutcome>, Option<AddedTransactionMeta<T::Transaction>>) {
595 match tx {
596 TransactionValidationOutcome::Valid {
597 balance,
598 state_nonce,
599 transaction,
600 propagate,
601 bytecode_hash,
602 authorities,
603 } => {
604 let sender_id = self.get_sender_id(transaction.sender());
605 let transaction_id = TransactionId::new(sender_id, transaction.nonce());
606
607 let (transaction, blob_sidecar) = match transaction {
609 ValidTransaction::Valid(tx) => (tx, None),
610 ValidTransaction::ValidWithSidecar { transaction, sidecar } => {
611 debug_assert!(
612 transaction.is_eip4844(),
613 "validator returned sidecar for non EIP-4844 transaction"
614 );
615 (transaction, Some(sidecar))
616 }
617 };
618
619 let tx = ValidPoolTransaction {
620 transaction,
621 transaction_id,
622 propagate,
623 timestamp,
624 origin,
625 authority_ids: authorities.map(|auths| self.get_sender_ids(auths)),
626 };
627
628 let added = match pool.add_transaction(tx, balance, state_nonce, bytecode_hash) {
629 Ok(added) => added,
630 Err(err) => return (Err(err), None),
631 };
632 let hash = *added.hash();
633 let state = added.transaction_state();
634
635 let meta = AddedTransactionMeta { added, blob_sidecar };
636
637 (Ok(AddedTransactionOutcome { hash, state }), Some(meta))
638 }
639 TransactionValidationOutcome::Invalid(tx, err) => {
640 self.with_event_listener(|listener| listener.invalid(tx.hash()));
641 (Err(PoolError::new(*tx.hash(), err)), None)
642 }
643 TransactionValidationOutcome::Error(tx_hash, err) => {
644 self.with_event_listener(|listener| listener.discarded(&tx_hash));
645 (Err(PoolError::other(tx_hash, err)), None)
646 }
647 }
648 }
649
650 pub fn add_transaction_and_subscribe(
652 &self,
653 origin: TransactionOrigin,
654 tx: TransactionValidationOutcome<T::Transaction>,
655 ) -> PoolResult<TransactionEvents> {
656 let listener = {
657 let mut listener = self.event_listener.write();
658 let events = listener.subscribe(tx.tx_hash());
659 self.mark_event_listener_installed();
660 events
661 };
662 let mut results = self.add_transactions(origin, std::iter::once(tx));
663 results.pop().expect("result length is the same as the input")?;
664 Ok(listener)
665 }
666
667 pub fn add_transactions(
672 &self,
673 origin: TransactionOrigin,
674 transactions: impl IntoIterator<Item = TransactionValidationOutcome<T::Transaction>>,
675 ) -> Vec<PoolResult<AddedTransactionOutcome>> {
676 self.add_transactions_with_origins(transactions.into_iter().map(|tx| (origin, tx)))
677 }
678
679 pub fn add_transactions_with_origins(
682 &self,
683 transactions: impl IntoIterator<
684 Item = (TransactionOrigin, TransactionValidationOutcome<T::Transaction>),
685 >,
686 ) -> Vec<PoolResult<AddedTransactionOutcome>> {
687 let transactions = transactions.into_iter();
688 let mut added_metas = Vec::with_capacity(transactions.size_hint().0);
689
690 let (mut results, added_metas, discarded) = {
692 let mut pool = self.pool.write();
693 let timestamp = Instant::now();
694
695 let results = transactions
696 .map(|(origin, tx)| {
697 let (result, meta) = self.add_transaction(&mut pool, origin, tx, timestamp);
698
699 if result.is_ok() &&
701 let Some(meta) = meta
702 {
703 added_metas.push(meta);
704 }
705
706 result
707 })
708 .collect::<Vec<_>>();
709
710 let discarded = if results.iter().any(Result::is_ok) {
712 let discarded = pool.discard_worst();
713 pool.update_size_metrics();
714 discarded
715 } else {
716 Default::default()
717 };
718
719 (results, added_metas, discarded)
720 };
721
722 for meta in added_metas {
723 self.on_added_transaction(meta);
724 }
725
726 if !discarded.is_empty() {
727 self.delete_discarded_blobs(discarded.iter());
729 self.with_event_listener(|listener| listener.discarded_many(&discarded));
730
731 const MAX_LINEAR_SEARCH_DISCARDS: usize = 4;
733 let discarded_hashes = (discarded.len() > MAX_LINEAR_SEARCH_DISCARDS)
734 .then(|| discarded.iter().map(|tx| *tx.hash()).collect::<B256Set>());
735 let is_discarded = |hash: &TxHash| match &discarded_hashes {
736 Some(hashes) => hashes.contains(hash),
737 None => discarded.iter().any(|tx| tx.hash() == hash),
738 };
739
740 for res in &mut results {
743 if let Ok(AddedTransactionOutcome { hash, .. }) = res &&
744 is_discarded(hash)
745 {
746 *res = Err(PoolError::new(*hash, PoolErrorKind::DiscardedOnInsert))
747 }
748 }
749 };
750
751 results
752 }
753
754 fn on_added_transaction(&self, mut meta: AddedTransactionMeta<T::Transaction>) {
759 if let Some(sidecar) = meta.blob_sidecar {
761 let hash = *meta.added.hash();
762 self.on_new_blob_sidecar(&hash, &sidecar);
763 self.insert_blob(hash, sidecar);
764 }
765
766 if let Some(replaced) = meta.added.replaced_blob_transaction() {
768 debug!(target: "txpool", "[{:?}] delete replaced blob sidecar", replaced);
769 self.delete_blob(replaced);
770 }
771
772 if let Some(discarded) = meta.added.discarded_transactions() {
774 self.delete_discarded_blobs(discarded.iter());
775 }
776
777 if let Some(pending) = meta.added.as_pending() {
779 self.on_new_pending_transaction(pending);
780 }
781
782 let promoted = meta.added.take_parked_promoted();
785 if !promoted.is_empty() {
786 self.notify_on_transaction_updates(promoted, Vec::new());
787 }
788
789 self.notify_event_listeners(&meta.added);
791
792 self.on_new_transaction(meta.added.into_new_transaction_event());
794 }
795
796 pub fn on_new_pending_transaction(&self, pending: &AddedPendingTransaction<T::Transaction>) {
805 let mut needs_cleanup = false;
806
807 {
808 let listeners = self.pending_transaction_listener.read();
809 for listener in listeners.iter() {
810 if !listener.send_all(pending.pending_transactions(listener.kind)) {
811 needs_cleanup = true;
812 }
813 }
814 }
815
816 if needs_cleanup {
818 self.pending_transaction_listener
819 .write()
820 .retain(|listener| !listener.sender.is_closed());
821 }
822 }
823
824 pub fn on_new_transaction(&self, event: NewTransactionEvent<T::Transaction>) {
833 let mut needs_cleanup = false;
834
835 {
836 let listeners = self.transaction_listener.read();
837 for listener in listeners.iter() {
838 if listener.kind.is_propagate_only() && !event.transaction.propagate {
839 if listener.sender.is_closed() {
840 needs_cleanup = true;
841 }
842 continue
844 }
845
846 if !listener.send(event.clone()) {
847 needs_cleanup = true;
848 }
849 }
850 }
851
852 if needs_cleanup {
854 self.transaction_listener.write().retain(|listener| !listener.sender.is_closed());
855 }
856 }
857
858 fn on_new_blob_sidecar(&self, tx_hash: &TxHash, sidecar: &BlobTransactionSidecarVariant) {
860 let mut sidecar_listeners = self.blob_transaction_sidecar_listener.lock();
861 if sidecar_listeners.is_empty() {
862 return
863 }
864 let sidecar = Arc::new(sidecar.clone());
865 sidecar_listeners.retain_mut(|listener| {
866 let new_blob_event = NewBlobSidecar { tx_hash: *tx_hash, sidecar: sidecar.clone() };
867 match listener.sender.try_send(new_blob_event) {
868 Ok(()) => true,
869 Err(err) => {
870 if matches!(err, mpsc::error::TrySendError::Full(_)) {
871 debug!(
872 target: "txpool",
873 "[{:?}] failed to send blob sidecar; channel full",
874 sidecar,
875 );
876 true
877 } else {
878 false
879 }
880 }
881 }
882 })
883 }
884
885 fn notify_on_new_state(&self, outcome: OnNewCanonicalStateOutcome<T::Transaction>) {
887 trace!(target: "txpool", promoted=outcome.promoted.len(), discarded= outcome.discarded.len() ,"notifying listeners on state change");
888
889 let mut needs_pending_cleanup = false;
891 {
892 let listeners = self.pending_transaction_listener.read();
893 for listener in listeners.iter() {
894 if !listener.send_all(outcome.pending_transactions(listener.kind)) {
895 needs_pending_cleanup = true;
896 }
897 }
898 }
899 if needs_pending_cleanup {
900 self.pending_transaction_listener.write().retain(|l| !l.sender.is_closed());
901 }
902
903 let mut needs_tx_cleanup = false;
905 {
906 let listeners = self.transaction_listener.read();
907 for listener in listeners.iter() {
908 if !listener.send_all(outcome.full_pending_transactions(listener.kind)) {
909 needs_tx_cleanup = true;
910 }
911 }
912 }
913 if needs_tx_cleanup {
914 self.transaction_listener.write().retain(|l| !l.sender.is_closed());
915 }
916
917 let OnNewCanonicalStateOutcome { mined, promoted, discarded, block_hash } = outcome;
918
919 self.with_event_listener(|listener| {
921 for tx in &mined {
922 listener.mined(tx, block_hash);
923 }
924 for tx in &promoted {
925 listener.pending(tx.hash(), None);
926 }
927 for tx in &discarded {
928 listener.discarded(tx.hash());
929 }
930 })
931 }
932
933 pub fn notify_on_transaction_updates(
942 &self,
943 promoted: Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
944 discarded: Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
945 ) {
946 if !promoted.is_empty() {
948 let mut needs_pending_cleanup = false;
949 {
950 let listeners = self.pending_transaction_listener.read();
951 for listener in listeners.iter() {
952 let promoted_hashes = promoted.iter().filter_map(|tx| {
953 if listener.kind.is_propagate_only() && !tx.propagate {
954 None
955 } else {
956 Some(*tx.hash())
957 }
958 });
959 if !listener.send_all(promoted_hashes) {
960 needs_pending_cleanup = true;
961 }
962 }
963 }
964 if needs_pending_cleanup {
965 self.pending_transaction_listener.write().retain(|l| !l.sender.is_closed());
966 }
967
968 let mut needs_tx_cleanup = false;
970 {
971 let listeners = self.transaction_listener.read();
972 for listener in listeners.iter() {
973 let promoted_txs = promoted.iter().filter_map(|tx| {
974 if listener.kind.is_propagate_only() && !tx.propagate {
975 None
976 } else {
977 Some(NewTransactionEvent::pending(tx.clone()))
978 }
979 });
980 if !listener.send_all(promoted_txs) {
981 needs_tx_cleanup = true;
982 }
983 }
984 }
985 if needs_tx_cleanup {
986 self.transaction_listener.write().retain(|l| !l.sender.is_closed());
987 }
988 }
989
990 self.with_event_listener(|listener| {
991 for tx in &promoted {
992 listener.pending(tx.hash(), None);
993 }
994 for tx in &discarded {
995 listener.discarded(tx.hash());
996 }
997 });
998
999 if !discarded.is_empty() {
1000 self.delete_discarded_blobs(discarded.iter());
1003 }
1004 }
1005
1006 pub fn notify_event_listeners(&self, tx: &AddedTransaction<T::Transaction>) {
1015 self.with_event_listener(|listener| match tx {
1016 AddedTransaction::Pending(tx) => {
1017 let AddedPendingTransaction { transaction, promoted, discarded, replaced } = tx;
1018
1019 listener.pending(transaction.hash(), replaced.clone());
1020 for tx in promoted {
1021 listener.pending(tx.hash(), None);
1022 }
1023 for tx in discarded {
1024 listener.discarded(tx.hash());
1025 }
1026 }
1027 AddedTransaction::Parked { transaction, replaced, queued_reason, .. } => {
1028 listener.queued(transaction.hash(), queued_reason.clone());
1029 if let Some(replaced) = replaced {
1030 listener.replaced(replaced.clone(), *transaction.hash());
1031 }
1032 }
1033 });
1034 }
1035
1036 pub fn best_transactions(&self) -> BestTransactions<T> {
1038 self.get_pool_data().best_transactions()
1039 }
1040
1041 pub fn best_transactions_with_attributes(
1044 &self,
1045 best_transactions_attributes: BestTransactionsAttributes,
1046 ) -> Box<dyn crate::traits::BestTransactions<Item = Arc<ValidPoolTransaction<T::Transaction>>>>
1047 {
1048 self.get_pool_data().best_transactions_with_attributes(best_transactions_attributes)
1049 }
1050
1051 pub fn pending_transactions_max(
1053 &self,
1054 max: usize,
1055 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1056 self.get_pool_data().pending_transactions_iter().take(max).collect()
1057 }
1058
1059 pub fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1061 self.get_pool_data().pending_transactions()
1062 }
1063
1064 pub fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1066 self.get_pool_data().queued_transactions()
1067 }
1068
1069 pub fn all_transactions(&self) -> AllPoolTransactions<T::Transaction> {
1071 let pool = self.get_pool_data();
1072 AllPoolTransactions {
1073 pending: pool.pending_transactions(),
1074 queued: pool.queued_transactions(),
1075 }
1076 }
1077
1078 pub fn all_transactions_by_sender(
1081 &self,
1082 sender: Address,
1083 ) -> AllPoolTransactions<T::Transaction> {
1084 let Some(sender_id) = self.sender_id(&sender) else { return Default::default() };
1085 let pool = self.get_pool_data();
1086 AllPoolTransactions {
1087 pending: pool.pending_txs_by_sender(sender_id),
1088 queued: pool.queued_txs_by_sender(sender_id),
1089 }
1090 }
1091
1092 pub fn all_transaction_hashes(&self) -> Vec<TxHash> {
1094 self.get_pool_data().all().transactions_iter().map(|tx| *tx.hash()).collect()
1095 }
1096
1097 pub fn remove_transactions(
1102 &self,
1103 hashes: Vec<TxHash>,
1104 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1105 if hashes.is_empty() {
1106 return Vec::new()
1107 }
1108 let removed = self.pool.write().remove_transactions(hashes);
1109
1110 self.with_event_listener(|listener| listener.discarded_many(&removed));
1111
1112 removed
1113 }
1114
1115 pub fn remove_transactions_and_descendants(
1118 &self,
1119 hashes: Vec<TxHash>,
1120 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1121 if hashes.is_empty() {
1122 return Vec::new()
1123 }
1124 let removed = self.pool.write().remove_transactions_and_descendants(hashes);
1125
1126 self.with_event_listener(|listener| {
1127 for tx in &removed {
1128 listener.discarded(tx.hash());
1129 }
1130 });
1131
1132 removed
1133 }
1134
1135 pub fn remove_transactions_by_sender(
1137 &self,
1138 sender: Address,
1139 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1140 let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1141 let removed = self.pool.write().remove_transactions_by_sender(sender_id);
1142
1143 self.with_event_listener(|listener| listener.discarded_many(&removed));
1144
1145 removed
1146 }
1147
1148 pub fn prune_transactions(
1153 &self,
1154 hashes: Vec<TxHash>,
1155 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1156 if hashes.is_empty() {
1157 return Vec::new()
1158 }
1159
1160 self.pool.write().prune_transactions(hashes)
1161 }
1162
1163 pub fn retain_unknown<A>(&self, announcement: &mut A)
1165 where
1166 A: HandleMempoolData,
1167 {
1168 if announcement.is_empty() {
1169 return
1170 }
1171 let pool = self.get_pool_data();
1172 announcement.retain_by_hash(|tx| !pool.contains(tx))
1173 }
1174
1175 pub fn retain_contains<A>(&self, announcement: &mut A)
1177 where
1178 A: HandleMempoolData,
1179 {
1180 if announcement.is_empty() {
1181 return
1182 }
1183 let pool = self.get_pool_data();
1184 announcement.retain_by_hash(|tx| pool.contains(tx))
1185 }
1186
1187 pub fn get(&self, tx_hash: &TxHash) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1189 self.get_pool_data().get(tx_hash)
1190 }
1191
1192 pub fn get_transactions_by_sender(
1194 &self,
1195 sender: Address,
1196 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1197 let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1198 self.get_pool_data().get_transactions_by_sender(sender_id)
1199 }
1200
1201 pub fn get_pending_transaction_by_sender_and_nonce(
1203 &self,
1204 sender: Address,
1205 nonce: u64,
1206 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1207 let sender_id = self.sender_id(&sender)?;
1208 self.get_pool_data().get_pending_transaction_by_sender_and_nonce(sender_id, nonce)
1209 }
1210
1211 pub fn get_queued_transactions_by_sender(
1213 &self,
1214 sender: Address,
1215 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1216 let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1217 self.get_pool_data().queued_txs_by_sender(sender_id)
1218 }
1219
1220 pub fn pending_transactions_with_predicate(
1222 &self,
1223 predicate: impl FnMut(&ValidPoolTransaction<T::Transaction>) -> bool,
1224 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1225 self.get_pool_data().pending_transactions_with_predicate(predicate)
1226 }
1227
1228 pub fn get_pending_transactions_by_sender(
1230 &self,
1231 sender: Address,
1232 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1233 let Some(sender_id) = self.sender_id(&sender) else { return Vec::new() };
1234 self.get_pending_transactions_by_sender_id(sender_id)
1235 }
1236
1237 pub fn get_pending_transactions_by_sender_id(
1239 &self,
1240 sender_id: SenderId,
1241 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1242 self.get_pool_data().pending_txs_by_sender(sender_id)
1243 }
1244
1245 pub fn get_highest_transaction_by_sender(
1247 &self,
1248 sender: Address,
1249 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1250 let sender_id = self.sender_id(&sender)?;
1251 self.get_highest_transaction_by_sender_id(sender_id)
1252 }
1253
1254 pub fn get_highest_transaction_by_sender_id(
1256 &self,
1257 sender_id: SenderId,
1258 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1259 self.get_pool_data().get_highest_transaction_by_sender(sender_id)
1260 }
1261
1262 pub fn get_highest_consecutive_transaction_by_sender(
1264 &self,
1265 sender: Address,
1266 on_chain_nonce: u64,
1267 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1268 let sender_id = self.sender_id(&sender)?;
1269 self.get_highest_consecutive_transaction_by_sender_id(sender_id, on_chain_nonce)
1270 }
1271
1272 pub fn get_highest_consecutive_transaction_by_sender_id(
1274 &self,
1275 sender_id: SenderId,
1276 on_chain_nonce: u64,
1277 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1278 self.get_pool_data().get_highest_consecutive_transaction_by_sender(
1279 sender_id.into_transaction_id(on_chain_nonce),
1280 )
1281 }
1282
1283 pub fn get_transaction_by_transaction_id(
1285 &self,
1286 transaction_id: &TransactionId,
1287 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
1288 self.get_pool_data().all().get(transaction_id).map(|tx| tx.transaction.clone())
1289 }
1290
1291 pub fn get_transactions_by_origin(
1293 &self,
1294 origin: TransactionOrigin,
1295 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1296 self.get_pool_data()
1297 .all()
1298 .transactions_iter()
1299 .filter(|tx| tx.origin == origin)
1300 .cloned()
1301 .collect()
1302 }
1303
1304 pub fn get_pending_transactions_by_origin(
1306 &self,
1307 origin: TransactionOrigin,
1308 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1309 self.get_pool_data().pending_transactions_iter().filter(|tx| tx.origin == origin).collect()
1310 }
1311
1312 pub fn get_all(&self, txs: Vec<TxHash>) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1316 if txs.is_empty() {
1317 return Vec::new()
1318 }
1319 self.get_pool_data().get_all(txs).collect()
1320 }
1321
1322 fn get_all_propagatable(
1326 &self,
1327 txs: &[TxHash],
1328 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
1329 if txs.is_empty() {
1330 return Vec::new()
1331 }
1332 let pool = self.get_pool_data();
1333 txs.iter().filter_map(|tx| pool.get(tx).filter(|tx| tx.propagate)).collect()
1334 }
1335
1336 pub fn on_propagated(&self, txs: PropagatedTransactions) {
1338 if txs.is_empty() {
1339 return
1340 }
1341 self.with_event_listener(|listener| {
1342 txs.into_iter().for_each(|(hash, peers)| listener.propagated(&hash, peers));
1343 });
1344 }
1345
1346 pub fn len(&self) -> usize {
1348 self.get_pool_data().len()
1349 }
1350
1351 pub fn is_empty(&self) -> bool {
1353 self.get_pool_data().is_empty()
1354 }
1355
1356 pub fn is_exceeded(&self) -> bool {
1358 self.pool.read().is_exceeded()
1359 }
1360
1361 fn insert_blob(&self, hash: TxHash, blob: PooledBlobSidecar) {
1363 debug!(target: "txpool", "[{:?}] storing blob sidecar", hash);
1364 if let Err(err) = self.blob_store.insert(hash, blob) {
1365 warn!(target: "txpool", %err, "[{:?}] failed to insert blob", hash);
1366 self.blob_store_metrics.blobstore_failed_inserts.increment(1);
1367 }
1368 self.update_blob_store_metrics();
1369 }
1370
1371 pub fn delete_blob(&self, blob: TxHash) {
1373 let _ = self.blob_store.delete(blob);
1374 }
1375
1376 pub fn delete_blobs(&self, txs: Vec<TxHash>) {
1378 let _ = self.blob_store.delete_all(txs);
1379 }
1380
1381 pub fn cleanup_blobs(&self) {
1383 let stat = self.blob_store.cleanup();
1384 self.blob_store_metrics.blobstore_failed_deletes.increment(stat.delete_failed as u64);
1385 self.update_blob_store_metrics();
1386 }
1387
1388 fn update_blob_store_metrics(&self) {
1389 if let Some(data_size) = self.blob_store.data_size_hint() {
1390 self.blob_store_metrics.blobstore_byte_size.set(data_size as f64);
1391 }
1392 self.blob_store_metrics.blobstore_entries.set(self.blob_store.blobs_len() as f64);
1393 }
1394
1395 fn delete_discarded_blobs<'a>(
1397 &'a self,
1398 transactions: impl IntoIterator<Item = &'a Arc<ValidPoolTransaction<T::Transaction>>>,
1399 ) {
1400 let blob_txs = transactions
1401 .into_iter()
1402 .filter(|tx| tx.transaction.is_eip4844())
1403 .map(|tx| *tx.hash())
1404 .collect();
1405 self.delete_blobs(blob_txs);
1406 }
1407}
1408
1409impl<V, T: TransactionOrdering, S> fmt::Debug for PoolInner<V, T, S> {
1410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1411 f.debug_struct("PoolInner").field("config", &self.config).finish_non_exhaustive()
1412 }
1413}
1414
1415#[derive(Debug)]
1420struct AddedTransactionMeta<T: PoolTransaction> {
1421 added: AddedTransaction<T>,
1423 blob_sidecar: Option<PooledBlobSidecar>,
1425}
1426
1427#[derive(Debug, Clone)]
1429pub struct AddedPendingTransaction<T: PoolTransaction> {
1430 pub transaction: Arc<ValidPoolTransaction<T>>,
1432 pub replaced: Option<Arc<ValidPoolTransaction<T>>>,
1434 pub promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1436 pub discarded: Vec<Arc<ValidPoolTransaction<T>>>,
1438}
1439
1440impl<T: PoolTransaction> AddedPendingTransaction<T> {
1441 pub(crate) fn pending_transactions(
1447 &self,
1448 kind: TransactionListenerKind,
1449 ) -> impl Iterator<Item = B256> + '_ {
1450 let iter = std::iter::once(&self.transaction).chain(self.promoted.iter());
1451 PendingTransactionIter { kind, iter }
1452 }
1453}
1454
1455pub(crate) struct PendingTransactionIter<Iter> {
1456 kind: TransactionListenerKind,
1457 iter: Iter,
1458}
1459
1460impl<'a, Iter, T> Iterator for PendingTransactionIter<Iter>
1461where
1462 Iter: Iterator<Item = &'a Arc<ValidPoolTransaction<T>>>,
1463 T: PoolTransaction + 'a,
1464{
1465 type Item = B256;
1466
1467 fn next(&mut self) -> Option<Self::Item> {
1468 loop {
1469 let next = self.iter.next()?;
1470 if self.kind.is_propagate_only() && !next.propagate {
1471 continue
1472 }
1473 return Some(*next.hash())
1474 }
1475 }
1476}
1477
1478pub(crate) struct FullPendingTransactionIter<Iter> {
1480 kind: TransactionListenerKind,
1481 iter: Iter,
1482}
1483
1484impl<'a, Iter, T> Iterator for FullPendingTransactionIter<Iter>
1485where
1486 Iter: Iterator<Item = &'a Arc<ValidPoolTransaction<T>>>,
1487 T: PoolTransaction + 'a,
1488{
1489 type Item = NewTransactionEvent<T>;
1490
1491 fn next(&mut self) -> Option<Self::Item> {
1492 loop {
1493 let next = self.iter.next()?;
1494 if self.kind.is_propagate_only() && !next.propagate {
1495 continue
1496 }
1497 return Some(NewTransactionEvent {
1498 subpool: SubPool::Pending,
1499 transaction: next.clone(),
1500 })
1501 }
1502 }
1503}
1504
1505#[derive(Debug, Clone)]
1507pub enum AddedTransaction<T: PoolTransaction> {
1508 Pending(AddedPendingTransaction<T>),
1510 Parked {
1513 transaction: Arc<ValidPoolTransaction<T>>,
1515 replaced: Option<Arc<ValidPoolTransaction<T>>>,
1517 subpool: SubPool,
1519 queued_reason: Option<QueuedReason>,
1521 promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1527 },
1528}
1529
1530impl<T: PoolTransaction> AddedTransaction<T> {
1531 pub const fn as_pending(&self) -> Option<&AddedPendingTransaction<T>> {
1533 match self {
1534 Self::Pending(tx) => Some(tx),
1535 _ => None,
1536 }
1537 }
1538
1539 pub const fn replaced(&self) -> Option<&Arc<ValidPoolTransaction<T>>> {
1541 match self {
1542 Self::Pending(tx) => tx.replaced.as_ref(),
1543 Self::Parked { replaced, .. } => replaced.as_ref(),
1544 }
1545 }
1546
1547 pub(crate) fn take_parked_promoted(&mut self) -> Vec<Arc<ValidPoolTransaction<T>>> {
1552 match self {
1553 Self::Parked { promoted, .. } => std::mem::take(promoted),
1554 Self::Pending(_) => Vec::new(),
1555 }
1556 }
1557
1558 pub(crate) fn discarded_transactions(&self) -> Option<&[Arc<ValidPoolTransaction<T>>]> {
1560 match self {
1561 Self::Pending(tx) => Some(&tx.discarded),
1562 Self::Parked { .. } => None,
1563 }
1564 }
1565
1566 pub(crate) fn replaced_blob_transaction(&self) -> Option<B256> {
1568 self.replaced().filter(|tx| tx.transaction.is_eip4844()).map(|tx| *tx.transaction.hash())
1569 }
1570
1571 pub fn hash(&self) -> &TxHash {
1573 match self {
1574 Self::Pending(tx) => tx.transaction.hash(),
1575 Self::Parked { transaction, .. } => transaction.hash(),
1576 }
1577 }
1578
1579 pub fn into_new_transaction_event(self) -> NewTransactionEvent<T> {
1581 match self {
1582 Self::Pending(tx) => {
1583 NewTransactionEvent { subpool: SubPool::Pending, transaction: tx.transaction }
1584 }
1585 Self::Parked { transaction, subpool, .. } => {
1586 NewTransactionEvent { transaction, subpool }
1587 }
1588 }
1589 }
1590
1591 pub(crate) const fn subpool(&self) -> SubPool {
1593 match self {
1594 Self::Pending(_) => SubPool::Pending,
1595 Self::Parked { subpool, .. } => *subpool,
1596 }
1597 }
1598
1599 #[cfg(test)]
1601 pub(crate) fn id(&self) -> &TransactionId {
1602 match self {
1603 Self::Pending(added) => added.transaction.id(),
1604 Self::Parked { transaction, .. } => transaction.id(),
1605 }
1606 }
1607
1608 pub const fn queued_reason(&self) -> Option<&QueuedReason> {
1610 match self {
1611 Self::Pending(_) => None,
1612 Self::Parked { queued_reason, .. } => queued_reason.as_ref(),
1613 }
1614 }
1615
1616 pub fn transaction_state(&self) -> AddedTransactionState {
1618 match self.subpool() {
1619 SubPool::Pending => AddedTransactionState::Pending,
1620 _ => {
1621 if let Some(reason) = self.queued_reason() {
1624 AddedTransactionState::Queued(reason.clone())
1625 } else {
1626 AddedTransactionState::Queued(QueuedReason::NonceGap)
1628 }
1629 }
1630 }
1631 }
1632}
1633
1634#[derive(Debug, Clone, PartialEq, Eq)]
1636pub enum QueuedReason {
1637 NonceGap,
1639 ParkedAncestors,
1641 InsufficientBalance,
1643 TooMuchGas,
1645 InsufficientBaseFee,
1647 InsufficientBlobFee,
1649}
1650
1651#[derive(Debug, Clone, PartialEq, Eq)]
1653pub enum AddedTransactionState {
1654 Pending,
1656 Queued(QueuedReason),
1658}
1659
1660impl AddedTransactionState {
1661 pub const fn is_queued(&self) -> bool {
1663 matches!(self, Self::Queued(_))
1664 }
1665
1666 pub const fn is_pending(&self) -> bool {
1668 matches!(self, Self::Pending)
1669 }
1670
1671 pub const fn queued_reason(&self) -> Option<&QueuedReason> {
1673 match self {
1674 Self::Queued(reason) => Some(reason),
1675 Self::Pending => None,
1676 }
1677 }
1678}
1679
1680#[derive(Debug, Clone, PartialEq, Eq)]
1682pub struct AddedTransactionOutcome {
1683 pub hash: TxHash,
1685 pub state: AddedTransactionState,
1687}
1688
1689impl AddedTransactionOutcome {
1690 pub const fn is_queued(&self) -> bool {
1692 self.state.is_queued()
1693 }
1694
1695 pub const fn is_pending(&self) -> bool {
1697 self.state.is_pending()
1698 }
1699}
1700
1701#[derive(Debug)]
1703pub(crate) struct OnNewCanonicalStateOutcome<T: PoolTransaction> {
1704 pub(crate) block_hash: B256,
1706 pub(crate) mined: Vec<TxHash>,
1708 pub(crate) promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1710 pub(crate) discarded: Vec<Arc<ValidPoolTransaction<T>>>,
1712}
1713
1714impl<T: PoolTransaction> OnNewCanonicalStateOutcome<T> {
1715 pub(crate) fn pending_transactions(
1721 &self,
1722 kind: TransactionListenerKind,
1723 ) -> impl Iterator<Item = B256> + '_ {
1724 let iter = self.promoted.iter();
1725 PendingTransactionIter { kind, iter }
1726 }
1727
1728 pub(crate) fn full_pending_transactions(
1734 &self,
1735 kind: TransactionListenerKind,
1736 ) -> impl Iterator<Item = NewTransactionEvent<T>> + '_ {
1737 let iter = self.promoted.iter();
1738 FullPendingTransactionIter { kind, iter }
1739 }
1740}
1741
1742#[cfg(test)]
1743mod tests {
1744 use super::{AddedPendingTransaction, AddedTransaction};
1745 use crate::{
1746 blobstore::{BlobStore, InMemoryBlobStore, PooledBlobSidecar},
1747 identifier::SenderId,
1748 test_utils::{
1749 testing_pool, MockTransaction, MockTransactionFactory, TestPool, TestPoolBuilder,
1750 },
1751 validate::ValidTransaction,
1752 BlockInfo, FullTransactionEvent, PoolConfig, SubPool, SubPoolLimit, TransactionEvent,
1753 TransactionListenerKind, TransactionOrigin, TransactionPool, TransactionPoolExt,
1754 TransactionValidationOutcome, ValidPoolTransaction, U256,
1755 };
1756 use alloy_consensus::Transaction;
1757 use alloy_eips::{
1758 eip4844::{Blob, BlobTransactionSidecar, Bytes48},
1759 eip7594::BlobTransactionSidecarVariant,
1760 };
1761 use alloy_primitives::{Address, B256};
1762 use futures_util::{FutureExt, StreamExt};
1763 use std::sync::Arc;
1764 use tokio::sync::mpsc::error::TryRecvError;
1765
1766 fn insert_with_state_nonce(pool: &TestPool, nonce: u64, state_nonce: u64, propagate: bool) {
1768 let transaction = MockTransaction::eip1559()
1769 .with_sender(Address::with_last_byte(1))
1770 .with_nonce(nonce)
1771 .with_hash(B256::repeat_byte(nonce as u8));
1772 pool.pool
1773 .add_transactions(
1774 TransactionOrigin::External,
1775 [TransactionValidationOutcome::Valid {
1776 balance: U256::MAX,
1777 state_nonce,
1778 bytecode_hash: None,
1779 transaction: ValidTransaction::Valid(transaction),
1780 propagate,
1781 authorities: None,
1782 }],
1783 )
1784 .pop()
1785 .unwrap()
1786 .unwrap();
1787 }
1788
1789 fn transaction_nonces(txs: &[Arc<ValidPoolTransaction<MockTransaction>>]) -> Vec<u64> {
1790 let mut nonces: Vec<_> = txs.iter().map(|tx| tx.transaction.nonce()).collect();
1791 nonces.sort_unstable();
1792 nonces
1793 }
1794
1795 #[tokio::test]
1796 async fn all_transactions_by_sender_across_reclassification() {
1797 let pool = testing_pool();
1798 let sender = Address::with_last_byte(1);
1799 for nonce in [0, 1, 9] {
1801 let tx =
1802 MockTransaction::legacy().with_sender(sender).with_nonce(nonce).with_gas_price(100);
1803 pool.add_transaction(TransactionOrigin::External, tx).await.unwrap();
1804 }
1805 let nonces = |txs: &[Arc<ValidPoolTransaction<MockTransaction>>]| {
1806 let mut nonces: Vec<_> = txs.iter().map(|tx| tx.transaction.nonce()).collect();
1807 nonces.sort_unstable();
1808 nonces
1809 };
1810
1811 let txs = pool.all_transactions_by_sender(sender);
1812 assert_eq!(nonces(&txs.pending), [0, 1]);
1813 assert_eq!(nonces(&txs.queued), [9]);
1814
1815 let sender_id = pool.inner().sender_id(&sender).unwrap();
1816 assert_eq!(nonces(&pool.inner().get_pending_transactions_by_sender_id(sender_id)), [0, 1]);
1817 assert_eq!(
1818 pool.inner().get_highest_transaction_by_sender_id(sender_id).unwrap().nonce(),
1819 9
1820 );
1821 assert_eq!(
1822 pool.inner()
1823 .get_highest_consecutive_transaction_by_sender_id(sender_id, 0)
1824 .unwrap()
1825 .nonce(),
1826 1
1827 );
1828
1829 pool.set_block_info(BlockInfo {
1832 pending_basefee: 200,
1833 block_gas_limit: 30_000_000,
1834 ..Default::default()
1835 });
1836 let txs = pool.all_transactions_by_sender(sender);
1837 assert!(txs.pending.is_empty());
1838 assert_eq!(nonces(&txs.queued), [0, 1, 9]);
1839 assert_eq!(nonces(&pool.get_transactions_by_sender(sender)), [0, 1, 9]);
1840 }
1841
1842 #[test]
1843 fn subscribe_transaction_events_without_pool_residency() {
1844 let test_pool = testing_pool();
1845 let pool = &test_pool.pool;
1846 let tx = MockTransactionFactory::default().validated_arc(MockTransaction::eip1559());
1847 assert!(pool.add_transaction_event_listener(*tx.hash()).is_none());
1848
1849 let mut events = pool.subscribe_transaction_events(*tx.hash());
1850 pool.notify_event_listeners(&AddedTransaction::Pending(AddedPendingTransaction {
1851 transaction: tx,
1852 replaced: None,
1853 promoted: vec![],
1854 discarded: vec![],
1855 }));
1856 assert_eq!(events.next().now_or_never(), Some(Some(TransactionEvent::Pending)));
1857 }
1858
1859 #[test]
1860 fn queued_insertion_notifies_older_promotions() {
1861 let test_pool = testing_pool();
1862 let pool = &test_pool.pool;
1863 let mut network = pool.add_pending_listener(TransactionListenerKind::PropagateOnly);
1864 let mut all = pool.add_pending_listener(TransactionListenerKind::All);
1865 insert_with_state_nonce(&test_pool, 1, 0, true);
1867 insert_with_state_nonce(&test_pool, 2, 0, true);
1868 let txs = test_pool.all_transactions_by_sender(Address::with_last_byte(1));
1869 assert!(txs.pending.is_empty());
1870 assert_eq!(transaction_nonces(&txs.queued), [1, 2]);
1871 assert_eq!(network.try_recv(), Err(TryRecvError::Empty));
1872 assert_eq!(all.try_recv(), Err(TryRecvError::Empty));
1873
1874 let mut full_network =
1875 pool.add_new_transaction_listener(TransactionListenerKind::PropagateOnly);
1876 let mut full_all = pool.add_new_transaction_listener(TransactionListenerKind::All);
1877 let mut events = pool.add_all_transactions_event_listener();
1878
1879 insert_with_state_nonce(&test_pool, 4, 1, true);
1882 let txs = test_pool.all_transactions_by_sender(Address::with_last_byte(1));
1883 assert_eq!(transaction_nonces(&txs.pending), [1, 2]);
1884 assert_eq!(transaction_nonces(&txs.queued), [4]);
1885
1886 let expected = vec![B256::repeat_byte(1), B256::repeat_byte(2)];
1887 for (kind, listener) in [("network", &mut network), ("all", &mut all)] {
1888 let mut received = Vec::new();
1889 while let Ok(hash) = listener.try_recv() {
1890 received.push(hash);
1891 }
1892 received.sort_unstable();
1893 assert_eq!(received, expected, "{kind} pending notifications");
1894 }
1895
1896 for (kind, listener) in [("network", &mut full_network), ("all", &mut full_all)] {
1899 let mut received = Vec::new();
1900 while let Ok(event) = listener.try_recv() {
1901 received.push((*event.transaction.hash(), event.subpool));
1902 }
1903 received.sort_unstable_by_key(|(hash, _)| *hash);
1904 let expected = vec![
1905 (B256::repeat_byte(1), SubPool::Pending),
1906 (B256::repeat_byte(2), SubPool::Pending),
1907 (B256::repeat_byte(4), SubPool::Queued),
1908 ];
1909 assert_eq!(received, expected, "{kind} full transaction notifications");
1910 }
1911
1912 let mut pending_events = Vec::new();
1913 let mut queued_events = Vec::new();
1914 while let Some(Some(event)) = events.next().now_or_never() {
1915 match event {
1916 FullTransactionEvent::Pending(hash) => pending_events.push(hash),
1917 FullTransactionEvent::Queued(hash, _) => queued_events.push(hash),
1918 other => panic!("unexpected event: {other:?}"),
1919 }
1920 }
1921 pending_events.sort_unstable();
1922 assert_eq!(pending_events, expected);
1923 assert_eq!(queued_events, vec![B256::repeat_byte(4)]);
1924
1925 insert_with_state_nonce(&test_pool, 5, 1, true);
1927 assert_eq!(network.try_recv(), Err(TryRecvError::Empty));
1928 assert_eq!(all.try_recv(), Err(TryRecvError::Empty));
1929 for listener in [&mut full_network, &mut full_all] {
1930 let event = listener.try_recv().unwrap();
1931 assert_eq!(*event.transaction.hash(), B256::repeat_byte(5));
1932 assert_eq!(event.subpool, SubPool::Queued);
1933 assert!(matches!(listener.try_recv(), Err(TryRecvError::Empty)));
1934 }
1935 assert!(matches!(
1936 events.next().now_or_never(),
1937 Some(Some(FullTransactionEvent::Queued(hash, _))) if hash == B256::repeat_byte(5)
1938 ));
1939 assert!(events.next().now_or_never().is_none());
1940 }
1941
1942 #[test]
1943 fn queued_insertion_promotions_respect_propagation_filter() {
1944 let test_pool = testing_pool();
1945 let pool = &test_pool.pool;
1946 insert_with_state_nonce(&test_pool, 1, 0, false);
1947 insert_with_state_nonce(&test_pool, 2, 0, true);
1948
1949 let mut network = pool.add_pending_listener(TransactionListenerKind::PropagateOnly);
1950 let mut all = pool.add_pending_listener(TransactionListenerKind::All);
1951 let mut full_network =
1952 pool.add_new_transaction_listener(TransactionListenerKind::PropagateOnly);
1953 let mut full_all = pool.add_new_transaction_listener(TransactionListenerKind::All);
1954 insert_with_state_nonce(&test_pool, 4, 1, true);
1955
1956 assert_eq!(network.try_recv().unwrap(), B256::repeat_byte(2));
1957 assert_eq!(network.try_recv(), Err(TryRecvError::Empty));
1958 let mut received = Vec::new();
1959 while let Ok(hash) = all.try_recv() {
1960 received.push(hash);
1961 }
1962 received.sort_unstable();
1963 assert_eq!(received, [B256::repeat_byte(1), B256::repeat_byte(2)]);
1964
1965 for (listener, expected) in [
1966 (
1967 &mut full_network,
1968 vec![
1969 (B256::repeat_byte(2), SubPool::Pending),
1970 (B256::repeat_byte(4), SubPool::Queued),
1971 ],
1972 ),
1973 (
1974 &mut full_all,
1975 vec![
1976 (B256::repeat_byte(1), SubPool::Pending),
1977 (B256::repeat_byte(2), SubPool::Pending),
1978 (B256::repeat_byte(4), SubPool::Queued),
1979 ],
1980 ),
1981 ] {
1982 let mut received = Vec::new();
1983 while let Ok(event) = listener.try_recv() {
1984 received.push((*event.transaction.hash(), event.subpool));
1985 }
1986 received.sort_unstable_by_key(|(hash, _)| *hash);
1987 assert_eq!(received, expected);
1988 }
1989 }
1990
1991 #[test]
1992 fn pending_insertion_notifies_older_promotions() {
1993 let test_pool = testing_pool();
1994 let pool = &test_pool.pool;
1995 insert_with_state_nonce(&test_pool, 1, 0, true);
1996 insert_with_state_nonce(&test_pool, 2, 0, true);
1997 let mut network = pool.add_pending_listener(TransactionListenerKind::PropagateOnly);
1998 let mut all = pool.add_pending_listener(TransactionListenerKind::All);
1999
2000 insert_with_state_nonce(&test_pool, 3, 1, true);
2002 let txs = test_pool.all_transactions_by_sender(Address::with_last_byte(1));
2003 assert_eq!(transaction_nonces(&txs.pending), [1, 2, 3]);
2004 assert!(txs.queued.is_empty());
2005 for listener in [&mut network, &mut all] {
2006 let mut received = Vec::new();
2007 while let Ok(hash) = listener.try_recv() {
2008 received.push(hash);
2009 }
2010 received.sort_unstable();
2011 assert_eq!(
2012 received,
2013 [B256::repeat_byte(1), B256::repeat_byte(2), B256::repeat_byte(3)]
2014 );
2015 }
2016 }
2017
2018 #[test]
2019 fn test_discard_blobs_on_blob_tx_eviction() {
2020 let mut point_at_infinity = [0; 48];
2023 point_at_infinity[0] = 0xc0;
2024 let sidecar = BlobTransactionSidecarVariant::Eip4844(BlobTransactionSidecar::new(
2025 vec![Blob::default()],
2026 vec![Bytes48::from(point_at_infinity)],
2027 vec![Bytes48::from(point_at_infinity)],
2028 ));
2029
2030 let blob_limit = SubPoolLimit::new(1000, usize::MAX);
2032
2033 let test_pool = &TestPoolBuilder::default()
2035 .with_config(PoolConfig { blob_limit, ..Default::default() })
2036 .pool;
2037
2038 test_pool
2040 .set_block_info(BlockInfo { pending_blob_fee: Some(10_000_000), ..Default::default() });
2041
2042 let blob_store = InMemoryBlobStore::default();
2044
2045 for n in 0..blob_limit.max_txs + 10 {
2047 let mut tx = MockTransaction::eip4844_with_sidecar(sidecar.clone());
2049
2050 tx.set_size(1844674407370951);
2052
2053 if n < blob_limit.max_txs {
2055 blob_store.insert(*tx.get_hash(), sidecar.clone().into()).unwrap();
2056 }
2057
2058 test_pool.add_transactions(
2060 TransactionOrigin::External,
2061 [TransactionValidationOutcome::Valid {
2062 balance: U256::from(1_000),
2063 state_nonce: 0,
2064 bytecode_hash: None,
2065 transaction: ValidTransaction::ValidWithSidecar {
2066 transaction: tx,
2067 sidecar: PooledBlobSidecar::from(sidecar.clone()),
2068 },
2069 propagate: true,
2070 authorities: None,
2071 }],
2072 );
2073 }
2074
2075 assert_eq!(test_pool.size().blob, blob_limit.max_txs);
2077
2078 assert_eq!(test_pool.size().blob_size, 1844674407370951000);
2080
2081 assert_eq!(*test_pool.blob_store(), blob_store);
2083 }
2084
2085 #[test]
2086 fn test_auths_stored_in_identifiers() {
2087 let test_pool = &TestPoolBuilder::default().with_config(Default::default()).pool;
2089
2090 let auth = Address::repeat_byte(1);
2091 let tx = MockTransaction::eip7702();
2092
2093 test_pool.add_transactions(
2094 TransactionOrigin::Local,
2095 [TransactionValidationOutcome::Valid {
2096 balance: U256::from(1_000),
2097 state_nonce: 0,
2098 bytecode_hash: None,
2099 transaction: ValidTransaction::Valid(tx),
2100 propagate: true,
2101 authorities: Some(vec![auth]),
2102 }],
2103 );
2104
2105 let identifiers = test_pool.identifiers.read();
2106 assert_eq!(identifiers.sender_id(&auth), Some(SenderId::from(1)));
2107 }
2108
2109 #[test]
2110 fn sender_queries_do_not_allocate_ids_for_unknown_addresses() {
2111 let test_pool = &TestPoolBuilder::default().with_config(Default::default()).pool;
2112 let sender = Address::repeat_byte(9);
2113
2114 assert_eq!(test_pool.sender_id(&sender), None);
2115 assert!(test_pool.get_transactions_by_sender(sender).is_empty());
2116 assert!(test_pool.get_pending_transaction_by_sender_and_nonce(sender, 0).is_none());
2117 assert!(test_pool.get_queued_transactions_by_sender(sender).is_empty());
2118 assert!(test_pool.get_pending_transactions_by_sender(sender).is_empty());
2119 assert!(test_pool.get_highest_transaction_by_sender(sender).is_none());
2120 assert!(test_pool.get_highest_consecutive_transaction_by_sender(sender, 0).is_none());
2121 assert!(test_pool.remove_transactions_by_sender(sender).is_empty());
2122 assert_eq!(test_pool.sender_id(&sender), None);
2123 }
2124}