-
Notifications
You must be signed in to change notification settings - Fork 83
feat: add block metering RPC endpoints #216
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
Open
niran
wants to merge
2
commits into
main
Choose a base branch
from
meter-block
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| use std::{sync::Arc, time::Instant}; | ||
|
|
||
| use alloy_consensus::{BlockHeader, transaction::SignerRecoverable}; | ||
| use alloy_primitives::B256; | ||
| use eyre::{Result as EyreResult, eyre}; | ||
| use reth::revm::db::State; | ||
| use reth_evm::{ConfigureEvm, execute::BlockBuilder}; | ||
| use reth_optimism_chainspec::OpChainSpec; | ||
| use reth_optimism_evm::{OpEvmConfig, OpNextBlockEnvAttributes}; | ||
| use reth_optimism_primitives::OpBlock; | ||
| use reth_primitives_traits::{Block as BlockT, SealedHeader}; | ||
| use reth_provider::{HashedPostStateProvider, StateRootProvider}; | ||
|
|
||
| use crate::types::{MeterBlockResponse, MeterBlockTransactions}; | ||
|
|
||
| /// Re-executes a block and meters execution time, state root calculation time, and total time. | ||
| /// | ||
| /// Takes a state provider at the parent block, the chain spec, and the block to meter. | ||
| /// | ||
| /// Returns `MeterBlockResponse` containing: | ||
| /// - Block hash | ||
| /// - EVM execution time for all transactions | ||
| /// - State root calculation time | ||
| /// - Total time | ||
| /// - Per-transaction timing information | ||
| pub fn meter_block<SP>( | ||
| state_provider: SP, | ||
| chain_spec: Arc<OpChainSpec>, | ||
| block: &OpBlock, | ||
| parent_header: &SealedHeader, | ||
| ) -> EyreResult<MeterBlockResponse> | ||
| where | ||
| SP: reth_provider::StateProvider + StateRootProvider + HashedPostStateProvider, | ||
| { | ||
| let block_hash = block.header().hash_slow(); | ||
| let block_number = block.header().number(); | ||
| let transactions: Vec<_> = block.body().transactions().cloned().collect(); | ||
| let tx_count = transactions.len(); | ||
|
|
||
| // Create state database from parent state | ||
| let state_db = reth::revm::database::StateProviderDatabase::new(&state_provider); | ||
| let mut db = State::builder().with_database(state_db).with_bundle_update().build(); | ||
|
|
||
| // Set up block attributes from the actual block header | ||
| let attributes = OpNextBlockEnvAttributes { | ||
| timestamp: block.header().timestamp(), | ||
| suggested_fee_recipient: block.header().beneficiary(), | ||
| prev_randao: block.header().mix_hash().unwrap_or(B256::random()), | ||
| gas_limit: block.header().gas_limit(), | ||
| parent_beacon_block_root: block.header().parent_beacon_block_root(), | ||
| extra_data: block.header().extra_data().clone(), | ||
| }; | ||
|
|
||
| // Execute transactions and measure time | ||
| let mut transaction_times = Vec::with_capacity(tx_count); | ||
|
|
||
| let evm_start = Instant::now(); | ||
| { | ||
| let evm_config = OpEvmConfig::optimism(chain_spec); | ||
| let mut builder = evm_config.builder_for_next_block(&mut db, parent_header, attributes)?; | ||
|
|
||
| builder.apply_pre_execution_changes()?; | ||
|
|
||
| for tx in &transactions { | ||
| let tx_start = Instant::now(); | ||
| let tx_hash = tx.tx_hash(); | ||
|
|
||
| // Recover the signer to create a Recovered transaction for execution | ||
| let signer = tx | ||
| .recover_signer() | ||
| .map_err(|e| eyre!("Failed to recover signer for tx {}: {}", tx_hash, e))?; | ||
| let recovered_tx = | ||
| alloy_consensus::transaction::Recovered::new_unchecked(tx.clone(), signer); | ||
|
|
||
| let gas_used = builder | ||
| .execute_transaction(recovered_tx) | ||
| .map_err(|e| eyre!("Transaction {} execution failed: {}", tx_hash, e))?; | ||
|
|
||
| let execution_time = tx_start.elapsed().as_micros(); | ||
|
|
||
| transaction_times.push(MeterBlockTransactions { | ||
| tx_hash, | ||
| gas_used, | ||
| execution_time_us: execution_time, | ||
| }); | ||
| } | ||
| } | ||
| let execution_time = evm_start.elapsed().as_micros(); | ||
|
|
||
| // Calculate state root and measure time | ||
| let state_root_start = Instant::now(); | ||
| let bundle_state = db.bundle_state.clone(); | ||
| let hashed_state = state_provider.hashed_post_state(&bundle_state); | ||
| let _state_root = state_provider | ||
| .state_root(hashed_state) | ||
| .map_err(|e| eyre!("Failed to calculate state root: {}", e))?; | ||
| let state_root_time = state_root_start.elapsed().as_micros(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This may depend heavily on the age of the block, as historical tries may need to be fully recomputed from state diffs. |
||
|
|
||
| let total_time = execution_time + state_root_time; | ||
|
|
||
| Ok(MeterBlockResponse { | ||
| block_hash, | ||
| block_number, | ||
| execution_time_us: execution_time, | ||
| state_root_time_us: state_root_time, | ||
| total_time_us: total_time, | ||
| transactions: transaction_times, | ||
| }) | ||
| } | ||
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,12 @@ | ||
| mod meter; | ||
| mod block; | ||
| mod bundle; | ||
| mod rpc; | ||
| #[cfg(test)] | ||
| mod tests; | ||
| mod types; | ||
|
|
||
| pub use meter::meter_bundle; | ||
| pub use block::meter_block; | ||
| pub use bundle::meter_bundle; | ||
| pub use rpc::{MeteringApiImpl, MeteringApiServer}; | ||
| pub use tips_core::types::{Bundle, MeterBundleResponse, TransactionResult}; | ||
| pub use types::{MeterBlockResponse, MeterBlockTransactions}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| // TODO: Move these types to tips-core alongside MeterBundleResponse | ||
|
|
||
| use alloy_primitives::B256; | ||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| /// Response for block metering RPC calls. | ||
| /// Contains the block hash plus timing information for EVM execution and state root calculation. | ||
| #[derive(Debug, Clone, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct MeterBlockResponse { | ||
| /// The block hash that was metered | ||
| pub block_hash: B256, | ||
| /// The block number that was metered | ||
| pub block_number: u64, | ||
| /// Duration of EVM execution in microseconds | ||
| pub execution_time_us: u128, | ||
| /// Duration of state root calculation in microseconds | ||
| pub state_root_time_us: u128, | ||
| /// Total duration (EVM execution + state root calculation) in microseconds | ||
| pub total_time_us: u128, | ||
| /// Per-transaction metering data | ||
| pub transactions: Vec<MeterBlockTransactions>, | ||
| } | ||
|
|
||
| /// Metering data for a single transaction | ||
| #[derive(Debug, Clone, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct MeterBlockTransactions { | ||
| /// Transaction hash | ||
| pub tx_hash: B256, | ||
| /// Gas used by this transaction | ||
| pub gas_used: u64, | ||
| /// Execution time in microseconds | ||
| pub execution_time_us: u128, | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would expect signer recovery to not be part of the metered tx execution time. This is something that can always be parallelized, so we should probably record this separately.