Skip to main content

reth_bb/
main.rs

1//! reth-bb: a modified reth node for benchmarking big block execution.
2#![allow(missing_docs)]
3
4#[global_allocator]
5static ALLOC: reth_cli_util::allocator::Allocator = reth_cli_util::allocator::new_allocator();
6
7mod evm_config;
8
9use alloy_consensus::Header;
10use alloy_primitives::Bytes;
11use alloy_rpc_types::engine::ExecutionData;
12use clap::Parser;
13use evm_config::{BbEvmConfig, BigBlockData};
14use reth_chainspec::{ChainSpec, EthChainSpec, EthereumHardforks};
15use reth_consensus::noop::NoopConsensus;
16use reth_ethereum_cli::{chainspec::EthereumChainSpecParser, interface::Cli};
17use reth_ethereum_primitives::{Block, EthPrimitives};
18use reth_node_api::{
19    AddOnsContext, FullNodeComponents, NewPayloadError, NodeTypes, PayloadTypes, PayloadValidator,
20};
21use reth_node_builder::{
22    components::{
23        BasicPayloadServiceBuilder, ComponentsBuilder, ConsensusBuilder, ExecutorBuilder,
24    },
25    node::FullNodeTypes,
26    rpc::{NoopEngineApiBuilder, PayloadValidatorBuilder, RpcAddOns},
27    BuilderContext, Node, NodeAdapter,
28};
29use reth_node_core::args::DefaultEngineValues;
30use reth_node_ethereum::{
31    EthPayloadTypes, EthereumEngineValidator, EthereumEthApiBuilder, EthereumExecutorBuilder,
32    EthereumNetworkBuilder, EthereumNode, EthereumPayloadBuilder, EthereumPoolBuilder,
33};
34use reth_primitives_traits::SealedBlock;
35use reth_provider::EthStorage;
36use std::sync::Arc;
37use tracing::info;
38
39#[derive(Debug, Clone, Default)]
40pub struct BbPayloadTypes;
41
42impl PayloadTypes for BbPayloadTypes {
43    type ExecutionData = BigBlockData<ExecutionData>;
44    type BuiltPayload = <EthPayloadTypes as PayloadTypes>::BuiltPayload;
45    type PayloadAttributes = <EthPayloadTypes as PayloadTypes>::PayloadAttributes;
46
47    fn block_to_payload(
48        _block: SealedBlock<
49                <<Self::BuiltPayload as reth_node_api::BuiltPayload>::Primitives as reth_node_api::NodePrimitives>::Block,
50            >,
51        _bal: Option<Bytes>,
52    ) -> Self::ExecutionData {
53        unreachable!()
54    }
55}
56
57#[derive(Debug, Default, Clone)]
58pub struct BbEngineValidatorBuilder;
59
60impl<Node> PayloadValidatorBuilder<Node> for BbEngineValidatorBuilder
61where
62    Node: FullNodeComponents<Types = BbNode>,
63{
64    type Validator = BbEngineValidator;
65
66    async fn build(self, ctx: &AddOnsContext<'_, Node>) -> eyre::Result<Self::Validator> {
67        Ok(BbEngineValidator { inner: EthereumEngineValidator::new(ctx.config.chain.clone()) })
68    }
69}
70
71#[derive(Debug, Clone)]
72pub struct BbEngineValidator {
73    inner: EthereumEngineValidator,
74}
75
76impl PayloadValidator<BbPayloadTypes> for BbEngineValidator {
77    type Block = Block;
78
79    fn convert_payload_to_block(
80        &self,
81        payload: BigBlockData<ExecutionData>,
82    ) -> Result<Arc<SealedBlock<Block>>, NewPayloadError> {
83        if payload.env_switches.is_empty() {
84            return Err(NewPayloadError::other(std::io::Error::new(
85                std::io::ErrorKind::InvalidData,
86                "big-block payload has no environment segments",
87            )))
88        }
89
90        let mut blocks = payload
91            .env_switches
92            .into_iter()
93            .map(|data| {
94                PayloadValidator::<EthPayloadTypes>::convert_payload_to_block(&self.inner, data)
95                    .map(Arc::unwrap_or_clone)
96            })
97            .collect::<Result<Vec<SealedBlock<Block>>, NewPayloadError>>()?;
98
99        let (mut block, hash) = blocks.pop().unwrap().split();
100
101        // Override the block number
102        block.header.number = payload.block_number;
103
104        // Set block's parent hash to the parent of the first block in this batch so that engine
105        // tree state is consistent.
106        if let Some(first) = blocks.first() {
107            block.header.parent_hash = first.parent_hash;
108        }
109
110        // Update block's gas usage to make sure metrics are correct
111        block.header.gas_used += blocks.iter().map(|b| b.gas_used).sum::<u64>();
112        block.header.gas_limit += blocks.iter().map(|b| b.gas_limit).sum::<u64>();
113
114        // Prepend transactions from previous blocks to make sure that persistence indices are
115        // correct.
116        block.body.transactions = blocks
117            .into_iter()
118            .flat_map(|b| b.into_body().transactions)
119            .chain(core::mem::take(&mut block.body.transactions))
120            .collect();
121
122        // Use `new_unchecked` to preserve the hash
123        Ok(Arc::new(SealedBlock::new_unchecked(block, hash)))
124    }
125}
126
127// ---------------------------------------------------------------------------
128// Custom executor builder
129// ---------------------------------------------------------------------------
130
131/// Executor builder that creates a [`BbEvmConfig`].
132#[derive(Debug, Default)]
133#[non_exhaustive]
134pub struct BbExecutorBuilder;
135
136impl<Node> ExecutorBuilder<Node> for BbExecutorBuilder
137where
138    Node: FullNodeTypes<
139        Types: NodeTypes<
140            ChainSpec: reth_ethereum_forks::Hardforks
141                           + EthChainSpec<Header = Header>
142                           + EthereumHardforks,
143            Primitives = EthPrimitives,
144        >,
145    >,
146{
147    type EVM = BbEvmConfig<<Node::Types as NodeTypes>::ChainSpec>;
148
149    async fn build_evm(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::EVM> {
150        Ok(BbEvmConfig::new(EthereumExecutorBuilder::default().build_evm(ctx).await?))
151    }
152}
153
154// ---------------------------------------------------------------------------
155// Node type
156// ---------------------------------------------------------------------------
157
158/// Node type for big block execution.
159#[derive(Debug, Clone, Default)]
160#[non_exhaustive]
161pub struct BbNode;
162
163impl NodeTypes for BbNode {
164    type Primitives = EthPrimitives;
165    type ChainSpec = ChainSpec;
166    type Storage = EthStorage;
167    type Payload = BbPayloadTypes;
168}
169
170impl<N> Node<N> for BbNode
171where
172    N: FullNodeTypes<Types = Self>,
173{
174    type ComponentsBuilder = ComponentsBuilder<
175        N,
176        EthereumPoolBuilder,
177        BasicPayloadServiceBuilder<EthereumPayloadBuilder>,
178        EthereumNetworkBuilder,
179        BbExecutorBuilder,
180        BbConsensusBuilder,
181    >;
182
183    type AddOns = RpcAddOns<
184        NodeAdapter<N>,
185        EthereumEthApiBuilder,
186        BbEngineValidatorBuilder,
187        NoopEngineApiBuilder,
188    >;
189
190    fn components_builder(&self) -> Self::ComponentsBuilder {
191        EthereumNode::components()
192            .executor(BbExecutorBuilder::default())
193            .consensus(BbConsensusBuilder)
194    }
195
196    fn add_ons(&self) -> Self::AddOns {
197        Default::default()
198    }
199}
200
201// ---------------------------------------------------------------------------
202// Consensus builder
203// ---------------------------------------------------------------------------
204
205/// Consensus builder for big block execution.
206#[derive(Debug, Default, Clone, Copy)]
207pub struct BbConsensusBuilder;
208
209impl<Node> ConsensusBuilder<Node> for BbConsensusBuilder
210where
211    Node: FullNodeTypes<Types: NodeTypes<Primitives = EthPrimitives>>,
212{
213    type Consensus = NoopConsensus;
214
215    async fn build_consensus(self, _ctx: &BuilderContext<Node>) -> eyre::Result<Self::Consensus> {
216        Ok(NoopConsensus::default())
217    }
218}
219
220// ---------------------------------------------------------------------------
221// Main
222// ---------------------------------------------------------------------------
223
224fn main() {
225    #[cfg(feature = "jit")]
226    match reth_node_ethereum::node::maybe_run_jit_helper() {
227        Ok(std::ops::ControlFlow::Break(())) => return,
228        Ok(std::ops::ControlFlow::Continue(())) => {}
229        Err(err) => {
230            eprintln!("Error: {err:?}");
231            std::process::exit(1);
232        }
233    }
234
235    reth_cli_util::sigsegv_handler::install();
236
237    reth_node_core::version::try_init_version_metadata(reth_node_core::reth_version_metadata!())
238        .expect("version metadata is set once, before anything reads it");
239
240    if std::env::var_os("RUST_BACKTRACE").is_none() {
241        unsafe { std::env::set_var("RUST_BACKTRACE", "1") };
242    }
243
244    let _ = DefaultEngineValues::default().with_bal_parallel_execution_disabled(false).try_init();
245
246    if let Err(err) = Cli::<EthereumChainSpecParser>::parse().run(async move |builder, _| {
247        info!(target: "reth::cli", "Launching big block node");
248        let handle = builder.launch_node(BbNode::default()).await?;
249
250        handle.wait_for_node_exit().await
251    }) {
252        eprintln!("Error: {err:?}");
253        std::process::exit(1);
254    }
255}