1use crate::{
69 blobstore::BlobStore,
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::{Address, TxHash, B256};
92use best::BestTransactions;
93use parking_lot::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
94use reth_eth_wire_types::HandleMempoolData;
95use reth_execution_types::ChangedAccount;
96
97use alloy_eips::{eip7594::BlobTransactionSidecarVariant, Typed2718};
98use reth_primitives_traits::Recovered;
99use rustc_hash::FxHashMap;
100use std::{collections::HashSet, fmt, sync::Arc, time::Instant};
101use tokio::sync::mpsc;
102use tracing::{debug, trace, warn};
103mod events;
104pub use best::{BestTransactionFilter, BestTransactionsWithPrioritizedSenders};
105pub use blob::{blob_tx_priority, fee_delta, BlobOrd, BlobTransactions};
106pub use events::{FullTransactionEvent, NewTransactionEvent, TransactionEvent};
107pub use listener::{AllTransactionsEvents, TransactionEvents, TransactionListenerKind};
108pub use parked::{BasefeeOrd, ParkedOrd, ParkedPool, QueuedOrd};
109pub use pending::PendingPool;
110use reth_primitives_traits::Block;
111
112mod best;
113mod blob;
114mod listener;
115mod parked;
116pub mod pending;
117pub(crate) mod size;
118pub(crate) mod state;
119pub mod txpool;
120mod update;
121
122pub const PENDING_TX_LISTENER_BUFFER_SIZE: usize = 2048;
124pub const NEW_TX_LISTENER_BUFFER_SIZE: usize = 1024;
126
127const BLOB_SIDECAR_LISTENER_BUFFER_SIZE: usize = 512;
128
129pub struct PoolInner<V, T, S>
131where
132 T: TransactionOrdering,
133{
134 identifiers: RwLock<SenderIdentifiers>,
136 validator: V,
138 blob_store: S,
140 pool: RwLock<TxPool<T>>,
142 config: PoolConfig,
144 event_listener: RwLock<PoolEventBroadcast<T::Transaction>>,
146 pending_transaction_listener: Mutex<Vec<PendingTransactionHashListener>>,
148 transaction_listener: Mutex<Vec<TransactionListener<T::Transaction>>>,
150 blob_transaction_sidecar_listener: Mutex<Vec<BlobTransactionSidecarListener>>,
152 blob_store_metrics: BlobStoreMetrics,
154}
155
156impl<V, T, S> PoolInner<V, T, S>
159where
160 V: TransactionValidator,
161 T: TransactionOrdering<Transaction = <V as TransactionValidator>::Transaction>,
162 S: BlobStore,
163{
164 pub fn new(validator: V, ordering: T, blob_store: S, config: PoolConfig) -> Self {
166 Self {
167 identifiers: Default::default(),
168 validator,
169 event_listener: Default::default(),
170 pool: RwLock::new(TxPool::new(ordering, config.clone())),
171 pending_transaction_listener: Default::default(),
172 transaction_listener: Default::default(),
173 blob_transaction_sidecar_listener: Default::default(),
174 config,
175 blob_store,
176 blob_store_metrics: Default::default(),
177 }
178 }
179
180 pub const fn blob_store(&self) -> &S {
182 &self.blob_store
183 }
184
185 pub fn size(&self) -> PoolSize {
187 self.get_pool_data().size()
188 }
189
190 pub fn block_info(&self) -> BlockInfo {
192 self.get_pool_data().block_info()
193 }
194 pub fn set_block_info(&self, info: BlockInfo) {
196 self.pool.write().set_block_info(info)
197 }
198
199 pub fn get_sender_id(&self, addr: Address) -> SenderId {
201 self.identifiers.write().sender_id_or_create(addr)
202 }
203
204 pub fn get_sender_ids(&self, addrs: impl IntoIterator<Item = Address>) -> Vec<SenderId> {
206 self.identifiers.write().sender_ids_or_create(addrs)
207 }
208
209 pub fn unique_senders(&self) -> HashSet<Address> {
211 self.get_pool_data().unique_senders()
212 }
213
214 fn changed_senders(
217 &self,
218 accs: impl Iterator<Item = ChangedAccount>,
219 ) -> FxHashMap<SenderId, SenderInfo> {
220 let mut identifiers = self.identifiers.write();
221 accs.into_iter()
222 .map(|acc| {
223 let ChangedAccount { address, nonce, balance } = acc;
224 let sender_id = identifiers.sender_id_or_create(address);
225 (sender_id, SenderInfo { state_nonce: nonce, balance })
226 })
227 .collect()
228 }
229
230 pub const fn config(&self) -> &PoolConfig {
232 &self.config
233 }
234
235 pub const fn validator(&self) -> &V {
237 &self.validator
238 }
239
240 pub fn add_pending_listener(&self, kind: TransactionListenerKind) -> mpsc::Receiver<TxHash> {
243 let (sender, rx) = mpsc::channel(self.config.pending_tx_listener_buffer_size);
244 let listener = PendingTransactionHashListener { sender, kind };
245 self.pending_transaction_listener.lock().push(listener);
246 rx
247 }
248
249 pub fn add_new_transaction_listener(
251 &self,
252 kind: TransactionListenerKind,
253 ) -> mpsc::Receiver<NewTransactionEvent<T::Transaction>> {
254 let (sender, rx) = mpsc::channel(self.config.new_tx_listener_buffer_size);
255 let listener = TransactionListener { sender, kind };
256 self.transaction_listener.lock().push(listener);
257 rx
258 }
259 pub fn add_blob_sidecar_listener(&self) -> mpsc::Receiver<NewBlobSidecar> {
262 let (sender, rx) = mpsc::channel(BLOB_SIDECAR_LISTENER_BUFFER_SIZE);
263 let listener = BlobTransactionSidecarListener { sender };
264 self.blob_transaction_sidecar_listener.lock().push(listener);
265 rx
266 }
267
268 pub fn add_transaction_event_listener(&self, tx_hash: TxHash) -> Option<TransactionEvents> {
271 self.get_pool_data()
272 .contains(&tx_hash)
273 .then(|| self.event_listener.write().subscribe(tx_hash))
274 }
275
276 pub fn add_all_transactions_event_listener(&self) -> AllTransactionsEvents<T::Transaction> {
278 self.event_listener.write().subscribe_all()
279 }
280
281 pub fn get_pool_data(&self) -> RwLockReadGuard<'_, TxPool<T>> {
283 self.pool.read()
284 }
285
286 pub fn pooled_transactions_hashes(&self) -> Vec<TxHash> {
288 self.get_pool_data()
289 .all()
290 .transactions_iter()
291 .filter(|tx| tx.propagate)
292 .map(|tx| *tx.hash())
293 .collect()
294 }
295
296 pub fn pooled_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
298 self.get_pool_data().all().transactions_iter().filter(|tx| tx.propagate).cloned().collect()
299 }
300
301 pub fn pooled_transactions_max(
303 &self,
304 max: usize,
305 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
306 self.get_pool_data()
307 .all()
308 .transactions_iter()
309 .filter(|tx| tx.propagate)
310 .take(max)
311 .cloned()
312 .collect()
313 }
314
315 fn to_pooled_transaction(
320 &self,
321 transaction: Arc<ValidPoolTransaction<T::Transaction>>,
322 ) -> Option<Recovered<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>>
323 where
324 <V as TransactionValidator>::Transaction: EthPoolTransaction,
325 {
326 if transaction.is_eip4844() {
327 let sidecar = self.blob_store.get(*transaction.hash()).ok()??;
328 transaction.transaction.clone().try_into_pooled_eip4844(sidecar)
329 } else {
330 transaction
331 .transaction
332 .clone()
333 .try_into_pooled()
334 .inspect_err(|err| {
335 debug!(
336 target: "txpool", %err,
337 "failed to convert transaction to pooled element; skipping",
338 );
339 })
340 .ok()
341 }
342 }
343
344 pub fn get_pooled_transaction_elements(
347 &self,
348 tx_hashes: Vec<TxHash>,
349 limit: GetPooledTransactionLimit,
350 ) -> Vec<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>
351 where
352 <V as TransactionValidator>::Transaction: EthPoolTransaction,
353 {
354 let transactions = self.get_all_propagatable(tx_hashes);
355 let mut elements = Vec::with_capacity(transactions.len());
356 let mut size = 0;
357 for transaction in transactions {
358 let encoded_len = transaction.encoded_length();
359 let Some(pooled) = self.to_pooled_transaction(transaction) else {
360 continue;
361 };
362
363 size += encoded_len;
364 elements.push(pooled.into_inner());
365
366 if limit.exceeds(size) {
367 break
368 }
369 }
370
371 elements
372 }
373
374 pub fn get_pooled_transaction_element(
376 &self,
377 tx_hash: TxHash,
378 ) -> Option<Recovered<<<V as TransactionValidator>::Transaction as PoolTransaction>::Pooled>>
379 where
380 <V as TransactionValidator>::Transaction: EthPoolTransaction,
381 {
382 self.get(&tx_hash).and_then(|tx| self.to_pooled_transaction(tx))
383 }
384
385 pub fn on_canonical_state_change<B>(&self, update: CanonicalStateUpdate<'_, B>)
387 where
388 B: Block,
389 {
390 trace!(target: "txpool", ?update, "updating pool on canonical state change");
391
392 let block_info = update.block_info();
393 let CanonicalStateUpdate {
394 new_tip, changed_accounts, mined_transactions, update_kind, ..
395 } = update;
396 self.validator.on_new_head_block(new_tip);
397
398 let changed_senders = self.changed_senders(changed_accounts.into_iter());
399
400 let outcome = self.pool.write().on_canonical_state_change(
402 block_info,
403 mined_transactions,
404 changed_senders,
405 update_kind,
406 );
407
408 self.delete_discarded_blobs(outcome.discarded.iter());
410
411 self.notify_on_new_state(outcome);
413 }
414
415 pub fn update_accounts(&self, accounts: Vec<ChangedAccount>) {
421 let changed_senders = self.changed_senders(accounts.into_iter());
422 let UpdateOutcome { promoted, discarded } =
423 self.pool.write().update_accounts(changed_senders);
424
425 if !promoted.is_empty() {
427 self.pending_transaction_listener.lock().retain_mut(|listener| {
428 let promoted_hashes = promoted.iter().filter_map(|tx| {
429 if listener.kind.is_propagate_only() && !tx.propagate {
430 None
431 } else {
432 Some(*tx.hash())
433 }
434 });
435 listener.send_all(promoted_hashes)
436 });
437
438 self.transaction_listener.lock().retain_mut(|listener| {
440 let promoted_txs = promoted.iter().filter_map(|tx| {
441 if listener.kind.is_propagate_only() && !tx.propagate {
442 None
443 } else {
444 Some(NewTransactionEvent::pending(tx.clone()))
445 }
446 });
447 listener.send_all(promoted_txs)
448 });
449 }
450
451 {
452 let mut listener = self.event_listener.write();
453 if !listener.is_empty() {
454 for tx in &promoted {
455 listener.pending(tx.hash(), None);
456 }
457 for tx in &discarded {
458 listener.discarded(tx.hash());
459 }
460 }
461 }
462
463 self.delete_discarded_blobs(discarded.iter());
466 }
467
468 fn add_transaction(
473 &self,
474 pool: &mut RwLockWriteGuard<'_, TxPool<T>>,
475 origin: TransactionOrigin,
476 tx: TransactionValidationOutcome<T::Transaction>,
477 ) -> PoolResult<AddedTransactionOutcome> {
478 match tx {
479 TransactionValidationOutcome::Valid {
480 balance,
481 state_nonce,
482 transaction,
483 propagate,
484 bytecode_hash,
485 authorities,
486 } => {
487 let sender_id = self.get_sender_id(transaction.sender());
488 let transaction_id = TransactionId::new(sender_id, transaction.nonce());
489
490 let (transaction, maybe_sidecar) = match transaction {
492 ValidTransaction::Valid(tx) => (tx, None),
493 ValidTransaction::ValidWithSidecar { transaction, sidecar } => {
494 debug_assert!(
495 transaction.is_eip4844(),
496 "validator returned sidecar for non EIP-4844 transaction"
497 );
498 (transaction, Some(sidecar))
499 }
500 };
501
502 let tx = ValidPoolTransaction {
503 transaction,
504 transaction_id,
505 propagate,
506 timestamp: Instant::now(),
507 origin,
508 authority_ids: authorities.map(|auths| self.get_sender_ids(auths)),
509 };
510
511 let added = pool.add_transaction(tx, balance, state_nonce, bytecode_hash)?;
512 let hash = *added.hash();
513 let state = added.transaction_state();
514
515 if let Some(sidecar) = maybe_sidecar {
517 self.on_new_blob_sidecar(&hash, &sidecar);
519 self.insert_blob(hash, sidecar);
521 }
522
523 if let Some(replaced) = added.replaced_blob_transaction() {
524 debug!(target: "txpool", "[{:?}] delete replaced blob sidecar", replaced);
525 self.delete_blob(replaced);
527 }
528
529 if let Some(pending) = added.as_pending() {
531 self.on_new_pending_transaction(pending);
532 }
533
534 self.notify_event_listeners(&added);
536
537 if let Some(discarded) = added.discarded_transactions() {
538 self.delete_discarded_blobs(discarded.iter());
539 }
540
541 self.on_new_transaction(added.into_new_transaction_event());
543
544 Ok(AddedTransactionOutcome { hash, state })
545 }
546 TransactionValidationOutcome::Invalid(tx, err) => {
547 let mut listener = self.event_listener.write();
548 listener.invalid(tx.hash());
549 Err(PoolError::new(*tx.hash(), err))
550 }
551 TransactionValidationOutcome::Error(tx_hash, err) => {
552 let mut listener = self.event_listener.write();
553 listener.discarded(&tx_hash);
554 Err(PoolError::other(tx_hash, err))
555 }
556 }
557 }
558
559 pub fn add_transaction_and_subscribe(
561 &self,
562 origin: TransactionOrigin,
563 tx: TransactionValidationOutcome<T::Transaction>,
564 ) -> PoolResult<TransactionEvents> {
565 let listener = {
566 let mut listener = self.event_listener.write();
567 listener.subscribe(tx.tx_hash())
568 };
569 let mut results = self.add_transactions(origin, std::iter::once(tx));
570 results.pop().expect("result length is the same as the input")?;
571 Ok(listener)
572 }
573
574 pub fn add_transactions(
580 &self,
581 origin: TransactionOrigin,
582 transactions: impl IntoIterator<Item = TransactionValidationOutcome<T::Transaction>>,
583 ) -> Vec<PoolResult<AddedTransactionOutcome>> {
584 let (mut added, discarded) = {
586 let mut pool = self.pool.write();
587 let added = transactions
588 .into_iter()
589 .map(|tx| self.add_transaction(&mut pool, origin, tx))
590 .collect::<Vec<_>>();
591
592 let discarded = if added.iter().any(Result::is_ok) {
594 pool.discard_worst()
595 } else {
596 Default::default()
597 };
598
599 (added, discarded)
600 };
601
602 if !discarded.is_empty() {
603 self.delete_discarded_blobs(discarded.iter());
605 self.event_listener.write().discarded_many(&discarded);
606
607 let discarded_hashes =
608 discarded.into_iter().map(|tx| *tx.hash()).collect::<HashSet<_>>();
609
610 for res in &mut added {
613 if let Ok(AddedTransactionOutcome { hash, .. }) = res &&
614 discarded_hashes.contains(hash)
615 {
616 *res = Err(PoolError::new(*hash, PoolErrorKind::DiscardedOnInsert))
617 }
618 }
619 };
620
621 added
622 }
623
624 pub fn on_new_pending_transaction(&self, pending: &AddedPendingTransaction<T::Transaction>) {
633 let propagate_allowed = pending.is_propagate_allowed();
634
635 let mut transaction_listeners = self.pending_transaction_listener.lock();
636 transaction_listeners.retain_mut(|listener| {
637 if listener.kind.is_propagate_only() && !propagate_allowed {
638 return !listener.sender.is_closed()
641 }
642
643 listener.send_all(pending.pending_transactions(listener.kind))
645 });
646 }
647
648 pub fn on_new_transaction(&self, event: NewTransactionEvent<T::Transaction>) {
657 let mut transaction_listeners = self.transaction_listener.lock();
658 transaction_listeners.retain_mut(|listener| {
659 if listener.kind.is_propagate_only() && !event.transaction.propagate {
660 return !listener.sender.is_closed()
663 }
664
665 listener.send(event.clone())
666 });
667 }
668
669 fn on_new_blob_sidecar(&self, tx_hash: &TxHash, sidecar: &BlobTransactionSidecarVariant) {
671 let mut sidecar_listeners = self.blob_transaction_sidecar_listener.lock();
672 if sidecar_listeners.is_empty() {
673 return
674 }
675 let sidecar = Arc::new(sidecar.clone());
676 sidecar_listeners.retain_mut(|listener| {
677 let new_blob_event = NewBlobSidecar { tx_hash: *tx_hash, sidecar: sidecar.clone() };
678 match listener.sender.try_send(new_blob_event) {
679 Ok(()) => true,
680 Err(err) => {
681 if matches!(err, mpsc::error::TrySendError::Full(_)) {
682 debug!(
683 target: "txpool",
684 "[{:?}] failed to send blob sidecar; channel full",
685 sidecar,
686 );
687 true
688 } else {
689 false
690 }
691 }
692 }
693 })
694 }
695
696 fn notify_on_new_state(&self, outcome: OnNewCanonicalStateOutcome<T::Transaction>) {
698 trace!(target: "txpool", promoted=outcome.promoted.len(), discarded= outcome.discarded.len() ,"notifying listeners on state change");
699
700 self.pending_transaction_listener
703 .lock()
704 .retain_mut(|listener| listener.send_all(outcome.pending_transactions(listener.kind)));
705
706 self.transaction_listener.lock().retain_mut(|listener| {
708 listener.send_all(outcome.full_pending_transactions(listener.kind))
709 });
710
711 let OnNewCanonicalStateOutcome { mined, promoted, discarded, block_hash } = outcome;
712
713 let mut listener = self.event_listener.write();
715
716 if !listener.is_empty() {
717 for tx in &mined {
718 listener.mined(tx, block_hash);
719 }
720 for tx in &promoted {
721 listener.pending(tx.hash(), None);
722 }
723 for tx in &discarded {
724 listener.discarded(tx.hash());
725 }
726 }
727 }
728
729 pub fn notify_event_listeners(&self, tx: &AddedTransaction<T::Transaction>) {
738 let mut listener = self.event_listener.write();
739 if listener.is_empty() {
740 return
742 }
743
744 match tx {
745 AddedTransaction::Pending(tx) => {
746 let AddedPendingTransaction { transaction, promoted, discarded, replaced } = tx;
747
748 listener.pending(transaction.hash(), replaced.clone());
749 for tx in promoted {
750 listener.pending(tx.hash(), None);
751 }
752 for tx in discarded {
753 listener.discarded(tx.hash());
754 }
755 }
756 AddedTransaction::Parked { transaction, replaced, queued_reason, .. } => {
757 listener.queued(transaction.hash(), queued_reason.clone());
758 if let Some(replaced) = replaced {
759 listener.replaced(replaced.clone(), *transaction.hash());
760 }
761 }
762 }
763 }
764
765 pub fn best_transactions(&self) -> BestTransactions<T> {
767 self.get_pool_data().best_transactions()
768 }
769
770 pub fn best_transactions_with_attributes(
773 &self,
774 best_transactions_attributes: BestTransactionsAttributes,
775 ) -> Box<dyn crate::traits::BestTransactions<Item = Arc<ValidPoolTransaction<T::Transaction>>>>
776 {
777 self.get_pool_data().best_transactions_with_attributes(best_transactions_attributes)
778 }
779
780 pub fn pending_transactions_max(
782 &self,
783 max: usize,
784 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
785 self.get_pool_data().pending_transactions_iter().take(max).collect()
786 }
787
788 pub fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
790 self.get_pool_data().pending_transactions()
791 }
792
793 pub fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
795 self.get_pool_data().queued_transactions()
796 }
797
798 pub fn all_transactions(&self) -> AllPoolTransactions<T::Transaction> {
800 let pool = self.get_pool_data();
801 AllPoolTransactions {
802 pending: pool.pending_transactions(),
803 queued: pool.queued_transactions(),
804 }
805 }
806
807 pub fn all_transaction_hashes(&self) -> Vec<TxHash> {
809 self.get_pool_data().all().transactions_iter().map(|tx| *tx.hash()).collect()
810 }
811
812 pub fn remove_transactions(
817 &self,
818 hashes: Vec<TxHash>,
819 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
820 if hashes.is_empty() {
821 return Vec::new()
822 }
823 let removed = self.pool.write().remove_transactions(hashes);
824
825 self.event_listener.write().discarded_many(&removed);
826
827 removed
828 }
829
830 pub fn remove_transactions_and_descendants(
833 &self,
834 hashes: Vec<TxHash>,
835 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
836 if hashes.is_empty() {
837 return Vec::new()
838 }
839 let removed = self.pool.write().remove_transactions_and_descendants(hashes);
840
841 let mut listener = self.event_listener.write();
842
843 for tx in &removed {
844 listener.discarded(tx.hash());
845 }
846
847 removed
848 }
849
850 pub fn remove_transactions_by_sender(
852 &self,
853 sender: Address,
854 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
855 let sender_id = self.get_sender_id(sender);
856 let removed = self.pool.write().remove_transactions_by_sender(sender_id);
857
858 self.event_listener.write().discarded_many(&removed);
859
860 removed
861 }
862
863 pub fn retain_unknown<A>(&self, announcement: &mut A)
865 where
866 A: HandleMempoolData,
867 {
868 if announcement.is_empty() {
869 return
870 }
871 let pool = self.get_pool_data();
872 announcement.retain_by_hash(|tx| !pool.contains(tx))
873 }
874
875 pub fn get(&self, tx_hash: &TxHash) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
877 self.get_pool_data().get(tx_hash)
878 }
879
880 pub fn get_transactions_by_sender(
882 &self,
883 sender: Address,
884 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
885 let sender_id = self.get_sender_id(sender);
886 self.get_pool_data().get_transactions_by_sender(sender_id)
887 }
888
889 pub fn get_queued_transactions_by_sender(
891 &self,
892 sender: Address,
893 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
894 let sender_id = self.get_sender_id(sender);
895 self.get_pool_data().queued_txs_by_sender(sender_id)
896 }
897
898 pub fn pending_transactions_with_predicate(
900 &self,
901 predicate: impl FnMut(&ValidPoolTransaction<T::Transaction>) -> bool,
902 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
903 self.get_pool_data().pending_transactions_with_predicate(predicate)
904 }
905
906 pub fn get_pending_transactions_by_sender(
908 &self,
909 sender: Address,
910 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
911 let sender_id = self.get_sender_id(sender);
912 self.get_pool_data().pending_txs_by_sender(sender_id)
913 }
914
915 pub fn get_highest_transaction_by_sender(
917 &self,
918 sender: Address,
919 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
920 let sender_id = self.get_sender_id(sender);
921 self.get_pool_data().get_highest_transaction_by_sender(sender_id)
922 }
923
924 pub fn get_highest_consecutive_transaction_by_sender(
926 &self,
927 sender: Address,
928 on_chain_nonce: u64,
929 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
930 let sender_id = self.get_sender_id(sender);
931 self.get_pool_data().get_highest_consecutive_transaction_by_sender(
932 sender_id.into_transaction_id(on_chain_nonce),
933 )
934 }
935
936 pub fn get_transaction_by_transaction_id(
938 &self,
939 transaction_id: &TransactionId,
940 ) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
941 self.get_pool_data().all().get(transaction_id).map(|tx| tx.transaction.clone())
942 }
943
944 pub fn get_transactions_by_origin(
946 &self,
947 origin: TransactionOrigin,
948 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
949 self.get_pool_data()
950 .all()
951 .transactions_iter()
952 .filter(|tx| tx.origin == origin)
953 .cloned()
954 .collect()
955 }
956
957 pub fn get_pending_transactions_by_origin(
959 &self,
960 origin: TransactionOrigin,
961 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
962 self.get_pool_data().pending_transactions_iter().filter(|tx| tx.origin == origin).collect()
963 }
964
965 pub fn get_all(&self, txs: Vec<TxHash>) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
969 if txs.is_empty() {
970 return Vec::new()
971 }
972 self.get_pool_data().get_all(txs).collect()
973 }
974
975 fn get_all_propagatable(
979 &self,
980 txs: Vec<TxHash>,
981 ) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
982 if txs.is_empty() {
983 return Vec::new()
984 }
985 self.get_pool_data().get_all(txs).filter(|tx| tx.propagate).collect()
986 }
987
988 pub fn on_propagated(&self, txs: PropagatedTransactions) {
990 if txs.0.is_empty() {
991 return
992 }
993 let mut listener = self.event_listener.write();
994
995 if !listener.is_empty() {
996 txs.0.into_iter().for_each(|(hash, peers)| listener.propagated(&hash, peers));
997 }
998 }
999
1000 pub fn len(&self) -> usize {
1002 self.get_pool_data().len()
1003 }
1004
1005 pub fn is_empty(&self) -> bool {
1007 self.get_pool_data().is_empty()
1008 }
1009
1010 pub fn is_exceeded(&self) -> bool {
1012 self.pool.read().is_exceeded()
1013 }
1014
1015 fn insert_blob(&self, hash: TxHash, blob: BlobTransactionSidecarVariant) {
1017 debug!(target: "txpool", "[{:?}] storing blob sidecar", hash);
1018 if let Err(err) = self.blob_store.insert(hash, blob) {
1019 warn!(target: "txpool", %err, "[{:?}] failed to insert blob", hash);
1020 self.blob_store_metrics.blobstore_failed_inserts.increment(1);
1021 }
1022 self.update_blob_store_metrics();
1023 }
1024
1025 pub fn delete_blob(&self, blob: TxHash) {
1027 let _ = self.blob_store.delete(blob);
1028 }
1029
1030 pub fn delete_blobs(&self, txs: Vec<TxHash>) {
1032 let _ = self.blob_store.delete_all(txs);
1033 }
1034
1035 pub fn cleanup_blobs(&self) {
1037 let stat = self.blob_store.cleanup();
1038 self.blob_store_metrics.blobstore_failed_deletes.increment(stat.delete_failed as u64);
1039 self.update_blob_store_metrics();
1040 }
1041
1042 fn update_blob_store_metrics(&self) {
1043 if let Some(data_size) = self.blob_store.data_size_hint() {
1044 self.blob_store_metrics.blobstore_byte_size.set(data_size as f64);
1045 }
1046 self.blob_store_metrics.blobstore_entries.set(self.blob_store.blobs_len() as f64);
1047 }
1048
1049 fn delete_discarded_blobs<'a>(
1051 &'a self,
1052 transactions: impl IntoIterator<Item = &'a Arc<ValidPoolTransaction<T::Transaction>>>,
1053 ) {
1054 let blob_txs = transactions
1055 .into_iter()
1056 .filter(|tx| tx.transaction.is_eip4844())
1057 .map(|tx| *tx.hash())
1058 .collect();
1059 self.delete_blobs(blob_txs);
1060 }
1061}
1062
1063impl<V, T: TransactionOrdering, S> fmt::Debug for PoolInner<V, T, S> {
1064 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 f.debug_struct("PoolInner").field("config", &self.config).finish_non_exhaustive()
1066 }
1067}
1068
1069#[derive(Debug, Clone)]
1071pub struct AddedPendingTransaction<T: PoolTransaction> {
1072 transaction: Arc<ValidPoolTransaction<T>>,
1074 replaced: Option<Arc<ValidPoolTransaction<T>>>,
1076 promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1078 discarded: Vec<Arc<ValidPoolTransaction<T>>>,
1080}
1081
1082impl<T: PoolTransaction> AddedPendingTransaction<T> {
1083 pub(crate) fn pending_transactions(
1089 &self,
1090 kind: TransactionListenerKind,
1091 ) -> impl Iterator<Item = B256> + '_ {
1092 let iter = std::iter::once(&self.transaction).chain(self.promoted.iter());
1093 PendingTransactionIter { kind, iter }
1094 }
1095
1096 pub(crate) fn is_propagate_allowed(&self) -> bool {
1098 self.transaction.propagate
1099 }
1100}
1101
1102pub(crate) struct PendingTransactionIter<Iter> {
1103 kind: TransactionListenerKind,
1104 iter: Iter,
1105}
1106
1107impl<'a, Iter, T> Iterator for PendingTransactionIter<Iter>
1108where
1109 Iter: Iterator<Item = &'a Arc<ValidPoolTransaction<T>>>,
1110 T: PoolTransaction + 'a,
1111{
1112 type Item = B256;
1113
1114 fn next(&mut self) -> Option<Self::Item> {
1115 loop {
1116 let next = self.iter.next()?;
1117 if self.kind.is_propagate_only() && !next.propagate {
1118 continue
1119 }
1120 return Some(*next.hash())
1121 }
1122 }
1123}
1124
1125pub(crate) struct FullPendingTransactionIter<Iter> {
1127 kind: TransactionListenerKind,
1128 iter: Iter,
1129}
1130
1131impl<'a, Iter, T> Iterator for FullPendingTransactionIter<Iter>
1132where
1133 Iter: Iterator<Item = &'a Arc<ValidPoolTransaction<T>>>,
1134 T: PoolTransaction + 'a,
1135{
1136 type Item = NewTransactionEvent<T>;
1137
1138 fn next(&mut self) -> Option<Self::Item> {
1139 loop {
1140 let next = self.iter.next()?;
1141 if self.kind.is_propagate_only() && !next.propagate {
1142 continue
1143 }
1144 return Some(NewTransactionEvent {
1145 subpool: SubPool::Pending,
1146 transaction: next.clone(),
1147 })
1148 }
1149 }
1150}
1151
1152#[derive(Debug, Clone)]
1154pub enum AddedTransaction<T: PoolTransaction> {
1155 Pending(AddedPendingTransaction<T>),
1157 Parked {
1160 transaction: Arc<ValidPoolTransaction<T>>,
1162 replaced: Option<Arc<ValidPoolTransaction<T>>>,
1164 subpool: SubPool,
1166 queued_reason: Option<QueuedReason>,
1168 },
1169}
1170
1171impl<T: PoolTransaction> AddedTransaction<T> {
1172 pub(crate) const fn as_pending(&self) -> Option<&AddedPendingTransaction<T>> {
1174 match self {
1175 Self::Pending(tx) => Some(tx),
1176 _ => None,
1177 }
1178 }
1179
1180 pub(crate) const fn replaced(&self) -> Option<&Arc<ValidPoolTransaction<T>>> {
1182 match self {
1183 Self::Pending(tx) => tx.replaced.as_ref(),
1184 Self::Parked { replaced, .. } => replaced.as_ref(),
1185 }
1186 }
1187
1188 pub(crate) fn discarded_transactions(&self) -> Option<&[Arc<ValidPoolTransaction<T>>]> {
1190 match self {
1191 Self::Pending(tx) => Some(&tx.discarded),
1192 Self::Parked { .. } => None,
1193 }
1194 }
1195
1196 pub(crate) fn replaced_blob_transaction(&self) -> Option<B256> {
1198 self.replaced().filter(|tx| tx.transaction.is_eip4844()).map(|tx| *tx.transaction.hash())
1199 }
1200
1201 pub(crate) fn hash(&self) -> &TxHash {
1203 match self {
1204 Self::Pending(tx) => tx.transaction.hash(),
1205 Self::Parked { transaction, .. } => transaction.hash(),
1206 }
1207 }
1208
1209 pub(crate) fn into_new_transaction_event(self) -> NewTransactionEvent<T> {
1211 match self {
1212 Self::Pending(tx) => {
1213 NewTransactionEvent { subpool: SubPool::Pending, transaction: tx.transaction }
1214 }
1215 Self::Parked { transaction, subpool, .. } => {
1216 NewTransactionEvent { transaction, subpool }
1217 }
1218 }
1219 }
1220
1221 pub(crate) const fn subpool(&self) -> SubPool {
1223 match self {
1224 Self::Pending(_) => SubPool::Pending,
1225 Self::Parked { subpool, .. } => *subpool,
1226 }
1227 }
1228
1229 #[cfg(test)]
1231 pub(crate) fn id(&self) -> &TransactionId {
1232 match self {
1233 Self::Pending(added) => added.transaction.id(),
1234 Self::Parked { transaction, .. } => transaction.id(),
1235 }
1236 }
1237
1238 pub(crate) const fn queued_reason(&self) -> Option<&QueuedReason> {
1240 match self {
1241 Self::Pending(_) => None,
1242 Self::Parked { queued_reason, .. } => queued_reason.as_ref(),
1243 }
1244 }
1245
1246 pub(crate) fn transaction_state(&self) -> AddedTransactionState {
1248 match self.subpool() {
1249 SubPool::Pending => AddedTransactionState::Pending,
1250 _ => {
1251 if let Some(reason) = self.queued_reason() {
1254 AddedTransactionState::Queued(reason.clone())
1255 } else {
1256 AddedTransactionState::Queued(QueuedReason::NonceGap)
1258 }
1259 }
1260 }
1261 }
1262}
1263
1264#[derive(Debug, Clone, PartialEq, Eq)]
1266pub enum QueuedReason {
1267 NonceGap,
1269 ParkedAncestors,
1271 InsufficientBalance,
1273 TooMuchGas,
1275 InsufficientBaseFee,
1277 InsufficientBlobFee,
1279}
1280
1281#[derive(Debug, Clone, PartialEq, Eq)]
1283pub enum AddedTransactionState {
1284 Pending,
1286 Queued(QueuedReason),
1288}
1289
1290impl AddedTransactionState {
1291 pub const fn is_queued(&self) -> bool {
1293 matches!(self, Self::Queued(_))
1294 }
1295
1296 pub const fn is_pending(&self) -> bool {
1298 matches!(self, Self::Pending)
1299 }
1300
1301 pub const fn queued_reason(&self) -> Option<&QueuedReason> {
1303 match self {
1304 Self::Queued(reason) => Some(reason),
1305 Self::Pending => None,
1306 }
1307 }
1308}
1309
1310#[derive(Debug, Clone, PartialEq, Eq)]
1312pub struct AddedTransactionOutcome {
1313 pub hash: TxHash,
1315 pub state: AddedTransactionState,
1317}
1318
1319impl AddedTransactionOutcome {
1320 pub const fn is_queued(&self) -> bool {
1322 self.state.is_queued()
1323 }
1324
1325 pub const fn is_pending(&self) -> bool {
1327 self.state.is_pending()
1328 }
1329}
1330
1331#[derive(Debug)]
1333pub(crate) struct OnNewCanonicalStateOutcome<T: PoolTransaction> {
1334 pub(crate) block_hash: B256,
1336 pub(crate) mined: Vec<TxHash>,
1338 pub(crate) promoted: Vec<Arc<ValidPoolTransaction<T>>>,
1340 pub(crate) discarded: Vec<Arc<ValidPoolTransaction<T>>>,
1342}
1343
1344impl<T: PoolTransaction> OnNewCanonicalStateOutcome<T> {
1345 pub(crate) fn pending_transactions(
1351 &self,
1352 kind: TransactionListenerKind,
1353 ) -> impl Iterator<Item = B256> + '_ {
1354 let iter = self.promoted.iter();
1355 PendingTransactionIter { kind, iter }
1356 }
1357
1358 pub(crate) fn full_pending_transactions(
1364 &self,
1365 kind: TransactionListenerKind,
1366 ) -> impl Iterator<Item = NewTransactionEvent<T>> + '_ {
1367 let iter = self.promoted.iter();
1368 FullPendingTransactionIter { kind, iter }
1369 }
1370}
1371
1372#[cfg(test)]
1373mod tests {
1374 use crate::{
1375 blobstore::{BlobStore, InMemoryBlobStore},
1376 identifier::SenderId,
1377 test_utils::{MockTransaction, TestPoolBuilder},
1378 validate::ValidTransaction,
1379 BlockInfo, PoolConfig, SubPoolLimit, TransactionOrigin, TransactionValidationOutcome, U256,
1380 };
1381 use alloy_eips::{eip4844::BlobTransactionSidecar, eip7594::BlobTransactionSidecarVariant};
1382 use alloy_primitives::Address;
1383 use std::{fs, path::PathBuf};
1384
1385 #[test]
1386 fn test_discard_blobs_on_blob_tx_eviction() {
1387 let blobs = {
1388 let json_content = fs::read_to_string(
1390 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_data/blob1.json"),
1391 )
1392 .expect("Failed to read the blob data file");
1393
1394 let json_value: serde_json::Value =
1396 serde_json::from_str(&json_content).expect("Failed to deserialize JSON");
1397
1398 vec![
1400 json_value
1402 .get("data")
1403 .unwrap()
1404 .as_str()
1405 .expect("Data is not a valid string")
1406 .to_string(),
1407 ]
1408 };
1409
1410 let sidecar = BlobTransactionSidecarVariant::Eip4844(
1412 BlobTransactionSidecar::try_from_blobs_hex(blobs).unwrap(),
1413 );
1414
1415 let blob_limit = SubPoolLimit::new(1000, usize::MAX);
1417
1418 let test_pool = &TestPoolBuilder::default()
1420 .with_config(PoolConfig { blob_limit, ..Default::default() })
1421 .pool;
1422
1423 test_pool
1425 .set_block_info(BlockInfo { pending_blob_fee: Some(10_000_000), ..Default::default() });
1426
1427 let blob_store = InMemoryBlobStore::default();
1429
1430 for n in 0..blob_limit.max_txs + 10 {
1432 let mut tx = MockTransaction::eip4844_with_sidecar(sidecar.clone());
1434
1435 tx.set_size(1844674407370951);
1437
1438 if n < blob_limit.max_txs {
1440 blob_store.insert(*tx.get_hash(), sidecar.clone()).unwrap();
1441 }
1442
1443 test_pool.add_transactions(
1445 TransactionOrigin::External,
1446 [TransactionValidationOutcome::Valid {
1447 balance: U256::from(1_000),
1448 state_nonce: 0,
1449 bytecode_hash: None,
1450 transaction: ValidTransaction::ValidWithSidecar {
1451 transaction: tx,
1452 sidecar: sidecar.clone(),
1453 },
1454 propagate: true,
1455 authorities: None,
1456 }],
1457 );
1458 }
1459
1460 assert_eq!(test_pool.size().blob, blob_limit.max_txs);
1462
1463 assert_eq!(test_pool.size().blob_size, 1844674407370951000);
1465
1466 assert_eq!(*test_pool.blob_store(), blob_store);
1468 }
1469
1470 #[test]
1471 fn test_auths_stored_in_identifiers() {
1472 let test_pool = &TestPoolBuilder::default().with_config(Default::default()).pool;
1474
1475 let auth = Address::new([1; 20]);
1476 let tx = MockTransaction::eip7702();
1477
1478 test_pool.add_transactions(
1479 TransactionOrigin::Local,
1480 [TransactionValidationOutcome::Valid {
1481 balance: U256::from(1_000),
1482 state_nonce: 0,
1483 bytecode_hash: None,
1484 transaction: ValidTransaction::Valid(tx),
1485 propagate: true,
1486 authorities: Some(vec![auth]),
1487 }],
1488 );
1489
1490 let identifiers = test_pool.identifiers.read();
1491 assert_eq!(identifiers.sender_id(&auth), Some(SenderId::from(1)));
1492 }
1493}