reth_bench/bench/
new_payload_only.rs

1//! Runs the `reth bench` command, sending only newPayload, without a forkchoiceUpdated call.
2
3use crate::{
4    bench::{
5        context::BenchContext,
6        output::{
7            NewPayloadResult, TotalGasOutput, TotalGasRow, GAS_OUTPUT_SUFFIX,
8            NEW_PAYLOAD_OUTPUT_SUFFIX,
9        },
10    },
11    valid_payload::{block_to_new_payload, call_new_payload},
12};
13use alloy_provider::Provider;
14use clap::Parser;
15use csv::Writer;
16use eyre::{Context, OptionExt};
17use reth_cli_runner::CliContext;
18use reth_node_core::args::BenchmarkArgs;
19use std::time::{Duration, Instant};
20use tracing::{debug, info};
21
22/// `reth benchmark new-payload-only` command
23#[derive(Debug, Parser)]
24pub struct Command {
25    /// The RPC url to use for getting data.
26    #[arg(long, value_name = "RPC_URL", verbatim_doc_comment)]
27    rpc_url: String,
28
29    /// The size of the block buffer (channel capacity) for prefetching blocks from the RPC
30    /// endpoint.
31    #[arg(
32        long = "rpc-block-buffer-size",
33        value_name = "RPC_BLOCK_BUFFER_SIZE",
34        default_value = "20",
35        verbatim_doc_comment
36    )]
37    rpc_block_buffer_size: usize,
38
39    #[command(flatten)]
40    benchmark: BenchmarkArgs,
41}
42
43impl Command {
44    /// Execute `benchmark new-payload-only` command
45    pub async fn execute(self, _ctx: CliContext) -> eyre::Result<()> {
46        let BenchContext {
47            benchmark_mode,
48            block_provider,
49            auth_provider,
50            mut next_block,
51            is_optimism,
52            ..
53        } = BenchContext::new(&self.benchmark, self.rpc_url).await?;
54
55        let buffer_size = self.rpc_block_buffer_size;
56
57        // Use a oneshot channel to propagate errors from the spawned task
58        let (error_sender, mut error_receiver) = tokio::sync::oneshot::channel();
59        let (sender, mut receiver) = tokio::sync::mpsc::channel(buffer_size);
60
61        tokio::task::spawn(async move {
62            while benchmark_mode.contains(next_block) {
63                let block_res = block_provider
64                    .get_block_by_number(next_block.into())
65                    .full()
66                    .await
67                    .wrap_err_with(|| format!("Failed to fetch block by number {next_block}"));
68                let block = match block_res.and_then(|opt| opt.ok_or_eyre("Block not found")) {
69                    Ok(block) => block,
70                    Err(e) => {
71                        tracing::error!("Failed to fetch block {next_block}: {e}");
72                        let _ = error_sender.send(e);
73                        break;
74                    }
75                };
76
77                next_block += 1;
78                if let Err(e) = sender.send(block).await {
79                    tracing::error!("Failed to send block data: {e}");
80                    break;
81                }
82            }
83        });
84
85        // put results in a summary vec so they can be printed at the end
86        let mut results = Vec::new();
87        let total_benchmark_duration = Instant::now();
88        let mut total_wait_time = Duration::ZERO;
89
90        while let Some(block) = {
91            let wait_start = Instant::now();
92            let result = receiver.recv().await;
93            total_wait_time += wait_start.elapsed();
94            result
95        } {
96            let block_number = block.header.number;
97            let transaction_count = block.transactions.len() as u64;
98            let gas_used = block.header.gas_used;
99
100            debug!(number=?block.header.number, "Sending payload to engine");
101
102            let (version, params) = block_to_new_payload(block, is_optimism)?;
103
104            let start = Instant::now();
105            call_new_payload(&auth_provider, version, params).await?;
106
107            let new_payload_result = NewPayloadResult { gas_used, latency: start.elapsed() };
108            info!(%new_payload_result);
109
110            // current duration since the start of the benchmark minus the time
111            // waiting for blocks
112            let current_duration = total_benchmark_duration.elapsed() - total_wait_time;
113
114            // record the current result
115            let row =
116                TotalGasRow { block_number, transaction_count, gas_used, time: current_duration };
117            results.push((row, new_payload_result));
118        }
119
120        // Check if the spawned task encountered an error
121        if let Ok(error) = error_receiver.try_recv() {
122            return Err(error);
123        }
124
125        let (gas_output_results, new_payload_results): (_, Vec<NewPayloadResult>) =
126            results.into_iter().unzip();
127
128        // write the csv output to files
129        if let Some(path) = self.benchmark.output {
130            // first write the new payload results to a file
131            let output_path = path.join(NEW_PAYLOAD_OUTPUT_SUFFIX);
132            info!("Writing newPayload call latency output to file: {:?}", output_path);
133            let mut writer = Writer::from_path(output_path)?;
134            for result in new_payload_results {
135                writer.serialize(result)?;
136            }
137            writer.flush()?;
138
139            // now write the gas output to a file
140            let output_path = path.join(GAS_OUTPUT_SUFFIX);
141            info!("Writing total gas output to file: {:?}", output_path);
142            let mut writer = Writer::from_path(output_path)?;
143            for row in &gas_output_results {
144                writer.serialize(row)?;
145            }
146            writer.flush()?;
147
148            info!("Finished writing benchmark output files to {:?}.", path);
149        }
150
151        // accumulate the results and calculate the overall Ggas/s
152        let gas_output = TotalGasOutput::new(gas_output_results)?;
153        info!(
154            total_duration=?gas_output.total_duration,
155            total_gas_used=?gas_output.total_gas_used,
156            blocks_processed=?gas_output.blocks_processed,
157            "Total Ggas/s: {:.4}",
158            gas_output.total_gigagas_per_second()
159        );
160
161        Ok(())
162    }
163}