-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
txpool.rs
2595 lines (2313 loc) · 104 KB
/
txpool.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The internal transaction pool implementation.
use crate::{
config::{LocalTransactionConfig, TXPOOL_MAX_ACCOUNT_SLOTS_PER_SENDER},
error::{Eip4844PoolTransactionError, InvalidPoolTransactionError, PoolError, PoolErrorKind},
identifier::{SenderId, TransactionId},
metrics::TxPoolMetrics,
pool::{
best::BestTransactions,
blob::BlobTransactions,
parked::{BasefeeOrd, ParkedPool, QueuedOrd},
pending::PendingPool,
state::{SubPool, TxState},
update::{Destination, PoolUpdate},
AddedPendingTransaction, AddedTransaction, OnNewCanonicalStateOutcome,
},
traits::{BestTransactionsAttributes, BlockInfo, PoolSize},
PoolConfig, PoolResult, PoolTransaction, PriceBumpConfig, TransactionOrdering,
ValidPoolTransaction, U256,
};
use fnv::FnvHashMap;
use reth_primitives::{
constants::{
eip4844::BLOB_TX_MIN_BLOB_GASPRICE, ETHEREUM_BLOCK_GAS_LIMIT, MIN_PROTOCOL_BASE_FEE,
},
Address, TxHash, B256,
};
use std::{
cmp::Ordering,
collections::{btree_map::Entry, hash_map, BTreeMap, HashMap, HashSet},
fmt,
ops::Bound::{Excluded, Unbounded},
sync::Arc,
};
/// A pool that manages transactions.
///
/// This pool maintains the state of all transactions and stores them accordingly.
#[cfg_attr(doc, aquamarine::aquamarine)]
/// ```mermaid
/// graph TB
/// subgraph TxPool
/// direction TB
/// pool[(All Transactions)]
/// subgraph Subpools
/// direction TB
/// B3[(Queued)]
/// B1[(Pending)]
/// B2[(Basefee)]
/// B4[(Blob)]
/// end
/// end
/// discard([discard])
/// production([Block Production])
/// new([New Block])
/// A[Incoming Tx] --> B[Validation] -->|insert| pool
/// pool --> |if ready + blobfee too low| B4
/// pool --> |if ready| B1
/// pool --> |if ready + basfee too low| B2
/// pool --> |nonce gap or lack of funds| B3
/// pool --> |update| pool
/// B1 --> |best| production
/// B2 --> |worst| discard
/// B3 --> |worst| discard
/// B4 --> |worst| discard
/// B1 --> |increased blob fee| B4
/// B4 --> |decreased blob fee| B1
/// B1 --> |increased base fee| B2
/// B2 --> |decreased base fee| B1
/// B3 --> |promote| B1
/// B3 --> |promote| B2
/// new --> |apply state changes| pool
/// ```
pub struct TxPool<T: TransactionOrdering> {
/// Contains the currently known information about the senders.
sender_info: FnvHashMap<SenderId, SenderInfo>,
/// pending subpool
///
/// Holds transactions that are ready to be executed on the current state.
pending_pool: PendingPool<T>,
/// Pool settings to enforce limits etc.
config: PoolConfig,
/// queued subpool
///
/// Holds all parked transactions that depend on external changes from the sender:
///
/// - blocked by missing ancestor transaction (has nonce gaps)
/// - sender lacks funds to pay for this transaction.
queued_pool: ParkedPool<QueuedOrd<T::Transaction>>,
/// base fee subpool
///
/// Holds all parked transactions that currently violate the dynamic fee requirement but could
/// be moved to pending if the base fee changes in their favor (decreases) in future blocks.
basefee_pool: ParkedPool<BasefeeOrd<T::Transaction>>,
/// Blob transactions in the pool that are __not pending__.
///
/// This means they either do not satisfy the dynamic fee requirement or the blob fee
/// requirement. These transactions can be moved to pending if the base fee or blob fee changes
/// in their favor (decreases) in future blocks. The transaction may need both the base fee and
/// blob fee to decrease to become executable.
blob_pool: BlobTransactions<T::Transaction>,
/// All transactions in the pool.
all_transactions: AllTransactions<T::Transaction>,
/// Transaction pool metrics
metrics: TxPoolMetrics,
}
// === impl TxPool ===
impl<T: TransactionOrdering> TxPool<T> {
/// Create a new graph pool instance.
pub(crate) fn new(ordering: T, config: PoolConfig) -> Self {
Self {
sender_info: Default::default(),
pending_pool: PendingPool::new(ordering),
queued_pool: Default::default(),
basefee_pool: Default::default(),
blob_pool: Default::default(),
all_transactions: AllTransactions::new(&config),
config,
metrics: Default::default(),
}
}
/// Returns access to the [`AllTransactions`] container.
pub(crate) fn all(&self) -> &AllTransactions<T::Transaction> {
&self.all_transactions
}
/// Returns all senders in the pool
pub(crate) fn unique_senders(&self) -> HashSet<Address> {
self.all_transactions.txs.values().map(|tx| tx.transaction.sender()).collect()
}
/// Returns stats about the size of pool.
pub(crate) fn size(&self) -> PoolSize {
PoolSize {
pending: self.pending_pool.len(),
pending_size: self.pending_pool.size(),
basefee: self.basefee_pool.len(),
basefee_size: self.basefee_pool.size(),
queued: self.queued_pool.len(),
queued_size: self.queued_pool.size(),
blob: self.blob_pool.len(),
blob_size: self.blob_pool.size(),
total: self.all_transactions.len(),
}
}
/// Returns the currently tracked block values
pub(crate) fn block_info(&self) -> BlockInfo {
BlockInfo {
last_seen_block_hash: self.all_transactions.last_seen_block_hash,
last_seen_block_number: self.all_transactions.last_seen_block_number,
pending_basefee: self.all_transactions.pending_fees.base_fee,
pending_blob_fee: Some(self.all_transactions.pending_fees.blob_fee),
}
}
/// Updates the tracked blob fee
fn update_blob_fee(&mut self, mut pending_blob_fee: u128, base_fee_update: Ordering) {
std::mem::swap(&mut self.all_transactions.pending_fees.blob_fee, &mut pending_blob_fee);
match (self.all_transactions.pending_fees.blob_fee.cmp(&pending_blob_fee), base_fee_update)
{
(Ordering::Equal, Ordering::Equal) => {
// fee unchanged, nothing to update
}
(Ordering::Greater, Ordering::Equal) |
(Ordering::Equal, Ordering::Greater) |
(Ordering::Greater, Ordering::Greater) => {
// increased blob fee: recheck pending pool and remove all that are no longer valid
let removed =
self.pending_pool.update_blob_fee(self.all_transactions.pending_fees.blob_fee);
for tx in removed {
let to = {
let tx =
self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
// we unset the blob fee cap block flag, if the base fee is too high now
tx.state.remove(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
tx.subpool = tx.state.into();
tx.subpool
};
self.add_transaction_to_subpool(to, tx);
}
}
(Ordering::Less, Ordering::Equal) | (_, Ordering::Less) => {
// decreased blob fee or base fee: recheck blob pool and promote all that are now
// valid
let removed =
self.blob_pool.enforce_pending_fees(&self.all_transactions.pending_fees);
for tx in removed {
let to = {
let tx =
self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
tx.state.insert(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
tx.state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
tx.subpool = tx.state.into();
tx.subpool
};
self.add_transaction_to_subpool(to, tx);
}
}
(Ordering::Less, Ordering::Greater) => {
// increased blob fee: recheck pending pool and remove all that are no longer valid
let removed =
self.pending_pool.update_blob_fee(self.all_transactions.pending_fees.blob_fee);
for tx in removed {
let to = {
let tx =
self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
// we unset the blob fee cap block flag, if the base fee is too high now
tx.state.remove(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
tx.subpool = tx.state.into();
tx.subpool
};
self.add_transaction_to_subpool(to, tx);
}
// decreased blob fee or base fee: recheck blob pool and promote all that are now
// valid
let removed =
self.blob_pool.enforce_pending_fees(&self.all_transactions.pending_fees);
for tx in removed {
let to = {
let tx =
self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
tx.state.insert(TxState::ENOUGH_BLOB_FEE_CAP_BLOCK);
tx.state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
tx.subpool = tx.state.into();
tx.subpool
};
self.add_transaction_to_subpool(to, tx);
}
}
}
}
/// Updates the tracked basefee
///
/// Depending on the change in direction of the basefee, this will promote or demote
/// transactions from the basefee pool.
fn update_basefee(&mut self, mut pending_basefee: u64) -> Ordering {
std::mem::swap(&mut self.all_transactions.pending_fees.base_fee, &mut pending_basefee);
match self.all_transactions.pending_fees.base_fee.cmp(&pending_basefee) {
Ordering::Equal => {
// fee unchanged, nothing to update
Ordering::Equal
}
Ordering::Greater => {
// increased base fee: recheck pending pool and remove all that are no longer valid
let removed =
self.pending_pool.update_base_fee(self.all_transactions.pending_fees.base_fee);
for tx in removed {
let to = {
let tx =
self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
tx.state.remove(TxState::ENOUGH_FEE_CAP_BLOCK);
tx.subpool = tx.state.into();
tx.subpool
};
self.add_transaction_to_subpool(to, tx);
}
Ordering::Greater
}
Ordering::Less => {
// decreased base fee: recheck basefee pool and promote all that are now valid
let removed =
self.basefee_pool.enforce_basefee(self.all_transactions.pending_fees.base_fee);
for tx in removed {
let to = {
let tx =
self.all_transactions.txs.get_mut(tx.id()).expect("tx exists in set");
tx.state.insert(TxState::ENOUGH_FEE_CAP_BLOCK);
tx.subpool = tx.state.into();
tx.subpool
};
self.add_transaction_to_subpool(to, tx);
}
Ordering::Less
}
}
}
/// Sets the current block info for the pool.
///
/// This will also apply updates to the pool based on the new base fee
pub(crate) fn set_block_info(&mut self, info: BlockInfo) {
let BlockInfo {
last_seen_block_hash,
last_seen_block_number,
pending_basefee,
pending_blob_fee,
} = info;
self.all_transactions.last_seen_block_hash = last_seen_block_hash;
self.all_transactions.last_seen_block_number = last_seen_block_number;
let basefee_ordering = self.update_basefee(pending_basefee);
if let Some(blob_fee) = pending_blob_fee {
self.update_blob_fee(blob_fee, basefee_ordering)
}
}
/// Returns an iterator that yields transactions that are ready to be included in the block.
pub(crate) fn best_transactions(&self) -> BestTransactions<T> {
self.pending_pool.best()
}
/// Returns an iterator that yields transactions that are ready to be included in the block with
/// the given base fee.
pub(crate) fn best_transactions_with_base_fee(
&self,
basefee: u64,
) -> Box<dyn crate::traits::BestTransactions<Item = Arc<ValidPoolTransaction<T::Transaction>>>>
{
match basefee.cmp(&self.all_transactions.pending_fees.base_fee) {
Ordering::Equal => {
// fee unchanged, nothing to shift
Box::new(self.best_transactions())
}
Ordering::Greater => {
// base fee increased, we only need to enforces this on the pending pool
Box::new(self.pending_pool.best_with_basefee(basefee))
}
Ordering::Less => {
// base fee decreased, we need to move transactions from the basefee pool to the
// pending pool
let unlocked = self.basefee_pool.satisfy_base_fee_transactions(basefee);
Box::new(
self.pending_pool
.best_with_unlocked(unlocked, self.all_transactions.pending_fees.base_fee),
)
}
}
}
/// Returns an iterator that yields transactions that are ready to be included in the block with
/// the given base fee and optional blob fee.
pub(crate) fn best_transactions_with_attributes(
&self,
best_transactions_attributes: BestTransactionsAttributes,
) -> Box<dyn crate::traits::BestTransactions<Item = Arc<ValidPoolTransaction<T::Transaction>>>>
{
match best_transactions_attributes.basefee.cmp(&self.all_transactions.pending_fees.base_fee)
{
Ordering::Equal => {
// fee unchanged, nothing to shift
Box::new(self.best_transactions())
}
Ordering::Greater => {
// base fee increased, we only need to enforce this on the pending pool
Box::new(self.pending_pool.best_with_basefee(best_transactions_attributes.basefee))
}
Ordering::Less => {
// base fee decreased, we need to move transactions from the basefee pool to the
// pending pool and satisfy blob fee transactions as well
let unlocked_with_blob =
self.blob_pool.satisfy_attributes(best_transactions_attributes);
Box::new(self.pending_pool.best_with_unlocked(
unlocked_with_blob,
self.all_transactions.pending_fees.base_fee,
))
}
}
}
/// Returns all transactions from the pending sub-pool
pub(crate) fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
self.pending_pool.all().collect()
}
/// Returns all transactions from parked pools
pub(crate) fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
let mut queued = self.basefee_pool.all().collect::<Vec<_>>();
queued.extend(self.queued_pool.all());
queued
}
/// Returns `true` if the transaction with the given hash is already included in this pool.
pub(crate) fn contains(&self, tx_hash: &TxHash) -> bool {
self.all_transactions.contains(tx_hash)
}
/// Returns `true` if the transaction with the given id is already included in the given subpool
#[cfg(test)]
pub(crate) fn subpool_contains(&self, subpool: SubPool, id: &TransactionId) -> bool {
match subpool {
SubPool::Queued => self.queued_pool.contains(id),
SubPool::Pending => self.pending_pool.contains(id),
SubPool::BaseFee => self.basefee_pool.contains(id),
SubPool::Blob => self.blob_pool.contains(id),
}
}
/// Returns the transaction for the given hash.
pub(crate) fn get(
&self,
tx_hash: &TxHash,
) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
self.all_transactions.by_hash.get(tx_hash).cloned()
}
/// Returns transactions for the multiple given hashes, if they exist.
pub(crate) fn get_all(
&self,
txs: Vec<TxHash>,
) -> impl Iterator<Item = Arc<ValidPoolTransaction<T::Transaction>>> + '_ {
txs.into_iter().filter_map(|tx| self.get(&tx))
}
/// Returns all transactions sent from the given sender.
pub(crate) fn get_transactions_by_sender(
&self,
sender: SenderId,
) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
self.all_transactions.txs_iter(sender).map(|(_, tx)| Arc::clone(&tx.transaction)).collect()
}
/// Updates the transactions for the changed senders.
pub(crate) fn update_accounts(
&mut self,
changed_senders: HashMap<SenderId, SenderInfo>,
) -> UpdateOutcome<T::Transaction> {
// track changed accounts
self.sender_info.extend(changed_senders.clone());
// Apply the state changes to the total set of transactions which triggers sub-pool updates.
let updates = self.all_transactions.update(changed_senders);
// Process the sub-pool updates
let update = self.process_updates(updates);
// update the metrics after the update
self.update_size_metrics();
update
}
/// Updates the entire pool after a new block was mined.
///
/// This removes all mined transactions, updates according to the new base fee and rechecks
/// sender allowance.
pub(crate) fn on_canonical_state_change(
&mut self,
block_info: BlockInfo,
mined_transactions: Vec<TxHash>,
changed_senders: HashMap<SenderId, SenderInfo>,
) -> OnNewCanonicalStateOutcome<T::Transaction> {
// update block info
let block_hash = block_info.last_seen_block_hash;
self.all_transactions.set_block_info(block_info);
// Remove all transaction that were included in the block
for tx_hash in mined_transactions.iter() {
if self.prune_transaction_by_hash(tx_hash).is_some() {
// Update removed transactions metric
self.metrics.removed_transactions.increment(1);
}
}
let UpdateOutcome { promoted, discarded } = self.update_accounts(changed_senders);
self.metrics.performed_state_updates.increment(1);
OnNewCanonicalStateOutcome { block_hash, mined: mined_transactions, promoted, discarded }
}
/// Update sub-pools size metrics.
pub(crate) fn update_size_metrics(&mut self) {
let stats = self.size();
self.metrics.pending_pool_transactions.set(stats.pending as f64);
self.metrics.pending_pool_size_bytes.set(stats.pending_size as f64);
self.metrics.basefee_pool_transactions.set(stats.basefee as f64);
self.metrics.basefee_pool_size_bytes.set(stats.basefee_size as f64);
self.metrics.queued_pool_transactions.set(stats.queued as f64);
self.metrics.queued_pool_size_bytes.set(stats.queued_size as f64);
self.metrics.total_transactions.set(stats.total as f64);
}
/// Adds the transaction into the pool.
///
/// This pool consists of four sub-pools: `Queued`, `Pending`, `BaseFee`, and `Blob`.
///
/// The `Queued` pool contains transactions with gaps in its dependency tree: It requires
/// additional transactions that are note yet present in the pool. And transactions that the
/// sender can not afford with the current balance.
///
/// The `Pending` pool contains all transactions that have no nonce gaps, and can be afforded by
/// the sender. It only contains transactions that are ready to be included in the pending
/// block. The pending pool contains all transactions that could be listed currently, but not
/// necessarily independently. However, this pool never contains transactions with nonce gaps. A
/// transaction is considered `ready` when it has the lowest nonce of all transactions from the
/// same sender. Which is equals to the chain nonce of the sender in the pending pool.
///
/// The `BaseFee` pool contains transactions that currently can't satisfy the dynamic fee
/// requirement. With EIP-1559, transactions can become executable or not without any changes to
/// the sender's balance or nonce and instead their `feeCap` determines whether the
/// transaction is _currently_ (on the current state) ready or needs to be parked until the
/// `feeCap` satisfies the block's `baseFee`.
///
/// The `Blob` pool contains _blob_ transactions that currently can't satisfy the dynamic fee
/// requirement, or blob fee requirement. Transactions become executable only if the
/// transaction `feeCap` is greater than the block's `baseFee` and the `maxBlobFee` is greater
/// than the block's `blobFee`.
pub(crate) fn add_transaction(
&mut self,
tx: ValidPoolTransaction<T::Transaction>,
on_chain_balance: U256,
on_chain_nonce: u64,
) -> PoolResult<AddedTransaction<T::Transaction>> {
if self.contains(tx.hash()) {
return Err(PoolError::new(*tx.hash(), PoolErrorKind::AlreadyImported))
}
// Update sender info with balance and nonce
self.sender_info
.entry(tx.sender_id())
.or_default()
.update(on_chain_nonce, on_chain_balance);
match self.all_transactions.insert_tx(tx, on_chain_balance, on_chain_nonce) {
Ok(InsertOk { transaction, move_to, replaced_tx, updates, .. }) => {
// replace the new tx and remove the replaced in the subpool(s)
self.add_new_transaction(transaction.clone(), replaced_tx.clone(), move_to);
// Update inserted transactions metric
self.metrics.inserted_transactions.increment(1);
let UpdateOutcome { promoted, discarded } = self.process_updates(updates);
let replaced = replaced_tx.map(|(tx, _)| tx);
// This transaction was moved to the pending pool.
let res = if move_to.is_pending() {
AddedTransaction::Pending(AddedPendingTransaction {
transaction,
promoted,
discarded,
replaced,
})
} else {
AddedTransaction::Parked { transaction, subpool: move_to, replaced }
};
Ok(res)
}
Err(err) => {
// Update invalid transactions metric
self.metrics.invalid_transactions.increment(1);
match err {
InsertErr::Underpriced { existing, transaction: _ } => {
Err(PoolError::new(existing, PoolErrorKind::ReplacementUnderpriced))
}
InsertErr::FeeCapBelowMinimumProtocolFeeCap { transaction, fee_cap } => {
Err(PoolError::new(
*transaction.hash(),
PoolErrorKind::FeeCapBelowMinimumProtocolFeeCap(fee_cap),
))
}
InsertErr::ExceededSenderTransactionsCapacity { transaction } => {
Err(PoolError::new(
*transaction.hash(),
PoolErrorKind::SpammerExceededCapacity(transaction.sender()),
))
}
InsertErr::TxGasLimitMoreThanAvailableBlockGas {
transaction,
block_gas_limit,
tx_gas_limit,
} => Err(PoolError::new(
*transaction.hash(),
PoolErrorKind::InvalidTransaction(
InvalidPoolTransactionError::ExceedsGasLimit(
block_gas_limit,
tx_gas_limit,
),
),
)),
InsertErr::BlobTxHasNonceGap { transaction } => Err(PoolError::new(
*transaction.hash(),
PoolErrorKind::InvalidTransaction(
Eip4844PoolTransactionError::Eip4844NonceGap.into(),
),
)),
InsertErr::Overdraft { transaction } => Err(PoolError::new(
*transaction.hash(),
PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Overdraft),
)),
InsertErr::TxTypeConflict { transaction } => Err(PoolError::new(
*transaction.hash(),
PoolErrorKind::ExistingConflictingTransactionType(
transaction.sender(),
transaction.tx_type(),
),
)),
}
}
}
}
/// Maintenance task to apply a series of updates.
///
/// This will move/discard the given transaction according to the `PoolUpdate`
fn process_updates(&mut self, updates: Vec<PoolUpdate>) -> UpdateOutcome<T::Transaction> {
let mut outcome = UpdateOutcome::default();
for update in updates {
let PoolUpdate { id, hash, current, destination } = update;
match destination {
Destination::Discard => {
// remove the transaction from the pool and subpool
if let Some(tx) = self.prune_transaction_by_hash(&hash) {
outcome.discarded.push(tx);
}
self.metrics.removed_transactions.increment(1);
}
Destination::Pool(move_to) => {
debug_assert!(!move_to.eq(¤t), "destination must be different");
let moved = self.move_transaction(current, move_to, &id);
if matches!(move_to, SubPool::Pending) {
if let Some(tx) = moved {
outcome.promoted.push(tx);
}
}
}
}
}
outcome
}
/// Moves a transaction from one sub pool to another.
///
/// This will remove the given transaction from one sub-pool and insert it into the other
/// sub-pool.
fn move_transaction(
&mut self,
from: SubPool,
to: SubPool,
id: &TransactionId,
) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
let tx = self.remove_from_subpool(from, id)?;
self.add_transaction_to_subpool(to, tx.clone());
Some(tx)
}
/// Removes and returns all matching transactions from the pool.
///
/// Note: this does not advance any descendants of the removed transactions and does not apply
/// any additional updates.
pub(crate) fn remove_transactions(
&mut self,
hashes: Vec<TxHash>,
) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
hashes.into_iter().filter_map(|hash| self.remove_transaction_by_hash(&hash)).collect()
}
/// Remove the transaction from the entire pool.
///
/// This includes the total set of transaction and the subpool it currently resides in.
fn remove_transaction(
&mut self,
id: &TransactionId,
) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
let (tx, pool) = self.all_transactions.remove_transaction(id)?;
self.remove_from_subpool(pool, tx.id())
}
/// Remove the transaction from the entire pool via its hash.
///
/// This includes the total set of transactions and the subpool it currently resides in.
fn remove_transaction_by_hash(
&mut self,
tx_hash: &B256,
) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
let (tx, pool) = self.all_transactions.remove_transaction_by_hash(tx_hash)?;
self.remove_from_subpool(pool, tx.id())
}
/// This removes the transaction from the pool and advances any descendant state inside the
/// subpool.
///
/// This is intended to be used when a transaction is included in a block,
/// [Self::on_canonical_state_change]
fn prune_transaction_by_hash(
&mut self,
tx_hash: &B256,
) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
let (tx, pool) = self.all_transactions.remove_transaction_by_hash(tx_hash)?;
self.prune_from_subpool(pool, tx.id())
}
/// Removes the transaction from the given pool.
///
/// Caution: this only removes the tx from the sub-pool and not from the pool itself
fn remove_from_subpool(
&mut self,
pool: SubPool,
tx: &TransactionId,
) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
match pool {
SubPool::Queued => self.queued_pool.remove_transaction(tx),
SubPool::Pending => self.pending_pool.remove_transaction(tx),
SubPool::BaseFee => self.basefee_pool.remove_transaction(tx),
SubPool::Blob => self.blob_pool.remove_transaction(tx),
}
}
/// Removes the transaction from the given pool and advance sub-pool internal state, with the
/// expectation that the given transaction is included in a block.
fn prune_from_subpool(
&mut self,
pool: SubPool,
tx: &TransactionId,
) -> Option<Arc<ValidPoolTransaction<T::Transaction>>> {
match pool {
SubPool::Pending => self.pending_pool.prune_transaction(tx),
SubPool::Queued => self.queued_pool.remove_transaction(tx),
SubPool::BaseFee => self.basefee_pool.remove_transaction(tx),
SubPool::Blob => self.blob_pool.remove_transaction(tx),
}
}
/// Removes _only_ the descendants of the given transaction from the entire pool.
///
/// All removed transactions are added to the `removed` vec.
fn remove_descendants(
&mut self,
tx: &TransactionId,
removed: &mut Vec<Arc<ValidPoolTransaction<T::Transaction>>>,
) {
let mut id = *tx;
// this will essentially pop _all_ descendant transactions one by one
loop {
let descendant =
self.all_transactions.descendant_txs_exclusive(&id).map(|(id, _)| *id).next();
if let Some(descendant) = descendant {
if let Some(tx) = self.remove_transaction(&descendant) {
removed.push(tx)
}
id = descendant;
} else {
return
}
}
}
/// Inserts the transaction into the given sub-pool.
fn add_transaction_to_subpool(
&mut self,
pool: SubPool,
tx: Arc<ValidPoolTransaction<T::Transaction>>,
) {
match pool {
SubPool::Queued => {
self.queued_pool.add_transaction(tx);
}
SubPool::Pending => {
self.pending_pool.add_transaction(tx, self.all_transactions.pending_fees.base_fee);
}
SubPool::BaseFee => {
self.basefee_pool.add_transaction(tx);
}
SubPool::Blob => {
self.blob_pool.add_transaction(tx);
}
}
}
/// Inserts the transaction into the given sub-pool.
/// Optionally, removes the replacement transaction.
fn add_new_transaction(
&mut self,
transaction: Arc<ValidPoolTransaction<T::Transaction>>,
replaced: Option<(Arc<ValidPoolTransaction<T::Transaction>>, SubPool)>,
pool: SubPool,
) {
if let Some((replaced, replaced_pool)) = replaced {
// Remove the replaced transaction
self.remove_from_subpool(replaced_pool, replaced.id());
}
self.add_transaction_to_subpool(pool, transaction)
}
/// Ensures that the transactions in the sub-pools are within the given bounds.
///
/// If the current size exceeds the given bounds, the worst transactions are evicted from the
/// pool and returned.
pub(crate) fn discard_worst(&mut self) -> Vec<Arc<ValidPoolTransaction<T::Transaction>>> {
let mut removed = Vec::new();
// Helper macro that discards the worst transactions for the pools
macro_rules! discard_worst {
($this:ident, $removed:ident, [$($limit:ident => $pool:ident),*] ) => {
$ (
while $this
.config
.$limit
.is_exceeded($this.$pool.len(), $this.$pool.size())
{
removed = $this.$pool.truncate_pool($this.config.$limit.clone());
for tx in removed.clone().iter() {
$this.remove_descendants(tx.id(), &mut $removed);
}
}
)*
};
}
discard_worst!(
self, removed, [
pending_limit => pending_pool,
basefee_limit => basefee_pool,
blob_limit => blob_pool,
queued_limit => queued_pool
]
);
removed
}
/// Number of transactions in the entire pool
pub(crate) fn len(&self) -> usize {
self.all_transactions.len()
}
/// Whether the pool is empty
pub(crate) fn is_empty(&self) -> bool {
self.all_transactions.is_empty()
}
/// Asserts all invariants of the pool's:
///
/// - All maps are bijections (`by_id`, `by_hash`)
/// - Total size is equal to the sum of all sub-pools
///
/// # Panics
/// if any invariant is violated
#[cfg(any(test, feature = "test-utils"))]
pub fn assert_invariants(&self) {
let size = self.size();
let actual = size.basefee + size.pending + size.queued + size.blob;
assert_eq!(size.total, actual, "total size must be equal to the sum of all sub-pools, basefee:{}, pending:{}, queued:{}, blob:{}", size.basefee, size.pending, size.queued, size.blob);
self.all_transactions.assert_invariants();
self.pending_pool.assert_invariants();
self.basefee_pool.assert_invariants();
self.queued_pool.assert_invariants();
self.blob_pool.assert_invariants();
}
}
#[cfg(any(test, feature = "test-utils"))]
impl TxPool<crate::test_utils::MockOrdering> {
/// Creates a mock instance for testing.
pub fn mock() -> Self {
Self::new(crate::test_utils::MockOrdering::default(), PoolConfig::default())
}
}
#[cfg(test)]
impl<T: TransactionOrdering> Drop for TxPool<T> {
fn drop(&mut self) {
self.assert_invariants();
}
}
// Additional test impls
#[cfg(any(test, feature = "test-utils"))]
#[allow(missing_docs)]
impl<T: TransactionOrdering> TxPool<T> {
pub(crate) fn pending(&self) -> &PendingPool<T> {
&self.pending_pool
}
pub(crate) fn base_fee(&self) -> &ParkedPool<BasefeeOrd<T::Transaction>> {
&self.basefee_pool
}
pub(crate) fn queued(&self) -> &ParkedPool<QueuedOrd<T::Transaction>> {
&self.queued_pool
}
}
impl<T: TransactionOrdering> fmt::Debug for TxPool<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TxPool").field("config", &self.config).finish_non_exhaustive()
}
}
/// Container for _all_ transaction in the pool.
///
/// This is the sole entrypoint that's guarding all sub-pools, all sub-pool actions are always
/// derived from this set. Updates returned from this type must be applied to the sub-pools.
pub(crate) struct AllTransactions<T: PoolTransaction> {
/// Minimum base fee required by the protocol.
///
/// Transactions with a lower base fee will never be included by the chain
minimal_protocol_basefee: u64,
/// The max gas limit of the block
block_gas_limit: u64,
/// Max number of executable transaction slots guaranteed per account
max_account_slots: usize,
/// _All_ transactions identified by their hash.
by_hash: HashMap<TxHash, Arc<ValidPoolTransaction<T>>>,
/// _All_ transaction in the pool sorted by their sender and nonce pair.
txs: BTreeMap<TransactionId, PoolInternalTransaction<T>>,
/// Tracks the number of transactions by sender that are currently in the pool.
tx_counter: FnvHashMap<SenderId, usize>,
/// The current block number the pool keeps track of.
last_seen_block_number: u64,
/// The current block hash the pool keeps track of.
last_seen_block_hash: B256,
/// Expected blob and base fee for the pending block.
pending_fees: PendingFees,
/// Configured price bump settings for replacements
price_bumps: PriceBumpConfig,
/// How to handle [TransactionOrigin::Local](crate::TransactionOrigin) transactions.
local_transactions_config: LocalTransactionConfig,
}
impl<T: PoolTransaction> AllTransactions<T> {
/// Create a new instance
fn new(config: &PoolConfig) -> Self {
Self {
max_account_slots: config.max_account_slots,
price_bumps: config.price_bumps,
local_transactions_config: config.local_transactions_config.clone(),
..Default::default()
}
}
/// Returns an iterator over all _unique_ hashes in the pool
#[allow(unused)]
pub(crate) fn hashes_iter(&self) -> impl Iterator<Item = TxHash> + '_ {
self.by_hash.keys().copied()
}
/// Returns an iterator over all _unique_ hashes in the pool
pub(crate) fn transactions_iter(
&self,
) -> impl Iterator<Item = Arc<ValidPoolTransaction<T>>> + '_ {
self.by_hash.values().cloned()
}
/// Returns if the transaction for the given hash is already included in this pool
pub(crate) fn contains(&self, tx_hash: &TxHash) -> bool {
self.by_hash.contains_key(tx_hash)
}
/// Returns the internal transaction with additional metadata
#[cfg(test)]
pub(crate) fn get(&self, id: &TransactionId) -> Option<&PoolInternalTransaction<T>> {
self.txs.get(id)
}
/// Increments the transaction counter for the sender
pub(crate) fn tx_inc(&mut self, sender: SenderId) {
let count = self.tx_counter.entry(sender).or_default();
*count += 1;
}
/// Decrements the transaction counter for the sender
pub(crate) fn tx_decr(&mut self, sender: SenderId) {
if let hash_map::Entry::Occupied(mut entry) = self.tx_counter.entry(sender) {
let count = entry.get_mut();
if *count == 1 {
entry.remove();
return
}
*count -= 1;
}
}
/// Updates the block specific info
fn set_block_info(&mut self, block_info: BlockInfo) {
let BlockInfo {
last_seen_block_hash,
last_seen_block_number,
pending_basefee,
pending_blob_fee,
} = block_info;
self.last_seen_block_number = last_seen_block_number;
self.last_seen_block_hash = last_seen_block_hash;
self.pending_fees.base_fee = pending_basefee;
if let Some(pending_blob_fee) = pending_blob_fee {
self.pending_fees.blob_fee = pending_blob_fee;
}
}
/// Rechecks all transactions in the pool against the changes.
///
/// Possible changes are:
///
/// For all transactions:
/// - decreased basefee: promotes from `basefee` to `pending` sub-pool.
/// - increased basefee: demotes from `pending` to `basefee` sub-pool.
/// Individually:
/// - decreased sender allowance: demote from (`basefee`|`pending`) to `queued`.
/// - increased sender allowance: promote from `queued` to
/// - `pending` if basefee condition is met.
/// - `basefee` if basefee condition is _not_ met.