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

refactor: rename BundleStateWithReceipts to BlockExecutionOutcome #8730

Merged
merged 10 commits into from
Jun 11, 2024
12 changes: 6 additions & 6 deletions bin/reth/src/commands/debug_cmd/build_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,17 +272,17 @@ impl Command {

let BlockExecutionOutput { state, receipts, requests, .. } =
executor.execute((&block_with_senders.clone().unseal(), U256::MAX).into())?;
let state = BlockExecutionOutcome::new(
let block_execution_outcome = BlockExecutionOutcome::new(
state,
receipts.into(),
block.number,
vec![requests.into()],
);

debug!(target: "reth::cli", ?state, "Executed block");
debug!(target: "reth::cli", ?block_execution_outcome, "Executed block");

let hashed_state = state.hash_state_slow();
let (state_root, trie_updates) = state
let hashed_post_state = block_execution_outcome.hash_state_slow();
let (state_root, trie_updates) = block_execution_outcome
.hash_state_slow()
.state_root_with_updates(provider_factory.provider()?.tx_ref())?;

Expand All @@ -298,8 +298,8 @@ impl Command {
let provider_rw = provider_factory.provider_rw()?;
provider_rw.append_blocks_with_state(
Vec::from([block_with_senders]),
state,
hashed_state,
block_execution_outcome,
hashed_post_state,
trie_updates,
None,
)?;
Expand Down
10 changes: 7 additions & 3 deletions bin/reth/src/commands/debug_cmd/in_memory_merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,12 @@ impl Command {
)
.into(),
)?;
let block_state =
let block_execution_outcome =
BlockExecutionOutcome::new(state, receipts.into(), block.number, vec![requests.into()]);

// Unpacked `BundleState::state_root_slow` function
let (in_memory_state_root, in_memory_updates) =
block_state.hash_state_slow().state_root_with_updates(provider.tx_ref())?;
block_execution_outcome.hash_state_slow().state_root_with_updates(provider.tx_ref())?;

if in_memory_state_root == block.state_root {
info!(target: "reth::cli", state_root = ?in_memory_state_root, "Computed in-memory state root matches");
Expand All @@ -168,7 +168,11 @@ impl Command {
.map_err(|_| BlockValidationError::SenderRecoveryError)?,
None,
)?;
block_state.write_to_storage(provider_rw.tx_ref(), None, OriginalValuesKnown::No)?;
block_execution_outcome.write_to_storage(
provider_rw.tx_ref(),
None,
OriginalValuesKnown::No,
)?;
let storage_lists = provider_rw.changed_storages_with_range(block.number..=block.number)?;
let storages = provider_rw.plain_state_storages(storage_lists)?;
provider_rw.insert_storage_for_hashing(storages)?;
Expand Down
4 changes: 2 additions & 2 deletions bin/reth/src/commands/import_receipts_op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ where
// We're reusing receipt writing code internal to
// `BlockExecutionOutcome::write_to_storage`, so we just use a default empty
// `BundleState`.
let bundled_state = BlockExecutionOutcome::new(
let block_execution_outcome = BlockExecutionOutcome::new(
Default::default(),
receipts,
first_block,
Expand All @@ -143,7 +143,7 @@ where
static_file_provider.get_writer(first_block, StaticFileSegment::Receipts)?;

// finally, write the receipts
bundled_state.write_to_storage::<DB::TXMut>(
block_execution_outcome.write_to_storage::<DB::TXMut>(
&tx,
Some(static_file_producer),
OriginalValuesKnown::Yes,
Expand Down
26 changes: 15 additions & 11 deletions crates/blockchain-tree/src/blockchain_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::{
metrics::{MakeCanonicalAction, MakeCanonicalDurationsRecorder, TreeMetrics},
state::{BlockchainId, TreeState},
AppendableChain, BlockIndices, BlockchainTreeConfig, BundleStateData, TreeExternals,
AppendableChain, BlockExecutionData, BlockIndices, BlockchainTreeConfig, TreeExternals,
};
use reth_blockchain_tree_api::{
error::{BlockchainTreeError, CanonicalError, InsertBlockError, InsertBlockErrorKind},
Expand Down Expand Up @@ -264,7 +264,7 @@ where
/// * block unknown.
/// * `chain_id` not present in state.
/// * there are no parent hashes stored.
pub fn post_state_data(&self, block_hash: BlockHash) -> Option<BundleStateData> {
pub fn post_state_data(&self, block_hash: BlockHash) -> Option<BlockExecutionData> {
trace!(target: "blockchain_tree", ?block_hash, "Searching for post state data");

let canonical_chain = self.state.block_indices.canonical_chain();
Expand All @@ -278,7 +278,7 @@ where
return None;
};
let block_number = chain.block_number(block_hash)?;
let state = chain.state_at_block(block_number)?;
let block_execution_outcome = chain.block_execution_outcome_at_block(block_number)?;

// get parent hashes
let mut parent_block_hashes = self.all_chain_hashes(chain_id);
Expand All @@ -295,15 +295,19 @@ where

// get canonical fork.
let canonical_fork = self.canonical_fork(chain_id)?;
return Some(BundleStateData { state, parent_block_hashes, canonical_fork })
return Some(BlockExecutionData {
block_execution_outcome,
parent_block_hashes,
canonical_fork,
})
}

// check if there is canonical block
if let Some(canonical_number) = canonical_chain.canonical_number(&block_hash) {
trace!(target: "blockchain_tree", %block_hash, "Constructing post state data based on canonical chain");
return Some(BundleStateData {
return Some(BlockExecutionData {
canonical_fork: ForkBlock { number: canonical_number, hash: block_hash },
state: BlockExecutionOutcome::default(),
block_execution_outcome: BlockExecutionOutcome::default(),
parent_block_hashes: canonical_chain.inner().clone(),
})
}
Expand Down Expand Up @@ -629,8 +633,8 @@ where
let chains_to_bump = self.find_all_dependent_chains(&hash);
if !chains_to_bump.is_empty() {
// if there is such chain, revert state to this block.
let mut cloned_state = chain.state().clone();
cloned_state.revert_to(*number);
let mut cloned_block_execution_outcome = chain.block_execution_outcome().clone();
cloned_block_execution_outcome.revert_to(*number);

// prepend state to all chains that fork from this block.
for chain_id in chains_to_bump {
Expand All @@ -645,7 +649,7 @@ where
chain_tip = ?chain.tip().num_hash(),
"Prepend unwound block state to blockchain tree chain");

chain.prepend_state(cloned_state.state().clone())
chain.prepend_state(cloned_block_execution_outcome.state().clone())
}
}
}
Expand Down Expand Up @@ -1961,12 +1965,12 @@ mod tests {
]))
.assert(&tree);
// chain 0 has two blocks so receipts and reverts len is 2
let chain0 = tree.state.chains.get(&0.into()).unwrap().state();
let chain0 = tree.state.chains.get(&0.into()).unwrap().block_execution_outcome();
assert_eq!(chain0.receipts().len(), 2);
assert_eq!(chain0.state().reverts.len(), 2);
assert_eq!(chain0.first_block(), block1.number);
// chain 1 has one block so receipts and reverts len is 1
let chain1 = tree.state.chains.get(&1.into()).unwrap().state();
let chain1 = tree.state.chains.get(&1.into()).unwrap().block_execution_outcome();
assert_eq!(chain1.receipts().len(), 1);
assert_eq!(chain1.state().reverts.len(), 1);
assert_eq!(chain1.first_block(), block2.number);
Expand Down
36 changes: 19 additions & 17 deletions crates/blockchain-tree/src/bundle.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
//! [`BundleStateDataProvider`] implementations used by the tree.
//! [`BlockExecutionDataProvider`] implementations used by the tree.

use reth_primitives::{BlockHash, BlockNumber, ForkBlock};
use reth_provider::{BlockExecutionOutcome, BundleStateDataProvider, BundleStateForkProvider};
use reth_provider::{
BlockExecutionDataProvider, BlockExecutionForkProvider, BlockExecutionOutcome,
};
use std::collections::BTreeMap;

/// Structure that combines references of required data to be a [`BundleStateDataProvider`].
/// Structure that combines references of required data to be a [`BlockExecutionDataProvider`].
#[derive(Clone, Debug)]
pub struct BundleStateDataRef<'a> {
/// The wrapped state after execution of one or more transactions and/or blocks.
pub state: &'a BlockExecutionOutcome,
/// The block execution outcome after execution of one or more transactions and/or blocks.
pub block_execution_outcome: &'a BlockExecutionOutcome,
/// The blocks in the sidechain.
pub sidechain_block_hashes: &'a BTreeMap<BlockNumber, BlockHash>,
/// The blocks in the canonical chain.
Expand All @@ -17,9 +19,9 @@ pub struct BundleStateDataRef<'a> {
pub canonical_fork: ForkBlock,
}

impl<'a> BundleStateDataProvider for BundleStateDataRef<'a> {
fn state(&self) -> &BlockExecutionOutcome {
self.state
impl<'a> BlockExecutionDataProvider for BundleStateDataRef<'a> {
fn block_execution_outcome(&self) -> &BlockExecutionOutcome {
self.block_execution_outcome
}

fn block_hash(&self, block_number: BlockNumber) -> Option<BlockHash> {
Expand All @@ -32,17 +34,17 @@ impl<'a> BundleStateDataProvider for BundleStateDataRef<'a> {
}
}

impl<'a> BundleStateForkProvider for BundleStateDataRef<'a> {
impl<'a> BlockExecutionForkProvider for BundleStateDataRef<'a> {
fn canonical_fork(&self) -> ForkBlock {
self.canonical_fork
}
}

/// Structure that owns the relevant data needs to be a [`BundleStateDataProvider`]
/// Structure that owns the relevant data needs to be a [`BlockExecutionDataProvider`]
#[derive(Clone, Debug)]
pub struct BundleStateData {
/// Post state with changes
pub state: BlockExecutionOutcome,
pub struct BlockExecutionData {
/// Block execution outcome.
pub block_execution_outcome: BlockExecutionOutcome,
/// Parent block hashes needs for evm BLOCKHASH opcode.
/// NOTE: it does not mean that all hashes are there but all until finalized are there.
/// Other hashes can be obtained from provider
Expand All @@ -51,17 +53,17 @@ pub struct BundleStateData {
pub canonical_fork: ForkBlock,
}

impl BundleStateDataProvider for BundleStateData {
fn state(&self) -> &BlockExecutionOutcome {
&self.state
impl BlockExecutionDataProvider for BlockExecutionData {
fn block_execution_outcome(&self) -> &BlockExecutionOutcome {
&self.block_execution_outcome
}

fn block_hash(&self, block_number: BlockNumber) -> Option<BlockHash> {
self.parent_block_hashes.get(&block_number).cloned()
}
}

impl BundleStateForkProvider for BundleStateData {
impl BlockExecutionForkProvider for BlockExecutionData {
fn canonical_fork(&self) -> ForkBlock {
self.canonical_fork
}
Expand Down
39 changes: 20 additions & 19 deletions crates/blockchain-tree/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@ impl AppendableChain {
DB: Database + Clone,
E: BlockExecutorProvider,
{
let state = BlockExecutionOutcome::default();
let block_execution_outcome = BlockExecutionOutcome::default();
let empty = BTreeMap::new();

let state_provider = BundleStateDataRef {
state: &state,
block_execution_outcome: &block_execution_outcome,
sidechain_block_hashes: &empty,
canonical_block_hashes,
canonical_fork,
Expand Down Expand Up @@ -122,14 +122,14 @@ impl AppendableChain {
BlockchainTreeError::BlockNumberNotFoundInChain { block_number: parent_number },
)?;

let mut state = self.state().clone();
let mut block_execution_outcome = self.block_execution_outcome().clone();

// Revert state to the state after execution of the parent block
state.revert_to(parent.number);
block_execution_outcome.revert_to(parent.number);

// Revert changesets to get the state of the parent that we need to apply the change.
let bundle_state_data = BundleStateDataRef {
state: &state,
block_execution_outcome: &block_execution_outcome,
sidechain_block_hashes: &side_chain_block_hashes,
canonical_block_hashes,
canonical_fork,
Expand All @@ -144,17 +144,17 @@ impl AppendableChain {
)?;
// extending will also optimize few things, mostly related to selfdestruct and wiping of
// storage.
state.extend(block_state);
block_execution_outcome.extend(block_state);

// remove all receipts and reverts (except the last one), as they belong to the chain we
// forked from and not the new chain we are creating.
let size = state.receipts().len();
state.receipts_mut().drain(0..size - 1);
state.state_mut().take_n_reverts(size - 1);
state.set_first_block(block.number);
let size = block_execution_outcome.receipts().len();
block_execution_outcome.receipts_mut().drain(0..size - 1);
block_execution_outcome.state_mut().take_n_reverts(size - 1);
block_execution_outcome.set_first_block(block.number);

// If all is okay, return new chain back. Present chain is not modified.
Ok(Self { chain: Chain::from_block(block, state, None) })
Ok(Self { chain: Chain::from_block(block, block_execution_outcome, None) })
}

/// Validate and execute the given block that _extends the canonical chain_, validating its
Expand Down Expand Up @@ -214,7 +214,7 @@ impl AppendableChain {
.consensus
.validate_block_post_execution(&block, PostExecutionInput::new(&receipts, &requests))?;

let bundle_state =
let block_execution_outcome =
BlockExecutionOutcome::new(state, receipts.into(), block.number, vec![requests.into()]);

// check state root if the block extends the canonical chain __and__ if state root
Expand All @@ -223,15 +223,16 @@ impl AppendableChain {
// calculate and check state root
let start = Instant::now();
let (state_root, trie_updates) = if block_attachment.is_canonical() {
let mut state = provider.bundle_state_data_provider.state().clone();
state.extend(bundle_state.clone());
let hashed_state = state.hash_state_slow();
let mut block_execution_outcome =
provider.block_execution_data_provider.block_execution_outcome().clone();
block_execution_outcome.extend(block_execution_outcome.clone());
let hashed_state = block_execution_outcome.hash_state_slow();
ParallelStateRoot::new(consistent_view, hashed_state)
.incremental_root_with_updates()
.map(|(root, updates)| (root, Some(updates)))
.map_err(ProviderError::from)?
} else {
(provider.state_root(bundle_state.state())?, None)
(provider.state_root(block_execution_outcome.state())?, None)
};
if block.state_root != state_root {
return Err(ConsensusError::BodyStateRootDiff(
Expand All @@ -248,9 +249,9 @@ impl AppendableChain {
"Validated state root"
);

Ok((bundle_state, trie_updates))
Ok((block_execution_outcome, trie_updates))
} else {
Ok((bundle_state, None))
Ok((block_execution_outcome, None))
}
}

Expand Down Expand Up @@ -284,7 +285,7 @@ impl AppendableChain {
let parent_block = self.chain.tip();

let bundle_state_data = BundleStateDataRef {
state: self.state(),
block_execution_outcome: self.block_execution_outcome(),
sidechain_block_hashes: &side_chain_block_hashes,
canonical_block_hashes,
canonical_fork,
Expand Down
2 changes: 1 addition & 1 deletion crates/blockchain-tree/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub mod shareable;
pub use shareable::ShareableBlockchainTree;

mod bundle;
pub use bundle::{BundleStateData, BundleStateDataRef};
pub use bundle::{BlockExecutionData, BundleStateDataRef};

/// Buffer of not executed blocks.
pub mod block_buffer;
Expand Down
8 changes: 4 additions & 4 deletions crates/consensus/auto-seal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ impl StorageInner {
// execute the block
let BlockExecutionOutput { state, receipts, requests: block_execution_requests, .. } =
executor.executor(&mut db).execute((&block, U256::ZERO).into())?;
let bundle_state = BlockExecutionOutcome::new(
let block_execution_outcome = BlockExecutionOutcome::new(
state,
receipts.into(),
block.number,
Expand All @@ -405,10 +405,10 @@ impl StorageInner {
let Block { mut header, body, .. } = block.block;
let body = BlockBody { transactions: body, ommers, withdrawals, requests };

trace!(target: "consensus::auto", ?bundle_state, ?header, ?body, "executed block, calculating state root and completing header");
trace!(target: "consensus::auto", ?block_execution_outcome, ?header, ?body, "executed block, calculating state root and completing header");

// calculate the state root
header.state_root = db.state_root(bundle_state.state())?;
header.state_root = db.state_root(block_execution_outcome.state())?;
trace!(target: "consensus::auto", root=?header.state_root, ?body, "calculated root");

// finally insert into storage
Expand All @@ -417,6 +417,6 @@ impl StorageInner {
// set new header with hash that should have been updated by insert_new_block
let new_header = header.seal(self.best_hash);

Ok((new_header, bundle_state))
Ok((new_header, block_execution_outcome))
}
}
Loading
Loading