Skip to main content

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