reth_ethereum_payload_builder/
lib.rs

1//! A basic Ethereum payload builder implementation.
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
10#![allow(clippy::useless_let_if_seq)]
11
12use alloy_consensus::Transaction;
13use alloy_primitives::U256;
14use alloy_rlp::Encodable;
15use reth_basic_payload_builder::{
16    is_better_payload, BuildArguments, BuildOutcome, MissingPayloadBehaviour, PayloadBuilder,
17    PayloadConfig,
18};
19use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks};
20use reth_consensus_common::validation::MAX_RLP_BLOCK_SIZE;
21use reth_errors::{BlockExecutionError, BlockValidationError, ConsensusError};
22use reth_ethereum_primitives::{EthPrimitives, TransactionSigned};
23use reth_evm::{
24    execute::{BlockBuilder, BlockBuilderOutcome},
25    ConfigureEvm, Evm, NextBlockEnvAttributes,
26};
27use reth_evm_ethereum::EthEvmConfig;
28use reth_payload_builder::{BlobSidecars, EthBuiltPayload, EthPayloadBuilderAttributes};
29use reth_payload_builder_primitives::PayloadBuilderError;
30use reth_payload_primitives::PayloadBuilderAttributes;
31use reth_primitives_traits::transaction::error::InvalidTransactionError;
32use reth_revm::{database::StateProviderDatabase, db::State};
33use reth_storage_api::StateProviderFactory;
34use reth_transaction_pool::{
35    error::{Eip4844PoolTransactionError, InvalidPoolTransactionError},
36    BestTransactions, BestTransactionsAttributes, PoolTransaction, TransactionPool,
37    ValidPoolTransaction,
38};
39use revm::context_interface::Block as _;
40use std::sync::Arc;
41use tracing::{debug, trace, warn};
42
43mod config;
44pub use config::*;
45
46pub mod validator;
47pub use validator::EthereumExecutionPayloadValidator;
48
49type BestTransactionsIter<Pool> = Box<
50    dyn BestTransactions<Item = Arc<ValidPoolTransaction<<Pool as TransactionPool>::Transaction>>>,
51>;
52
53/// Ethereum payload builder
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct EthereumPayloadBuilder<Pool, Client, EvmConfig = EthEvmConfig> {
56    /// Client providing access to node state.
57    client: Client,
58    /// Transaction pool.
59    pool: Pool,
60    /// The type responsible for creating the evm.
61    evm_config: EvmConfig,
62    /// Payload builder configuration.
63    builder_config: EthereumBuilderConfig,
64}
65
66impl<Pool, Client, EvmConfig> EthereumPayloadBuilder<Pool, Client, EvmConfig> {
67    /// `EthereumPayloadBuilder` constructor.
68    pub const fn new(
69        client: Client,
70        pool: Pool,
71        evm_config: EvmConfig,
72        builder_config: EthereumBuilderConfig,
73    ) -> Self {
74        Self { client, pool, evm_config, builder_config }
75    }
76}
77
78// Default implementation of [PayloadBuilder] for unit type
79impl<Pool, Client, EvmConfig> PayloadBuilder for EthereumPayloadBuilder<Pool, Client, EvmConfig>
80where
81    EvmConfig: ConfigureEvm<Primitives = EthPrimitives, NextBlockEnvCtx = NextBlockEnvAttributes>,
82    Client: StateProviderFactory + ChainSpecProvider<ChainSpec: EthereumHardforks> + Clone,
83    Pool: TransactionPool<Transaction: PoolTransaction<Consensus = TransactionSigned>>,
84{
85    type Attributes = EthPayloadBuilderAttributes;
86    type BuiltPayload = EthBuiltPayload;
87
88    fn try_build(
89        &self,
90        args: BuildArguments<EthPayloadBuilderAttributes, EthBuiltPayload>,
91    ) -> Result<BuildOutcome<EthBuiltPayload>, PayloadBuilderError> {
92        default_ethereum_payload(
93            self.evm_config.clone(),
94            self.client.clone(),
95            self.pool.clone(),
96            self.builder_config.clone(),
97            args,
98            |attributes| self.pool.best_transactions_with_attributes(attributes),
99        )
100    }
101
102    fn on_missing_payload(
103        &self,
104        _args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
105    ) -> MissingPayloadBehaviour<Self::BuiltPayload> {
106        if self.builder_config.await_payload_on_missing {
107            MissingPayloadBehaviour::AwaitInProgress
108        } else {
109            MissingPayloadBehaviour::RaceEmptyPayload
110        }
111    }
112
113    fn build_empty_payload(
114        &self,
115        config: PayloadConfig<Self::Attributes>,
116    ) -> Result<EthBuiltPayload, PayloadBuilderError> {
117        let args = BuildArguments::new(Default::default(), config, Default::default(), None);
118
119        default_ethereum_payload(
120            self.evm_config.clone(),
121            self.client.clone(),
122            self.pool.clone(),
123            self.builder_config.clone(),
124            args,
125            |attributes| self.pool.best_transactions_with_attributes(attributes),
126        )?
127        .into_payload()
128        .ok_or_else(|| PayloadBuilderError::MissingPayload)
129    }
130}
131
132/// Constructs an Ethereum transaction payload using the best transactions from the pool.
133///
134/// Given build arguments including an Ethereum client, transaction pool,
135/// and configuration, this function creates a transaction payload. Returns
136/// a result indicating success with the payload or an error in case of failure.
137#[inline]
138pub fn default_ethereum_payload<EvmConfig, Client, Pool, F>(
139    evm_config: EvmConfig,
140    client: Client,
141    pool: Pool,
142    builder_config: EthereumBuilderConfig,
143    args: BuildArguments<EthPayloadBuilderAttributes, EthBuiltPayload>,
144    best_txs: F,
145) -> Result<BuildOutcome<EthBuiltPayload>, PayloadBuilderError>
146where
147    EvmConfig: ConfigureEvm<Primitives = EthPrimitives, NextBlockEnvCtx = NextBlockEnvAttributes>,
148    Client: StateProviderFactory + ChainSpecProvider<ChainSpec: EthereumHardforks>,
149    Pool: TransactionPool<Transaction: PoolTransaction<Consensus = TransactionSigned>>,
150    F: FnOnce(BestTransactionsAttributes) -> BestTransactionsIter<Pool>,
151{
152    let BuildArguments { mut cached_reads, config, cancel, best_payload } = args;
153    let PayloadConfig { parent_header, attributes } = config;
154
155    let state_provider = client.state_by_block_hash(parent_header.hash())?;
156    let state = StateProviderDatabase::new(&state_provider);
157    let mut db =
158        State::builder().with_database(cached_reads.as_db_mut(state)).with_bundle_update().build();
159
160    let mut builder = evm_config
161        .builder_for_next_block(
162            &mut db,
163            &parent_header,
164            NextBlockEnvAttributes {
165                timestamp: attributes.timestamp(),
166                suggested_fee_recipient: attributes.suggested_fee_recipient(),
167                prev_randao: attributes.prev_randao(),
168                gas_limit: builder_config.gas_limit(parent_header.gas_limit),
169                parent_beacon_block_root: attributes.parent_beacon_block_root(),
170                withdrawals: Some(attributes.withdrawals().clone()),
171            },
172        )
173        .map_err(PayloadBuilderError::other)?;
174
175    let chain_spec = client.chain_spec();
176
177    debug!(target: "payload_builder", id=%attributes.id, parent_header = ?parent_header.hash(), parent_number = parent_header.number, "building new payload");
178    let mut cumulative_gas_used = 0;
179    let block_gas_limit: u64 = builder.evm_mut().block().gas_limit;
180    let base_fee = builder.evm_mut().block().basefee;
181
182    let mut best_txs = best_txs(BestTransactionsAttributes::new(
183        base_fee,
184        builder.evm_mut().block().blob_gasprice().map(|gasprice| gasprice as u64),
185    ));
186    let mut total_fees = U256::ZERO;
187
188    builder.apply_pre_execution_changes().map_err(|err| {
189        warn!(target: "payload_builder", %err, "failed to apply pre-execution changes");
190        PayloadBuilderError::Internal(err.into())
191    })?;
192
193    // initialize empty blob sidecars at first. If cancun is active then this will be populated by
194    // blob sidecars if any.
195    let mut blob_sidecars = BlobSidecars::Empty;
196
197    let mut block_blob_count = 0;
198    let mut block_transactions_rlp_length = 0;
199
200    let blob_params = chain_spec.blob_params_at_timestamp(attributes.timestamp);
201    let max_blob_count =
202        blob_params.as_ref().map(|params| params.max_blob_count).unwrap_or_default();
203
204    let is_osaka = chain_spec.is_osaka_active_at_timestamp(attributes.timestamp);
205
206    while let Some(pool_tx) = best_txs.next() {
207        // ensure we still have capacity for this transaction
208        if cumulative_gas_used + pool_tx.gas_limit() > block_gas_limit {
209            // we can't fit this transaction into the block, so we need to mark it as invalid
210            // which also removes all dependent transaction from the iterator before we can
211            // continue
212            best_txs.mark_invalid(
213                &pool_tx,
214                InvalidPoolTransactionError::ExceedsGasLimit(pool_tx.gas_limit(), block_gas_limit),
215            );
216            continue
217        }
218
219        // check if the job was cancelled, if so we can exit early
220        if cancel.is_cancelled() {
221            return Ok(BuildOutcome::Cancelled)
222        }
223
224        // convert tx to a signed transaction
225        let tx = pool_tx.to_consensus();
226
227        let estimated_block_size_with_tx = block_transactions_rlp_length +
228            tx.inner().length() +
229            attributes.withdrawals().length() +
230            1024; // 1Kb of overhead for the block header
231
232        if is_osaka && estimated_block_size_with_tx > MAX_RLP_BLOCK_SIZE {
233            best_txs.mark_invalid(
234                &pool_tx,
235                InvalidPoolTransactionError::OversizedData(
236                    estimated_block_size_with_tx,
237                    MAX_RLP_BLOCK_SIZE,
238                ),
239            );
240            continue;
241        }
242
243        // There's only limited amount of blob space available per block, so we need to check if
244        // the EIP-4844 can still fit in the block
245        let mut blob_tx_sidecar = None;
246        if let Some(blob_tx) = tx.as_eip4844() {
247            let tx_blob_count = blob_tx.tx().blob_versioned_hashes.len() as u64;
248
249            if block_blob_count + tx_blob_count > max_blob_count {
250                // we can't fit this _blob_ transaction into the block, so we mark it as
251                // invalid, which removes its dependent transactions from
252                // the iterator. This is similar to the gas limit condition
253                // for regular transactions above.
254                trace!(target: "payload_builder", tx=?tx.hash(), ?block_blob_count, "skipping blob transaction because it would exceed the max blob count per block");
255                best_txs.mark_invalid(
256                    &pool_tx,
257                    InvalidPoolTransactionError::Eip4844(
258                        Eip4844PoolTransactionError::TooManyEip4844Blobs {
259                            have: block_blob_count + tx_blob_count,
260                            permitted: max_blob_count,
261                        },
262                    ),
263                );
264                continue
265            }
266
267            let blob_sidecar_result = 'sidecar: {
268                let Some(sidecar) =
269                    pool.get_blob(*tx.hash()).map_err(PayloadBuilderError::other)?
270                else {
271                    break 'sidecar Err(Eip4844PoolTransactionError::MissingEip4844BlobSidecar)
272                };
273
274                if chain_spec.is_osaka_active_at_timestamp(attributes.timestamp) {
275                    if sidecar.is_eip7594() {
276                        Ok(sidecar)
277                    } else {
278                        Err(Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka)
279                    }
280                } else if sidecar.is_eip4844() {
281                    Ok(sidecar)
282                } else {
283                    Err(Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka)
284                }
285            };
286
287            blob_tx_sidecar = match blob_sidecar_result {
288                Ok(sidecar) => Some(sidecar),
289                Err(error) => {
290                    best_txs.mark_invalid(&pool_tx, InvalidPoolTransactionError::Eip4844(error));
291                    continue
292                }
293            };
294        }
295
296        let gas_used = match builder.execute_transaction(tx.clone()) {
297            Ok(gas_used) => gas_used,
298            Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx {
299                error, ..
300            })) => {
301                if error.is_nonce_too_low() {
302                    // if the nonce is too low, we can skip this transaction
303                    trace!(target: "payload_builder", %error, ?tx, "skipping nonce too low transaction");
304                } else {
305                    // if the transaction is invalid, we can skip it and all of its
306                    // descendants
307                    trace!(target: "payload_builder", %error, ?tx, "skipping invalid transaction and its descendants");
308                    best_txs.mark_invalid(
309                        &pool_tx,
310                        InvalidPoolTransactionError::Consensus(
311                            InvalidTransactionError::TxTypeNotSupported,
312                        ),
313                    );
314                }
315                continue
316            }
317            // this is an error that we should treat as fatal for this attempt
318            Err(err) => return Err(PayloadBuilderError::evm(err)),
319        };
320
321        // add to the total blob gas used if the transaction successfully executed
322        if let Some(blob_tx) = tx.as_eip4844() {
323            block_blob_count += blob_tx.tx().blob_versioned_hashes.len() as u64;
324
325            // if we've reached the max blob count, we can skip blob txs entirely
326            if block_blob_count == max_blob_count {
327                best_txs.skip_blobs();
328            }
329        }
330
331        block_transactions_rlp_length += tx.inner().length();
332
333        // update and add to total fees
334        let miner_fee =
335            tx.effective_tip_per_gas(base_fee).expect("fee is always valid; execution succeeded");
336        total_fees += U256::from(miner_fee) * U256::from(gas_used);
337        cumulative_gas_used += gas_used;
338
339        // Add blob tx sidecar to the payload.
340        if let Some(sidecar) = blob_tx_sidecar {
341            blob_sidecars.push_sidecar_variant(sidecar.as_ref().clone());
342        }
343    }
344
345    // check if we have a better block
346    if !is_better_payload(best_payload.as_ref(), total_fees) {
347        // Release db
348        drop(builder);
349        // can skip building the block
350        return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads })
351    }
352
353    let BlockBuilderOutcome { execution_result, block, .. } = builder.finish(&state_provider)?;
354
355    let requests = chain_spec
356        .is_prague_active_at_timestamp(attributes.timestamp)
357        .then_some(execution_result.requests);
358
359    let sealed_block = Arc::new(block.sealed_block().clone());
360    debug!(target: "payload_builder", id=%attributes.id, sealed_block_header = ?sealed_block.sealed_header(), "sealed built block");
361
362    if sealed_block.rlp_length() > MAX_RLP_BLOCK_SIZE {
363        return Err(PayloadBuilderError::other(ConsensusError::BlockTooLarge {
364            rlp_length: sealed_block.rlp_length(),
365            max_rlp_length: MAX_RLP_BLOCK_SIZE,
366        }));
367    }
368
369    let payload = EthBuiltPayload::new(attributes.id, sealed_block, total_fees, requests)
370        // add blob sidecars from the executed txs
371        .with_sidecars(blob_sidecars);
372
373    Ok(BuildOutcome::Better { payload, cached_reads })
374}