1use alloy_consensus::{Header, Transaction};
18use alloy_eips::eip2718::Decodable2718;
19use alloy_evm::{Evm, RecoveredTx};
20use alloy_primitives::{map::HashSet, Address, U256};
21use alloy_rlp::Encodable;
22use alloy_rpc_types_engine::ExecutionPayloadEnvelopeV5;
23use async_trait::async_trait;
24use jsonrpsee::core::RpcResult;
25use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
26use reth_consensus_common::validation::MAX_RLP_BLOCK_SIZE;
27use reth_errors::RethError;
28use reth_ethereum_engine_primitives::EthBuiltPayload;
29use reth_ethereum_primitives::EthPrimitives;
30use reth_evm::{execute::BlockBuilder, ConfigureEvm, NextBlockEnvAttributes};
31use reth_primitives_traits::{
32 transaction::{recover::try_recover_signers, signed::RecoveryError},
33 AlloyBlockHeader as BlockTrait, TxTy,
34};
35use reth_revm::{database::StateProviderDatabase, db::State};
36use reth_rpc_api::{TestingApiServer, TestingBuildBlockRequestV1};
37use reth_rpc_eth_api::{helpers::Call, FromEthApiError};
38use reth_rpc_eth_types::EthApiError;
39use reth_storage_api::{BlockReader, HeaderProvider};
40use revm::context::Block;
41use revm_primitives::map::DefaultHashBuilder;
42use std::sync::Arc;
43use tracing::debug;
44
45#[derive(Debug, Clone)]
47pub struct TestingApi<Eth, Evm> {
48 eth_api: Eth,
49 evm_config: Evm,
50 skip_invalid_transactions: bool,
52}
53
54impl<Eth, Evm> TestingApi<Eth, Evm> {
55 pub const fn new(eth_api: Eth, evm_config: Evm) -> Self {
57 Self { eth_api, evm_config, skip_invalid_transactions: false }
58 }
59
60 pub const fn with_skip_invalid_transactions(mut self) -> Self {
64 self.skip_invalid_transactions = true;
65 self
66 }
67}
68
69impl<Eth, Evm> TestingApi<Eth, Evm>
70where
71 Eth: Call<
72 Provider: BlockReader<Header = Header> + ChainSpecProvider<ChainSpec: EthereumHardforks>,
73 >,
74 Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes, Primitives = EthPrimitives>
75 + 'static,
76{
77 async fn build_block_v1(
78 &self,
79 request: TestingBuildBlockRequestV1,
80 ) -> Result<ExecutionPayloadEnvelopeV5, Eth::Error> {
81 let evm_config = self.evm_config.clone();
82 let skip_invalid_transactions = self.skip_invalid_transactions;
83 self.eth_api
84 .spawn_with_state_at_block(request.parent_block_hash, move |eth_api, state| {
85 let state = state.database.0;
86 let mut db = State::builder()
87 .with_bundle_update()
88 .with_database(StateProviderDatabase::new(&state))
89 .build();
90 let parent = eth_api
91 .provider()
92 .sealed_header_by_hash(request.parent_block_hash)?
93 .ok_or_else(|| {
94 EthApiError::HeaderNotFound(request.parent_block_hash.into())
95 })?;
96
97 let chain_spec = eth_api.provider().chain_spec();
98 let is_osaka =
99 chain_spec.is_osaka_active_at_timestamp(request.payload_attributes.timestamp);
100
101 let withdrawals = request.payload_attributes.withdrawals.clone();
102 let withdrawals_rlp_length = withdrawals.as_ref().map(|w| w.length()).unwrap_or(0);
103
104 let env_attrs = NextBlockEnvAttributes {
105 timestamp: request.payload_attributes.timestamp,
106 suggested_fee_recipient: request.payload_attributes.suggested_fee_recipient,
107 prev_randao: request.payload_attributes.prev_randao,
108 gas_limit: parent.gas_limit(),
109 parent_beacon_block_root: request.payload_attributes.parent_beacon_block_root,
110 withdrawals: withdrawals.map(Into::into),
111 extra_data: request.extra_data.unwrap_or_default(),
112 };
113
114 let mut builder = evm_config
115 .builder_for_next_block(&mut db, &parent, env_attrs)
116 .map_err(RethError::other)
117 .map_err(Eth::Error::from_eth_err)?;
118 builder.apply_pre_execution_changes().map_err(Eth::Error::from_eth_err)?;
119
120 let mut total_fees = U256::ZERO;
121 let base_fee = builder.evm_mut().block().basefee();
122
123 let mut invalid_senders: HashSet<Address, DefaultHashBuilder> = HashSet::default();
124 let mut block_transactions_rlp_length = 0usize;
125
126 let recovered_txs = try_recover_signers(&request.transactions, |tx| {
128 TxTy::<Evm::Primitives>::decode_2718_exact(tx.as_ref())
129 .map_err(RecoveryError::from_source)
130 })
131 .or(Err(EthApiError::InvalidTransactionSignature))?;
132
133 for (idx, tx) in recovered_txs.into_iter().enumerate() {
134 let signer = tx.signer();
135 if skip_invalid_transactions && invalid_senders.contains(&signer) {
136 continue;
137 }
138
139 let tx_rlp_len = tx.tx().length();
141 if is_osaka {
142 let estimated_block_size = block_transactions_rlp_length +
144 tx_rlp_len +
145 withdrawals_rlp_length +
146 1024;
147 if estimated_block_size > MAX_RLP_BLOCK_SIZE {
148 if skip_invalid_transactions {
149 debug!(
150 target: "rpc::testing",
151 tx_idx = idx,
152 ?signer,
153 estimated_block_size,
154 max_size = MAX_RLP_BLOCK_SIZE,
155 "Skipping transaction: would exceed block size limit"
156 );
157 invalid_senders.insert(signer);
158 continue;
159 }
160 return Err(Eth::Error::from_eth_err(EthApiError::InvalidParams(
161 format!(
162 "transaction at index {} would exceed max block size: {} > {}",
163 idx, estimated_block_size, MAX_RLP_BLOCK_SIZE
164 ),
165 )));
166 }
167 }
168
169 let tip = tx.effective_tip_per_gas(base_fee).unwrap_or_default();
170 let gas_used = match builder.execute_transaction(tx) {
171 Ok(gas_used) => gas_used,
172 Err(err) => {
173 if skip_invalid_transactions {
174 debug!(
175 target: "rpc::testing",
176 tx_idx = idx,
177 ?signer,
178 error = ?err,
179 "Skipping invalid transaction"
180 );
181 invalid_senders.insert(signer);
182 continue;
183 }
184 debug!(
185 target: "rpc::testing",
186 tx_idx = idx,
187 ?signer,
188 error = ?err,
189 "Transaction execution failed"
190 );
191 return Err(Eth::Error::from_eth_err(err));
192 }
193 };
194
195 block_transactions_rlp_length += tx_rlp_len;
196 total_fees += U256::from(tip) * U256::from(gas_used);
197 }
198 let outcome = builder.finish(&state).map_err(Eth::Error::from_eth_err)?;
199
200 let has_requests = outcome.block.requests_hash().is_some();
201 let sealed_block = Arc::new(outcome.block.into_sealed_block());
202
203 let requests = has_requests.then_some(outcome.execution_result.requests);
204
205 EthBuiltPayload::new(
206 alloy_rpc_types_engine::PayloadId::default(),
207 sealed_block,
208 total_fees,
209 requests,
210 )
211 .try_into_v5()
212 .map_err(RethError::other)
213 .map_err(Eth::Error::from_eth_err)
214 })
215 .await
216 }
217}
218
219#[async_trait]
220impl<Eth, Evm> TestingApiServer for TestingApi<Eth, Evm>
221where
222 Eth: Call<
223 Provider: BlockReader<Header = Header> + ChainSpecProvider<ChainSpec: EthereumHardforks>,
224 >,
225 Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes, Primitives = EthPrimitives>
226 + 'static,
227{
228 async fn build_block_v1(
231 &self,
232 request: TestingBuildBlockRequestV1,
233 ) -> RpcResult<ExecutionPayloadEnvelopeV5> {
234 self.build_block_v1(request).await.map_err(Into::into)
235 }
236}