Skip to main content

reth_testing_utils/
generators.rs

1//! Generators for different data structures like block headers, block bodies and ranges of those.
2
3// TODO(rand): update ::random calls after rand_09 migration
4
5use alloy_consensus::{Header, SignableTransaction, Transaction as _, TxLegacy};
6use alloy_eips::{
7    eip1898::BlockWithParent,
8    eip4895::{Withdrawal, Withdrawals},
9    NumHash,
10};
11use alloy_primitives::{Address, BlockNumber, Bytes, TxKind, B256, B64, U256};
12pub use rand::Rng;
13use rand::{distr::uniform::SampleRange, prelude::IndexedRandom, rngs::StdRng, SeedableRng};
14use reth_ethereum_primitives::{Block, BlockBody, Receipt, Transaction, TransactionSigned};
15use reth_primitives_traits::{
16    crypto::secp256k1::sign_message, proofs, Account, Block as _, Log, SealedBlock, SealedHeader,
17    StorageEntry,
18};
19use secp256k1::Keypair;
20use std::{
21    cmp::{max, min},
22    collections::BTreeMap,
23    ops::{Range, RangeInclusive},
24};
25
26/// Used to pass arguments for random block generation function in tests
27#[derive(Debug, Default)]
28pub struct BlockParams {
29    /// The parent hash of the block.
30    pub parent: Option<B256>,
31    /// The number of transactions in the block.
32    pub tx_count: Option<u8>,
33    /// The number of ommers (uncles) in the block.
34    pub ommers_count: Option<u8>,
35    /// The number of requests in the block.
36    pub requests_count: Option<u8>,
37    /// The number of withdrawals in the block.
38    pub withdrawals_count: Option<u8>,
39}
40
41/// Used to pass arguments for random block generation function in tests
42#[derive(Debug)]
43pub struct BlockRangeParams {
44    /// The parent hash of the block.
45    pub parent: Option<B256>,
46    /// The range of transactions in the block.
47    /// If set, a random count between the range will be used.
48    /// If not set, a random number of transactions will be used.
49    pub tx_count: Range<u8>,
50    /// The number of requests in the block.
51    pub requests_count: Option<Range<u8>>,
52    /// The number of withdrawals in the block.
53    pub withdrawals_count: Option<Range<u8>>,
54}
55
56impl Default for BlockRangeParams {
57    fn default() -> Self {
58        Self {
59            parent: None,
60            tx_count: 0..u8::MAX / 2,
61            requests_count: None,
62            withdrawals_count: None,
63        }
64    }
65}
66
67/// Returns a random number generator that can be seeded using the `SEED` environment variable.
68///
69/// If `SEED` is not set, a random seed is used.
70pub fn rng() -> StdRng {
71    if let Ok(seed) = std::env::var("SEED") {
72        rng_with_seed(seed.as_bytes())
73    } else {
74        StdRng::from_rng(&mut rand::rng())
75    }
76}
77
78/// Returns a random number generator from a specific seed, as bytes.
79pub fn rng_with_seed(seed: &[u8]) -> StdRng {
80    let mut seed_bytes = [0u8; 32];
81    seed_bytes[..seed.len().min(32)].copy_from_slice(seed);
82    StdRng::from_seed(seed_bytes)
83}
84
85/// Generates a range of random [`SealedHeader`]s.
86///
87/// The parent hash of the first header
88/// in the result will be equal to `head`.
89///
90/// The headers are assumed not to be correct if validated.
91pub fn random_header_range<R: Rng>(
92    rng: &mut R,
93    range: Range<u64>,
94    head: B256,
95) -> Vec<SealedHeader> {
96    let mut headers = Vec::with_capacity(range.end.saturating_sub(range.start) as usize);
97    for idx in range {
98        headers.push(random_header(
99            rng,
100            idx,
101            Some(headers.last().map(|h: &SealedHeader| h.hash()).unwrap_or(head)),
102        ));
103    }
104    headers
105}
106
107/// Generate a random [`BlockWithParent`].
108pub fn random_block_with_parent<R: Rng>(
109    rng: &mut R,
110    number: u64,
111    parent: Option<B256>,
112) -> BlockWithParent {
113    BlockWithParent {
114        parent: parent.unwrap_or_default(),
115        block: NumHash::new(number, rng.random()),
116    }
117}
118
119/// Generate a random [`SealedHeader`].
120///
121/// The header is assumed not to be correct if validated.
122pub fn random_header<R: Rng>(rng: &mut R, number: u64, parent: Option<B256>) -> SealedHeader {
123    let header = alloy_consensus::Header {
124        number,
125        nonce: B64::random(),
126        difficulty: U256::from(rng.random::<u32>()),
127        parent_hash: parent.unwrap_or_default(),
128        ..Default::default()
129    };
130    SealedHeader::seal_slow(header)
131}
132
133/// Generates a random legacy [Transaction].
134///
135/// Every field is random, except:
136///
137/// - The chain ID, which is always 1
138/// - The input, which is always nothing
139pub fn random_tx<R: Rng>(rng: &mut R) -> Transaction {
140    Transaction::Legacy(TxLegacy {
141        chain_id: Some(1),
142        nonce: rng.random::<u16>().into(),
143        gas_price: rng.random::<u16>().into(),
144        gas_limit: rng.random::<u16>().into(),
145        to: TxKind::Call(Address::random()),
146        value: U256::from(rng.random::<u16>()),
147        input: Bytes::default(),
148    })
149}
150
151/// Generates a random legacy [Transaction] that is signed.
152///
153/// On top of the considerations of [`random_tx`], these apply as well:
154///
155/// - There is no guarantee that the nonce is not used twice for the same account
156pub fn random_signed_tx<R: Rng>(rng: &mut R) -> TransactionSigned {
157    let tx = random_tx(rng);
158    sign_tx_with_random_key_pair(rng, tx)
159}
160
161/// Signs the [Transaction] with a random key pair.
162pub fn sign_tx_with_random_key_pair<R: Rng>(_rng: &mut R, tx: Transaction) -> TransactionSigned {
163    let key_pair = Keypair::new(&mut rand::rng());
164    sign_tx_with_key_pair(key_pair, tx)
165}
166
167/// Signs the [Transaction] with the given key pair.
168pub fn sign_tx_with_key_pair(key_pair: Keypair, tx: Transaction) -> TransactionSigned {
169    let signature =
170        sign_message(B256::from_slice(&key_pair.to_secret_bytes()[..]), tx.signature_hash())
171            .unwrap();
172
173    tx.into_signed(signature).into()
174}
175
176/// Generates a new random [Keypair].
177pub fn generate_key<R: Rng>(_rng: &mut R) -> Keypair {
178    Keypair::new(&mut rand::rng())
179}
180
181/// Generates a set of [Keypair]s based on the desired count.
182pub fn generate_keys<R: Rng>(_rng: &mut R, count: usize) -> Vec<Keypair> {
183    (0..count).map(|_| Keypair::new(&mut rand::rng())).collect()
184}
185
186/// Generate a random block filled with signed transactions (generated using
187/// [`random_signed_tx`]). If no transaction count is provided, the number of transactions
188/// will be random, otherwise the provided count will be used.
189///
190/// All fields use the default values (and are assumed to be invalid) except for:
191///
192/// - `parent_hash`
193/// - `transactions_root`
194/// - `ommers_hash`
195///
196/// Additionally, `gas_used` and `gas_limit` always exactly match the total `gas_limit` of all
197/// transactions in the block.
198///
199/// The ommer headers are not assumed to be valid.
200pub fn random_block<R: Rng>(
201    rng: &mut R,
202    number: u64,
203    block_params: BlockParams,
204) -> SealedBlock<Block> {
205    // Generate transactions
206    let tx_count = block_params.tx_count.unwrap_or_else(|| rng.random::<u8>());
207    let transactions: Vec<TransactionSigned> =
208        (0..tx_count).map(|_| random_signed_tx(rng)).collect();
209    let total_gas = transactions.iter().fold(0, |sum, tx| sum + tx.gas_limit());
210
211    // Generate ommers
212    let ommers_count = block_params.ommers_count.unwrap_or_else(|| rng.random_range(0..2));
213    let ommers = (0..ommers_count)
214        .map(|_| random_header(rng, number, block_params.parent).unseal())
215        .collect::<Vec<_>>();
216
217    // Calculate roots
218    let transactions_root = proofs::calculate_transaction_root(&transactions);
219    let ommers_hash = proofs::calculate_ommers_root(&ommers);
220
221    let withdrawals = block_params.withdrawals_count.map(|count| {
222        (0..count)
223            .map(|i| Withdrawal {
224                amount: rng.random(),
225                index: i.into(),
226                validator_index: i.into(),
227                address: Address::random(),
228            })
229            .collect::<Vec<_>>()
230    });
231    let withdrawals_root = withdrawals.as_ref().map(|w| proofs::calculate_withdrawals_root(w));
232
233    let header = Header {
234        parent_hash: block_params.parent.unwrap_or_default(),
235        number,
236        gas_used: total_gas,
237        gas_limit: total_gas,
238        transactions_root,
239        ommers_hash,
240        base_fee_per_gas: Some(rng.random()),
241        // TODO(onbjerg): Proper EIP-7685 request support
242        requests_hash: None,
243        withdrawals_root,
244        ..Default::default()
245    };
246
247    Block {
248        header,
249        body: BlockBody { transactions, ommers, withdrawals: withdrawals.map(Withdrawals::new) },
250    }
251    .seal_slow()
252}
253
254/// Generate a range of random blocks.
255///
256/// The parent hash of the first block
257/// in the result will be equal to `head`.
258///
259/// See [`random_block`] for considerations when validating the generated blocks.
260pub fn random_block_range<R: Rng>(
261    rng: &mut R,
262    block_numbers: RangeInclusive<BlockNumber>,
263    block_range_params: BlockRangeParams,
264) -> Vec<SealedBlock<Block>> {
265    let mut blocks =
266        Vec::with_capacity(block_numbers.end().saturating_sub(*block_numbers.start()) as usize);
267    for idx in block_numbers {
268        let tx_count = block_range_params.tx_count.clone().sample_single(rng).unwrap();
269        let requests_count =
270            block_range_params.requests_count.clone().map(|r| r.sample_single(rng).unwrap());
271        let withdrawals_count =
272            block_range_params.withdrawals_count.clone().map(|r| r.sample_single(rng).unwrap());
273        let parent = block_range_params.parent.unwrap_or_default();
274        blocks.push(random_block(
275            rng,
276            idx,
277            BlockParams {
278                parent: Some(
279                    blocks.last().map(|block: &SealedBlock<Block>| block.hash()).unwrap_or(parent),
280                ),
281                tx_count: Some(tx_count),
282                ommers_count: None,
283                requests_count,
284                withdrawals_count,
285            },
286        ));
287    }
288    blocks
289}
290
291/// Collection of account and storage entry changes
292pub type ChangeSet = Vec<(Address, Account, Vec<StorageEntry>)>;
293type AccountState = (Account, Vec<StorageEntry>);
294
295/// Generate a range of changesets for given blocks and accounts.
296///
297/// Returns a Vec of account and storage changes for each block,
298/// along with the final state of all accounts and storages.
299#[allow(clippy::clone_on_copy)]
300pub fn random_changeset_range<'a, R: Rng, IBlk, IAcc>(
301    rng: &mut R,
302    blocks: IBlk,
303    accounts: IAcc,
304    n_storage_changes: Range<u64>,
305    key_range: Range<u64>,
306) -> (Vec<ChangeSet>, BTreeMap<Address, AccountState>)
307where
308    IBlk: IntoIterator<Item = &'a SealedBlock<Block>>,
309    IAcc: IntoIterator<Item = (Address, (Account, Vec<StorageEntry>))>,
310{
311    let mut state: BTreeMap<_, _> = accounts
312        .into_iter()
313        .map(|(addr, (acc, st))| (addr, (acc, st.into_iter().map(|e| (e.key, e.value)).collect())))
314        .collect();
315
316    let valid_addresses = state.keys().copied().collect::<Vec<_>>();
317
318    let mut changesets = Vec::new();
319
320    for _block in blocks {
321        let mut changeset = Vec::new();
322        let (from, to, mut transfer, new_entries) = random_account_change(
323            rng,
324            &valid_addresses,
325            n_storage_changes.clone(),
326            key_range.clone(),
327        );
328
329        // extract from sending account
330        let (prev_from, _) = state.get_mut(&from).unwrap();
331        changeset.push((from, prev_from.clone(), Vec::new()));
332
333        transfer = max(min(transfer, prev_from.balance), U256::ONE);
334        prev_from.balance = prev_from.balance.wrapping_sub(transfer);
335
336        // deposit in receiving account and update storage
337        let (prev_to, storage): &mut (Account, BTreeMap<B256, U256>) = state.get_mut(&to).unwrap();
338
339        let mut old_entries: Vec<_> = new_entries
340            .into_iter()
341            .filter_map(|entry| {
342                let old = if entry.value.is_zero() {
343                    let old = storage.remove(&entry.key);
344                    if matches!(old, Some(U256::ZERO)) {
345                        return None
346                    }
347                    old
348                } else {
349                    storage.insert(entry.key, entry.value)
350                };
351                Some(StorageEntry { value: old.unwrap_or(U256::ZERO), ..entry })
352            })
353            .collect();
354        old_entries.sort_by_key(|entry| entry.key);
355
356        changeset.push((to, prev_to.clone(), old_entries));
357
358        changeset.sort_by_key(|(address, _, _)| *address);
359
360        prev_to.balance = prev_to.balance.wrapping_add(transfer);
361
362        changesets.push(changeset);
363    }
364
365    let final_state = state
366        .into_iter()
367        .map(|(addr, (acc, storage))| {
368            (addr, (acc, storage.into_iter().map(|v| v.into()).collect()))
369        })
370        .collect();
371    (changesets, final_state)
372}
373
374/// Generate a random account change.
375///
376/// Returns two addresses, a `balance_change`, and a Vec of new storage entries.
377pub fn random_account_change<R: Rng>(
378    rng: &mut R,
379    valid_addresses: &[Address],
380    n_storage_changes: Range<u64>,
381    key_range: Range<u64>,
382) -> (Address, Address, U256, Vec<StorageEntry>) {
383    let mut addresses = valid_addresses.choose_multiple(rng, 2).copied();
384
385    let addr_from = addresses.next().unwrap_or_else(Address::random);
386    let addr_to = addresses.next().unwrap_or_else(Address::random);
387
388    let balance_change = U256::from(rng.random::<u64>());
389
390    let storage_changes = if n_storage_changes.is_empty() {
391        Vec::new()
392    } else {
393        (0..n_storage_changes.sample_single(rng).unwrap())
394            .map(|_| random_storage_entry(rng, key_range.clone()))
395            .collect()
396    };
397
398    (addr_from, addr_to, balance_change, storage_changes)
399}
400
401/// Generate a random storage change.
402pub fn random_storage_entry<R: Rng>(rng: &mut R, key_range: Range<u64>) -> StorageEntry {
403    let key = B256::new({
404        let n = key_range.sample_single(rng).unwrap();
405        let mut m = [0u8; 32];
406        m[24..32].copy_from_slice(&n.to_be_bytes());
407        m
408    });
409    let value = U256::from(rng.random::<u64>());
410
411    StorageEntry { key, value }
412}
413
414/// Generate random Externally Owned Account (EOA account without contract).
415pub fn random_eoa_account<R: Rng>(rng: &mut R) -> (Address, Account) {
416    let nonce: u64 = rng.random();
417    let balance = U256::from(rng.random::<u32>());
418    let addr = Address::random();
419
420    (addr, Account { nonce, balance, ..Default::default() })
421}
422
423/// Generate random Externally Owned Accounts
424pub fn random_eoa_accounts<R: Rng>(rng: &mut R, accounts_num: usize) -> Vec<(Address, Account)> {
425    let mut accounts = Vec::with_capacity(accounts_num);
426    for _ in 0..accounts_num {
427        accounts.push(random_eoa_account(rng))
428    }
429    accounts
430}
431
432/// Generate random Contract Accounts
433pub fn random_contract_account_range<R: Rng>(
434    rng: &mut R,
435    acc_range: &mut Range<u64>,
436) -> Vec<(Address, Account)> {
437    let mut accounts = Vec::with_capacity(acc_range.end.saturating_sub(acc_range.start) as usize);
438    for _ in acc_range {
439        let (address, eoa_account) = random_eoa_account(rng);
440        let account = Account { bytecode_hash: Some(B256::random()), ..eoa_account };
441        accounts.push((address, account))
442    }
443    accounts
444}
445
446/// Generate random receipt for transaction
447pub fn random_receipt<R: Rng>(
448    rng: &mut R,
449    transaction: &TransactionSigned,
450    logs_count: Option<u8>,
451    topics_count: Option<u8>,
452) -> Receipt {
453    let success = rng.random::<bool>();
454    let logs_count = logs_count.unwrap_or_else(|| rng.random::<u8>());
455    #[expect(clippy::needless_update)] // side-effect of optimism fields
456    Receipt {
457        tx_type: transaction.tx_type(),
458        success,
459        cumulative_gas_used: rng.random_range(0..=transaction.gas_limit()),
460        logs: if success {
461            (0..logs_count).map(|_| random_log(rng, None, topics_count)).collect()
462        } else {
463            vec![]
464        },
465        ..Default::default()
466    }
467}
468
469/// Generate random log
470pub fn random_log<R: Rng>(rng: &mut R, address: Option<Address>, topics_count: Option<u8>) -> Log {
471    let data_byte_count = rng.random::<u8>() as usize;
472    let topics_count = topics_count.unwrap_or_else(|| rng.random()) as usize;
473    Log::new_unchecked(
474        address.unwrap_or_else(|| Address::random()),
475        std::iter::repeat_with(|| B256::random()).take(topics_count).collect(),
476        std::iter::repeat_with(|| rng.random()).take(data_byte_count).collect::<Vec<_>>().into(),
477    )
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483    use alloy_consensus::TxEip1559;
484    use alloy_eips::eip2930::AccessList;
485    use alloy_primitives::{address, b256, bytes, hex, Signature};
486    use reth_primitives_traits::{crypto::secp256k1::sign_message, SignerRecoverable};
487    use std::str::FromStr;
488
489    #[test]
490    fn test_sign_message() {
491        let tx = Transaction::Eip1559(TxEip1559 {
492            chain_id: 1,
493            nonce: 0x42,
494            gas_limit: 44386,
495            to: TxKind::Call(address!("6069a6c32cf691f5982febae4faf8a6f3ab2f0f6")),
496            value: U256::ZERO,
497            input:  bytes!("a22cb4650000000000000000000000005eee75727d804a2b13038928d36f8b188945a57a0000000000000000000000000000000000000000000000000000000000000000"),
498            max_fee_per_gas: 0x4a817c800,
499            max_priority_fee_per_gas: 0x3b9aca00,
500            access_list: AccessList::default(),
501        });
502        let signature_hash = tx.signature_hash();
503
504        for _ in 0..100 {
505            let key_pair = Keypair::new(&mut rand::rng());
506
507            let signature =
508                sign_message(B256::from_slice(&key_pair.to_secret_bytes()[..]), signature_hash)
509                    .unwrap();
510
511            let signed: TransactionSigned = tx.clone().into_signed(signature).into();
512            let recovered = signed.recover_signer().unwrap();
513
514            let expected =
515                Address::from_raw_public_key(&key_pair.public_key().serialize_uncompressed()[1..]);
516            assert_eq!(recovered, expected);
517        }
518    }
519
520    #[test]
521    fn test_sign_eip_155() {
522        // reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md#example
523        let tx = TxLegacy {
524            chain_id: Some(1),
525            nonce: 9,
526            gas_price: 20 * 10_u128.pow(9),
527            gas_limit: 21000,
528            to: TxKind::Call(Address::repeat_byte(0x35)),
529            value: U256::from(10_u128.pow(18)),
530            input: Bytes::default(),
531        };
532        let transaction = Transaction::Legacy(tx.clone());
533
534        let expected = hex!("ec098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080018080");
535        assert_eq!(expected.as_slice(), &alloy_rlp::encode(tx));
536
537        let hash = transaction.signature_hash();
538        let expected = b256!("daf5a779ae972f972197303d7b574746c7ef83eadac0f2791ad23db92e4c8e53");
539        assert_eq!(expected, hash);
540
541        let secret = B256::repeat_byte(0x46);
542        let signature = sign_message(secret, hash).unwrap();
543
544        let expected = Signature::new(
545            U256::from_str(
546                "18515461264373351373200002665853028612451056578545711640558177340181847433846",
547            )
548            .unwrap(),
549            U256::from_str(
550                "46948507304638947509940763649030358759909902576025900602547168820602576006531",
551            )
552            .unwrap(),
553            false,
554        );
555        assert_eq!(expected, signature);
556    }
557}