reth_transaction_pool/test_utils/
pool.rs

1//! Test helpers for mocking an entire pool.
2
3#![allow(dead_code)]
4
5use crate::{
6    pool::{txpool::TxPool, AddedTransaction},
7    test_utils::{MockOrdering, MockTransactionDistribution, MockTransactionFactory},
8    TransactionOrdering,
9};
10use alloy_primitives::{Address, U256};
11use rand::Rng;
12use std::{
13    collections::HashMap,
14    ops::{Deref, DerefMut},
15};
16
17/// A wrapped `TxPool` with additional helpers for testing
18pub(crate) struct MockPool<T: TransactionOrdering = MockOrdering> {
19    // The wrapped pool.
20    pool: TxPool<T>,
21}
22
23impl MockPool {
24    /// The total size of all subpools
25    fn total_subpool_size(&self) -> usize {
26        self.pool.pending().len() + self.pool.base_fee().len() + self.pool.queued().len()
27    }
28
29    /// Checks that all pool invariants hold.
30    fn enforce_invariants(&self) {
31        assert_eq!(
32            self.pool.len(),
33            self.total_subpool_size(),
34            "Tx in AllTransactions and sum(subpools) must match"
35        );
36    }
37}
38
39impl Default for MockPool {
40    fn default() -> Self {
41        Self { pool: TxPool::new(MockOrdering::default(), Default::default()) }
42    }
43}
44
45impl<T: TransactionOrdering> Deref for MockPool<T> {
46    type Target = TxPool<T>;
47
48    fn deref(&self) -> &Self::Target {
49        &self.pool
50    }
51}
52
53impl<T: TransactionOrdering> DerefMut for MockPool<T> {
54    fn deref_mut(&mut self) -> &mut Self::Target {
55        &mut self.pool
56    }
57}
58
59/// Simulates transaction execution.
60pub(crate) struct MockTransactionSimulator<R: Rng> {
61    /// The pending base fee
62    base_fee: u128,
63    /// Generator for transactions
64    tx_generator: MockTransactionDistribution,
65    /// represents the on chain balance of a sender.
66    balances: HashMap<Address, U256>,
67    /// represents the on chain nonce of a sender.
68    nonces: HashMap<Address, u64>,
69    /// A set of addresses to as senders.
70    senders: Vec<Address>,
71    /// What scenarios to execute.
72    scenarios: Vec<ScenarioType>,
73    /// All previous scenarios executed by a sender.
74    executed: HashMap<Address, ExecutedScenarios>,
75    /// "Validates" generated transactions.
76    validator: MockTransactionFactory,
77    /// The rng instance used to select senders and scenarios.
78    rng: R,
79}
80
81impl<R: Rng> MockTransactionSimulator<R> {
82    /// Returns a new mock instance
83    pub(crate) fn new(mut rng: R, config: MockSimulatorConfig) -> Self {
84        let senders = config.addresses(&mut rng);
85        Self {
86            base_fee: config.base_fee,
87            balances: senders.iter().copied().map(|a| (a, rng.random())).collect(),
88            nonces: senders.iter().copied().map(|a| (a, 0)).collect(),
89            senders,
90            scenarios: config.scenarios,
91            tx_generator: config.tx_generator,
92            executed: Default::default(),
93            validator: Default::default(),
94            rng,
95        }
96    }
97
98    /// Returns a random address from the senders set
99    fn rng_address(&mut self) -> Address {
100        let idx = self.rng.random_range(0..self.senders.len());
101        self.senders[idx]
102    }
103
104    /// Returns a random scenario from the scenario set
105    fn rng_scenario(&mut self) -> ScenarioType {
106        let idx = self.rng.random_range(0..self.scenarios.len());
107        self.scenarios[idx].clone()
108    }
109
110    /// Executes the next scenario and applies it to the pool
111    pub(crate) fn next(&mut self, pool: &mut MockPool) {
112        let sender = self.rng_address();
113        let scenario = self.rng_scenario();
114        let on_chain_nonce = self.nonces[&sender];
115        let on_chain_balance = self.balances[&sender];
116
117        match scenario {
118            ScenarioType::OnchainNonce => {
119                let tx = self
120                    .tx_generator
121                    .tx(on_chain_nonce, &mut self.rng)
122                    .with_gas_price(self.base_fee);
123                let valid_tx = self.validator.validated(tx);
124
125                let res =
126                    pool.add_transaction(valid_tx, on_chain_balance, on_chain_nonce, None).unwrap();
127
128                // TODO(mattsse): need a way expect based on the current state of the pool and tx
129                // settings
130
131                match res {
132                    AddedTransaction::Pending(_) => {}
133                    AddedTransaction::Parked { .. } => {
134                        panic!("expected pending")
135                    }
136                }
137
138                // TODO(mattsse): check subpools
139            }
140            ScenarioType::HigherNonce { .. } => {
141                unimplemented!()
142            }
143        }
144
145        // make sure everything is set
146        pool.enforce_invariants()
147    }
148}
149
150/// How to configure a new mock transaction stream
151pub(crate) struct MockSimulatorConfig {
152    /// How many senders to generate.
153    pub(crate) num_senders: usize,
154    /// Scenarios to test
155    pub(crate) scenarios: Vec<ScenarioType>,
156    /// The start base fee
157    pub(crate) base_fee: u128,
158    /// generator for transactions
159    pub(crate) tx_generator: MockTransactionDistribution,
160}
161
162impl MockSimulatorConfig {
163    /// Generates a set of random addresses
164    pub(crate) fn addresses(&self, rng: &mut impl rand::Rng) -> Vec<Address> {
165        std::iter::repeat_with(|| Address::random_with(rng)).take(self.num_senders).collect()
166    }
167}
168
169/// Represents
170#[derive(Debug, Clone)]
171#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
172pub(crate) enum ScenarioType {
173    OnchainNonce,
174    HigherNonce { skip: u64 },
175}
176
177/// The actual scenario, ready to be executed
178///
179/// A scenario produces one or more transactions and expects a certain Outcome.
180///
181/// An executed scenario can affect previous executed transactions
182#[derive(Debug, Clone)]
183#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
184pub(crate) enum Scenario {
185    /// Send a tx with the same nonce as on chain.
186    OnchainNonce { nonce: u64 },
187    /// Send a tx with a higher nonce that what the sender has on chain
188    HigherNonce { onchain: u64, nonce: u64 },
189    Multi {
190        // Execute multiple test scenarios
191        scenario: Vec<Scenario>,
192    },
193}
194
195/// Represents an executed scenario
196#[derive(Debug, Clone)]
197#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
198pub(crate) struct ExecutedScenario {
199    /// balance at the time of execution
200    balance: U256,
201    /// nonce at the time of execution
202    nonce: u64,
203    /// The executed scenario
204    scenario: Scenario,
205}
206
207/// All executed scenarios by a sender
208#[derive(Debug, Clone)]
209#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
210pub(crate) struct ExecutedScenarios {
211    sender: Address,
212    scenarios: Vec<ExecutedScenario>,
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::test_utils::{MockFeeRange, MockTransactionRatio};
219
220    #[test]
221    fn test_on_chain_nonce_scenario() {
222        let transaction_ratio = MockTransactionRatio {
223            legacy_pct: 30,
224            dynamic_fee_pct: 70,
225            access_list_pct: 0,
226            blob_pct: 0,
227        };
228
229        let fee_ranges = MockFeeRange {
230            gas_price: (10u128..100).try_into().unwrap(),
231            priority_fee: (10u128..100).try_into().unwrap(),
232            max_fee: (100u128..110).try_into().unwrap(),
233            max_fee_blob: (1u128..100).try_into().unwrap(),
234        };
235
236        let config = MockSimulatorConfig {
237            num_senders: 10,
238            scenarios: vec![ScenarioType::OnchainNonce],
239            base_fee: 10,
240            tx_generator: MockTransactionDistribution::new(
241                transaction_ratio,
242                fee_ranges,
243                10..100,
244                10..100,
245            ),
246        };
247        let mut simulator = MockTransactionSimulator::new(rand::rng(), config);
248        let mut pool = MockPool::default();
249
250        simulator.next(&mut pool);
251    }
252}