reth_transaction_pool/pool/blob.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
use super::txpool::PendingFees;
use crate::{
identifier::TransactionId, pool::size::SizeTracker, traits::BestTransactionsAttributes,
PoolTransaction, SubPoolLimit, ValidPoolTransaction,
};
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
/// A set of validated blob transactions in the pool that are __not pending__.
///
/// The purpose of this pool is to keep track of blob transactions that are queued and to evict the
/// worst blob transactions once the sub-pool is full.
///
/// This expects that certain constraints are met:
/// - blob transactions are always gap less
pub(crate) struct BlobTransactions<T: PoolTransaction> {
/// Keeps track of transactions inserted in the pool.
///
/// This way we can determine when transactions were submitted to the pool.
submission_id: u64,
/// _All_ Transactions that are currently inside the pool grouped by their identifier.
by_id: BTreeMap<TransactionId, BlobTransaction<T>>,
/// _All_ transactions sorted by blob priority.
all: BTreeSet<BlobTransaction<T>>,
/// Keeps track of the current fees, so transaction priority can be calculated on insertion.
pending_fees: PendingFees,
/// Keeps track of the size of this pool.
///
/// See also [`PoolTransaction::size`].
size_of: SizeTracker,
}
// === impl BlobTransactions ===
impl<T: PoolTransaction> BlobTransactions<T> {
/// Adds a new transactions to the pending queue.
///
/// # Panics
///
/// - If the transaction is not a blob tx.
/// - If the transaction is already included.
pub(crate) fn add_transaction(&mut self, tx: Arc<ValidPoolTransaction<T>>) {
assert!(tx.is_eip4844(), "transaction is not a blob tx");
let id = *tx.id();
assert!(!self.contains(&id), "transaction already included {:?}", self.get(&id).unwrap());
let submission_id = self.next_id();
// keep track of size
self.size_of += tx.size();
// set transaction, which will also calculate priority based on current pending fees
let transaction = BlobTransaction::new(tx, submission_id, &self.pending_fees);
self.by_id.insert(id, transaction.clone());
self.all.insert(transaction);
}
fn next_id(&mut self) -> u64 {
let id = self.submission_id;
self.submission_id = self.submission_id.wrapping_add(1);
id
}
/// Removes the transaction from the pool
pub(crate) fn remove_transaction(
&mut self,
id: &TransactionId,
) -> Option<Arc<ValidPoolTransaction<T>>> {
// remove from queues
let tx = self.by_id.remove(id)?;
self.all.remove(&tx);
// keep track of size
self.size_of -= tx.transaction.size();
Some(tx.transaction)
}
/// Returns all transactions that satisfy the given basefee and blobfee.
///
/// Note: This does not remove any the transactions from the pool.
pub(crate) fn satisfy_attributes(
&self,
best_transactions_attributes: BestTransactionsAttributes,
) -> Vec<Arc<ValidPoolTransaction<T>>> {
let mut transactions = Vec::new();
{
// short path if blob_fee is None in provided best transactions attributes
if let Some(blob_fee_to_satisfy) =
best_transactions_attributes.blob_fee.map(|fee| fee as u128)
{
let mut iter = self.by_id.iter().peekable();
while let Some((id, tx)) = iter.next() {
if tx.transaction.max_fee_per_blob_gas().unwrap_or_default() <
blob_fee_to_satisfy ||
tx.transaction.max_fee_per_gas() <
best_transactions_attributes.basefee as u128
{
// does not satisfy the blob fee or base fee
// still parked in blob pool -> skip descendant transactions
'this: while let Some((peek, _)) = iter.peek() {
if peek.sender != id.sender {
break 'this
}
iter.next();
}
} else {
transactions.push(tx.transaction.clone());
}
}
}
}
transactions
}
/// Returns true if the pool exceeds the given limit
#[inline]
pub(crate) fn exceeds(&self, limit: &SubPoolLimit) -> bool {
limit.is_exceeded(self.len(), self.size())
}
/// The reported size of all transactions in this pool.
pub(crate) fn size(&self) -> usize {
self.size_of.into()
}
/// Number of transactions in the entire pool
pub(crate) fn len(&self) -> usize {
self.by_id.len()
}
/// Returns whether the pool is empty
#[cfg(test)]
#[allow(dead_code)]
pub(crate) fn is_empty(&self) -> bool {
self.by_id.is_empty()
}
/// Returns all transactions which:
/// * have a `max_fee_per_blob_gas` greater than or equal to the given `blob_fee`, _and_
/// * have a `max_fee_per_gas` greater than or equal to the given `base_fee`
fn satisfy_pending_fee_ids(&self, pending_fees: &PendingFees) -> Vec<TransactionId> {
let mut transactions = Vec::new();
{
let mut iter = self.by_id.iter().peekable();
while let Some((id, tx)) = iter.next() {
if tx.transaction.max_fee_per_blob_gas() < Some(pending_fees.blob_fee) ||
tx.transaction.max_fee_per_gas() < pending_fees.base_fee as u128
{
// still parked in blob pool -> skip descendant transactions
'this: while let Some((peek, _)) = iter.peek() {
if peek.sender != id.sender {
break 'this
}
iter.next();
}
} else {
transactions.push(*id);
}
}
}
transactions
}
/// Resorts the transactions in the pool based on the pool's current [`PendingFees`].
pub(crate) fn reprioritize(&mut self) {
// mem::take to modify without allocating, then collect to rebuild the BTreeSet
self.all = std::mem::take(&mut self.all)
.into_iter()
.map(|mut tx| {
tx.update_priority(&self.pending_fees);
tx
})
.collect();
// we need to update `by_id` as well because removal from `all` can only happen if the
// `BlobTransaction`s in each struct are consistent
for tx in self.by_id.values_mut() {
tx.update_priority(&self.pending_fees);
}
}
/// Removes all transactions (and their descendants) which:
/// * have a `max_fee_per_blob_gas` greater than or equal to the given `blob_fee`, _and_
/// * have a `max_fee_per_gas` greater than or equal to the given `base_fee`
///
/// This also sets the [`PendingFees`] for the pool, resorting transactions based on their
/// updated priority.
///
/// Note: the transactions are not returned in a particular order.
pub(crate) fn enforce_pending_fees(
&mut self,
pending_fees: &PendingFees,
) -> Vec<Arc<ValidPoolTransaction<T>>> {
let removed = self
.satisfy_pending_fee_ids(pending_fees)
.into_iter()
.map(|id| self.remove_transaction(&id).expect("transaction exists"))
.collect();
// Update pending fees and reprioritize
self.pending_fees = pending_fees.clone();
self.reprioritize();
removed
}
/// Removes transactions until the pool satisfies its [`SubPoolLimit`].
///
/// This is done by removing transactions according to their ordering in the pool, defined by
/// the [`BlobOrd`] struct.
///
/// Removed transactions are returned in the order they were removed.
pub(crate) fn truncate_pool(
&mut self,
limit: SubPoolLimit,
) -> Vec<Arc<ValidPoolTransaction<T>>> {
let mut removed = Vec::new();
while self.exceeds(&limit) {
let tx = self.all.last().expect("pool is not empty");
let id = *tx.transaction.id();
removed.push(self.remove_transaction(&id).expect("transaction exists"));
}
removed
}
/// Returns `true` if the transaction with the given id is already included in this pool.
pub(crate) fn contains(&self, id: &TransactionId) -> bool {
self.by_id.contains_key(id)
}
/// Retrieves a transaction with the given ID from the pool, if it exists.
fn get(&self, id: &TransactionId) -> Option<&BlobTransaction<T>> {
self.by_id.get(id)
}
/// Asserts that the bijection between `by_id` and `all` is valid.
#[cfg(any(test, feature = "test-utils"))]
pub(crate) fn assert_invariants(&self) {
assert_eq!(self.by_id.len(), self.all.len(), "by_id.len() != all.len()");
}
}
impl<T: PoolTransaction> Default for BlobTransactions<T> {
fn default() -> Self {
Self {
submission_id: 0,
by_id: Default::default(),
all: Default::default(),
size_of: Default::default(),
pending_fees: Default::default(),
}
}
}
/// A transaction that is ready to be included in a block.
#[derive(Debug)]
struct BlobTransaction<T: PoolTransaction> {
/// Actual blob transaction.
transaction: Arc<ValidPoolTransaction<T>>,
/// The value that determines the order of this transaction.
ord: BlobOrd,
}
impl<T: PoolTransaction> BlobTransaction<T> {
/// Creates a new blob transaction, based on the pool transaction, submission id, and current
/// pending fees.
pub(crate) fn new(
transaction: Arc<ValidPoolTransaction<T>>,
submission_id: u64,
pending_fees: &PendingFees,
) -> Self {
let priority = blob_tx_priority(
pending_fees.blob_fee,
transaction.max_fee_per_blob_gas().unwrap_or_default(),
pending_fees.base_fee as u128,
transaction.max_fee_per_gas(),
);
let ord = BlobOrd { priority, submission_id };
Self { transaction, ord }
}
/// Updates the priority for the transaction based on the current pending fees.
pub(crate) fn update_priority(&mut self, pending_fees: &PendingFees) {
self.ord.priority = blob_tx_priority(
pending_fees.blob_fee,
self.transaction.max_fee_per_blob_gas().unwrap_or_default(),
pending_fees.base_fee as u128,
self.transaction.max_fee_per_gas(),
);
}
}
impl<T: PoolTransaction> Clone for BlobTransaction<T> {
fn clone(&self) -> Self {
Self { transaction: self.transaction.clone(), ord: self.ord.clone() }
}
}
impl<T: PoolTransaction> Eq for BlobTransaction<T> {}
impl<T: PoolTransaction> PartialEq<Self> for BlobTransaction<T> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl<T: PoolTransaction> PartialOrd<Self> for BlobTransaction<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T: PoolTransaction> Ord for BlobTransaction<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.ord.cmp(&other.ord)
}
}
/// This is the log base 2 of 1.125, which we'll use to calculate the priority
const LOG_2_1_125: f64 = 0.16992500144231237;
/// The blob step function, attempting to compute the delta given the `max_tx_fee`, and
/// `current_fee`.
///
/// The `max_tx_fee` is the maximum fee that the transaction is willing to pay, this
/// would be the priority fee for the EIP1559 component of transaction fees, and the blob fee cap
/// for the blob component of transaction fees.
///
/// The `current_fee` is the current value of the fee, this would be the base fee for the EIP1559
/// component, and the blob fee (computed from the current head) for the blob component.
///
/// This is supposed to get the number of fee jumps required to get from the current fee to the fee
/// cap, or where the transaction would not be executable any more.
///
/// A positive value means that the transaction will remain executable unless the current fee
/// increases.
///
/// A negative value means that the transaction is currently not executable, and requires the
/// current fee to decrease by some number of jumps before the max fee is greater than the current
/// fee.
pub fn fee_delta(max_tx_fee: u128, current_fee: u128) -> i64 {
if max_tx_fee == current_fee {
// if these are equal, then there's no fee jump
return 0
}
let max_tx_fee_jumps = if max_tx_fee == 0 {
// we can't take log2 of 0, so we set this to zero here
0f64
} else {
(max_tx_fee.ilog2() as f64) / LOG_2_1_125
};
let current_fee_jumps = if current_fee == 0 {
// we can't take log2 of 0, so we set this to zero here
0f64
} else {
(current_fee.ilog2() as f64) / LOG_2_1_125
};
// jumps = log1.125(txfee) - log1.125(basefee)
let jumps = max_tx_fee_jumps - current_fee_jumps;
// delta = sign(jumps) * log(abs(jumps))
match (jumps as i64).cmp(&0) {
Ordering::Equal => {
// can't take ilog2 of 0
0
}
Ordering::Greater => (jumps.ceil() as i64).ilog2() as i64,
Ordering::Less => -((-jumps.floor() as i64).ilog2() as i64),
}
}
/// Returns the priority for the transaction, based on the "delta" blob fee and priority fee.
pub fn blob_tx_priority(
blob_fee_cap: u128,
blob_fee: u128,
max_priority_fee: u128,
base_fee: u128,
) -> i64 {
let delta_blob_fee = fee_delta(blob_fee_cap, blob_fee);
let delta_priority_fee = fee_delta(max_priority_fee, base_fee);
// TODO: this could be u64:
// * if all are positive, zero is returned
// * if all are negative, the min negative value is returned
// * if some are positive and some are negative, the min negative value is returned
//
// the BlobOrd could then just be a u64, and higher values represent worse transactions (more
// jumps for one of the fees until the cap satisfies)
//
// priority = min(delta-basefee, delta-blobfee, 0)
delta_blob_fee.min(delta_priority_fee).min(0)
}
/// A struct used to determine the ordering for a specific blob transaction in the pool. This uses
/// a `priority` value to determine the ordering, and uses the `submission_id` to break ties.
///
/// The `priority` value is calculated using the [`blob_tx_priority`] function, and should be
/// re-calculated on each block.
#[derive(Debug, Clone)]
struct BlobOrd {
/// Identifier that tags when transaction was submitted in the pool.
pub(crate) submission_id: u64,
/// The priority for this transaction, calculated using the [`blob_tx_priority`] function,
/// taking into account both the blob and priority fee.
pub(crate) priority: i64,
}
impl Eq for BlobOrd {}
impl PartialEq<Self> for BlobOrd {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl PartialOrd<Self> for BlobOrd {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for BlobOrd {
/// Compares two `BlobOrd` instances.
///
/// The comparison is performed in reverse order based on the priority field. This is
/// because transactions with larger negative values in the priority field will take more fee
/// jumps, making them take longer to become executable. Therefore, transactions with lower
/// ordering should return `Greater`, ensuring they are evicted first.
///
/// If the priority values are equal, the submission ID is used to break ties.
fn cmp(&self, other: &Self) -> Ordering {
other
.priority
.cmp(&self.priority)
.then_with(|| self.submission_id.cmp(&other.submission_id))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::{MockTransaction, MockTransactionFactory};
/// Represents the fees for a single transaction, which will be built inside of a test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TransactionFees {
/// The blob fee cap for the transaction.
max_blob_fee: u128,
/// The max priority fee for the transaction.
max_priority_fee_per_gas: u128,
/// The base fee for the transaction.
max_fee_per_gas: u128,
}
/// Represents an ordering of transactions based on their fees and the current network fees.
#[derive(Debug, Clone)]
struct TransactionOrdering {
/// The transaction fees, in the order that they're expected to be returned
fees: Vec<TransactionFees>,
/// The network fees
network_fees: PendingFees,
}
#[test]
fn test_blob_ordering() {
// Tests are from:
// <https://github.com/ethereum/go-ethereum/blob/e91cdb49beb4b2a3872b5f2548bf2d6559e4f561/core/txpool/blobpool/evictheap_test.go>
let mut factory = MockTransactionFactory::default();
let vectors = vec![
// If everything is above basefee and blobfee, order by miner tip
TransactionOrdering {
fees: vec![
TransactionFees {
max_blob_fee: 2,
max_priority_fee_per_gas: 0,
max_fee_per_gas: 2,
},
TransactionFees {
max_blob_fee: 3,
max_priority_fee_per_gas: 1,
max_fee_per_gas: 1,
},
TransactionFees {
max_blob_fee: 1,
max_priority_fee_per_gas: 2,
max_fee_per_gas: 3,
},
],
network_fees: PendingFees { base_fee: 0, blob_fee: 0 },
},
// If only basefees are used (blob fee matches with network), return the ones the
// furthest below the current basefee, splitting same ones with the tip. Anything above
// the basefee should be split by tip.
TransactionOrdering {
fees: vec![
TransactionFees {
max_blob_fee: 0,
max_priority_fee_per_gas: 50,
max_fee_per_gas: 500,
},
TransactionFees {
max_blob_fee: 0,
max_priority_fee_per_gas: 100,
max_fee_per_gas: 500,
},
TransactionFees {
max_blob_fee: 0,
max_priority_fee_per_gas: 50,
max_fee_per_gas: 1000,
},
TransactionFees {
max_blob_fee: 0,
max_priority_fee_per_gas: 100,
max_fee_per_gas: 1000,
},
TransactionFees {
max_blob_fee: 0,
max_priority_fee_per_gas: 1,
max_fee_per_gas: 2000,
},
TransactionFees {
max_blob_fee: 0,
max_priority_fee_per_gas: 2,
max_fee_per_gas: 2000,
},
TransactionFees {
max_blob_fee: 0,
max_priority_fee_per_gas: 3,
max_fee_per_gas: 2000,
},
],
network_fees: PendingFees { base_fee: 1999, blob_fee: 0 },
},
// If only blobfees are used (base fee matches with network), return the
// ones the furthest below the current blobfee, splitting same ones with
// the tip. Anything above the blobfee should be split by tip.
TransactionOrdering {
fees: vec![
TransactionFees {
max_blob_fee: 500,
max_priority_fee_per_gas: 50,
max_fee_per_gas: 0,
},
TransactionFees {
max_blob_fee: 500,
max_priority_fee_per_gas: 100,
max_fee_per_gas: 0,
},
TransactionFees {
max_blob_fee: 1000,
max_priority_fee_per_gas: 50,
max_fee_per_gas: 0,
},
TransactionFees {
max_blob_fee: 1000,
max_priority_fee_per_gas: 100,
max_fee_per_gas: 0,
},
TransactionFees {
max_blob_fee: 2000,
max_priority_fee_per_gas: 1,
max_fee_per_gas: 0,
},
TransactionFees {
max_blob_fee: 2000,
max_priority_fee_per_gas: 2,
max_fee_per_gas: 0,
},
TransactionFees {
max_blob_fee: 2000,
max_priority_fee_per_gas: 3,
max_fee_per_gas: 0,
},
],
network_fees: PendingFees { base_fee: 0, blob_fee: 1999 },
},
// If both basefee and blobfee is specified, sort by the larger distance
// of the two from the current network conditions, splitting same (loglog)
// ones via the tip.
//
// Basefee: 1000
// Blobfee: 100
//
// Tx #0: (800, 80) - 2 jumps below both => priority -1
// Tx #1: (630, 63) - 4 jumps below both => priority -2
// Tx #2: (800, 63) - 2 jumps below basefee, 4 jumps below blobfee => priority -2 (blob
// penalty dominates) Tx #3: (630, 80) - 4 jumps below basefee, 2 jumps
// below blobfee => priority -2 (base penalty dominates)
//
// Txs 1, 2, 3 share the same priority, split via tip, prefer 0 as the best
TransactionOrdering {
fees: vec![
TransactionFees {
max_blob_fee: 80,
max_priority_fee_per_gas: 4,
max_fee_per_gas: 630,
},
TransactionFees {
max_blob_fee: 63,
max_priority_fee_per_gas: 3,
max_fee_per_gas: 800,
},
TransactionFees {
max_blob_fee: 63,
max_priority_fee_per_gas: 2,
max_fee_per_gas: 630,
},
TransactionFees {
max_blob_fee: 80,
max_priority_fee_per_gas: 1,
max_fee_per_gas: 800,
},
],
network_fees: PendingFees { base_fee: 1000, blob_fee: 100 },
},
];
for ordering in vectors {
// create a new pool each time
let mut pool = BlobTransactions::default();
// create tx from fees
let txs = ordering
.fees
.iter()
.map(|fees| {
MockTransaction::eip4844()
.with_blob_fee(fees.max_blob_fee)
.with_priority_fee(fees.max_priority_fee_per_gas)
.with_max_fee(fees.max_fee_per_gas)
})
.collect::<Vec<_>>();
for tx in &txs {
pool.add_transaction(factory.validated_arc(tx.clone()));
}
// update fees and resort the pool
pool.pending_fees = ordering.network_fees.clone();
pool.reprioritize();
// now iterate through the pool and make sure they're in the same order as the original
// fees - map to TransactionFees so it's easier to compare the ordering without having
// to see irrelevant fields
let actual_txs = pool
.all
.iter()
.map(|tx| TransactionFees {
max_blob_fee: tx.transaction.max_fee_per_blob_gas().unwrap_or_default(),
max_priority_fee_per_gas: tx.transaction.priority_fee_or_price(),
max_fee_per_gas: tx.transaction.max_fee_per_gas(),
})
.collect::<Vec<_>>();
assert_eq!(
ordering.fees, actual_txs,
"ordering mismatch, expected: {:#?}, actual: {:#?}",
ordering.fees, actual_txs
);
}
}
#[test]
fn priority_tests() {
// Test vectors from:
// <https://github.com/ethereum/go-ethereum/blob/e91cdb49beb4b2a3872b5f2548bf2d6559e4f561/core/txpool/blobpool/priority_test.go#L27-L49>
let vectors = vec![
(7u128, 10u128, 2i64),
(17_200_000_000, 17_200_000_000, 0),
(9_853_941_692, 11_085_092_510, 0),
(11_544_106_391, 10_356_781_100, 0),
(17_200_000_000, 7, -7),
(7, 17_200_000_000, 7),
];
for (base_fee, tx_fee, expected) in vectors {
let actual = fee_delta(tx_fee, base_fee);
assert_eq!(
actual, expected,
"fee_delta({tx_fee}, {base_fee}) = {actual}, expected: {expected}"
);
}
}
#[test]
fn test_empty_pool_operations() {
let mut pool: BlobTransactions<MockTransaction> = BlobTransactions::default();
// Ensure pool is empty
assert!(pool.is_empty());
assert_eq!(pool.len(), 0);
assert_eq!(pool.size(), 0);
// Attempt to remove a non-existent transaction
let non_existent_id = TransactionId::new(0.into(), 0);
assert!(pool.remove_transaction(&non_existent_id).is_none());
// Check contains method on empty pool
assert!(!pool.contains(&non_existent_id));
}
#[test]
fn test_transaction_removal() {
let mut factory = MockTransactionFactory::default();
let mut pool = BlobTransactions::default();
// Add a transaction
let tx = factory.validated_arc(MockTransaction::eip4844());
let tx_id = *tx.id();
pool.add_transaction(tx);
// Remove the transaction
let removed = pool.remove_transaction(&tx_id);
assert!(removed.is_some());
assert_eq!(*removed.unwrap().id(), tx_id);
assert!(pool.is_empty());
}
#[test]
fn test_satisfy_attributes_empty_pool() {
let pool: BlobTransactions<MockTransaction> = BlobTransactions::default();
let attributes = BestTransactionsAttributes { blob_fee: Some(100), basefee: 100 };
// Satisfy attributes on an empty pool should return an empty vector
let satisfied = pool.satisfy_attributes(attributes);
assert!(satisfied.is_empty());
}
#[test]
#[should_panic(expected = "transaction is not a blob tx")]
fn test_add_non_blob_transaction() {
// Ensure that adding a non-blob transaction causes a panic
let mut factory = MockTransactionFactory::default();
let mut pool = BlobTransactions::default();
let tx = factory.validated_arc(MockTransaction::eip1559()); // Not a blob transaction
pool.add_transaction(tx);
}
#[test]
#[should_panic(expected = "transaction already included")]
fn test_add_duplicate_blob_transaction() {
// Ensure that adding a duplicate blob transaction causes a panic
let mut factory = MockTransactionFactory::default();
let mut pool = BlobTransactions::default();
let tx = factory.validated_arc(MockTransaction::eip4844());
pool.add_transaction(tx.clone()); // First addition
pool.add_transaction(tx); // Attempt to add the same transaction again
}
#[test]
fn test_remove_transactions_until_limit() {
// Test truncating the pool until it satisfies the given size limit
let mut factory = MockTransactionFactory::default();
let mut pool = BlobTransactions::default();
let tx1 = factory.validated_arc(MockTransaction::eip4844().with_size(100));
let tx2 = factory.validated_arc(MockTransaction::eip4844().with_size(200));
let tx3 = factory.validated_arc(MockTransaction::eip4844().with_size(300));
// Add transactions to the pool
pool.add_transaction(tx1);
pool.add_transaction(tx2);
pool.add_transaction(tx3);
// Set a size limit that requires truncation
let limit = SubPoolLimit { max_txs: 2, max_size: 300 };
let removed = pool.truncate_pool(limit);
// Check that only one transaction was removed to satisfy the limit
assert_eq!(removed.len(), 1);
assert_eq!(pool.len(), 2);
assert!(pool.size() <= limit.max_size);
}
#[test]
fn test_empty_pool_invariants() {
// Ensure that the invariants hold for an empty pool
let pool: BlobTransactions<MockTransaction> = BlobTransactions::default();
pool.assert_invariants();
assert!(pool.is_empty());
assert_eq!(pool.size(), 0);
assert_eq!(pool.len(), 0);
}
}