Skip to content

Commit

Permalink
Adjust the payload_builder according to ethereum impl.
Browse files Browse the repository at this point in the history
  • Loading branch information
evgenyzdanovich committed Dec 18, 2024
1 parent 4071768 commit 9f3c0fc
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 55 deletions.
2 changes: 0 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions crates/reth/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ reth-payload-validator.workspace = true
reth-primitives.workspace = true
reth-provider.workspace = true
reth-transaction-pool.workspace = true
reth-trie.workspace = true
reth-trie-common.workspace = true
reth-trie-db.workspace = true
revm.workspace = true
revm-primitives.workspace = true
Expand Down
24 changes: 24 additions & 0 deletions crates/reth/node/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ use reth_chainspec::ChainSpec;
use reth_evm::{ConfigureEvm, ConfigureEvmEnv, NextBlockEnvAttributes};
use reth_node_ethereum::EthEvmConfig;
use reth_primitives::{Header, TransactionSigned};
use revm::{inspector_handle_register, Database, Evm, EvmBuilder, GetInspector};
use revm_primitives::{
Address, AnalysisKind, BlockEnv, Bytes, CfgEnvWithHandlerCfg, Env, TxEnv, U256,
};
use strata_reth_evm::set_evm_handles;

/// Custom EVM configuration
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -66,6 +68,28 @@ impl ConfigureEvmEnv for StrataEvmConfig {
impl ConfigureEvm for StrataEvmConfig {
type DefaultExternalContext<'a> = ();

fn evm<DB: Database>(&self, db: DB) -> Evm<'_, Self::DefaultExternalContext<'_>, DB> {
EvmBuilder::default()
.with_db(db)
// add additional precompiles
.append_handler_register(set_evm_handles)
.build()
}

fn evm_with_inspector<DB, I>(&self, db: DB, inspector: I) -> Evm<'_, I, DB>
where
DB: Database,
I: GetInspector<DB>,
{
EvmBuilder::default()
.with_db(db)
.with_external_context(inspector)
// add additional precompiles
.append_handler_register(set_evm_handles)
.append_handler_register(inspector_handle_register)
.build()
}

#[doc = " Provides the default external context."]
fn default_external_context<'a>(&self) -> Self::DefaultExternalContext<'a> {
self.inner.default_external_context()
Expand Down
13 changes: 9 additions & 4 deletions crates/reth/node/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use reth_node_builder::{
};
use reth_node_ethereum::{
node::{EthereumConsensusBuilder, EthereumNetworkBuilder, EthereumPoolBuilder},
BasicBlockExecutorProvider, EthExecutionStrategyFactory, EthExecutorProvider,
BasicBlockExecutorProvider, EthExecutionStrategyFactory,
};
use reth_primitives::{BlockBody, PooledTransactionsElement};
use reth_provider::{
Expand Down Expand Up @@ -313,15 +313,20 @@ where
Node: FullNodeTypes<Types: NodeTypes<ChainSpec = ChainSpec, Primitives = StrataPrimitives>>,
{
type EVM = StrataEvmConfig;
type Executor = BasicBlockExecutorProvider<EthExecutionStrategyFactory>;
type Executor = BasicBlockExecutorProvider<EthExecutionStrategyFactory<Self::EVM>>;

async fn build_evm(
self,
ctx: &BuilderContext<Node>,
) -> eyre::Result<(Self::EVM, Self::Executor)> {
let evm_config = StrataEvmConfig::new(ctx.chain_spec());

Check warning on line 323 in crates/reth/node/src/node.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/node.rs#L322-L323

Added lines #L322 - L323 were not covered by tests
Ok((
StrataEvmConfig::new(ctx.chain_spec()),
EthExecutorProvider::ethereum(ctx.chain_spec()),
evm_config.clone(),
BasicBlockExecutorProvider::new(EthExecutionStrategyFactory::new(
ctx.chain_spec(),
evm_config,
)),

Check warning on line 329 in crates/reth/node/src/node.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/node.rs#L325-L329

Added lines #L325 - L329 were not covered by tests
))
}
}
2 changes: 1 addition & 1 deletion crates/reth/node/src/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl BuiltPayload for StrataBuiltPayload {
}

Check warning on line 125 in crates/reth/node/src/payload.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload.rs#L123-L125

Added lines #L123 - L125 were not covered by tests

fn requests(&self) -> Option<Requests> {
None
self.inner.requests()
}

Check warning on line 129 in crates/reth/node/src/payload.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload.rs#L127-L129

Added lines #L127 - L129 were not covered by tests
}

Expand Down
101 changes: 55 additions & 46 deletions crates/reth/node/src/payload_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use reth_basic_payload_builder::*;
use reth_chain_state::ExecutedBlock;
use reth_chainspec::{ChainSpec, ChainSpecProvider, EthereumHardforks};
use reth_errors::RethError;
use reth_evm::system_calls::SystemCaller;
use reth_evm::{system_calls::SystemCaller, ConfigureEvmEnv, NextBlockEnvAttributes};
use reth_evm_ethereum::{eip6110::parse_deposits_from_receipts, EthEvmConfig};
use reth_node_api::{
ConfigureEvm, FullNodeTypes, NodeTypesWithEngine, PayloadBuilderAttributes, TxTy,
Expand All @@ -30,14 +30,13 @@ use reth_transaction_pool::{
error::InvalidPoolTransactionError, BestTransactions, BestTransactionsAttributes,
PoolTransaction, TransactionPool,
};
use reth_trie::HashedPostState;
use reth_trie_common::KeccakKeyHasher;
use revm::{
db::{states::bundle_state::BundleRetention, State},
DatabaseCommit,
};
use revm_primitives::{
calc_excess_blob_gas, EVMError, EnvWithHandlerCfg, InvalidTransaction, ResultAndState, U256,
calc_excess_blob_gas, BlockEnv, CfgEnvWithHandlerCfg, EVMError, EnvWithHandlerCfg,
InvalidTransaction, ResultAndState, TxEnv, U256,
};
use strata_reth_evm::collect_withdrawal_intents;
use tracing::{debug, trace, warn};
Expand All @@ -56,6 +55,24 @@ pub struct StrataPayloadBuilder {
evm_config: StrataEvmConfig,
}

impl StrataPayloadBuilder {
/// Returns the configured [`CfgEnvWithHandlerCfg`] and [`BlockEnv`] for the targeted payload
/// (that has the `parent` as its parent).
pub fn cfg_and_block_env(
&self,
attributes: &StrataPayloadBuilderAttributes,
parent: &Header,
) -> Result<(CfgEnvWithHandlerCfg, BlockEnv), <StrataEvmConfig as ConfigureEvmEnv>::Error> {
let next_attributes = NextBlockEnvAttributes {
timestamp: attributes.timestamp(),
suggested_fee_recipient: attributes.suggested_fee_recipient(),
prev_randao: attributes.prev_randao(),
};
self.evm_config
.next_cfg_and_block_env(parent, next_attributes)
}

Check warning on line 73 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L61-L73

Added lines #L61 - L73 were not covered by tests
}

impl<Pool, Client> PayloadBuilder<Pool, Client> for StrataPayloadBuilder
where
Client: StateProviderFactory + ChainSpecProvider<ChainSpec = ChainSpec>,
Expand All @@ -68,7 +85,11 @@ where
&self,
args: BuildArguments<Pool, Client, Self::Attributes, Self::BuiltPayload>,
) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError> {
try_build_payload(self.evm_config.clone(), args)
let (cfg_env, block_env) = self
.cfg_and_block_env(&args.config.attributes, &args.config.parent_header)
.map_err(PayloadBuilderError::other)?;

Check warning on line 90 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L88-L90

Added lines #L88 - L90 were not covered by tests

try_build_payload(self.evm_config.clone(), args, cfg_env, block_env)

Check warning on line 92 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L92

Added line #L92 was not covered by tests
}

fn build_empty_payload(
Expand Down Expand Up @@ -189,6 +210,8 @@ where
pub fn try_build_payload<EvmConfig, Pool, Client>(
evm_config: EvmConfig,
args: BuildArguments<Pool, Client, StrataPayloadBuilderAttributes, StrataBuiltPayload>,
initialized_cfg: CfgEnvWithHandlerCfg,
initialized_block_env: BlockEnv,

Check warning on line 214 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L213-L214

Added lines #L213 - L214 were not covered by tests
) -> Result<BuildOutcome<StrataBuiltPayload>, PayloadBuilderError>
where
EvmConfig: ConfigureEvm<Header = Header, Transaction = TransactionSigned>,

Check warning on line 217 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L217

Added line #L217 was not covered by tests
Expand All @@ -204,42 +227,28 @@ where
best_payload,
} = args;

let PayloadConfig {
parent_header,
attributes,
extra_data,
} = config;

Check warning on line 235 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L230-L235

Added lines #L230 - L235 were not covered by tests
// convert to eth payload
let best_payload = best_payload.map(|p| p.inner);

let chain_spec = client.chain_spec();
let state_provider = client.state_by_block_hash(config.parent_header.hash())?;
let state_provider = client.state_by_block_hash(parent_header.hash())?;

Check warning on line 240 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L239-L240

Added lines #L239 - L240 were not covered by tests
let state = StateProviderDatabase::new(state_provider);
let mut db = State::builder()
.with_database_ref(cached_reads.as_db(state))
.with_database(cached_reads.as_db_mut(state))

Check warning on line 243 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L243

Added line #L243 was not covered by tests
.with_bundle_update()
.build();

let PayloadConfig {
parent_header,
attributes,
extra_data,
} = config;

debug!(target: "payload_builder", id=%attributes.payload_id(), parent_hash = ?parent_header.hash(), parent_number = parent_header.number, "building new payload");

Check warning on line 247 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L247

Added line #L247 was not covered by tests

let (initialized_cfg, initialized_block_env) = evm_config
.next_cfg_and_block_env(
&parent_header,
reth_evm::NextBlockEnvAttributes {
timestamp: attributes.timestamp(),
suggested_fee_recipient: attributes.suggested_fee_recipient(),
prev_randao: attributes.prev_randao(),
},
)
.map_err(PayloadBuilderError::other)?;

let mut cumulative_gas_used = 0;
let mut sum_blob_gas_used = 0;
let block_gas_limit: u64 = initialized_block_env
.gas_limit
.try_into()
.unwrap_or(chain_spec.max_gas_limit);
let block_gas_limit: u64 = initialized_block_env.gas_limit.to::<u64>();

Check warning on line 251 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L251

Added line #L251 was not covered by tests
let base_fee = initialized_block_env.basefee.to::<u64>();

let mut executed_senders = Vec::new();
Expand Down Expand Up @@ -285,6 +294,13 @@ where
)
.map_err(|err| PayloadBuilderError::Internal(err.into()))?;

let env = EnvWithHandlerCfg::new_with_cfg_env(
initialized_cfg.clone(),
initialized_block_env.clone(),
TxEnv::default(),
);
let mut evm = evm_config.evm_with_env(&mut db, env);

Check warning on line 303 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L297-L303

Added lines #L297 - L303 were not covered by tests
let mut receipts = Vec::new();
// let mut withdrawal_intents = Vec::new();
while let Some(pool_tx) = best_txs.next() {
Expand Down Expand Up @@ -329,14 +345,8 @@ where
}
}

let env = EnvWithHandlerCfg::new_with_cfg_env(
initialized_cfg.clone(),
initialized_block_env.clone(),
evm_config.tx_env(tx.as_signed(), tx.signer()),
);

// Configure the environment for the block.
let mut evm = evm_config.evm_with_env(&mut db, env);
// Configure the environment for the tx.
*evm.tx_mut() = evm_config.tx_env(tx.as_signed(), tx.signer());

Check warning on line 349 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L349

Added line #L349 was not covered by tests

let ResultAndState { result, state } = match evm.transact() {
Ok(res) => res,
Expand Down Expand Up @@ -368,10 +378,8 @@ where
}
};
debug!(?result, "EVM transaction executed");
// drop evm so db is released.
drop(evm);
// commit changes
db.commit(state);
evm.db_mut().commit(state);

Check warning on line 382 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L382

Added line #L382 was not covered by tests

// add to the total blob gas used if the transaction successfully executed
if let Some(blob_tx) = tx.transaction.as_eip4844() {
Expand Down Expand Up @@ -410,6 +418,9 @@ where
executed_txs.push(tx.into_signed());
}

// drop evm so db is released.
drop(evm);

Check warning on line 423 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L422-L423

Added lines #L422 - L423 were not covered by tests
// check if we have a better block
if !is_better_payload(best_payload.as_ref(), total_fees) {
// can skip building the block
Expand Down Expand Up @@ -477,14 +488,14 @@ where

// merge all transitions into bundle state, this would apply the withdrawal balance changes
// and 4788 contract call
db.merge_transitions(BundleRetention::PlainState);
db.merge_transitions(BundleRetention::Reverts);
let requests_hash = requests.as_ref().map(|requests| requests.requests_hash());

Check warning on line 492 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L491-L492

Added lines #L491 - L492 were not covered by tests

let execution_outcome = ExecutionOutcome::new(
db.take_bundle(),
vec![receipts].into(),
block_number,
vec![Requests::default()],
vec![requests.clone().unwrap_or_default()],

Check warning on line 498 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L498

Added line #L498 was not covered by tests
);
let receipts_root = execution_outcome
.receipts_root_slow(block_number)
Expand All @@ -494,12 +505,10 @@ where
.expect("Number is in range");

// calculate the state root
let hashed_state =
HashedPostState::from_bundle_state::<KeccakKeyHasher>(&execution_outcome.state().state);
let hashed_state = db.database.db.hashed_post_state(execution_outcome.state());

Check warning on line 508 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L508

Added line #L508 was not covered by tests
let (state_root, trie_output) = {
let state_provider = db.database.0.inner.borrow_mut();
state_provider
.db
db.database
.inner()

Check warning on line 511 in crates/reth/node/src/payload_builder.rs

View check run for this annotation

Codecov / codecov/patch

crates/reth/node/src/payload_builder.rs#L510-L511

Added lines #L510 - L511 were not covered by tests
.state_root_with_updates(hashed_state.clone())
.inspect_err(|err| {
warn!(target: "payload_builder",
Expand Down

0 comments on commit 9f3c0fc

Please sign in to comment.