Skip to content
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 rust/Cargo.lock

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

23 changes: 23 additions & 0 deletions rust/op-reth/crates/chainspec/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ impl OpChainSpecBuilder {
}
}

/// Default OP Stack block time in seconds for chain specs without an explicit configuration.
pub const DEFAULT_OP_BLOCK_TIME: u64 = 2;

/// OP stack chain spec type.
#[derive(Debug, Clone, Deref, Into, Constructor, PartialEq, Eq)]
pub struct OpChainSpec {
Expand All @@ -224,8 +227,28 @@ impl OpChainSpec {
pub fn from_genesis(genesis: Genesis) -> Self {
genesis.into()
}

/// Returns the configured block time in seconds.
pub fn block_time(&self) -> u64 {
OpChainSpecExt::block_time(self)
}
}

/// OP-specific extensions to a chain specification.
pub trait OpChainSpecExt: EthChainSpec {
/// Returns the configured block time in seconds.
fn block_time(&self) -> u64 {
self.genesis()
.config
.extra_fields
.get("blockTime")
.and_then(serde_json::Value::as_u64)
.unwrap_or(DEFAULT_OP_BLOCK_TIME)
}
}

impl<T: EthChainSpec + ?Sized> OpChainSpecExt for T {}

impl EthChainSpec for OpChainSpec {
type Header = Header;

Expand Down
10 changes: 10 additions & 0 deletions rust/op-reth/crates/chainspec/src/superchain/chain_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use serde::{Deserialize, Serialize};
#[serde(rename_all = "snake_case")]
pub(crate) struct ChainMetadata {
pub chain_id: ChainId,
pub block_time: u64,
pub hardforks: HardforkConfig,
pub optimism: Option<OptimismConfig>,
}
Expand Down Expand Up @@ -68,6 +69,7 @@ pub(crate) struct OptimismConfig {
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ChainConfigExtraFields {
pub block_time: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub bedrock_block: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -157,6 +159,7 @@ pub(crate) fn to_genesis_chain_config(chain_config: &ChainMetadata) -> ChainConf

// Add extra fields for ChainConfig from Genesis
let extra_fields = ChainConfigExtraFields {
block_time: chain_config.block_time,
bedrock_block: if chain_config.chain_id == NamedChain::Optimism as ChainId {
Some(105235063)
} else {
Expand Down Expand Up @@ -189,6 +192,7 @@ mod tests {
const GENERIC_CHAIN_METADATA: &str = r#"
{
"chain_id": 130,
"block_time": 1,
"hardforks": {
"canyon_time": 1704992401,
"delta_time": 1708560000,
Expand All @@ -210,6 +214,7 @@ mod tests {
fn test_deserialize_chain_config() {
let config: ChainMetadata = serde_json::from_str(GENERIC_CHAIN_METADATA).unwrap();
assert_eq!(config.chain_id, 130);
assert_eq!(config.block_time, 1);
// hardforks
assert_eq!(config.hardforks.canyon_time, Some(1704992401));
assert_eq!(config.hardforks.delta_time, Some(1708560000));
Expand All @@ -227,6 +232,7 @@ mod tests {
#[test]
fn test_chain_config_extra_fields() {
let extra_fields = ChainConfigExtraFields {
block_time: 2,
bedrock_block: Some(105235063),
regolith_time: Some(0),
canyon_time: Some(1704992401),
Expand All @@ -245,6 +251,7 @@ mod tests {
}),
};
let value = serde_json::to_value(extra_fields).unwrap();
assert_eq!(value.get("blockTime").unwrap(), 2);
assert_eq!(value.get("bedrockBlock").unwrap(), 105235063);
assert_eq!(value.get("regolithTime").unwrap(), 0);
assert_eq!(value.get("canyonTime").unwrap(), 1704992401);
Expand All @@ -267,6 +274,7 @@ mod tests {
let config: ChainMetadata = serde_json::from_str(GENERIC_CHAIN_METADATA).unwrap();
let chain_config = to_genesis_chain_config(&config);
assert_eq!(chain_config.chain_id, 130);
assert_eq!(chain_config.extra_fields.get("blockTime").unwrap(), 1);
assert_eq!(chain_config.homestead_block, Some(0));
assert_eq!(chain_config.dao_fork_block, None);
assert!(!chain_config.dao_fork_support);
Expand Down Expand Up @@ -312,6 +320,7 @@ mod tests {
const OP_CHAIN_METADATA: &str = r#"
{
"chain_id": 10,
"block_time": 2,
"hardforks": {
"canyon_time": 1704992401,
"delta_time": 1708560000,
Expand All @@ -332,6 +341,7 @@ mod tests {
assert_eq!(config.hardforks.canyon_time, Some(1704992401));
let chain_config = to_genesis_chain_config(&config);
assert_eq!(chain_config.chain_id, 10);
assert_eq!(chain_config.extra_fields.get("blockTime").unwrap(), 2);
assert_eq!(chain_config.shanghai_time, Some(1704992401));
assert_eq!(chain_config.cancun_time, Some(1710374401));
assert_eq!(chain_config.prague_time, Some(1746806401));
Expand Down
10 changes: 10 additions & 0 deletions rust/op-reth/crates/chainspec/src/superchain/configs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ mod tests {
fn test_read_superchain_genesis() {
let genesis = read_superchain_genesis("unichain", "mainnet").unwrap();
assert_eq!(genesis.config.chain_id, 130);
assert_eq!(genesis.config.extra_fields.get("blockTime").unwrap(), 1);
assert_eq!(genesis.timestamp, 1730748359);
assert!(genesis.alloc.contains_key(&L2_TO_L1_MESSAGE_PASSER_ADDRESS));
}
Expand All @@ -118,6 +119,7 @@ mod tests {
let archive = TarArchiveRef::new(SUPER_CHAIN_CONFIGS_TAR_BYTES).unwrap();
let chain_config = read_superchain_metadata("funki", "mainnet", &archive).unwrap();
assert_eq!(chain_config.chain_id, 33979);
assert_eq!(chain_config.block_time, 2);
}

#[test]
Expand Down Expand Up @@ -157,6 +159,14 @@ mod tests {
}
}

#[test]
fn test_block_times() {
assert_eq!(crate::UNICHAIN_MAINNET.block_time(), 1);
assert_eq!(crate::OP_MAINNET.block_time(), 2);
assert_eq!(crate::SWAN_MAINNET.block_time(), 5);
assert_eq!(crate::CYBER_SEPOLIA.block_time(), 10);
}

#[test]
fn test_hardfork_timestamps() {
for &chain in SUPPORTED_CHAINS {
Expand Down
3 changes: 2 additions & 1 deletion rust/op-reth/crates/evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ reth-execution-types.workspace = true
reth-storage-errors.workspace = true

reth-rpc-eth-api = { workspace = true, optional = true }
reth-rpc-eth-types = { workspace = true, optional = true }

# ethereum
alloy-eips.workspace = true
Expand Down Expand Up @@ -97,4 +98,4 @@ portable = [
"op-revm/portable",
"revm/portable",
]
rpc = ["reth-rpc-eth-api", "reth-optimism-primitives/serde", "reth-optimism-primitives/reth-codec", "alloy-evm/rpc", "alloy-op-evm/rpc", "op-alloy-rpc-types", "alloy-rpc-types-eth"]
rpc = ["reth-rpc-eth-api", "reth-rpc-eth-types", "reth-optimism-primitives/serde", "reth-optimism-primitives/reth-codec", "alloy-evm/rpc", "alloy-op-evm/rpc", "op-alloy-rpc-types", "alloy-rpc-types-eth"]
92 changes: 82 additions & 10 deletions rust/op-reth/crates/evm/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ pub use alloy_op_evm::{
spec as revm_spec, spec_by_timestamp_after_bedrock as revm_spec_by_timestamp_after_bedrock,
};
use op_alloy_rpc_types_engine::OpFlashblockPayloadBase;
#[cfg(feature = "rpc")]
use reth_evm::ConfigureEvm;
#[cfg(feature = "rpc")]
use reth_primitives_traits::HeaderTy;
#[cfg(feature = "rpc")]
use reth_rpc_eth_api::helpers::pending_block::PendingEnvBuilder;
use revm::primitives::{Address, B256, Bytes};

/// Context relevant for execution of a next block w.r.t OP.
Expand All @@ -22,20 +28,15 @@ pub struct OpNextBlockEnvAttributes {
}

#[cfg(feature = "rpc")]
impl<H: alloy_consensus::BlockHeader> reth_rpc_eth_api::helpers::pending_block::BuildPendingEnv<H>
for OpNextBlockEnvAttributes
{
/// UPSTREAM-MIRROR(copy): reth@rev:4553cf1
/// `reth_rpc_eth_api::helpers::pending_block::NextBlockEnvAttributes::build_pending_env`
///
/// Copies upstream pending-environment defaults for the OP attribute type, except that
/// `parent_beacon_block_root` carries the parent's actual root where upstream zeroes it.
fn build_pending_env(
impl OpNextBlockEnvAttributes {
/// Builds pending-block attributes using the configured block time.
fn build_pending_env_with_block_time<H: alloy_consensus::BlockHeader>(
parent: &crate::SealedHeader<H>,
block_overrides: Option<&alloy_rpc_types_eth::BlockOverrides>,
block_time: u64,
) -> Self {
let mut attributes = Self {
timestamp: parent.timestamp().saturating_add(12),
timestamp: parent.timestamp().saturating_add(block_time),
suggested_fee_recipient: parent.beneficiary(),
prev_randao: B256::random(),
gas_limit: parent.gas_limit(),
Expand All @@ -57,6 +58,40 @@ impl<H: alloy_consensus::BlockHeader> reth_rpc_eth_api::helpers::pending_block::
}
}

/// Builds OP pending-block attributes using the configured block time.
#[cfg(feature = "rpc")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpPendingEnvBuilder {
block_time: u64,
}

#[cfg(feature = "rpc")]
impl OpPendingEnvBuilder {
/// Creates a pending environment builder for the given block time in seconds.
pub const fn new(block_time: u64) -> Self {
Self { block_time }
}
}

#[cfg(feature = "rpc")]
impl<Evm> PendingEnvBuilder<Evm> for OpPendingEnvBuilder
where
Evm: ConfigureEvm<NextBlockEnvCtx = OpNextBlockEnvAttributes>,
HeaderTy<Evm::Primitives>: alloy_consensus::BlockHeader,
{
fn pending_env_attributes(
&self,
parent: &crate::SealedHeader<HeaderTy<Evm::Primitives>>,
block_overrides: Option<&alloy_rpc_types_eth::BlockOverrides>,
) -> Result<Evm::NextBlockEnvCtx, reth_rpc_eth_types::EthApiError> {
Ok(OpNextBlockEnvAttributes::build_pending_env_with_block_time(
parent,
block_overrides,
self.block_time,
))
}
}

impl From<OpFlashblockPayloadBase> for OpNextBlockEnvAttributes {
fn from(base: OpFlashblockPayloadBase) -> Self {
Self {
Expand All @@ -69,3 +104,40 @@ impl From<OpFlashblockPayloadBase> for OpNextBlockEnvAttributes {
}
}
}

#[cfg(all(test, feature = "rpc"))]
mod tests {
use super::*;
use alloy_consensus::Header;
use op_revm::OpSpecId;
use reth_chainspec::Hardforks;
use reth_optimism_chainspec::{OpHardfork, UNICHAIN_MAINNET};
use reth_primitives_traits::SealedHeader;

#[test]
fn pending_env_uses_configured_block_time_without_crossing_fork_early() {
let chain_spec = UNICHAIN_MAINNET.as_ref();
let isthmus_timestamp = chain_spec.fork(OpHardfork::Isthmus).as_timestamp().unwrap();
let parent = SealedHeader::seal_slow(Header {
timestamp: isthmus_timestamp - 2,
..Default::default()
});
let attributes =
<OpPendingEnvBuilder as PendingEnvBuilder<crate::OpEvmConfig>>::pending_env_attributes(
&OpPendingEnvBuilder::new(chain_spec.block_time()),
&parent,
None,
)
.unwrap();

assert_eq!(attributes.timestamp, isthmus_timestamp - 1);
assert_eq!(
revm_spec_by_timestamp_after_bedrock(chain_spec, attributes.timestamp),
OpSpecId::HOLOCENE
);
assert_eq!(
revm_spec_by_timestamp_after_bedrock(chain_spec, isthmus_timestamp),
OpSpecId::ISTHMUS
);
}
}
2 changes: 2 additions & 0 deletions rust/op-reth/crates/evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ use {
};

mod config;
#[cfg(feature = "rpc")]
pub use config::OpPendingEnvBuilder;
pub use config::{OpNextBlockEnvAttributes, revm_spec, revm_spec_by_timestamp_after_bedrock};
mod execute;
pub use execute::*;
Expand Down
3 changes: 2 additions & 1 deletion rust/op-reth/crates/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ reth-payload-util.workspace = true
reth-provider.workspace = true

# op-reth
reth-optimism-evm.workspace = true
reth-optimism-chainspec.workspace = true
reth-optimism-evm = { workspace = true, features = ["rpc"] }
reth-optimism-flashblocks.workspace = true
reth-optimism-payload-builder.workspace = true
reth-optimism-post-exec-replay.workspace = true
Expand Down
22 changes: 12 additions & 10 deletions rust/op-reth/crates/rpc/src/eth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ use eyre::WrapErr;
use futures::StreamExt;
use op_alloy_consensus::OpReceipt;
use op_alloy_network::Optimism;
use op_alloy_rpc_types_engine::OpFlashblockPayloadBase;
pub use receipt::{OpReceiptBuilder, OpReceiptFieldsBuilder};
use reqwest::Url;
use reth_chainspec::{EthereumHardforks, Hardforks};
use reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};
use reth_evm::ConfigureEvm;
use reth_node_api::{FullNodeComponents, FullNodeTypes, HeaderTy, NodeTypes};
use reth_node_api::{FullNodeComponents, FullNodeTypes, NodeTypes};
use reth_node_builder::rpc::{EthApiBuilder, EthApiCtx};
use reth_optimism_chainspec::OpChainSpecExt;
use reth_optimism_evm::{OpNextBlockEnvAttributes, OpPendingEnvBuilder};
use reth_optimism_flashblocks::{
FlashBlockBuildInfo, FlashBlockCompleteSequence, FlashBlockCompleteSequenceRx,
FlashBlockConsensusClient, FlashBlockRx, FlashBlockService, FlashblockCachedReceipt,
Expand All @@ -39,7 +40,7 @@ use reth_rpc_eth_api::{
RpcNodeCoreExt, RpcTypes,
helpers::{
EthApiSpec, EthFees, EthState, EthSubscriptions, LoadFee, LoadPendingBlock, LoadState,
SpawnBlocking, Trace, bal::GetBlockAccessList, pending_block::BuildPendingEnv,
SpawnBlocking, Trace, bal::GetBlockAccessList,
},
};
use reth_rpc_eth_types::{
Expand Down Expand Up @@ -589,11 +590,7 @@ impl<NetworkT> OpEthApiBuilder<NetworkT> {
impl<N, NetworkT> EthApiBuilder<N> for OpEthApiBuilder<NetworkT>
where
N: FullNodeComponents<
Evm: ConfigureEvm<
NextBlockEnvCtx: BuildPendingEnv<HeaderTy<N::Types>>
+ From<OpFlashblockPayloadBase>
+ Unpin,
>,
Evm: ConfigureEvm<NextBlockEnvCtx = OpNextBlockEnvAttributes>,
Types: NodeTypes<
ChainSpec: Hardforks + EthereumHardforks,
Payload: reth_node_api::PayloadTypes<
Expand Down Expand Up @@ -626,6 +623,7 @@ where
RpcConverter::new(OpReceiptConverter::new(ctx.components.provider().clone()))
.with_mapper(OpTxInfoMapper::new(ctx.components.provider().clone()))
.with_tx_env_converter(reth_optimism_evm::tx::OpTxEnvConverter);
let pending_block_time = ctx.components.provider().chain_spec().block_time();

let sequencer_client = if let Some(url) = sequencer_url {
Some(
Expand Down Expand Up @@ -675,7 +673,11 @@ where
None
};

let eth_api = ctx.eth_api_builder().with_rpc_converter(rpc_converter).build_inner();
let eth_api = ctx
.eth_api_builder()
.with_rpc_converter(rpc_converter)
.with_pending_env_builder(OpPendingEnvBuilder::new(pending_block_time))
.build_inner();

Ok(OpEthApi::new(
eth_api,
Expand Down
Loading