Skip to content

Commit

Permalink
chore: remove total difficulty from execution types
Browse files Browse the repository at this point in the history
  • Loading branch information
Rjected committed Dec 20, 2024
1 parent 8d214e4 commit 171537d
Show file tree
Hide file tree
Showing 44 changed files with 370 additions and 612 deletions.
2 changes: 1 addition & 1 deletion bin/reth/src/commands/debug_cmd/build_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ impl<C: ChainSpecParser<ChainSpec = ChainSpec>> Command<C> {
EthExecutorProvider::ethereum(provider_factory.chain_spec()).executor(db);

let block_execution_output =
executor.execute((&block_with_senders.clone().unseal(), U256::MAX).into())?;
executor.execute(&block_with_senders.clone().unseal())?;
let execution_outcome =
ExecutionOutcome::from((block_execution_output, block.number));
debug!(target: "reth::cli", ?execution_outcome, "Executed block");
Expand Down
22 changes: 7 additions & 15 deletions bin/reth/src/commands/debug_cmd/in_memory_merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ use reth_node_ethereum::EthExecutorProvider;
use reth_primitives::BlockExt;
use reth_provider::{
providers::ProviderNodeTypes, AccountExtReader, ChainSpecProvider, DatabaseProviderFactory,
HashedPostStateProvider, HashingWriter, HeaderProvider, LatestStateProviderRef,
OriginalValuesKnown, ProviderFactory, StageCheckpointReader, StateWriter, StorageLocation,
StorageReader,
HashedPostStateProvider, HashingWriter, LatestStateProviderRef, OriginalValuesKnown,
ProviderFactory, StageCheckpointReader, StateWriter, StorageLocation, StorageReader,
};
use reth_revm::database::StateProviderDatabase;
use reth_stages::StageId;
Expand Down Expand Up @@ -148,19 +147,12 @@ impl<C: ChainSpecParser<ChainSpec = ChainSpec>> Command<C> {
let db = StateProviderDatabase::new(&state_provider);

let executor = EthExecutorProvider::ethereum(provider_factory.chain_spec()).executor(db);

let merkle_block_td =
provider.header_td_by_number(merkle_block_number)?.unwrap_or_default();
let block_execution_output = executor.execute(
(
&block
.clone()
.unseal::<BlockTy<N>>()
.with_recovered_senders()
.ok_or(BlockValidationError::SenderRecoveryError)?,
merkle_block_td + block.difficulty,
)
.into(),
&block
.clone()
.unseal::<BlockTy<N>>()
.with_recovered_senders()
.ok_or(BlockValidationError::SenderRecoveryError)?,
)?;
let execution_outcome = ExecutionOutcome::from((block_execution_output, block.number));

Expand Down
2 changes: 1 addition & 1 deletion bin/reth/src/commands/debug_cmd/merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl<C: ChainSpecParser<ChainSpec = ChainSpec>> Command<C> {
let mut executor = executor_provider.batch_executor(StateProviderDatabase::new(
LatestStateProviderRef::new(&provider_rw),
));
executor.execute_and_verify_one((&sealed_block.clone().unseal(), td).into())?;
executor.execute_and_verify_one(&sealed_block.clone().unseal())?;
let execution_outcome = executor.finalize();

provider_rw.write_state(
Expand Down
18 changes: 16 additions & 2 deletions crates/blockchain-tree/src/blockchain_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,12 +393,16 @@ where
let provider = self.externals.provider_factory.provider()?;

// Validate that the block is post merge
let parent_td = provider
.header_td(&block.parent_hash)?
.ok_or_else(|| BlockchainTreeError::CanonicalChain { block_hash: block.parent_hash })?;

if !self
.externals
.provider_factory
.chain_spec()
.fork(EthereumHardfork::Paris)
.active_at_ttd(block.number)
.active_at_ttd(parent_td, U256::ZERO)
{
return Err(BlockExecutionError::Validation(BlockValidationError::BlockPreMerge {
hash: block.hash(),
Expand Down Expand Up @@ -1023,12 +1027,22 @@ where
durations_recorder.record_relative(MakeCanonicalAction::FindCanonicalHeader);
if let Some(header) = canonical_header {
info!(target: "blockchain_tree", %block_hash, "Block is already canonical, ignoring.");
// TODO: this could be fetched from the chainspec first
let td =
self.externals.provider_factory.provider()?.header_td(&block_hash)?.ok_or_else(
|| {
CanonicalError::from(BlockValidationError::MissingTotalDifficulty {
hash: block_hash,
})
},
)?;

if !self
.externals
.provider_factory
.chain_spec()
.fork(EthereumHardfork::Paris)
.active_at_ttd(header.number)
.active_at_ttd(td, U256::ZERO)
{
return Err(CanonicalError::from(BlockValidationError::BlockPreMerge {
hash: block_hash,
Expand Down
4 changes: 2 additions & 2 deletions crates/blockchain-tree/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use super::externals::TreeExternals;
use crate::BundleStateDataRef;
use alloy_eips::ForkBlock;
use alloy_primitives::{BlockHash, BlockNumber, U256};
use alloy_primitives::{BlockHash, BlockNumber};
use reth_blockchain_tree_api::{
error::{BlockchainTreeError, InsertBlockErrorKind},
BlockAttachment, BlockValidationKind,
Expand Down Expand Up @@ -209,7 +209,7 @@ impl AppendableChain {
let block_hash = block.hash();
let block = block.unseal();

let state = executor.execute((&block, U256::MAX).into())?;
let state = executor.execute(&block)?;
externals.consensus.validate_block_post_execution(
&block,
PostExecutionInput::new(&state.receipts, &state.requests),
Expand Down
29 changes: 20 additions & 9 deletions crates/chainspec/src/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ impl ChainSpec {

/// Returns the hardfork display helper.
pub fn display_hardforks(&self) -> DisplayHardforks {
DisplayHardforks::new(&self, self.paris_block_and_final_difficulty.map(|(block, _)| block))
DisplayHardforks::new(&self)
}

/// Get the fork id for the given hardfork.
Expand Down Expand Up @@ -609,9 +609,12 @@ impl From<Genesis> for ChainSpec {
hardforks.push((
EthereumHardfork::Paris.boxed(),
ForkCondition::TTD {
activation_block_number: genesis.config.merge_netsplit_block.expect("Merge netsplit block is required"),
total_difficulty: ttd,
activation_block_number: genesis
.config
.merge_netsplit_block
.expect("TODO: remove"),
fork_block: genesis.config.merge_netsplit_block,
total_difficulty: ttd,
},
));

Expand Down Expand Up @@ -847,7 +850,11 @@ impl ChainSpecBuilder {
self = self.london_activated();
self.hardforks.insert(
EthereumHardfork::Paris,
ForkCondition::TTD { activation_block_number: 0, total_difficulty: U256::ZERO, fork_block: None },
ForkCondition::TTD {
activation_block_number: 0,
total_difficulty: U256::ZERO,
fork_block: None,
},
);
self
}
Expand Down Expand Up @@ -889,7 +896,7 @@ impl ChainSpecBuilder {
pub fn build(self) -> ChainSpec {
let paris_block_and_final_difficulty = {
self.hardforks.get(EthereumHardfork::Paris).and_then(|cond| {
if let ForkCondition::TTD { total_difficulty, fork_block, .. } = cond {
if let ForkCondition::TTD { total_difficulty, fork_block, .. } = cond {
fork_block.map(|fork_block| (fork_block, total_difficulty))
} else {
None
Expand Down Expand Up @@ -1673,14 +1680,18 @@ Post-merge hard forks (timestamp based):
let chainspec = ChainSpecBuilder::mainnet().build();

// Check that Paris is not active on terminal PoW block #15537393.
let terminal_block_ttd = U256::from(58750003716598352816469_u128);
let terminal_block_difficulty = U256::from(11055787484078698_u128);
assert!(!chainspec
.fork(EthereumHardfork::Paris)
.active_at_ttd(15537393));
.active_at_ttd(terminal_block_ttd, terminal_block_difficulty));

// Check that Paris is active on first PoS block #15537394.
let first_pos_block_ttd = U256::from(58750003716598352816469_u128);
let first_pos_difficulty = U256::ZERO;
assert!(chainspec
.fork(EthereumHardfork::Paris)
.active_at_ttd(15537394));
.fork(EthereumHardfork::Paris)
.active_at_ttd(first_pos_block_ttd, first_pos_difficulty));
}

#[test]
Expand Down Expand Up @@ -2163,7 +2174,7 @@ Post-merge hard forks (timestamp based):
fn holesky_paris_activated_at_genesis() {
assert!(HOLESKY
.fork(EthereumHardfork::Paris)
.active_at_ttd(0));
.active_at_ttd(HOLESKY.genesis.difficulty, HOLESKY.genesis.difficulty));
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions crates/consensus/beacon/src/engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1991,7 +1991,7 @@ mod tests {
};
use alloy_rpc_types_engine::{ForkchoiceState, ForkchoiceUpdated, PayloadStatus};
use assert_matches::assert_matches;
use reth_chainspec::{ChainSpecBuilder, EthereumHardfork, MAINNET};
use reth_chainspec::{ChainSpecBuilder, MAINNET};
use reth_node_types::FullNodePrimitives;
use reth_primitives::BlockExt;
use reth_provider::{BlockWriter, ProviderFactory, StorageLocation};
Expand Down Expand Up @@ -2458,7 +2458,7 @@ mod tests {
.chain(MAINNET.chain)
.genesis(MAINNET.genesis.clone())
.london_activated()
.paris_at_ttd( U256::from(3), EthereumHardfork::London.activation_block(MAINNET.chain).unwrap())
.paris_at_ttd(U256::from(3), 1)
.build(),
);

Expand Down
19 changes: 8 additions & 11 deletions crates/consensus/common/src/calc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use alloy_consensus::constants::ETH_TO_WEI;
use alloy_primitives::{BlockNumber, U256};
use alloy_primitives::BlockNumber;
use reth_chainspec::{EthereumHardfork, Hardforks};

/// Calculates the base block reward.
Expand All @@ -21,13 +21,9 @@ use reth_chainspec::{EthereumHardfork, Hardforks};
/// - Definition: [Yellow Paper][yp] (page 15, 11.3)
///
/// [yp]: https://ethereum.github.io/yellowpaper/paper.pdf
pub fn base_block_reward(
chain_spec: impl Hardforks,
block_number: BlockNumber,
_block_difficulty: U256,
_total_difficulty: U256,
) -> Option<u128> {
if chain_spec.fork(EthereumHardfork::Paris).active_at_ttd(block_number) {
pub fn base_block_reward(chain_spec: impl Hardforks, block_number: BlockNumber) -> Option<u128> {
// TODO: check if mainnet vs sepolia
if Some(block_number) > EthereumHardfork::Paris.mainnet_activation_block() {
None
} else {
Some(base_block_reward_pre_merge(chain_spec, block_number))
Expand Down Expand Up @@ -113,6 +109,7 @@ pub const fn ommer_reward(
#[cfg(test)]
mod tests {
use super::*;
use alloy_primitives::U256;
use reth_chainspec::MAINNET;

#[test]
Expand All @@ -126,11 +123,11 @@ mod tests {
// Petersburg
((7280000, U256::ZERO), Some(ETH_TO_WEI * 2)),
// Merge
((20000000, U256::from(58_750_000_000_000_000_000_000_u128)), None),
((10000000, U256::from(58_750_000_000_000_000_000_000_u128)), None),
];

for ((block_number, td), expected_reward) in cases {
assert_eq!(base_block_reward(&*MAINNET, block_number, U256::ZERO, td), expected_reward);
for ((block_number, _td), expected_reward) in cases {
assert_eq!(base_block_reward(&*MAINNET, block_number), expected_reward);
}
}

Expand Down
5 changes: 2 additions & 3 deletions crates/engine/invalid-block-hooks/src/witness.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use alloy_consensus::BlockHeader;
use alloy_primitives::{keccak256, B256, U256};
use alloy_primitives::{keccak256, B256};
use alloy_rpc_types_debug::ExecutionWitness;
use eyre::OptionExt;
use pretty_assertions::Comparison;
Expand Down Expand Up @@ -79,7 +79,7 @@ where

// Setup environment for the execution.
let EvmEnv { cfg_env_with_handler_cfg, block_env } =
self.evm_config.cfg_and_block_env(block.header(), U256::MAX);
self.evm_config.cfg_and_block_env(block.header());

// Setup EVM
let mut evm = self.evm_config.evm_with_env(
Expand Down Expand Up @@ -116,7 +116,6 @@ where
let balance_increments = post_block_balance_increments(
self.provider.chain_spec().as_ref(),
&block.clone().unseal().block,
U256::MAX,
);

// increment balances
Expand Down
6 changes: 1 addition & 5 deletions crates/engine/tree/src/tree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2261,11 +2261,7 @@ where
// };
let state_hook = Box::new(|_state: &EvmState| {});

let output = self.metrics.executor.execute_metered(
executor,
(&block, U256::MAX).into(),
state_hook,
)?;
let output = self.metrics.executor.execute_metered(executor, &block, state_hook)?;

trace!(target: "engine::tree", elapsed=?exec_time.elapsed(), ?block_number, "Executed block");

Expand Down
3 changes: 1 addition & 2 deletions crates/engine/util/src/reorg.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Stream wrapper that simulates reorgs.
use alloy_consensus::{Header, Transaction};
use alloy_primitives::U256;
use alloy_rpc_types_engine::{
CancunPayloadFields, ExecutionPayload, ExecutionPayloadSidecar, ForkchoiceState, PayloadStatus,
};
Expand Down Expand Up @@ -299,7 +298,7 @@ where

// Configure environments
let EvmEnv { cfg_env_with_handler_cfg, block_env } =
evm_config.cfg_and_block_env(&reorg_target.header, U256::MAX);
evm_config.cfg_and_block_env(&reorg_target.header);
let env = EnvWithHandlerCfg::new_with_cfg_env(
cfg_env_with_handler_cfg,
block_env,
Expand Down
9 changes: 6 additions & 3 deletions crates/ethereum-forks/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ impl core::fmt::Display for DisplayHardforks {

impl DisplayHardforks {
/// Creates a new [`DisplayHardforks`] from an iterator of hardforks.
pub fn new<H: Hardforks>(hardforks: &H, known_paris_block: Option<u64>) -> Self {
pub fn new<H: Hardforks>(hardforks: &H) -> Self {
let mut pre_merge = Vec::new();
let mut with_merge = Vec::new();
let mut post_merge = Vec::new();
Expand All @@ -155,8 +155,11 @@ impl DisplayHardforks {
pre_merge.push(display_fork);
}
ForkCondition::TTD { activation_block_number, total_difficulty, fork_block } => {
display_fork.activated_at =
ForkCondition::TTD { activation_block_number, fork_block, total_difficulty };
display_fork.activated_at = ForkCondition::TTD {
activation_block_number,
fork_block,
total_difficulty,
};
with_merge.push(display_fork);
}
ForkCondition::Timestamp(_) => {
Expand Down
Loading

0 comments on commit 171537d

Please sign in to comment.