Skip to main content

reth_transaction_pool/test_utils/
tx_gen.rs

1use crate::{blobstore::BlobTransactionCellSidecar, EthPooledTransaction, PoolTransaction};
2use alloy_consensus::{
3    SignableTransaction, Signed, TxEip1559, TxEip4844, TxEip4844WithSidecar, TxLegacy,
4};
5use alloy_eips::{
6    eip1559::MIN_PROTOCOL_BASE_FEE,
7    eip2718::Encodable2718,
8    eip2930::AccessList,
9    eip4844::{env_settings::EnvKzgSettings, Blob},
10    eip7594::BlobTransactionSidecarEip7594,
11};
12use alloy_primitives::{Address, Bytes, Signature, TxKind, B256, U256};
13use rand::{Rng, RngCore};
14use reth_chainspec::MAINNET;
15use reth_ethereum_primitives::{PooledTransactionVariant, Transaction, TransactionSigned};
16use reth_primitives_traits::{crypto::secp256k1::sign_message, SignedTransaction};
17
18/// A generator for transactions for testing purposes.
19#[derive(Debug)]
20pub struct TransactionGenerator<R> {
21    /// The random number generator used for generating keys and selecting signers.
22    pub rng: R,
23    /// The set of signer keys available for transaction generation.
24    pub signer_keys: Vec<B256>,
25    /// The base fee for transactions.
26    pub base_fee: u128,
27    /// The gas limit for transactions.
28    pub gas_limit: u64,
29}
30
31impl<R: RngCore> TransactionGenerator<R> {
32    /// Initializes the generator with 10 random signers
33    pub fn new(rng: R) -> Self {
34        Self::with_num_signers(rng, 10)
35    }
36
37    /// Generates random signers
38    pub fn with_num_signers(rng: R, num_signers: usize) -> Self {
39        Self {
40            rng,
41            signer_keys: (0..num_signers).map(|_| B256::random()).collect(),
42            base_fee: MIN_PROTOCOL_BASE_FEE as u128,
43            gas_limit: 300_000,
44        }
45    }
46
47    /// Adds a new signer to the set
48    pub fn push_signer(&mut self, signer: B256) -> &mut Self {
49        self.signer_keys.push(signer);
50        self
51    }
52
53    /// Sets the default gas limit for all generated transactions
54    pub const fn set_gas_limit(&mut self, gas_limit: u64) -> &mut Self {
55        self.gas_limit = gas_limit;
56        self
57    }
58
59    /// Sets the default gas limit for all generated transactions
60    pub const fn with_gas_limit(mut self, gas_limit: u64) -> Self {
61        self.gas_limit = gas_limit;
62        self
63    }
64
65    /// Sets the base fee for the generated transactions
66    pub const fn set_base_fee(&mut self, base_fee: u64) -> &mut Self {
67        self.base_fee = base_fee as u128;
68        self
69    }
70
71    /// Sets the base fee for the generated transactions
72    pub const fn with_base_fee(mut self, base_fee: u64) -> Self {
73        self.base_fee = base_fee as u128;
74        self
75    }
76
77    /// Adds the given signers to the set.
78    pub fn extend_signers(&mut self, signers: impl IntoIterator<Item = B256>) -> &mut Self {
79        self.signer_keys.extend(signers);
80        self
81    }
82
83    /// Returns a random signer from the set
84    fn rng_signer(&mut self) -> B256 {
85        let idx = self.rng.random_range(0..self.signer_keys.len());
86        self.signer_keys[idx]
87    }
88
89    /// Creates a new transaction with a random signer
90    pub fn transaction(&mut self) -> TransactionBuilder {
91        TransactionBuilder::default()
92            .signer(self.rng_signer())
93            .max_fee_per_gas(self.base_fee)
94            .max_priority_fee_per_gas(self.base_fee)
95            .gas_limit(self.gas_limit)
96    }
97
98    /// Creates a new transaction with a random signer
99    pub fn gen_eip1559(&mut self) -> TransactionSigned {
100        self.transaction().into_eip1559()
101    }
102
103    /// Creates a new transaction with a random signer
104    pub fn gen_eip4844(&mut self) -> TransactionSigned {
105        self.transaction().into_eip4844()
106    }
107
108    /// Generates and returns a pooled EIP-1559 transaction with a random signer.
109    pub fn gen_eip1559_pooled(&mut self) -> EthPooledTransaction {
110        EthPooledTransaction::try_from_consensus(
111            SignedTransaction::try_into_recovered(self.gen_eip1559()).unwrap(),
112        )
113        .unwrap()
114    }
115
116    /// Generates and returns a pooled EIP-4844 transaction with a random signer.
117    pub fn gen_eip4844_pooled(&mut self) -> EthPooledTransaction {
118        let tx = self.gen_eip4844().try_into_recovered().unwrap();
119        let encoded_length = tx.encode_2718_len();
120        EthPooledTransaction::new(tx, encoded_length)
121    }
122}
123
124/// A Builder type to configure and create a transaction.
125#[derive(Debug)]
126pub struct TransactionBuilder {
127    /// The signer used to sign the transaction.
128    pub signer: B256,
129    /// The chain ID on which the transaction will be executed.
130    pub chain_id: u64,
131    /// The nonce value for the transaction to prevent replay attacks.
132    pub nonce: u64,
133    /// The maximum amount of gas units that the transaction can consume.
134    pub gas_limit: u64,
135    /// The maximum fee per gas unit that the sender is willing to pay.
136    pub max_fee_per_gas: u128,
137    /// The maximum priority fee per gas unit that the sender is willing to pay for faster
138    /// processing.
139    pub max_priority_fee_per_gas: u128,
140    /// The recipient or contract address of the transaction.
141    pub to: TxKind,
142    /// The value to be transferred in the transaction.
143    pub value: U256,
144    /// The list of addresses and storage keys that the transaction can access.
145    pub access_list: AccessList,
146    /// The input data for the transaction, typically containing function parameters for contract
147    /// calls.
148    pub input: Bytes,
149}
150
151impl TransactionBuilder {
152    /// Converts the transaction builder into a legacy transaction format.
153    pub fn into_legacy(self) -> TransactionSigned {
154        Self::signed(
155            TxLegacy {
156                chain_id: Some(self.chain_id),
157                nonce: self.nonce,
158                gas_limit: self.gas_limit,
159                gas_price: self.max_fee_per_gas,
160                to: self.to,
161                value: self.value,
162                input: self.input,
163            }
164            .into(),
165            self.signer,
166        )
167    }
168
169    /// Converts the transaction builder into a transaction format using EIP-1559.
170    pub fn into_eip1559(self) -> TransactionSigned {
171        Self::signed(
172            TxEip1559 {
173                chain_id: self.chain_id,
174                nonce: self.nonce,
175                gas_limit: self.gas_limit,
176                max_fee_per_gas: self.max_fee_per_gas,
177                max_priority_fee_per_gas: self.max_priority_fee_per_gas,
178                to: self.to,
179                value: self.value,
180                access_list: self.access_list,
181                input: self.input,
182            }
183            .into(),
184            self.signer,
185        )
186    }
187    /// Converts the transaction builder into a transaction format using EIP-4844.
188    pub fn into_eip4844(self) -> TransactionSigned {
189        Self::signed(
190            TxEip4844 {
191                chain_id: self.chain_id,
192                nonce: self.nonce,
193                gas_limit: self.gas_limit,
194                max_fee_per_gas: self.max_fee_per_gas,
195                max_priority_fee_per_gas: self.max_priority_fee_per_gas,
196                to: match self.to {
197                    TxKind::Call(to) => to,
198                    TxKind::Create => Address::default(),
199                },
200                value: self.value,
201                access_list: self.access_list,
202                input: self.input,
203                blob_versioned_hashes: Default::default(),
204                max_fee_per_blob_gas: Default::default(),
205            }
206            .into(),
207            self.signer,
208        )
209    }
210
211    /// Signs the provided transaction using the specified signer and returns a signed transaction.
212    fn signed(transaction: Transaction, signer: B256) -> TransactionSigned {
213        let signature = sign_message(signer, transaction.signature_hash()).unwrap();
214        TransactionSigned::new_unhashed(transaction, signature)
215    }
216
217    /// Sets the signer for the transaction builder.
218    pub const fn signer(mut self, signer: B256) -> Self {
219        self.signer = signer;
220        self
221    }
222
223    /// Sets the gas limit for the transaction builder.
224    pub const fn gas_limit(mut self, gas_limit: u64) -> Self {
225        self.gas_limit = gas_limit;
226        self
227    }
228
229    /// Sets the nonce for the transaction builder.
230    pub const fn nonce(mut self, nonce: u64) -> Self {
231        self.nonce = nonce;
232        self
233    }
234
235    /// Increments the nonce value of the transaction builder by 1.
236    pub const fn inc_nonce(mut self) -> Self {
237        self.nonce += 1;
238        self
239    }
240
241    /// Decrements the nonce value of the transaction builder by 1, avoiding underflow.
242    pub const fn decr_nonce(mut self) -> Self {
243        self.nonce = self.nonce.saturating_sub(1);
244        self
245    }
246
247    /// Sets the maximum fee per gas for the transaction builder.
248    pub const fn max_fee_per_gas(mut self, max_fee_per_gas: u128) -> Self {
249        self.max_fee_per_gas = max_fee_per_gas;
250        self
251    }
252
253    /// Sets the maximum priority fee per gas for the transaction builder.
254    pub const fn max_priority_fee_per_gas(mut self, max_priority_fee_per_gas: u128) -> Self {
255        self.max_priority_fee_per_gas = max_priority_fee_per_gas;
256        self
257    }
258
259    /// Sets the recipient or contract address for the transaction builder.
260    pub const fn to(mut self, to: Address) -> Self {
261        self.to = TxKind::Call(to);
262        self
263    }
264
265    /// Sets the value to be transferred in the transaction.
266    pub fn value(mut self, value: u128) -> Self {
267        self.value = U256::from(value);
268        self
269    }
270
271    /// Sets the access list for the transaction builder.
272    pub fn access_list(mut self, access_list: AccessList) -> Self {
273        self.access_list = access_list;
274        self
275    }
276
277    /// Sets the transaction input data.
278    pub fn input(mut self, input: impl Into<Bytes>) -> Self {
279        self.input = input.into();
280        self
281    }
282
283    /// Sets the chain ID for the transaction.
284    pub const fn chain_id(mut self, chain_id: u64) -> Self {
285        self.chain_id = chain_id;
286        self
287    }
288
289    /// Sets the chain ID for the transaction, mutable reference version.
290    pub const fn set_chain_id(&mut self, chain_id: u64) -> &mut Self {
291        self.chain_id = chain_id;
292        self
293    }
294
295    /// Sets the nonce for the transaction, mutable reference version.
296    pub const fn set_nonce(&mut self, nonce: u64) -> &mut Self {
297        self.nonce = nonce;
298        self
299    }
300
301    /// Sets the gas limit for the transaction, mutable reference version.
302    pub const fn set_gas_limit(&mut self, gas_limit: u64) -> &mut Self {
303        self.gas_limit = gas_limit;
304        self
305    }
306
307    /// Sets the maximum fee per gas for the transaction, mutable reference version.
308    pub const fn set_max_fee_per_gas(&mut self, max_fee_per_gas: u128) -> &mut Self {
309        self.max_fee_per_gas = max_fee_per_gas;
310        self
311    }
312
313    /// Sets the maximum priority fee per gas for the transaction, mutable reference version.
314    pub const fn set_max_priority_fee_per_gas(
315        &mut self,
316        max_priority_fee_per_gas: u128,
317    ) -> &mut Self {
318        self.max_priority_fee_per_gas = max_priority_fee_per_gas;
319        self
320    }
321
322    /// Sets the recipient or contract address for the transaction, mutable reference version.
323    pub fn set_to(&mut self, to: Address) -> &mut Self {
324        self.to = to.into();
325        self
326    }
327
328    /// Sets the value to be transferred in the transaction, mutable reference version.
329    pub fn set_value(&mut self, value: u128) -> &mut Self {
330        self.value = U256::from(value);
331        self
332    }
333
334    /// Sets the access list for the transaction, mutable reference version.
335    pub fn set_access_list(&mut self, access_list: AccessList) -> &mut Self {
336        self.access_list = access_list;
337        self
338    }
339
340    /// Sets the signer for the transaction, mutable reference version.
341    pub const fn set_signer(&mut self, signer: B256) -> &mut Self {
342        self.signer = signer;
343        self
344    }
345
346    /// Sets the transaction input data, mutable reference version.
347    pub fn set_input(&mut self, input: impl Into<Bytes>) -> &mut Self {
348        self.input = input.into();
349        self
350    }
351}
352
353impl Default for TransactionBuilder {
354    fn default() -> Self {
355        Self {
356            signer: B256::random(),
357            chain_id: MAINNET.chain.id(),
358            nonce: 0,
359            gas_limit: 0,
360            max_fee_per_gas: 0,
361            max_priority_fee_per_gas: 0,
362            to: Default::default(),
363            value: Default::default(),
364            access_list: Default::default(),
365            input: Default::default(),
366        }
367    }
368}
369
370/// Returns an eth/72 blob transaction without blobs and all the cells of its `blobs` distinct
371/// blobs. The same `blobs` always gives the same transaction and cells.
372pub fn blob_tx_without_blobs(blobs: u8) -> (EthPooledTransaction, BlobTransactionCellSidecar) {
373    let blobs = (0..blobs)
374        .map(|index| {
375            // The last byte of the first field element keeps it below the modulus.
376            let mut blob = Blob::default();
377            blob[31] = index;
378            blob
379        })
380        .collect();
381    let full = BlobTransactionSidecarEip7594::try_from_blobs(blobs).unwrap();
382    let cells =
383        BlobTransactionCellSidecar::try_from_sidecar(&full, EnvKzgSettings::Default.get()).unwrap();
384    let tx = TxEip4844 {
385        chain_id: 1,
386        gas_limit: 100_000,
387        max_fee_per_gas: 20_000_000_000,
388        max_priority_fee_per_gas: 1_000_000_000,
389        max_fee_per_blob_gas: 20_000_000_000,
390        blob_versioned_hashes: cells.versioned_hashes().collect(),
391        ..Default::default()
392    };
393    let tx = Signed::new_unhashed(
394        TxEip4844WithSidecar { tx, sidecar: cells.without_blobs().into() },
395        Signature::test_signature(),
396    );
397    let pooled = PooledTransactionVariant::Eip4844(tx).try_into_recovered().unwrap();
398    (EthPooledTransaction::from_pooled(pooled), cells)
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    use rand::rng;
405
406    #[test]
407    fn test_generate_transaction() {
408        let rng = rng();
409        let mut tx_gen = TransactionGenerator::new(rng);
410        let _tx = tx_gen.transaction().into_legacy();
411        let _tx = tx_gen.transaction().into_eip1559();
412    }
413}