Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move out helpers from payload builder #445

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/op-rbuilder/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ serde_with.workspace = true
serde.workspace = true
secp256k1.workspace = true
tokio.workspace = true
tokio-stream.workspace = true
jsonrpsee = { workspace = true }
async-trait = { workspace = true }
clap_builder = { workspace = true }
Expand Down
3 changes: 2 additions & 1 deletion crates/op-rbuilder/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use reth::providers::CanonStateSubscriptions;
use reth_optimism_cli::{chainspec::OpChainSpecParser, Cli};
use reth_optimism_node::node::OpAddOnsBuilder;
use reth_optimism_node::OpNode;

/// CLI argument parsing.
pub mod args;

Expand All @@ -20,6 +19,8 @@ mod payload_builder_vanilla;
mod tester;
mod tx_signer;

mod primitives;

fn main() {
Cli::<OpChainSpecParser, args::OpRbuilderArgs>::parse()
.run(|builder, builder_args| async move {
Expand Down
135 changes: 7 additions & 128 deletions crates/op-rbuilder/src/payload_builder_vanilla.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@ use crate::generator::BuildArguments;
use crate::{
generator::{BlockCell, PayloadBuilder},
metrics::OpRBuilderMetrics,
primitives::{
estimate_gas_for_builder_tx, signed_builder_tx, ExecutedPayload, ExecutionInfo,
PayloadBuilderService,
},
tx_signer::Signer,
};
use alloy_consensus::constants::EMPTY_WITHDRAWALS;
use alloy_consensus::transaction::Recovered;
use alloy_consensus::{
Eip658Value, Header, Transaction, TxEip1559, Typed2718, EMPTY_OMMER_ROOT_HASH,
};
use alloy_consensus::{Eip658Value, Header, Transaction, Typed2718, EMPTY_OMMER_ROOT_HASH};
use alloy_eips::merge::BEACON_NONCE;
use alloy_primitives::private::alloy_rlp::Encodable;
use alloy_primitives::{Address, Bytes, TxKind, B256, U256};
use alloy_primitives::{Bytes, U256};
use alloy_rpc_types_engine::PayloadId;
use alloy_rpc_types_eth::Withdrawals;
use op_alloy_consensus::{OpDepositReceipt, OpTypedTransaction};
use op_alloy_consensus::OpDepositReceipt;
use reth::builder::{components::PayloadServiceBuilder, node::FullNodeTypes, BuilderContext};
use reth::core::primitives::InMemorySize;
use reth::payload::PayloadBuilderHandle;
Expand Down Expand Up @@ -48,7 +49,6 @@ use reth_optimism_payload_builder::{
use reth_optimism_primitives::{
OpPrimitives, OpTransactionSigned, ADDRESS_L2_TO_L1_MESSAGE_PASSER,
};
use reth_payload_builder::PayloadBuilderService;
use reth_payload_builder_primitives::PayloadBuilderError;
use reth_payload_primitives::PayloadBuilderAttributes;
use reth_payload_util::BestPayloadTransactions;
Expand Down Expand Up @@ -692,72 +692,6 @@ impl<T: PoolTransaction> OpPayloadTransactions<T> for () {
}
}

/// Holds the state after execution
#[derive(Debug)]
pub struct ExecutedPayload<N: NodePrimitives> {
/// Tracked execution info
pub info: ExecutionInfo<N>,
/// Withdrawal hash.
pub withdrawals_root: Option<B256>,
}

/// This acts as the container for executed transactions and its byproducts (receipts, gas used)
#[derive(Default, Debug)]
pub struct ExecutionInfo<N: NodePrimitives> {
/// All executed transactions (unrecovered).
pub executed_transactions: Vec<N::SignedTx>,
/// The recovered senders for the executed transactions.
pub executed_senders: Vec<Address>,
/// The transaction receipts
pub receipts: Vec<N::Receipt>,
/// All gas used so far
pub cumulative_gas_used: u64,
/// Estimated DA size
pub cumulative_da_bytes_used: u64,
/// Tracks fees from executed mempool transactions
pub total_fees: U256,
}

impl<N: NodePrimitives> ExecutionInfo<N> {
/// Create a new instance with allocated slots.
pub fn with_capacity(capacity: usize) -> Self {
Self {
executed_transactions: Vec::with_capacity(capacity),
executed_senders: Vec::with_capacity(capacity),
receipts: Vec::with_capacity(capacity),
cumulative_gas_used: 0,
cumulative_da_bytes_used: 0,
total_fees: U256::ZERO,
}
}

/// Returns true if the transaction would exceed the block limits:
/// - block gas limit: ensures the transaction still fits into the block.
/// - tx DA limit: if configured, ensures the tx does not exceed the maximum allowed DA limit
/// per tx.
/// - block DA limit: if configured, ensures the transaction's DA size does not exceed the
/// maximum allowed DA limit per block.
pub fn is_tx_over_limits(
&self,
tx: &N::SignedTx,
block_gas_limit: u64,
tx_data_limit: Option<u64>,
block_data_limit: Option<u64>,
) -> bool {
if tx_data_limit.is_some_and(|da_limit| tx.length() as u64 > da_limit) {
return true;
}

if block_data_limit
.is_some_and(|da_limit| self.cumulative_da_bytes_used + (tx.length() as u64) > da_limit)
{
return true;
}

self.cumulative_gas_used + tx.gas_limit() > block_gas_limit
}
}

/// Container type that holds all necessities to build a new payload.
#[derive(Debug)]
pub struct OpPayloadBuilderCtx<EvmConfig: ConfigureEvmEnv, ChainSpec, N: NodePrimitives> {
Expand Down Expand Up @@ -1298,58 +1232,3 @@ where
})
}
}

/// Creates signed builder tx to Address::ZERO and specified message as input
pub fn signed_builder_tx<DB>(
db: &mut State<DB>,
builder_tx_gas: u64,
message: Vec<u8>,
signer: Signer,
base_fee: u64,
chain_id: u64,
) -> Result<Recovered<OpTransactionSigned>, PayloadBuilderError>
where
DB: Database<Error = ProviderError>,
{
// Create message with block number for the builder to sign
let nonce = db
.load_cache_account(signer.address)
.map(|acc| acc.account_info().unwrap_or_default().nonce)
.map_err(|_| {
PayloadBuilderError::other(OpPayloadBuilderError::AccountLoadFailed(signer.address))
})?;

// Create the EIP-1559 transaction
let tx = OpTypedTransaction::Eip1559(TxEip1559 {
chain_id,
nonce,
gas_limit: builder_tx_gas,
max_fee_per_gas: base_fee.into(),
max_priority_fee_per_gas: 0,
to: TxKind::Call(Address::ZERO),
// Include the message as part of the transaction data
input: message.into(),
..Default::default()
});
// Sign the transaction
let builder_tx = signer.sign_tx(tx).map_err(PayloadBuilderError::other)?;

Ok(builder_tx)
}

fn estimate_gas_for_builder_tx(input: Vec<u8>) -> u64 {
// Count zero and non-zero bytes
let (zero_bytes, nonzero_bytes) = input.iter().fold((0, 0), |(zeros, nonzeros), &byte| {
if byte == 0 {
(zeros + 1, nonzeros)
} else {
(zeros, nonzeros + 1)
}
});

// Calculate gas cost (4 gas per zero byte, 16 gas per non-zero byte)
let zero_cost = zero_bytes * 4;
let nonzero_cost = nonzero_bytes * 16;

zero_cost + nonzero_cost + 21_000
}
70 changes: 70 additions & 0 deletions crates/op-rbuilder/src/primitives/execution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use alloy_consensus::Transaction;
use alloy_primitives::private::alloy_rlp::Encodable;
use alloy_primitives::{Address, B256, U256};
use reth_primitives_traits::NodePrimitives;

/// Holds the state after execution
#[derive(Debug)]
pub struct ExecutedPayload<N: NodePrimitives> {
/// Tracked execution info
pub info: ExecutionInfo<N>,
/// Withdrawal hash.
pub withdrawals_root: Option<B256>,
}

/// This acts as the container for executed transactions and its byproducts (receipts, gas used)
#[derive(Default, Debug)]
pub struct ExecutionInfo<N: NodePrimitives> {
/// All executed transactions (unrecovered).
pub executed_transactions: Vec<N::SignedTx>,
/// The recovered senders for the executed transactions.
pub executed_senders: Vec<Address>,
/// The transaction receipts
pub receipts: Vec<N::Receipt>,
/// All gas used so far
pub cumulative_gas_used: u64,
/// Estimated DA size
pub cumulative_da_bytes_used: u64,
/// Tracks fees from executed mempool transactions
pub total_fees: U256,
}

impl<N: NodePrimitives> ExecutionInfo<N> {
/// Create a new instance with allocated slots.
pub fn with_capacity(capacity: usize) -> Self {
Self {
executed_transactions: Vec::with_capacity(capacity),
executed_senders: Vec::with_capacity(capacity),
receipts: Vec::with_capacity(capacity),
cumulative_gas_used: 0,
cumulative_da_bytes_used: 0,
total_fees: U256::ZERO,
}
}

/// Returns true if the transaction would exceed the block limits:
/// - block gas limit: ensures the transaction still fits into the block.
/// - tx DA limit: if configured, ensures the tx does not exceed the maximum allowed DA limit
/// per tx.
/// - block DA limit: if configured, ensures the transaction's DA size does not exceed the
/// maximum allowed DA limit per block.
pub fn is_tx_over_limits(
&self,
tx: &N::SignedTx,
block_gas_limit: u64,
tx_data_limit: Option<u64>,
block_data_limit: Option<u64>,
) -> bool {
if tx_data_limit.is_some_and(|da_limit| tx.length() as u64 > da_limit) {
return true;
}

if block_data_limit
.is_some_and(|da_limit| self.cumulative_da_bytes_used + (tx.length() as u64) > da_limit)
{
return true;
}

self.cumulative_gas_used + tx.gas_limit() > block_gas_limit
}
}
64 changes: 64 additions & 0 deletions crates/op-rbuilder/src/primitives/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use crate::tx_signer::Signer;
use alloy_consensus::transaction::Recovered;
use alloy_consensus::TxEip1559;
use alloy_primitives::{Address, TxKind};
use op_alloy_consensus::OpTypedTransaction;
use reth_evm::Database;
use reth_optimism_payload_builder::error::OpPayloadBuilderError;
use reth_optimism_primitives::OpTransactionSigned;
use reth_payload_primitives::PayloadBuilderError;
use reth_provider::ProviderError;
use revm::db::State;
pub fn estimate_gas_for_builder_tx(input: Vec<u8>) -> u64 {
// Count zero and non-zero bytes
let (zero_bytes, nonzero_bytes) = input.iter().fold((0, 0), |(zeros, nonzeros), &byte| {
if byte == 0 {
(zeros + 1, nonzeros)
} else {
(zeros, nonzeros + 1)
}
});

// Calculate gas cost (4 gas per zero byte, 16 gas per non-zero byte)
let zero_cost = zero_bytes * 4;
let nonzero_cost = nonzero_bytes * 16;

zero_cost + nonzero_cost + 21_000
}
/// Creates signed builder tx to Address::ZERO and specified message as input
pub fn signed_builder_tx<DB>(
db: &mut State<DB>,
builder_tx_gas: u64,
message: Vec<u8>,
signer: Signer,
base_fee: u64,
chain_id: u64,
) -> Result<Recovered<OpTransactionSigned>, PayloadBuilderError>
where
DB: Database<Error = ProviderError>,
{
// Create message with block number for the builder to sign
let nonce = db
.load_cache_account(signer.address)
.map(|acc| acc.account_info().unwrap_or_default().nonce)
.map_err(|_| {
PayloadBuilderError::other(OpPayloadBuilderError::AccountLoadFailed(signer.address))
})?;

// Create the EIP-1559 transaction
let tx = OpTypedTransaction::Eip1559(TxEip1559 {
chain_id,
nonce,
gas_limit: builder_tx_gas,
max_fee_per_gas: base_fee.into(),
max_priority_fee_per_gas: 0,
to: TxKind::Call(Address::ZERO),
// Include the message as part of the transaction data
input: message.into(),
..Default::default()
});
// Sign the transaction
let builder_tx = signer.sign_tx(tx).map_err(PayloadBuilderError::other)?;

Ok(builder_tx)
}
10 changes: 10 additions & 0 deletions crates/op-rbuilder/src/primitives/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//! This module contains types from the reth that weren't heavily modified
mod execution;
mod helpers;
mod payload_builder_service;

pub use payload_builder_service::PayloadBuilderService;

pub use helpers::{estimate_gas_for_builder_tx, signed_builder_tx};

pub use execution::{ExecutedPayload, ExecutionInfo};
Loading
Loading