Skip to content

Commit

Permalink
chore: unify empty payload building (#10807)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse authored Sep 10, 2024
1 parent 72c53b8 commit e4b5325
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 310 deletions.
189 changes: 17 additions & 172 deletions crates/ethereum/payload/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ use reth_payload_builder::{
error::PayloadBuilderError, EthBuiltPayload, EthPayloadBuilderAttributes,
};
use reth_primitives::{
constants::{
eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE, EMPTY_RECEIPTS, EMPTY_TRANSACTIONS,
},
constants::{eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE},
eip4844::calculate_excess_blob_gas,
proofs::{self, calculate_requests_root},
Block, EthereumHardforks, Header, IntoRecoveredTransaction, Receipt, EMPTY_OMMER_ROOT_HASH,
U256,
};
use reth_provider::StateProviderFactory;
use reth_revm::database::StateProviderDatabase;
use reth_transaction_pool::{BestTransactionsAttributes, TransactionPool};
use reth_transaction_pool::{
noop::NoopTransactionPool, BestTransactionsAttributes, TransactionPool,
};
use reth_trie::HashedPostState;
use revm::{
db::states::bundle_state::BundleRetention,
Expand Down Expand Up @@ -83,181 +83,26 @@ where
&self,
args: BuildArguments<Pool, Client, EthPayloadBuilderAttributes, EthBuiltPayload>,
) -> Result<BuildOutcome<EthBuiltPayload>, PayloadBuilderError> {
default_ethereum_payload_builder(self.evm_config.clone(), args)
default_ethereum_payload(self.evm_config.clone(), args)
}

fn build_empty_payload(
&self,
client: &Client,
config: PayloadConfig<Self::Attributes>,
) -> Result<EthBuiltPayload, 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_gas_limit =
initialized_block_env.gas_limit.try_into().unwrap_or(chain_spec.max_gas_limit);

// apply eip-4788 pre block contract call
pre_block_beacon_root_contract_call(
&mut db,
&self.evm_config,
&chain_spec,
&initialized_cfg,
&initialized_block_env,
attributes.parent_beacon_block_root,
)
.map_err(|err| {
warn!(target: "payload_builder",
parent_hash=%parent_block.hash(),
%err,
"failed to apply beacon root contract call for empty payload"
);
PayloadBuilderError::Internal(err.into())
})?;

// apply eip-2935 blockhashes update
pre_block_blockhashes_contract_call(
&mut db,
&self.evm_config,
&chain_spec,
&initialized_cfg,
&initialized_block_env,
parent_block.hash(),
)
.map_err(|err| {
warn!(target: "payload_builder", parent_hash=%parent_block.hash(), %err, "failed to update blockhashes for empty payload");
PayloadBuilderError::Internal(err.into())
})?;

let WithdrawalsOutcome { withdrawals_root, withdrawals } = commit_withdrawals(
&mut db,
&chain_spec,
attributes.timestamp,
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(HashedPostState::from_bundle_state(&bundle_state.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.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);
}

// Calculate the requests and the requests root.
let (requests, requests_root) =
if chain_spec.is_prague_active_at_timestamp(attributes.timestamp) {
// We do not calculate the EIP-6110 deposit requests because there are no
// transactions in an empty payload.
let withdrawal_requests = post_block_withdrawal_requests_contract_call(
&self.evm_config,
&mut db,
&initialized_cfg,
&initialized_block_env,
)
.map_err(|err| PayloadBuilderError::Internal(err.into()))?;
let consolidation_requests = post_block_consolidation_requests_contract_call(
&self.evm_config,
&mut db,
&initialized_cfg,
&initialized_block_env,
)
.map_err(|err| PayloadBuilderError::Internal(err.into()))?;

let requests = [withdrawal_requests, consolidation_requests].concat();
let requests_root = calculate_requests_root(&requests);
(Some(requests.into()), Some(requests_root))
} else {
(None, None)
};

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.timestamp,
mix_hash: 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.parent_beacon_block_root,
requests_root,
let args = BuildArguments {
client,
config,
// we use defaults here because for the empty payload we don't need to execute anything
pool: NoopTransactionPool::default(),
cached_reads: Default::default(),
cancel: Default::default(),
best_payload: None,
};

let block = Block { header, body: vec![], ommers: vec![], withdrawals, requests };
let sealed_block = block.seal_slow();

Ok(EthBuiltPayload::new(attributes.payload_id(), sealed_block, U256::ZERO, None))
default_ethereum_payload(self.evm_config.clone(), args)?
.into_payload()
.ok_or_else(|| PayloadBuilderError::MissingPayload)
}
}

Expand All @@ -267,7 +112,7 @@ where
/// 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 fn default_ethereum_payload_builder<EvmConfig, Pool, Client>(
pub fn default_ethereum_payload<EvmConfig, Pool, Client>(
evm_config: EvmConfig,
args: BuildArguments<Pool, Client, EthPayloadBuilderAttributes, EthBuiltPayload>,
) -> Result<BuildOutcome<EthBuiltPayload>, PayloadBuilderError>
Expand Down
Loading

0 comments on commit e4b5325

Please sign in to comment.