chore: move optimism payload crate to optimism folder (#8169)

This commit is contained in:
Matthias Seitz
2024-05-10 13:26:06 +02:00
committed by GitHub
parent efa5d41bf5
commit 12cce00ec2
6 changed files with 3 additions and 3 deletions

View File

@ -1,43 +0,0 @@
[package]
name = "reth-optimism-payload-builder"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
description = "A payload builder for op-reth that builds optimistic payloads."
[lints]
workspace = true
[dependencies]
# reth
reth-primitives.workspace = true
reth-revm.workspace = true
reth-transaction-pool.workspace = true
reth-provider.workspace = true
reth-rpc-types.workspace = true
reth-rpc-types-compat.workspace = true
reth-engine-primitives.workspace = true
reth-evm.workspace = true
reth-evm-optimism.workspace = true
reth-payload-builder.workspace = true
reth-basic-payload-builder.workspace = true
# ethereum
revm.workspace = true
alloy-rlp.workspace = true
# misc
tracing.workspace = true
thiserror.workspace = true
sha2.workspace = true
[features]
optimism = [
"reth-primitives/optimism",
"reth-provider/optimism",
"reth-rpc-types-compat/optimism",
"reth-evm-optimism/optimism",
]

View File

@ -1,600 +0,0 @@
//! Optimism payload builder implementation.
use crate::{
error::OptimismPayloadBuilderError,
payload::{OptimismBuiltPayload, OptimismPayloadBuilderAttributes},
};
use reth_basic_payload_builder::*;
use reth_evm::ConfigureEvm;
use reth_payload_builder::error::PayloadBuilderError;
use reth_primitives::{
constants::{BEACON_NONCE, EMPTY_RECEIPTS, EMPTY_TRANSACTIONS},
eip4844::calculate_excess_blob_gas,
proofs,
revm::env::tx_env_with_recovered,
Block, ChainSpec, Hardfork, Header, IntoRecoveredTransaction, Receipt, Receipts, TxType,
EMPTY_OMMER_ROOT_HASH, U256,
};
use reth_provider::{BundleStateWithReceipts, StateProviderFactory};
use reth_revm::database::StateProviderDatabase;
use reth_transaction_pool::{BestTransactionsAttributes, TransactionPool};
use revm::{
db::states::bundle_state::BundleRetention,
primitives::{EVMError, EnvWithHandlerCfg, InvalidTransaction, ResultAndState},
DatabaseCommit, State,
};
use std::sync::Arc;
use tracing::{debug, trace, warn};
/// Optimism's payload builder
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OptimismPayloadBuilder<EvmConfig> {
/// The rollup's compute pending block configuration option.
// TODO(clabby): Implement this feature.
compute_pending_block: bool,
/// The rollup's chain spec.
chain_spec: Arc<ChainSpec>,
evm_config: EvmConfig,
}
impl<EvmConfig> OptimismPayloadBuilder<EvmConfig> {
/// OptimismPayloadBuilder constructor.
pub fn new(chain_spec: Arc<ChainSpec>, evm_config: EvmConfig) -> Self {
Self { compute_pending_block: true, chain_spec, evm_config }
}
/// Sets the rollup's compute pending block configuration option.
pub fn set_compute_pending_block(mut self, compute_pending_block: bool) -> Self {
self.compute_pending_block = compute_pending_block;
self
}
/// Enables the rollup's compute pending block configuration option.
pub fn compute_pending_block(self) -> Self {
self.set_compute_pending_block(true)
}
/// Returns the rollup's compute pending block configuration option.
pub fn is_compute_pending_block(&self) -> bool {
self.compute_pending_block
}
/// Sets the rollup's chainspec.
pub fn set_chain_spec(mut self, chain_spec: Arc<ChainSpec>) -> Self {
self.chain_spec = chain_spec;
self
}
}
/// Implementation of the [PayloadBuilder] trait for [OptimismPayloadBuilder].
impl<Pool, Client, EvmConfig> PayloadBuilder<Pool, Client> for OptimismPayloadBuilder<EvmConfig>
where
Client: StateProviderFactory,
Pool: TransactionPool,
EvmConfig: ConfigureEvm,
{
type Attributes = OptimismPayloadBuilderAttributes;
type BuiltPayload = OptimismBuiltPayload;
fn try_build(
&self,
args: BuildArguments<Pool, Client, OptimismPayloadBuilderAttributes, OptimismBuiltPayload>,
) -> Result<BuildOutcome<OptimismBuiltPayload>, PayloadBuilderError> {
optimism_payload_builder(self.evm_config.clone(), args, self.compute_pending_block)
}
fn on_missing_payload(
&self,
args: BuildArguments<Pool, Client, OptimismPayloadBuilderAttributes, OptimismBuiltPayload>,
) -> Option<OptimismBuiltPayload> {
// In Optimism, the PayloadAttributes can specify a `no_tx_pool` option that implies we
// should not pull transactions from the tx pool. In this case, we build the payload
// upfront with the list of transactions sent in the attributes without caring about
// the results of the polling job, if a best payload has not already been built.
if args.config.attributes.no_tx_pool {
if let Ok(BuildOutcome::Better { payload, .. }) = self.try_build(args) {
trace!(target: "payload_builder", "[OPTIMISM] Forced best payload");
return Some(payload)
}
}
None
}
fn build_empty_payload(
client: &Client,
config: PayloadConfig<Self::Attributes>,
) -> Result<OptimismBuiltPayload, PayloadBuilderError> {
let extra_data = config.extra_data();
let PayloadConfig {
initialized_block_env,
parent_block,
attributes,
chain_spec,
initialized_cfg,
..
} = config;
debug!(target: "payload_builder", parent_hash = ?parent_block.hash(), parent_number = parent_block.number, "building empty payload");
let state = client.state_by_block_hash(parent_block.hash()).map_err(|err| {
warn!(target: "payload_builder", parent_hash=%parent_block.hash(), %err, "failed to get state for empty payload");
err
})?;
let mut db = State::builder()
.with_database(StateProviderDatabase::new(state))
.with_bundle_update()
.build();
let base_fee = initialized_block_env.basefee.to::<u64>();
let block_number = initialized_block_env.number.to::<u64>();
let block_gas_limit: u64 = initialized_block_env.gas_limit.try_into().unwrap_or(u64::MAX);
// apply eip-4788 pre block contract call
pre_block_beacon_root_contract_call(
&mut db,
&chain_spec,
block_number,
&initialized_cfg,
&initialized_block_env,
&attributes,
)
.map_err(|err| {
warn!(target: "payload_builder",
parent_hash=%parent_block.hash(),
%err,
"failed to apply beacon root contract call for empty payload"
);
err
})?;
let WithdrawalsOutcome { withdrawals_root, withdrawals } = commit_withdrawals(
&mut db,
&chain_spec,
attributes.payload_attributes.timestamp,
attributes.payload_attributes.withdrawals.clone(),
)
.map_err(|err| {
warn!(target: "payload_builder",
parent_hash=%parent_block.hash(),
%err,
"failed to commit withdrawals for empty payload"
);
err
})?;
// merge all transitions into bundle state, this would apply the withdrawal balance
// changes and 4788 contract call
db.merge_transitions(BundleRetention::PlainState);
// calculate the state root
let bundle_state = db.take_bundle();
let state_root = db.database.state_root(&bundle_state).map_err(|err| {
warn!(target: "payload_builder",
parent_hash=%parent_block.hash(),
%err,
"failed to calculate state root for empty payload"
);
err
})?;
let mut excess_blob_gas = None;
let mut blob_gas_used = None;
if chain_spec.is_cancun_active_at_timestamp(attributes.payload_attributes.timestamp) {
excess_blob_gas = if chain_spec.is_cancun_active_at_timestamp(parent_block.timestamp) {
let parent_excess_blob_gas = parent_block.excess_blob_gas.unwrap_or_default();
let parent_blob_gas_used = parent_block.blob_gas_used.unwrap_or_default();
Some(calculate_excess_blob_gas(parent_excess_blob_gas, parent_blob_gas_used))
} else {
// for the first post-fork block, both parent.blob_gas_used and
// parent.excess_blob_gas are evaluated as 0
Some(calculate_excess_blob_gas(0, 0))
};
blob_gas_used = Some(0);
}
let header = Header {
parent_hash: parent_block.hash(),
ommers_hash: EMPTY_OMMER_ROOT_HASH,
beneficiary: initialized_block_env.coinbase,
state_root,
transactions_root: EMPTY_TRANSACTIONS,
withdrawals_root,
receipts_root: EMPTY_RECEIPTS,
logs_bloom: Default::default(),
timestamp: attributes.payload_attributes.timestamp,
mix_hash: attributes.payload_attributes.prev_randao,
nonce: BEACON_NONCE,
base_fee_per_gas: Some(base_fee),
number: parent_block.number + 1,
gas_limit: block_gas_limit,
difficulty: U256::ZERO,
gas_used: 0,
extra_data,
blob_gas_used,
excess_blob_gas,
parent_beacon_block_root: attributes.payload_attributes.parent_beacon_block_root,
};
let block = Block { header, body: vec![], ommers: vec![], withdrawals };
let sealed_block = block.seal_slow();
Ok(OptimismBuiltPayload::new(
attributes.payload_attributes.payload_id(),
sealed_block,
U256::ZERO,
chain_spec,
attributes,
))
}
}
/// Constructs an Ethereum transaction payload from the transactions sent through the
/// Payload attributes by the sequencer. If the `no_tx_pool` argument is passed in
/// the payload attributes, the transaction pool will be ignored and the only transactions
/// included in the payload will be those sent through the attributes.
///
/// Given build arguments including an Ethereum client, transaction pool,
/// and configuration, this function creates a transaction payload. Returns
/// a result indicating success with the payload or an error in case of failure.
#[inline]
pub(crate) fn optimism_payload_builder<EvmConfig, Pool, Client>(
evm_config: EvmConfig,
args: BuildArguments<Pool, Client, OptimismPayloadBuilderAttributes, OptimismBuiltPayload>,
_compute_pending_block: bool,
) -> Result<BuildOutcome<OptimismBuiltPayload>, PayloadBuilderError>
where
EvmConfig: ConfigureEvm,
Client: StateProviderFactory,
Pool: TransactionPool,
{
let BuildArguments { client, pool, mut cached_reads, config, cancel, best_payload } = args;
let state_provider = client.state_by_block_hash(config.parent_block.hash())?;
let state = StateProviderDatabase::new(state_provider);
let mut db =
State::builder().with_database_ref(cached_reads.as_db(state)).with_bundle_update().build();
let extra_data = config.extra_data();
let PayloadConfig {
initialized_block_env,
initialized_cfg,
parent_block,
attributes,
chain_spec,
..
} = config;
debug!(target: "payload_builder", id=%attributes.payload_attributes.payload_id(), parent_hash = ?parent_block.hash(), parent_number = parent_block.number, "building new payload");
let mut cumulative_gas_used = 0;
let block_gas_limit: u64 = attributes
.gas_limit
.unwrap_or_else(|| initialized_block_env.gas_limit.try_into().unwrap_or(u64::MAX));
let base_fee = initialized_block_env.basefee.to::<u64>();
let mut executed_txs = Vec::with_capacity(attributes.transactions.len());
let mut best_txs = pool.best_transactions_with_attributes(BestTransactionsAttributes::new(
base_fee,
initialized_block_env.get_blob_gasprice().map(|gasprice| gasprice as u64),
));
let mut total_fees = U256::ZERO;
let block_number = initialized_block_env.number.to::<u64>();
let is_regolith = chain_spec
.is_fork_active_at_timestamp(Hardfork::Regolith, attributes.payload_attributes.timestamp);
// apply eip-4788 pre block contract call
pre_block_beacon_root_contract_call(
&mut db,
&chain_spec,
block_number,
&initialized_cfg,
&initialized_block_env,
&attributes,
)?;
// Ensure that the create2deployer is force-deployed at the canyon transition. Optimism
// blocks will always have at least a single transaction in them (the L1 info transaction),
// so we can safely assume that this will always be triggered upon the transition and that
// the above check for empty blocks will never be hit on OP chains.
reth_evm_optimism::ensure_create2_deployer(
chain_spec.clone(),
attributes.payload_attributes.timestamp,
&mut db,
)
.map_err(|err| {
warn!(target: "payload_builder", %err, "missing create2 deployer, skipping block.");
PayloadBuilderError::other(OptimismPayloadBuilderError::ForceCreate2DeployerFail)
})?;
let mut receipts = Vec::with_capacity(attributes.transactions.len());
for sequencer_tx in &attributes.transactions {
// Check if the job was cancelled, if so we can exit early.
if cancel.is_cancelled() {
return Ok(BuildOutcome::Cancelled)
}
// A sequencer's block should never contain blob transactions.
if sequencer_tx.is_eip4844() {
return Err(PayloadBuilderError::other(
OptimismPayloadBuilderError::BlobTransactionRejected,
))
}
// Convert the transaction to a [TransactionSignedEcRecovered]. This is
// purely for the purposes of utilizing the [tx_env_with_recovered] function.
// Deposit transactions do not have signatures, so if the tx is a deposit, this
// will just pull in its `from` address.
let sequencer_tx = sequencer_tx.clone().try_into_ecrecovered().map_err(|_| {
PayloadBuilderError::other(OptimismPayloadBuilderError::TransactionEcRecoverFailed)
})?;
// Cache the depositor account prior to the state transition for the deposit nonce.
//
// Note that this *only* needs to be done post-regolith hardfork, as deposit nonces
// were not introduced in Bedrock. In addition, regular transactions don't have deposit
// nonces, so we don't need to touch the DB for those.
let depositor = (is_regolith && sequencer_tx.is_deposit())
.then(|| {
db.load_cache_account(sequencer_tx.signer())
.map(|acc| acc.account_info().unwrap_or_default())
})
.transpose()
.map_err(|_| {
PayloadBuilderError::other(OptimismPayloadBuilderError::AccountLoadFailed(
sequencer_tx.signer(),
))
})?;
let env = EnvWithHandlerCfg::new_with_cfg_env(
initialized_cfg.clone(),
initialized_block_env.clone(),
tx_env_with_recovered(&sequencer_tx),
);
let mut evm = evm_config.evm_with_env(&mut db, env);
let ResultAndState { result, state } = match evm.transact() {
Ok(res) => res,
Err(err) => {
match err {
EVMError::Transaction(err) => {
trace!(target: "payload_builder", %err, ?sequencer_tx, "Error in sequencer transaction, skipping.");
continue
}
err => {
// this is an error that we should treat as fatal for this attempt
return Err(PayloadBuilderError::EvmExecutionError(err))
}
}
}
};
// to release the db reference drop evm.
drop(evm);
// commit changes
db.commit(state);
let gas_used = result.gas_used();
// add gas used by the transaction to cumulative gas used, before creating the receipt
cumulative_gas_used += gas_used;
// Push transaction changeset and calculate header bloom filter for receipt.
receipts.push(Some(Receipt {
tx_type: sequencer_tx.tx_type(),
success: result.is_success(),
cumulative_gas_used,
logs: result.into_logs().into_iter().map(Into::into).collect(),
deposit_nonce: depositor.map(|account| account.nonce),
// The deposit receipt version was introduced in Canyon to indicate an update to how
// receipt hashes should be computed when set. The state transition process
// ensures this is only set for post-Canyon deposit transactions.
deposit_receipt_version: chain_spec
.is_fork_active_at_timestamp(
Hardfork::Canyon,
attributes.payload_attributes.timestamp,
)
.then_some(1),
}));
// append transaction to the list of executed transactions
executed_txs.push(sequencer_tx.into_signed());
}
if !attributes.no_tx_pool {
while let Some(pool_tx) = best_txs.next() {
// ensure we still have capacity for this transaction
if cumulative_gas_used + pool_tx.gas_limit() > block_gas_limit {
// we can't fit this transaction into the block, so we need to mark it as
// invalid which also removes all dependent transaction from
// the iterator before we can continue
best_txs.mark_invalid(&pool_tx);
continue
}
// A sequencer's block should never contain blob or deposit transactions from the pool.
if pool_tx.is_eip4844() || pool_tx.tx_type() == TxType::Deposit as u8 {
best_txs.mark_invalid(&pool_tx)
}
// check if the job was cancelled, if so we can exit early
if cancel.is_cancelled() {
return Ok(BuildOutcome::Cancelled)
}
// convert tx to a signed transaction
let tx = pool_tx.to_recovered_transaction();
let env = EnvWithHandlerCfg::new_with_cfg_env(
initialized_cfg.clone(),
initialized_block_env.clone(),
tx_env_with_recovered(&tx),
);
// Configure the environment for the block.
let mut evm = evm_config.evm_with_env(&mut db, env);
let ResultAndState { result, state } = match evm.transact() {
Ok(res) => res,
Err(err) => {
match err {
EVMError::Transaction(err) => {
if matches!(err, InvalidTransaction::NonceTooLow { .. }) {
// if the nonce is too low, we can skip this transaction
trace!(target: "payload_builder", %err, ?tx, "skipping nonce too low transaction");
} else {
// if the transaction is invalid, we can skip it and all of its
// descendants
trace!(target: "payload_builder", %err, ?tx, "skipping invalid transaction and its descendants");
best_txs.mark_invalid(&pool_tx);
}
continue
}
err => {
// this is an error that we should treat as fatal for this attempt
return Err(PayloadBuilderError::EvmExecutionError(err))
}
}
}
};
// drop evm so db is released.
drop(evm);
// commit changes
db.commit(state);
let gas_used = result.gas_used();
// add gas used by the transaction to cumulative gas used, before creating the
// receipt
cumulative_gas_used += gas_used;
// Push transaction changeset and calculate header bloom filter for receipt.
receipts.push(Some(Receipt {
tx_type: tx.tx_type(),
success: result.is_success(),
cumulative_gas_used,
logs: result.into_logs().into_iter().map(Into::into).collect(),
deposit_nonce: None,
deposit_receipt_version: None,
}));
// update add to total fees
let miner_fee = tx
.effective_tip_per_gas(Some(base_fee))
.expect("fee is always valid; execution succeeded");
total_fees += U256::from(miner_fee) * U256::from(gas_used);
// append transaction to the list of executed transactions
executed_txs.push(tx.into_signed());
}
}
// check if we have a better block
if !is_better_payload(best_payload.as_ref(), total_fees) {
// can skip building the block
return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads })
}
let WithdrawalsOutcome { withdrawals_root, withdrawals } = commit_withdrawals(
&mut db,
&chain_spec,
attributes.payload_attributes.timestamp,
attributes.clone().payload_attributes.withdrawals,
)?;
// merge all transitions into bundle state, this would apply the withdrawal balance changes
// and 4788 contract call
db.merge_transitions(BundleRetention::PlainState);
let bundle = BundleStateWithReceipts::new(
db.take_bundle(),
Receipts::from_vec(vec![receipts]),
block_number,
);
let receipts_root = bundle
.optimism_receipts_root_slow(
block_number,
chain_spec.as_ref(),
attributes.payload_attributes.timestamp,
)
.expect("Number is in range");
let logs_bloom = bundle.block_logs_bloom(block_number).expect("Number is in range");
// calculate the state root
let state_root = {
let state_provider = db.database.0.inner.borrow_mut();
state_provider.db.state_root(bundle.state())?
};
// create the block header
let transactions_root = proofs::calculate_transaction_root(&executed_txs);
// initialize empty blob sidecars. There are no blob transactions on L2.
let blob_sidecars = Vec::new();
let mut excess_blob_gas = None;
let mut blob_gas_used = None;
// only determine cancun fields when active
if chain_spec.is_cancun_active_at_timestamp(attributes.payload_attributes.timestamp) {
excess_blob_gas = if chain_spec.is_cancun_active_at_timestamp(parent_block.timestamp) {
let parent_excess_blob_gas = parent_block.excess_blob_gas.unwrap_or_default();
let parent_blob_gas_used = parent_block.blob_gas_used.unwrap_or_default();
Some(calculate_excess_blob_gas(parent_excess_blob_gas, parent_blob_gas_used))
} else {
// for the first post-fork block, both parent.blob_gas_used and
// parent.excess_blob_gas are evaluated as 0
Some(calculate_excess_blob_gas(0, 0))
};
blob_gas_used = Some(0);
}
let header = Header {
parent_hash: parent_block.hash(),
ommers_hash: EMPTY_OMMER_ROOT_HASH,
beneficiary: initialized_block_env.coinbase,
state_root,
transactions_root,
receipts_root,
withdrawals_root,
logs_bloom,
timestamp: attributes.payload_attributes.timestamp,
mix_hash: attributes.payload_attributes.prev_randao,
nonce: BEACON_NONCE,
base_fee_per_gas: Some(base_fee),
number: parent_block.number + 1,
gas_limit: block_gas_limit,
difficulty: U256::ZERO,
gas_used: cumulative_gas_used,
extra_data,
parent_beacon_block_root: attributes.payload_attributes.parent_beacon_block_root,
blob_gas_used,
excess_blob_gas,
};
// seal the block
let block = Block { header, body: executed_txs, ommers: vec![], withdrawals };
let sealed_block = block.seal_slow();
debug!(target: "payload_builder", ?sealed_block, "sealed built block");
let mut payload = OptimismBuiltPayload::new(
attributes.payload_attributes.id,
sealed_block,
total_fees,
chain_spec,
attributes,
);
// extend the payload with the blob sidecars from the executed txs
payload.extend_sidecars(blob_sidecars);
Ok(BuildOutcome::Better { payload, cached_reads })
}

View File

@ -1,23 +0,0 @@
//! Error type
/// Optimism specific payload building errors.
#[derive(Debug, thiserror::Error)]
pub enum OptimismPayloadBuilderError {
/// Thrown when a transaction fails to convert to a
/// [reth_primitives::TransactionSignedEcRecovered].
#[error("failed to convert deposit transaction to TransactionSignedEcRecovered")]
TransactionEcRecoverFailed,
/// Thrown when the L1 block info could not be parsed from the calldata of the
/// first transaction supplied in the payload attributes.
#[error("failed to parse L1 block info from L1 info tx calldata")]
L1BlockInfoParseFailed,
/// Thrown when a database account could not be loaded.
#[error("failed to load account {0}")]
AccountLoadFailed(reth_primitives::Address),
/// Thrown when force deploy of create2deployer code fails.
#[error("failed to force create2deployer account code")]
ForceCreate2DeployerFail,
/// Thrown when a blob transaction is included in a sequencer's block.
#[error("blob transaction included in sequencer block")]
BlobTransactionRejected,
}

View File

@ -1,18 +0,0 @@
//! Optimism's payload builder implementation.
#![doc(
html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
)]
#![cfg_attr(all(not(test), feature = "optimism"), warn(unused_crate_dependencies))]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#![allow(clippy::useless_let_if_seq)]
// The `optimism` feature must be enabled to use this crate.
#![cfg(feature = "optimism")]
pub mod builder;
pub use builder::OptimismPayloadBuilder;
pub mod error;
pub mod payload;
pub use payload::{OptimismBuiltPayload, OptimismPayloadBuilderAttributes};

View File

@ -1,314 +0,0 @@
//! Payload related types
//! Optimism builder support
use alloy_rlp::Encodable;
use reth_engine_primitives::{BuiltPayload, PayloadBuilderAttributes};
use reth_payload_builder::EthPayloadBuilderAttributes;
use reth_primitives::{
revm::config::revm_spec_by_timestamp_after_merge,
revm_primitives::{BlobExcessGasAndPrice, BlockEnv, CfgEnv, CfgEnvWithHandlerCfg, SpecId},
Address, BlobTransactionSidecar, ChainSpec, Header, SealedBlock, TransactionSigned,
Withdrawals, B256, U256,
};
use reth_rpc_types::engine::{
ExecutionPayloadEnvelopeV2, ExecutionPayloadV1, OptimismExecutionPayloadEnvelopeV3,
OptimismPayloadAttributes, PayloadId,
};
use reth_rpc_types_compat::engine::payload::{
block_to_payload_v1, block_to_payload_v3, convert_block_to_payload_field_v2,
};
use revm::primitives::HandlerCfg;
use std::sync::Arc;
/// Optimism Payload Builder Attributes
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OptimismPayloadBuilderAttributes {
/// Inner ethereum payload builder attributes
pub payload_attributes: EthPayloadBuilderAttributes,
/// NoTxPool option for the generated payload
pub no_tx_pool: bool,
/// Transactions for the generated payload
pub transactions: Vec<TransactionSigned>,
/// The gas limit for the generated payload
pub gas_limit: Option<u64>,
}
impl PayloadBuilderAttributes for OptimismPayloadBuilderAttributes {
type RpcPayloadAttributes = OptimismPayloadAttributes;
type Error = alloy_rlp::Error;
/// Creates a new payload builder for the given parent block and the attributes.
///
/// Derives the unique [PayloadId] for the given parent and attributes
fn try_new(parent: B256, attributes: OptimismPayloadAttributes) -> Result<Self, Self::Error> {
let (id, transactions) = {
let transactions: Vec<_> = attributes
.transactions
.as_deref()
.unwrap_or(&[])
.iter()
.map(|tx| TransactionSigned::decode_enveloped(&mut tx.as_ref()))
.collect::<Result<_, _>>()?;
(payload_id_optimism(&parent, &attributes, &transactions), transactions)
};
let payload_attributes = EthPayloadBuilderAttributes {
id,
parent,
timestamp: attributes.payload_attributes.timestamp,
suggested_fee_recipient: attributes.payload_attributes.suggested_fee_recipient,
prev_randao: attributes.payload_attributes.prev_randao,
withdrawals: attributes.payload_attributes.withdrawals.unwrap_or_default().into(),
parent_beacon_block_root: attributes.payload_attributes.parent_beacon_block_root,
};
Ok(Self {
payload_attributes,
no_tx_pool: attributes.no_tx_pool.unwrap_or_default(),
transactions,
gas_limit: attributes.gas_limit,
})
}
fn payload_id(&self) -> PayloadId {
self.payload_attributes.id
}
fn parent(&self) -> B256 {
self.payload_attributes.parent
}
fn timestamp(&self) -> u64 {
self.payload_attributes.timestamp
}
fn parent_beacon_block_root(&self) -> Option<B256> {
self.payload_attributes.parent_beacon_block_root
}
fn suggested_fee_recipient(&self) -> Address {
self.payload_attributes.suggested_fee_recipient
}
fn prev_randao(&self) -> B256 {
self.payload_attributes.prev_randao
}
fn withdrawals(&self) -> &Withdrawals {
&self.payload_attributes.withdrawals
}
fn cfg_and_block_env(
&self,
chain_spec: &ChainSpec,
parent: &Header,
) -> (CfgEnvWithHandlerCfg, BlockEnv) {
// configure evm env based on parent block
let mut cfg = CfgEnv::default();
cfg.chain_id = chain_spec.chain().id();
// ensure we're not missing any timestamp based hardforks
let spec_id = revm_spec_by_timestamp_after_merge(chain_spec, self.timestamp());
// if the parent block did not have excess blob gas (i.e. it was pre-cancun), but it is
// cancun now, we need to set the excess blob gas to the default value
let blob_excess_gas_and_price = parent
.next_block_excess_blob_gas()
.or_else(|| {
if spec_id.is_enabled_in(SpecId::CANCUN) {
// default excess blob gas is zero
Some(0)
} else {
None
}
})
.map(BlobExcessGasAndPrice::new);
let block_env = BlockEnv {
number: U256::from(parent.number + 1),
coinbase: self.suggested_fee_recipient(),
timestamp: U256::from(self.timestamp()),
difficulty: U256::ZERO,
prevrandao: Some(self.prev_randao()),
gas_limit: U256::from(parent.gas_limit),
// calculate basefee based on parent block's gas usage
basefee: U256::from(
parent
.next_block_base_fee(chain_spec.base_fee_params_at_timestamp(self.timestamp()))
.unwrap_or_default(),
),
// calculate excess gas based on parent block's blob gas usage
blob_excess_gas_and_price,
};
let cfg_with_handler_cfg;
{
cfg_with_handler_cfg = CfgEnvWithHandlerCfg {
cfg_env: cfg,
handler_cfg: HandlerCfg { spec_id, is_optimism: chain_spec.is_optimism() },
};
}
(cfg_with_handler_cfg, block_env)
}
}
/// Contains the built payload.
#[derive(Debug, Clone)]
pub struct OptimismBuiltPayload {
/// Identifier of the payload
pub(crate) id: PayloadId,
/// The built block
pub(crate) block: SealedBlock,
/// The fees of the block
pub(crate) fees: U256,
/// The blobs, proofs, and commitments in the block. If the block is pre-cancun, this will be
/// empty.
pub(crate) sidecars: Vec<BlobTransactionSidecar>,
/// The rollup's chainspec.
pub(crate) chain_spec: Arc<ChainSpec>,
/// The payload attributes.
pub(crate) attributes: OptimismPayloadBuilderAttributes,
}
// === impl BuiltPayload ===
impl OptimismBuiltPayload {
/// Initializes the payload with the given initial block.
pub fn new(
id: PayloadId,
block: SealedBlock,
fees: U256,
chain_spec: Arc<ChainSpec>,
attributes: OptimismPayloadBuilderAttributes,
) -> Self {
Self { id, block, fees, sidecars: Vec::new(), chain_spec, attributes }
}
/// Returns the identifier of the payload.
pub fn id(&self) -> PayloadId {
self.id
}
/// Returns the built block(sealed)
pub fn block(&self) -> &SealedBlock {
&self.block
}
/// Fees of the block
pub fn fees(&self) -> U256 {
self.fees
}
/// Adds sidecars to the payload.
pub fn extend_sidecars(&mut self, sidecars: Vec<BlobTransactionSidecar>) {
self.sidecars.extend(sidecars)
}
}
impl BuiltPayload for OptimismBuiltPayload {
fn block(&self) -> &SealedBlock {
&self.block
}
fn fees(&self) -> U256 {
self.fees
}
}
impl<'a> BuiltPayload for &'a OptimismBuiltPayload {
fn block(&self) -> &SealedBlock {
(**self).block()
}
fn fees(&self) -> U256 {
(**self).fees()
}
}
// V1 engine_getPayloadV1 response
impl From<OptimismBuiltPayload> for ExecutionPayloadV1 {
fn from(value: OptimismBuiltPayload) -> Self {
block_to_payload_v1(value.block)
}
}
// V2 engine_getPayloadV2 response
impl From<OptimismBuiltPayload> for ExecutionPayloadEnvelopeV2 {
fn from(value: OptimismBuiltPayload) -> Self {
let OptimismBuiltPayload { block, fees, .. } = value;
ExecutionPayloadEnvelopeV2 {
block_value: fees,
execution_payload: convert_block_to_payload_field_v2(block),
}
}
}
impl From<OptimismBuiltPayload> for OptimismExecutionPayloadEnvelopeV3 {
fn from(value: OptimismBuiltPayload) -> Self {
let OptimismBuiltPayload { block, fees, sidecars, chain_spec, attributes, .. } = value;
let parent_beacon_block_root =
if chain_spec.is_cancun_active_at_timestamp(attributes.timestamp()) {
attributes.parent_beacon_block_root().unwrap_or(B256::ZERO)
} else {
B256::ZERO
};
OptimismExecutionPayloadEnvelopeV3 {
execution_payload: block_to_payload_v3(block),
block_value: fees,
// From the engine API spec:
//
// > Client software **MAY** use any heuristics to decide whether to set
// `shouldOverrideBuilder` flag or not. If client software does not implement any
// heuristic this flag **SHOULD** be set to `false`.
//
// Spec:
// <https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/cancun.md#specification-2>
should_override_builder: false,
blobs_bundle: sidecars.into_iter().map(Into::into).collect::<Vec<_>>().into(),
parent_beacon_block_root,
}
}
}
/// Generates the payload id for the configured payload from the [OptimismPayloadAttributes].
///
/// Returns an 8-byte identifier by hashing the payload components with sha256 hash.
pub(crate) fn payload_id_optimism(
parent: &B256,
attributes: &OptimismPayloadAttributes,
txs: &[TransactionSigned],
) -> PayloadId {
use sha2::Digest;
let mut hasher = sha2::Sha256::new();
hasher.update(parent.as_slice());
hasher.update(&attributes.payload_attributes.timestamp.to_be_bytes()[..]);
hasher.update(attributes.payload_attributes.prev_randao.as_slice());
hasher.update(attributes.payload_attributes.suggested_fee_recipient.as_slice());
if let Some(withdrawals) = &attributes.payload_attributes.withdrawals {
let mut buf = Vec::new();
withdrawals.encode(&mut buf);
hasher.update(buf);
}
if let Some(parent_beacon_block) = attributes.payload_attributes.parent_beacon_block_root {
hasher.update(parent_beacon_block);
}
let no_tx_pool = attributes.no_tx_pool.unwrap_or_default();
if no_tx_pool || !txs.is_empty() {
hasher.update([no_tx_pool as u8]);
hasher.update(txs.len().to_be_bytes());
txs.iter().for_each(|tx| hasher.update(tx.hash()));
}
if let Some(gas_limit) = attributes.gas_limit {
hasher.update(gas_limit.to_be_bytes());
}
let out = hasher.finalize();
PayloadId::new(out.as_slice()[..8].try_into().expect("sufficient length"))
}