Skip to main content

reth_node_core/args/
payload_builder.rs

1use crate::{cli::config::PayloadBuilderConfig, version::default_extra_data};
2use alloy_consensus::constants::MAXIMUM_EXTRA_DATA_SIZE;
3use alloy_primitives::{hex, Bytes};
4use clap::{
5    builder::{RangedU64ValueParser, TypedValueParser},
6    Arg, Args, Command,
7};
8use reth_cli_util::{
9    parse_duration_from_secs, parse_duration_from_secs_or_ms,
10    parsers::format_duration_as_secs_or_ms,
11};
12use std::{ffi::OsStr, sync::OnceLock, time::Duration};
13
14/// Registered defaults and the decoded extra data used to construct node configs.
15static PAYLOAD_BUILDER_DEFAULTS: OnceLock<(DefaultPayloadBuilderValues, Bytes)> = OnceLock::new();
16
17/// Default values for payload builder that can be customized
18///
19/// Global defaults can be set via [`DefaultPayloadBuilderValues::try_init`].
20#[derive(Debug, Clone)]
21pub struct DefaultPayloadBuilderValues {
22    /// Default extra data for blocks
23    extra_data: String,
24    /// Default interval between payload builds in seconds
25    interval: String,
26    /// Default deadline for payload builds in seconds
27    deadline: String,
28    /// Default maximum number of concurrent payload building tasks
29    max_payload_tasks: usize,
30}
31
32impl DefaultPayloadBuilderValues {
33    /// Initialize the global payload builder defaults with this configuration.
34    ///
35    /// Returns the supplied configuration if defaults are already installed or the extra data
36    /// is invalid. Use [`Self::try_init_detailed`] to distinguish the two cases.
37    pub fn try_init(self) -> Result<(), Self> {
38        self.try_init_detailed().map_err(|err| match err {
39            PayloadBuilderDefaultsError::AlreadyInitialized(defaults) |
40            PayloadBuilderDefaultsError::InvalidExtraData { defaults, .. } => defaults,
41        })
42    }
43
44    /// Initialize the global payload builder defaults, returning the reason for failure.
45    ///
46    /// Returns [`PayloadBuilderDefaultsError::AlreadyInitialized`] if defaults are already
47    /// installed. [`PayloadBuilderDefaultsError::InvalidExtraData`] returns the configuration
48    /// for correction without initializing the defaults.
49    pub fn try_init_detailed(self) -> Result<(), PayloadBuilderDefaultsError> {
50        if PAYLOAD_BUILDER_DEFAULTS.get().is_some() {
51            return Err(PayloadBuilderDefaultsError::AlreadyInitialized(self));
52        }
53        let extra_data = match decode_extra_data(&self.extra_data) {
54            Ok(bytes) => bytes,
55            Err(source) => {
56                return Err(PayloadBuilderDefaultsError::InvalidExtraData { defaults: self, source })
57            }
58        };
59        PAYLOAD_BUILDER_DEFAULTS
60            .set((self, extra_data))
61            .map_err(|(defaults, _)| PayloadBuilderDefaultsError::AlreadyInitialized(defaults))
62    }
63
64    /// Get a reference to the global payload builder defaults
65    pub fn get_global() -> &'static Self {
66        &Self::global().0
67    }
68
69    /// Set the default extra data as `0x`-prefixed hex or plain UTF-8 text.
70    ///
71    /// [`Self::try_init`] checks the hex encoding. The 32-byte limit is enforced when the CLI
72    /// parses the default, since programmatic configs may target chains with a higher limit.
73    pub fn with_extra_data(mut self, v: impl Into<String>) -> Self {
74        self.extra_data = v.into();
75        self
76    }
77
78    /// Set the default interval in seconds
79    pub fn with_interval(mut self, v: Duration) -> Self {
80        self.interval = format_duration_as_secs_or_ms(v);
81        self
82    }
83
84    /// Set the default deadline in seconds
85    pub fn with_deadline(mut self, v: u64) -> Self {
86        self.deadline = format!("{}", v);
87        self
88    }
89
90    /// Set the default maximum payload tasks
91    pub const fn with_max_payload_tasks(mut self, v: usize) -> Self {
92        self.max_payload_tasks = v;
93        self
94    }
95
96    fn global() -> &'static (Self, Bytes) {
97        PAYLOAD_BUILDER_DEFAULTS.get_or_init(|| {
98            let defaults = Self::default();
99            let extra_data = Bytes::copy_from_slice(defaults.extra_data.as_bytes());
100            (defaults, extra_data)
101        })
102    }
103}
104
105impl Default for DefaultPayloadBuilderValues {
106    fn default() -> Self {
107        Self {
108            extra_data: default_extra_data(),
109            interval: "1".to_string(),
110            deadline: "12".to_string(),
111            max_payload_tasks: 3,
112        }
113    }
114}
115
116/// Parameters for configuring the Payload Builder
117#[derive(Debug, Clone, Args, PartialEq, Eq)]
118#[command(next_help_heading = "Builder")]
119pub struct PayloadBuilderArgs {
120    /// Block extra data set by the payload builder.
121    ///
122    /// If the value is a `0x`-prefixed hex string, it is decoded into raw bytes. Otherwise, the
123    /// raw UTF-8 bytes of the string are used.
124    #[arg(
125        long = "builder.extradata",
126        value_parser = ExtraDataValueParser::default(),
127        default_value = DefaultPayloadBuilderValues::get_global().extra_data.as_str()
128    )]
129    pub extra_data: Bytes,
130
131    /// Target gas limit for built blocks.
132    #[arg(long = "builder.gaslimit", alias = "miner.gaslimit", value_name = "GAS_LIMIT")]
133    pub gas_limit: Option<u64>,
134
135    /// The interval at which the job should build a new payload after the last.
136    ///
137    /// Interval is specified in seconds or in milliseconds if the value ends with `ms`:
138    ///   * `50ms` -> 50 milliseconds
139    ///   * `1` -> 1 second
140    #[arg(
141        long = "builder.interval",
142        value_parser = parse_duration_from_secs_or_ms,
143        default_value = DefaultPayloadBuilderValues::get_global().interval.as_str(),
144        value_name = "DURATION"
145    )]
146    pub interval: Duration,
147
148    /// The deadline for when the payload builder job should resolve.
149    #[arg(
150        long = "builder.deadline",
151        value_parser = parse_duration_from_secs,
152        default_value = DefaultPayloadBuilderValues::get_global().deadline.as_str(),
153        value_name = "SECONDS"
154    )]
155    pub deadline: Duration,
156
157    /// Maximum number of tasks to spawn for building a payload.
158    #[arg(
159        long = "builder.max-tasks",
160        value_parser = RangedU64ValueParser::<usize>::new().range(1..),
161        default_value_t = DefaultPayloadBuilderValues::get_global().max_payload_tasks
162    )]
163    pub max_payload_tasks: usize,
164
165    /// Maximum number of blobs to include per block.
166    #[arg(long = "builder.max-blobs", value_name = "COUNT")]
167    pub max_blobs_per_block: Option<u64>,
168}
169
170impl Default for PayloadBuilderArgs {
171    fn default() -> Self {
172        let (defaults, extra_data) = DefaultPayloadBuilderValues::global();
173        Self {
174            extra_data: extra_data.clone(),
175            interval: parse_duration_from_secs_or_ms(defaults.interval.as_str()).unwrap(),
176            gas_limit: None,
177            deadline: Duration::from_secs(defaults.deadline.parse().unwrap()),
178            max_payload_tasks: defaults.max_payload_tasks,
179            max_blobs_per_block: None,
180        }
181    }
182}
183
184impl PayloadBuilderConfig for PayloadBuilderArgs {
185    fn extra_data(&self) -> Bytes {
186        self.extra_data.clone()
187    }
188
189    fn interval(&self) -> Duration {
190        self.interval
191    }
192
193    fn deadline(&self) -> Duration {
194        self.deadline
195    }
196
197    fn gas_limit(&self) -> Option<u64> {
198        self.gas_limit
199    }
200
201    fn max_payload_tasks(&self) -> usize {
202        self.max_payload_tasks
203    }
204
205    fn max_blobs_per_block(&self) -> Option<u64> {
206        self.max_blobs_per_block
207    }
208}
209
210/// Failure to register global payload builder defaults. Both variants return the supplied values.
211#[derive(Debug, thiserror::Error)]
212pub enum PayloadBuilderDefaultsError {
213    /// Another configuration has already been installed.
214    #[error("payload builder defaults already initialized")]
215    AlreadyInitialized(DefaultPayloadBuilderValues),
216    /// The supplied `0x`-prefixed extra data is not valid hex and was not installed.
217    #[error("invalid hex in payload builder default extra data")]
218    InvalidExtraData {
219        /// The supplied defaults, which can be corrected and submitted again.
220        defaults: DefaultPayloadBuilderValues,
221        /// The reason the extra data was rejected.
222        source: hex::FromHexError,
223    },
224}
225
226#[derive(Clone, Debug, Default)]
227#[non_exhaustive]
228struct ExtraDataValueParser;
229
230impl TypedValueParser for ExtraDataValueParser {
231    type Value = Bytes;
232
233    fn parse_ref(
234        &self,
235        _cmd: &Command,
236        _arg: Option<&Arg>,
237        value: &OsStr,
238    ) -> Result<Self::Value, clap::Error> {
239        let val =
240            value.to_str().ok_or_else(|| clap::Error::new(clap::error::ErrorKind::InvalidUtf8))?;
241
242        let max_len = if val.starts_with("0x") {
243            "0x".len() + 2 * MAXIMUM_EXTRA_DATA_SIZE
244        } else {
245            MAXIMUM_EXTRA_DATA_SIZE
246        };
247        if val.len() > max_len {
248            return Err(clap::Error::raw(
249                clap::error::ErrorKind::InvalidValue,
250                format!(
251                    "Payload builder extradata size exceeds {MAXIMUM_EXTRA_DATA_SIZE}-byte limit"
252                ),
253            ))
254        }
255
256        decode_extra_data(val).map_err(|e| {
257            clap::Error::raw(
258                clap::error::ErrorKind::InvalidValue,
259                format!("Invalid hex in extradata: {e}"),
260            )
261        })
262    }
263}
264
265/// Decodes `0x`-prefixed hex and keeps any other value as UTF-8 bytes.
266fn decode_extra_data(val: &str) -> Result<Bytes, hex::FromHexError> {
267    if val.starts_with("0x") {
268        hex::decode(val).map(Bytes::from)
269    } else {
270        Ok(Bytes::copy_from_slice(val.as_bytes()))
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277    use clap::Parser;
278
279    /// A helper type to parse Args more easily
280    #[derive(Debug, Parser)]
281    struct CommandParser<T: Args> {
282        #[command(flatten)]
283        args: T,
284    }
285
286    #[test]
287    fn test_args_with_valid_max_tasks() {
288        let args =
289            CommandParser::<PayloadBuilderArgs>::parse_from(["reth", "--builder.max-tasks", "1"])
290                .args;
291        assert_eq!(args.max_payload_tasks, 1)
292    }
293
294    #[test]
295    fn test_args_with_invalid_max_tasks() {
296        assert!(CommandParser::<PayloadBuilderArgs>::try_parse_from([
297            "reth",
298            "--builder.max-tasks",
299            "0"
300        ])
301        .is_err());
302    }
303
304    #[test]
305    fn test_default_extra_data() {
306        let extra_data = default_extra_data();
307        let args = CommandParser::<PayloadBuilderArgs>::parse_from([
308            "reth",
309            "--builder.extradata",
310            extra_data.as_str(),
311        ])
312        .args;
313        assert_eq!(args.extra_data.as_ref(), extra_data.as_bytes());
314    }
315
316    #[test]
317    fn test_invalid_extra_data() {
318        let extra_data = "x".repeat(MAXIMUM_EXTRA_DATA_SIZE + 1);
319        let args = CommandParser::<PayloadBuilderArgs>::try_parse_from([
320            "reth",
321            "--builder.extradata",
322            extra_data.as_str(),
323        ]);
324        assert!(args.is_err());
325    }
326
327    #[test]
328    fn test_valid_hex_extra_data() {
329        let hex = format!("0x{}", "ab".repeat(MAXIMUM_EXTRA_DATA_SIZE));
330        let args = CommandParser::<PayloadBuilderArgs>::parse_from([
331            "reth",
332            "--builder.extradata",
333            hex.as_str(),
334        ])
335        .args;
336        assert_eq!(args.extra_data.as_ref(), vec![0xab; MAXIMUM_EXTRA_DATA_SIZE].as_slice());
337    }
338
339    #[test]
340    fn test_oversized_hex_extra_data() {
341        let hex = format!("0x{}", "ab".repeat(MAXIMUM_EXTRA_DATA_SIZE + 1));
342        assert!(CommandParser::<PayloadBuilderArgs>::try_parse_from([
343            "reth",
344            "--builder.extradata",
345            hex.as_str(),
346        ])
347        .is_err());
348    }
349
350    #[test]
351    fn extra_data_size_is_checked_before_hex_decoding() {
352        let oversized = format!("0x{}zz", "ff".repeat(MAXIMUM_EXTRA_DATA_SIZE));
353        let err = ExtraDataValueParser
354            .parse_ref(&Command::new("reth"), None, OsStr::new(&oversized))
355            .unwrap_err();
356        assert_eq!(err.kind(), clap::error::ErrorKind::InvalidValue);
357        assert_eq!(
358            err.to_string(),
359            format!("error: Payload builder extradata size exceeds {MAXIMUM_EXTRA_DATA_SIZE}-byte limit")
360        );
361    }
362
363    #[test]
364    fn test_invalid_hex_extra_data() {
365        for invalid in ["0xZZZZ", "0x0x", "0x0xab", "0x0Xab"] {
366            let err = CommandParser::<PayloadBuilderArgs>::try_parse_from([
367                "reth",
368                "--builder.extradata",
369                invalid,
370            ])
371            .unwrap_err();
372            assert_eq!(err.kind(), clap::error::ErrorKind::InvalidValue);
373        }
374    }
375
376    #[test]
377    fn test_odd_length_hex_extra_data() {
378        assert!(CommandParser::<PayloadBuilderArgs>::try_parse_from([
379            "reth",
380            "--builder.extradata",
381            "0xabc",
382        ])
383        .is_err());
384    }
385
386    #[test]
387    fn payload_builder_args_default_sanity_check() {
388        let default_args = PayloadBuilderArgs::default();
389        let args = CommandParser::<PayloadBuilderArgs>::parse_from(["reth"]).args;
390        assert_eq!(args, default_args);
391    }
392
393    #[test]
394    fn test_args_with_s_interval() {
395        let args =
396            CommandParser::<PayloadBuilderArgs>::parse_from(["reth", "--builder.interval", "50"])
397                .args;
398        assert_eq!(args.interval, Duration::from_secs(50));
399    }
400
401    #[test]
402    fn test_args_with_ms_interval() {
403        let args =
404            CommandParser::<PayloadBuilderArgs>::parse_from(["reth", "--builder.interval", "50ms"])
405                .args;
406        assert_eq!(args.interval, Duration::from_millis(50));
407    }
408}