reth_chain_state/
test_utils.rs

1use crate::{
2    in_memory::ExecutedBlock, CanonStateNotification, CanonStateNotifications,
3    CanonStateSubscriptions, ComputedTrieData,
4};
5use alloy_consensus::{Header, SignableTransaction, TxEip1559, TxReceipt, EMPTY_ROOT_HASH};
6use alloy_eips::{
7    eip1559::{ETHEREUM_BLOCK_GAS_LIMIT_30M, INITIAL_BASE_FEE},
8    eip7685::Requests,
9};
10use alloy_primitives::{Address, BlockNumber, B256, U256};
11use alloy_signer::SignerSync;
12use alloy_signer_local::PrivateKeySigner;
13use core::marker::PhantomData;
14use rand::Rng;
15use reth_chainspec::{ChainSpec, EthereumHardfork, MIN_TRANSACTION_GAS};
16use reth_ethereum_primitives::{
17    Block, BlockBody, EthPrimitives, Receipt, Transaction, TransactionSigned,
18};
19use reth_execution_types::{Chain, ExecutionOutcome};
20use reth_primitives_traits::{
21    proofs::{calculate_receipt_root, calculate_transaction_root, calculate_withdrawals_root},
22    Account, NodePrimitives, Recovered, RecoveredBlock, SealedBlock, SealedHeader,
23    SignedTransaction,
24};
25use reth_storage_api::NodePrimitivesProvider;
26use reth_trie::root::state_root_unhashed;
27use revm_database::BundleState;
28use revm_state::AccountInfo;
29use std::{
30    ops::Range,
31    sync::{Arc, Mutex},
32};
33use tokio::sync::broadcast::{self, Sender};
34
35/// Functionality to build blocks for tests and help with assertions about
36/// their execution.
37#[derive(Debug)]
38pub struct TestBlockBuilder<N: NodePrimitives = EthPrimitives> {
39    /// The account that signs all the block's transactions.
40    pub signer: Address,
41    /// Private key for signing.
42    pub signer_pk: PrivateKeySigner,
43    /// Keeps track of signer's account info after execution, will be updated in
44    /// methods related to block execution.
45    pub signer_execute_account_info: AccountInfo,
46    /// Keeps track of signer's nonce, will be updated in methods related
47    /// to block execution.
48    pub signer_build_account_info: AccountInfo,
49    /// Chain spec of the blocks generated by this builder
50    pub chain_spec: ChainSpec,
51    _prims: PhantomData<N>,
52}
53
54impl<N: NodePrimitives> Default for TestBlockBuilder<N> {
55    fn default() -> Self {
56        let initial_account_info = AccountInfo::from_balance(U256::from(10).pow(U256::from(18)));
57        let signer_pk = PrivateKeySigner::random();
58        let signer = signer_pk.address();
59        Self {
60            chain_spec: ChainSpec::default(),
61            signer,
62            signer_pk,
63            signer_execute_account_info: initial_account_info.clone(),
64            signer_build_account_info: initial_account_info,
65            _prims: PhantomData,
66        }
67    }
68}
69
70impl<N: NodePrimitives> TestBlockBuilder<N> {
71    /// Signer pk setter.
72    pub fn with_signer_pk(mut self, signer_pk: PrivateKeySigner) -> Self {
73        self.signer = signer_pk.address();
74        self.signer_pk = signer_pk;
75
76        self
77    }
78
79    /// Chainspec setter.
80    pub fn with_chain_spec(mut self, chain_spec: ChainSpec) -> Self {
81        self.chain_spec = chain_spec;
82        self
83    }
84
85    /// Gas cost of a single transaction generated by the block builder.
86    pub fn single_tx_cost() -> U256 {
87        U256::from(INITIAL_BASE_FEE * MIN_TRANSACTION_GAS)
88    }
89
90    /// Generates a random [`RecoveredBlock`].
91    pub fn generate_random_block(
92        &mut self,
93        number: BlockNumber,
94        parent_hash: B256,
95    ) -> SealedBlock<reth_ethereum_primitives::Block> {
96        let mut rng = rand::rng();
97
98        let mock_tx = |nonce: u64| -> Recovered<_> {
99            let tx = Transaction::Eip1559(TxEip1559 {
100                chain_id: self.chain_spec.chain.id(),
101                nonce,
102                gas_limit: MIN_TRANSACTION_GAS,
103                to: Address::random().into(),
104                max_fee_per_gas: INITIAL_BASE_FEE as u128,
105                max_priority_fee_per_gas: 1,
106                ..Default::default()
107            });
108            let signature_hash = tx.signature_hash();
109            let signature = self.signer_pk.sign_hash_sync(&signature_hash).unwrap();
110
111            TransactionSigned::new_unhashed(tx, signature).with_signer(self.signer)
112        };
113
114        let num_txs = rng.random_range(0..5);
115        let signer_balance_decrease = Self::single_tx_cost() * U256::from(num_txs);
116        let transactions: Vec<Recovered<_>> = (0..num_txs)
117            .map(|_| {
118                let tx = mock_tx(self.signer_build_account_info.nonce);
119                self.signer_build_account_info.nonce += 1;
120                self.signer_build_account_info.balance -= signer_balance_decrease;
121                tx
122            })
123            .collect();
124
125        let receipts = transactions
126            .iter()
127            .enumerate()
128            .map(|(idx, tx)| {
129                Receipt {
130                    tx_type: tx.tx_type(),
131                    success: true,
132                    cumulative_gas_used: (idx as u64 + 1) * MIN_TRANSACTION_GAS,
133                    ..Default::default()
134                }
135                .into_with_bloom()
136            })
137            .collect::<Vec<_>>();
138
139        let initial_signer_balance = U256::from(10).pow(U256::from(18));
140
141        let header = Header {
142            number,
143            parent_hash,
144            gas_used: transactions.len() as u64 * MIN_TRANSACTION_GAS,
145            mix_hash: B256::random(),
146            gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,
147            base_fee_per_gas: Some(INITIAL_BASE_FEE),
148            transactions_root: calculate_transaction_root(&transactions),
149            receipts_root: calculate_receipt_root(&receipts),
150            beneficiary: Address::random(),
151            state_root: state_root_unhashed([(
152                self.signer,
153                Account {
154                    balance: initial_signer_balance - signer_balance_decrease,
155                    nonce: num_txs,
156                    ..Default::default()
157                }
158                .into_trie_account(EMPTY_ROOT_HASH),
159            )]),
160            // use the number as the timestamp so it is monotonically increasing
161            timestamp: number +
162                EthereumHardfork::Cancun.activation_timestamp(self.chain_spec.chain).unwrap(),
163            withdrawals_root: Some(calculate_withdrawals_root(&[])),
164            blob_gas_used: Some(0),
165            excess_blob_gas: Some(0),
166            parent_beacon_block_root: Some(B256::random()),
167            ..Default::default()
168        };
169
170        SealedBlock::from_sealed_parts(
171            SealedHeader::seal_slow(header),
172            BlockBody {
173                transactions: transactions.into_iter().map(|tx| tx.into_inner()).collect(),
174                ommers: Vec::new(),
175                withdrawals: Some(vec![].into()),
176            },
177        )
178    }
179
180    /// Creates a fork chain with the given base block.
181    pub fn create_fork(
182        &mut self,
183        base_block: &SealedBlock<Block>,
184        length: u64,
185    ) -> Vec<RecoveredBlock<Block>> {
186        let mut fork = Vec::with_capacity(length as usize);
187        let mut parent = base_block.clone();
188
189        for _ in 0..length {
190            let block = self.generate_random_block(parent.number + 1, parent.hash());
191            parent = block.clone();
192            let senders = vec![self.signer; block.body().transactions.len()];
193            let block = block.with_senders(senders);
194            fork.push(block);
195        }
196
197        fork
198    }
199
200    /// Gets an [`ExecutedBlock`] with [`BlockNumber`], receipts and parent hash.
201    fn get_executed_block(
202        &mut self,
203        block_number: BlockNumber,
204        receipts: Vec<Vec<Receipt>>,
205        parent_hash: B256,
206    ) -> ExecutedBlock {
207        let block = self.generate_random_block(block_number, parent_hash);
208        let senders = vec![self.signer; block.body().transactions.len()];
209        let trie_data = ComputedTrieData::default();
210        ExecutedBlock::new(
211            Arc::new(RecoveredBlock::new_sealed(block, senders)),
212            Arc::new(ExecutionOutcome::new(
213                BundleState::default(),
214                receipts,
215                block_number,
216                vec![Requests::default()],
217            )),
218            trie_data,
219        )
220    }
221
222    /// Generates an [`ExecutedBlock`] that includes the given receipts.
223    pub fn get_executed_block_with_receipts(
224        &mut self,
225        receipts: Vec<Vec<Receipt>>,
226        parent_hash: B256,
227    ) -> ExecutedBlock {
228        let number = rand::rng().random::<u64>();
229        self.get_executed_block(number, receipts, parent_hash)
230    }
231
232    /// Generates an [`ExecutedBlock`] with the given [`BlockNumber`].
233    pub fn get_executed_block_with_number(
234        &mut self,
235        block_number: BlockNumber,
236        parent_hash: B256,
237    ) -> ExecutedBlock {
238        self.get_executed_block(block_number, vec![vec![]], parent_hash)
239    }
240
241    /// Generates a range of executed blocks with ascending block numbers.
242    pub fn get_executed_blocks(
243        &mut self,
244        range: Range<u64>,
245    ) -> impl Iterator<Item = ExecutedBlock> + '_ {
246        let mut parent_hash = B256::default();
247        range.map(move |number| {
248            let current_parent_hash = parent_hash;
249            let block = self.get_executed_block_with_number(number, current_parent_hash);
250            parent_hash = block.recovered_block().hash();
251            block
252        })
253    }
254
255    /// Returns the execution outcome for a block created with this builder.
256    /// In order to properly include the bundle state, the signer balance is
257    /// updated.
258    pub fn get_execution_outcome(
259        &mut self,
260        block: RecoveredBlock<reth_ethereum_primitives::Block>,
261    ) -> ExecutionOutcome {
262        let num_txs = block.body().transactions.len() as u64;
263        let single_cost = Self::single_tx_cost();
264
265        let mut final_balance = self.signer_execute_account_info.balance;
266        for _ in 0..num_txs {
267            final_balance -= single_cost;
268        }
269
270        let final_nonce = self.signer_execute_account_info.nonce + num_txs;
271
272        let receipts = block
273            .body()
274            .transactions
275            .iter()
276            .enumerate()
277            .map(|(idx, tx)| Receipt {
278                tx_type: tx.tx_type(),
279                success: true,
280                cumulative_gas_used: (idx as u64 + 1) * MIN_TRANSACTION_GAS,
281                ..Default::default()
282            })
283            .collect::<Vec<_>>();
284
285        let bundle_state = BundleState::builder(block.number..=block.number)
286            .state_present_account_info(
287                self.signer,
288                AccountInfo { nonce: final_nonce, balance: final_balance, ..Default::default() },
289            )
290            .build();
291
292        self.signer_execute_account_info.balance = final_balance;
293        self.signer_execute_account_info.nonce = final_nonce;
294
295        let execution_outcome =
296            ExecutionOutcome::new(bundle_state, vec![vec![]], block.number, Vec::new());
297
298        execution_outcome.with_receipts(vec![receipts])
299    }
300}
301
302impl TestBlockBuilder {
303    /// Creates a `TestBlockBuilder` configured for Ethereum primitives.
304    pub fn eth() -> Self {
305        Self::default()
306    }
307}
308/// A test `ChainEventSubscriptions`
309#[derive(Clone, Debug, Default)]
310pub struct TestCanonStateSubscriptions<N: NodePrimitives = reth_ethereum_primitives::EthPrimitives>
311{
312    canon_notif_tx: Arc<Mutex<Vec<Sender<CanonStateNotification<N>>>>>,
313}
314
315impl TestCanonStateSubscriptions {
316    /// Adds new block commit to the queue that can be consumed with
317    /// [`TestCanonStateSubscriptions::subscribe_to_canonical_state`]
318    pub fn add_next_commit(&self, new: Arc<Chain>) {
319        let event = CanonStateNotification::Commit { new };
320        self.canon_notif_tx.lock().as_mut().unwrap().retain(|tx| tx.send(event.clone()).is_ok())
321    }
322
323    /// Adds reorg to the queue that can be consumed with
324    /// [`TestCanonStateSubscriptions::subscribe_to_canonical_state`]
325    pub fn add_next_reorg(&self, old: Arc<Chain>, new: Arc<Chain>) {
326        let event = CanonStateNotification::Reorg { old, new };
327        self.canon_notif_tx.lock().as_mut().unwrap().retain(|tx| tx.send(event.clone()).is_ok())
328    }
329}
330
331impl NodePrimitivesProvider for TestCanonStateSubscriptions {
332    type Primitives = EthPrimitives;
333}
334
335impl CanonStateSubscriptions for TestCanonStateSubscriptions {
336    /// Sets up a broadcast channel with a buffer size of 100.
337    fn subscribe_to_canonical_state(&self) -> CanonStateNotifications {
338        let (canon_notif_tx, canon_notif_rx) = broadcast::channel(100);
339        self.canon_notif_tx.lock().as_mut().unwrap().push(canon_notif_tx);
340
341        canon_notif_rx
342    }
343}