Skip to main content

reth_basic_payload_builder/
lib.rs

1//! A basic payload generator for reth.
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10
11use crate::metrics::PayloadBuilderMetrics;
12use alloy_eips::merge::SLOT_DURATION;
13use alloy_primitives::{B256, U256};
14use futures_core::ready;
15use futures_util::FutureExt;
16use reth_chain_state::CanonStateNotification;
17use reth_evm::cached::CachedReads;
18use reth_execution_cache::SavedCache;
19use reth_payload_builder::{
20    BuildNewPayload, KeepPayloadJobAlive, PayloadBuilderLease, PayloadId, PayloadJob,
21    PayloadJobGenerator,
22};
23use reth_payload_builder_primitives::PayloadBuilderError;
24use reth_payload_primitives::{BuiltPayload, PayloadAttributes, PayloadKind};
25use reth_primitives_traits::{AlloyBlockHeader, HeaderTy, NodePrimitives, SealedHeader};
26use reth_storage_api::{BlockReaderIdExt, StateProviderFactory};
27use reth_tasks::{CancelOnDrop, Runtime};
28use reth_trie_parallel::state_root_task::PayloadStateRootHandle;
29use std::{
30    fmt,
31    future::Future,
32    ops::Deref,
33    pin::Pin,
34    sync::Arc,
35    task::{Context, Poll},
36    time::{Duration, SystemTime, UNIX_EPOCH},
37};
38use tokio::{
39    sync::{oneshot, Semaphore},
40    time::{Interval, Sleep},
41};
42use tracing::{debug, debug_span, trace, warn, Span};
43
44mod better_payload_emitter;
45mod metrics;
46mod stack;
47
48pub use better_payload_emitter::BetterPayloadEmitter;
49pub use stack::PayloadBuilderStack;
50
51const PAYLOAD_BUILDER_THREAD_NAME: &str = "payload-builder";
52
53/// Helper to access [`NodePrimitives::BlockHeader`] from [`PayloadBuilder::BuiltPayload`].
54pub type HeaderForPayload<P> = <<P as BuiltPayload>::Primitives as NodePrimitives>::BlockHeader;
55
56/// The [`PayloadJobGenerator`] that creates [`BasicPayloadJob`]s.
57#[derive(Debug)]
58pub struct BasicPayloadJobGenerator<Client, Builder> {
59    /// The client that can interact with the chain.
60    client: Client,
61    /// The task executor to spawn payload building tasks on.
62    executor: Runtime,
63    /// The configuration for the job generator.
64    config: BasicPayloadJobGeneratorConfig,
65    /// Restricts how many generator tasks can be executed at once.
66    payload_task_guard: PayloadTaskGuard,
67    /// The type responsible for building payloads.
68    ///
69    /// See [`PayloadBuilder`]
70    builder: Builder,
71    /// Stored `cached_reads` for new payload jobs.
72    pre_cached: Option<PrecachedState>,
73    /// Stored parent block information for new payload jobs.
74    pre_cached_parent_block_info: Option<PrecachedParentBlockInfo>,
75}
76
77// === impl BasicPayloadJobGenerator ===
78
79impl<Client, Builder> BasicPayloadJobGenerator<Client, Builder> {
80    /// Creates a new [`BasicPayloadJobGenerator`] with the given config and custom
81    /// [`PayloadBuilder`]
82    pub fn with_builder(
83        client: Client,
84        executor: Runtime,
85        config: BasicPayloadJobGeneratorConfig,
86        builder: Builder,
87    ) -> Self {
88        Self {
89            client,
90            executor,
91            payload_task_guard: PayloadTaskGuard::new(config.max_payload_tasks),
92            config,
93            builder,
94            pre_cached: None,
95            pre_cached_parent_block_info: None,
96        }
97    }
98
99    /// Returns the maximum duration a job should be allowed to run.
100    ///
101    /// This adheres to the following specification:
102    /// > Client software SHOULD stop the updating process when either a call to engine_getPayload
103    /// > with the build process's payloadId is made or SECONDS_PER_SLOT (12s in the Mainnet
104    /// > configuration) have passed since the point in time identified by the timestamp parameter.
105    ///
106    /// See also <https://github.com/ethereum/execution-apis/blob/431cf72fd3403d946ca3e3afc36b973fc87e0e89/src/engine/paris.md?plain=1#L137>
107    #[inline]
108    fn max_job_duration(&self, unix_timestamp: u64) -> Duration {
109        let duration_until_timestamp = duration_until(unix_timestamp);
110
111        // safety in case clocks are bad
112        let duration_until_timestamp = duration_until_timestamp.min(self.config.deadline * 3);
113
114        self.config.deadline + duration_until_timestamp
115    }
116
117    /// Returns the [Instant](tokio::time::Instant) at which the job should be terminated because it
118    /// is considered timed out.
119    #[inline]
120    fn job_deadline(&self, unix_timestamp: u64) -> tokio::time::Instant {
121        tokio::time::Instant::now() + self.max_job_duration(unix_timestamp)
122    }
123
124    /// Returns a reference to the tasks type
125    pub const fn tasks(&self) -> &Runtime {
126        &self.executor
127    }
128
129    /// Returns the pre-cached reads for the given parent header if it matches the cached state's
130    /// block.
131    fn maybe_pre_cached(&self, parent: B256) -> Option<CachedReads> {
132        if !self.config.pre_cache_state {
133            return None
134        }
135
136        self.pre_cached.as_ref().filter(|pc| pc.block == parent).map(|pc| pc.cached.clone())
137    }
138
139    /// Returns the cached parent block information if it matches the requested parent.
140    fn maybe_parent_block_info(&self, parent: B256) -> Option<PayloadParentBlockInfo> {
141        self.pre_cached_parent_block_info
142            .as_ref()
143            .filter(|info| info.block == parent)
144            .map(|info| info.parent_block_info)
145    }
146}
147
148// === impl BasicPayloadJobGenerator ===
149
150impl<Client, Builder> PayloadJobGenerator for BasicPayloadJobGenerator<Client, Builder>
151where
152    Client: StateProviderFactory
153        + BlockReaderIdExt<Header = HeaderForPayload<Builder::BuiltPayload>>
154        + Clone
155        + Unpin
156        + 'static,
157    Builder: PayloadBuilder + Unpin + 'static,
158    Builder::Attributes: Unpin + Clone,
159    Builder::BuiltPayload: Unpin + Clone,
160{
161    type Job = BasicPayloadJob<Builder>;
162
163    fn new_payload_job(
164        &self,
165        input: BuildNewPayload<Builder::Attributes>,
166        id: PayloadId,
167    ) -> Result<Self::Job, PayloadBuilderError> {
168        let BuildNewPayload { attributes, parent_hash, mut resources } = input;
169        let parent_header = if parent_hash.is_zero() {
170            // Use latest header for genesis block case
171            self.client
172                .latest_header()?
173                .ok_or_else(|| PayloadBuilderError::MissingParentHeader(B256::ZERO))?
174        } else {
175            // Fetch specific header by hash
176            self.client
177                .sealed_header_by_hash(parent_hash)?
178                .ok_or_else(|| PayloadBuilderError::MissingParentHeader(parent_hash))?
179        };
180
181        let parent_hash = parent_header.hash();
182        let cached_reads = self.maybe_pre_cached(parent_hash);
183        let parent_block_info = self.maybe_parent_block_info(parent_hash);
184
185        let config = PayloadConfig::new(Arc::new(parent_header), attributes, id)
186            .with_parent_block_info(parent_block_info);
187
188        let until = self.job_deadline(config.attributes.timestamp());
189        let deadline = Box::pin(tokio::time::sleep_until(until));
190
191        let mut job = BasicPayloadJob {
192            config,
193            executor: self.executor.clone(),
194            deadline,
195            // The first build is spawned below, so the first tick is due one interval later.
196            interval: tokio::time::interval_at(
197                tokio::time::Instant::now() + self.config.interval,
198                self.config.interval,
199            ),
200            best_payload: PayloadState::Missing,
201            pending_block: None,
202            cached_reads,
203            execution_cache: resources.take_execution_cache(),
204            state_root_handle: resources.take_state_root_handle(),
205            leases: resources.take_leases(),
206            payload_task_guard: self.payload_task_guard.clone(),
207            metrics: Default::default(),
208            builder: self.builder.clone(),
209        };
210
211        // start the first job right away
212        job.spawn_build_job();
213
214        Ok(job)
215    }
216
217    fn on_new_state<N: NodePrimitives>(&mut self, new_state: CanonStateNotification<N>) {
218        if !self.config.pre_cache_state {
219            self.pre_cached = None;
220            return
221        }
222
223        let mut cached = CachedReads::default();
224
225        // extract the state from the notification and put it into the cache
226        let committed = new_state.committed();
227        let new_execution_outcome = committed.execution_outcome();
228        for (addr, acc) in new_execution_outcome.bundle_accounts_iter() {
229            if let Some(info) = acc.info.clone() {
230                // we want pre cache existing accounts and their storage
231                // this only includes changed accounts and storage but is better than nothing
232                let storage =
233                    acc.storage.iter().map(|(key, slot)| (*key, slot.present_value)).collect();
234                cached.insert_account(addr, info, storage);
235            }
236        }
237
238        let tip = committed.tip();
239        let block = tip.hash();
240        let parent_block_info =
241            PayloadParentBlockInfo { transaction_count: tip.transaction_count() };
242
243        self.pre_cached = Some(PrecachedState { block, cached });
244        self.pre_cached_parent_block_info =
245            Some(PrecachedParentBlockInfo { block, parent_block_info });
246    }
247}
248
249/// Pre-filled [`CachedReads`] for a specific block.
250///
251/// This is extracted from the [`CanonStateNotification`] for the tip block.
252#[derive(Debug, Clone)]
253pub struct PrecachedState {
254    /// The block for which the state is pre-cached.
255    pub block: B256,
256    /// Cached state for the block.
257    pub cached: CachedReads,
258}
259
260/// Pre-filled parent block information for a specific block.
261#[derive(Debug, Clone, Copy)]
262struct PrecachedParentBlockInfo {
263    /// The block for which the parent block information is cached.
264    block: B256,
265    /// Cached parent block information.
266    parent_block_info: PayloadParentBlockInfo,
267}
268
269/// Restricts how many generator tasks can be executed at once.
270#[derive(Debug, Clone)]
271pub struct PayloadTaskGuard(Arc<Semaphore>);
272
273impl Deref for PayloadTaskGuard {
274    type Target = Semaphore;
275
276    fn deref(&self) -> &Self::Target {
277        &self.0
278    }
279}
280
281// === impl PayloadTaskGuard ===
282
283impl PayloadTaskGuard {
284    /// Constructs `Self` with a maximum task count of `max_payload_tasks`.
285    pub fn new(max_payload_tasks: usize) -> Self {
286        Self(Arc::new(Semaphore::new(max_payload_tasks)))
287    }
288
289    /// Acquires an owned permit for a payload build task.
290    async fn acquire_owned(&self) -> tokio::sync::OwnedSemaphorePermit {
291        self.0.clone().acquire_owned().await.expect("payload task semaphore closed")
292    }
293}
294
295/// Settings for the [`BasicPayloadJobGenerator`].
296#[derive(Debug, Clone)]
297pub struct BasicPayloadJobGeneratorConfig {
298    /// The interval at which the job should build a new payload after the last.
299    interval: Duration,
300    /// The deadline for when the payload builder job should resolve.
301    ///
302    /// By default this is [`SLOT_DURATION`]: 12s
303    deadline: Duration,
304    /// Maximum number of tasks to spawn for building a payload.
305    max_payload_tasks: usize,
306    /// Whether to pre-cache changed state from canonical state notifications.
307    pre_cache_state: bool,
308}
309
310// === impl BasicPayloadJobGeneratorConfig ===
311
312impl BasicPayloadJobGeneratorConfig {
313    /// Sets the interval at which the job should build a new payload after the last.
314    pub const fn interval(mut self, interval: Duration) -> Self {
315        self.interval = interval;
316        self
317    }
318
319    /// Sets the deadline when this job should resolve.
320    pub const fn deadline(mut self, deadline: Duration) -> Self {
321        self.deadline = deadline;
322        self
323    }
324
325    /// Sets the maximum number of tasks to spawn for building a payload(s).
326    ///
327    /// # Panics
328    ///
329    /// If `max_payload_tasks` is 0.
330    pub fn max_payload_tasks(mut self, max_payload_tasks: usize) -> Self {
331        assert!(max_payload_tasks > 0, "max_payload_tasks must be greater than 0");
332        self.max_payload_tasks = max_payload_tasks;
333        self
334    }
335
336    /// Sets whether to pre-cache changed state from canonical state notifications.
337    ///
338    /// This keeps the parent block's state changes in memory so payload jobs building on top of it
339    /// can reuse those reads.
340    pub const fn pre_cache_state(mut self, pre_cache_state: bool) -> Self {
341        self.pre_cache_state = pre_cache_state;
342        self
343    }
344}
345
346impl Default for BasicPayloadJobGeneratorConfig {
347    fn default() -> Self {
348        Self {
349            interval: Duration::from_secs(1),
350            // 12s slot time
351            deadline: SLOT_DURATION,
352            max_payload_tasks: 3,
353            pre_cache_state: true,
354        }
355    }
356}
357
358/// A basic payload job that continuously builds a payload with the best transactions from the pool.
359///
360/// This type is a [`PayloadJob`] and [`Future`] that terminates when the deadline is reached or
361/// when the job is resolved: [`PayloadJob::resolve`].
362///
363/// This basic job implementation will trigger new payload build task continuously until the job is
364/// resolved or the deadline is reached, or until the built payload is marked as frozen:
365/// [`BuildOutcome::Freeze`]. Once a frozen payload is returned, no additional payloads will be
366/// built and this future will wait to be resolved: [`PayloadJob::resolve`] or terminated if the
367/// deadline is reached.
368#[derive(Debug)]
369pub struct BasicPayloadJob<Builder>
370where
371    Builder: PayloadBuilder,
372{
373    /// The configuration for how the payload will be created.
374    config: PayloadConfig<Builder::Attributes, HeaderForPayload<Builder::BuiltPayload>>,
375    /// How to spawn building tasks
376    executor: Runtime,
377    /// The deadline when this job should resolve.
378    deadline: Pin<Box<Sleep>>,
379    /// The interval at which the job should build a new payload after the last.
380    interval: Interval,
381    /// The best payload so far and its state.
382    best_payload: PayloadState<Builder::BuiltPayload>,
383    /// Receiver for the block that is currently being built.
384    pending_block: Option<PendingPayload<Builder::BuiltPayload>>,
385    /// Restricts how many generator tasks can be executed at once.
386    payload_task_guard: PayloadTaskGuard,
387    /// Caches all disk reads for the state the new payloads builds on
388    ///
389    /// This is used to avoid reading the same state over and over again when new attempts are
390    /// triggered, because during the building process we'll repeatedly execute the transactions.
391    cached_reads: Option<CachedReads>,
392    /// Optional execution cache shared with the engine.
393    execution_cache: Option<SavedCache>,
394    /// Optional state-root task handle, shared with the engine.
395    state_root_handle: Option<PayloadStateRootHandle>,
396    /// Lifecycle leases shared with the payload-builder service.
397    ///
398    /// Every detached build task clones these so that the loaned resources remain available until
399    /// `try_build` completes, even if the payload job is resolved first.
400    leases: Vec<PayloadBuilderLease>,
401    /// metrics for this type
402    metrics: PayloadBuilderMetrics,
403    /// The type responsible for building payloads.
404    ///
405    /// See [`PayloadBuilder`]
406    builder: Builder,
407}
408
409impl<Builder> BasicPayloadJob<Builder>
410where
411    Builder: PayloadBuilder + Unpin + 'static,
412    Builder::Attributes: Unpin + Clone,
413    Builder::BuiltPayload: Unpin + Clone,
414{
415    /// Spawns a new payload build task.
416    fn spawn_build_job(&mut self) {
417        trace!(target: "payload_builder", id = %self.config.payload_id(), "spawn new payload build task");
418        let (tx, rx) = oneshot::channel();
419        let cancel = CancelOnDrop::default();
420        let pending_cancel = cancel.clone();
421        let guard = self.payload_task_guard.clone();
422        let payload_config = self.config.clone();
423        let best_payload = self.best_payload.payload().cloned();
424        self.metrics.inc_initiated_payload_builds();
425        let cached_reads = self.cached_reads.take().unwrap_or_default();
426        let execution_cache = self.execution_cache.clone();
427        let mut state_root_handle = self.state_root_handle.take();
428        let on_payload_built =
429            state_root_handle.as_mut().and_then(PayloadStateRootHandle::take_on_payload_built);
430        let leases = self.leases.clone();
431        let builder = self.builder.clone();
432        let executor = self.executor.clone();
433        let span = Span::current();
434        self.executor.spawn_task(async move {
435            // acquire the permit for executing the task
436            let permit = guard.acquire_owned().await;
437            executor.spawn_blocking_named_or_tokio(PAYLOAD_BUILDER_THREAD_NAME, move || {
438                // Restore the parent even when the worker span is filtered out.
439                let _parent = span.enter();
440                let _span = debug_span!(target: "payload_builder", "build_payload").entered();
441                let _permit = permit;
442                let args = BuildArguments {
443                    cached_reads,
444                    execution_cache,
445                    state_root_handle,
446                    config: payload_config,
447                    cancel,
448                    best_payload,
449                };
450                let result = builder.try_build(args);
451                if let Some(on_payload_built) = on_payload_built &&
452                    let Ok(outcome) = &result &&
453                    let Some(payload) = outcome.payload()
454                {
455                    on_payload_built(payload.block().hash(), payload.block().state_root());
456                }
457                drop(leases);
458                let _ = tx.send(result);
459            });
460        });
461
462        self.pending_block = Some(PendingPayload { cancel: pending_cancel, payload: rx });
463    }
464}
465
466impl<Builder> Future for BasicPayloadJob<Builder>
467where
468    Builder: PayloadBuilder + Unpin + 'static,
469    Builder::Attributes: Unpin + Clone,
470    Builder::BuiltPayload: Unpin + Clone,
471{
472    type Output = Result<(), PayloadBuilderError>;
473
474    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
475        let this = self.get_mut();
476
477        // check if the deadline is reached
478        if this.deadline.as_mut().poll(cx).is_ready() {
479            trace!(target: "payload_builder", "payload building deadline reached");
480            return Poll::Ready(Ok(()))
481        }
482
483        loop {
484            // Wait for any pending build to complete before polling the next tick.
485            //
486            // This avoids consuming interval ticks while a build is still in-flight,
487            // which would delay the follow-up build by a full interval even though
488            // the current attempt has already finished.
489            if let Some(mut fut) = this.pending_block.take() {
490                match fut.poll_unpin(cx) {
491                    Poll::Ready(Ok(outcome)) => match outcome {
492                        BuildOutcome::Better { payload, cached_reads } => {
493                            this.cached_reads = Some(cached_reads);
494                            debug!(target: "payload_builder", value = %payload.fees(), "built better payload");
495                            this.best_payload = PayloadState::Best(payload);
496                        }
497                        BuildOutcome::Freeze(payload) => {
498                            debug!(target: "payload_builder", "payload frozen, no further building will occur");
499                            this.best_payload = PayloadState::Frozen(payload);
500                        }
501                        BuildOutcome::Aborted { fees, cached_reads } => {
502                            this.cached_reads = Some(cached_reads);
503                            trace!(target: "payload_builder", worse_fees = %fees, "skipped payload build of worse block");
504                        }
505                        BuildOutcome::Cancelled => {
506                            unreachable!("the cancel signal never fired")
507                        }
508                    },
509                    Poll::Ready(Err(error)) => {
510                        // job failed, but we simply try again next interval
511                        debug!(target: "payload_builder", %error, "payload build attempt failed");
512                        this.metrics.inc_failed_payload_builds();
513                    }
514                    Poll::Pending => {
515                        this.pending_block = Some(fut);
516                        return Poll::Pending
517                    }
518                }
519            }
520
521            if this.best_payload.is_frozen() {
522                return Poll::Pending
523            }
524
525            // Wait for the next build interval tick.
526            //
527            // The loop is needed because `poll_tick` does not register a waker
528            // when it returns `Ready`, so we must loop back after spawning a job
529            // to reach a point that *does* register one (the pending block poll above).
530            ready!(this.interval.poll_tick(cx));
531            this.spawn_build_job()
532        }
533    }
534}
535
536impl<Builder> PayloadJob for BasicPayloadJob<Builder>
537where
538    Builder: PayloadBuilder + Unpin + 'static,
539    Builder::Attributes: Unpin + Clone,
540    Builder::BuiltPayload: Unpin + Clone,
541{
542    type PayloadAttributes = Builder::Attributes;
543    type ResolvePayloadFuture = ResolveBestPayload<Self::BuiltPayload>;
544    type BuiltPayload = Builder::BuiltPayload;
545
546    fn best_payload(&self) -> Result<Self::BuiltPayload, PayloadBuilderError> {
547        if let Some(payload) = self.best_payload.payload() {
548            Ok(payload.clone())
549        } else {
550            // No payload has been built yet, but we need to return something that the CL then
551            // can deliver, so we need to return an empty payload.
552            //
553            // Note: it is assumed that this is unlikely to happen, as the payload job is
554            // started right away and the first full block should have been
555            // built by the time CL is requesting the payload.
556            self.metrics.inc_requested_empty_payload();
557            self.builder.build_empty_payload(self.config.clone())
558        }
559    }
560
561    fn payload_attributes(&self) -> Result<Self::PayloadAttributes, PayloadBuilderError> {
562        Ok(self.config.attributes.clone())
563    }
564
565    fn payload_timestamp(&self) -> Result<u64, PayloadBuilderError> {
566        Ok(self.config.attributes.timestamp())
567    }
568
569    fn resolve_kind(
570        &mut self,
571        kind: PayloadKind,
572    ) -> (Self::ResolvePayloadFuture, KeepPayloadJobAlive) {
573        let best_payload = self.best_payload.payload().cloned();
574        if best_payload.is_none() && self.pending_block.is_none() {
575            // ensure we have a job scheduled if we don't have a best payload yet and none is active
576            self.spawn_build_job();
577        }
578
579        let maybe_better = self.pending_block.take();
580        let mut empty_payload = None;
581
582        if best_payload.is_none() {
583            if let Some(pending) = maybe_better.as_ref() {
584                pending.cancel.request_finalization();
585            }
586
587            debug!(target: "payload_builder", id=%self.config.payload_id(), "no best payload yet to resolve, building empty payload");
588
589            let args = BuildArguments {
590                cached_reads: self.cached_reads.take().unwrap_or_default(),
591                execution_cache: self.execution_cache.clone(),
592                state_root_handle: None,
593                config: self.config.clone(),
594                cancel: CancelOnDrop::default(),
595                best_payload: None,
596            };
597
598            match self.builder.on_missing_payload(args) {
599                MissingPayloadBehaviour::AwaitInProgress => {
600                    debug!(target: "payload_builder", id=%self.config.payload_id(), "awaiting in progress payload build job");
601                }
602                MissingPayloadBehaviour::RaceEmptyPayload => {
603                    debug!(target: "payload_builder", id=%self.config.payload_id(), "racing empty payload");
604
605                    // if no payload has been built yet
606                    self.metrics.inc_requested_empty_payload();
607                    // no payload built yet, so we need to return an empty payload
608                    let (tx, rx) = oneshot::channel();
609                    let config = self.config.clone();
610                    let builder = self.builder.clone();
611                    let span = Span::current();
612                    self.executor.spawn_blocking_named_or_tokio(
613                        PAYLOAD_BUILDER_THREAD_NAME,
614                        move || {
615                            let _parent = span.enter();
616                            let _span =
617                                debug_span!(target: "payload_builder", "build_empty_payload")
618                                    .entered();
619                            let res = builder.build_empty_payload(config);
620                            let _ = tx.send(res);
621                        },
622                    );
623
624                    empty_payload = Some(rx);
625                }
626                MissingPayloadBehaviour::RacePayload(job) => {
627                    debug!(target: "payload_builder", id=%self.config.payload_id(), "racing fallback payload");
628                    // race the in progress job with this job
629                    let (tx, rx) = oneshot::channel();
630                    let span = Span::current();
631                    self.executor.spawn_blocking_named_or_tokio(
632                        PAYLOAD_BUILDER_THREAD_NAME,
633                        move || {
634                            let _parent = span.enter();
635                            let _span =
636                                debug_span!(target: "payload_builder", "build_fallback_payload")
637                                    .entered();
638                            let _ = tx.send(job());
639                        },
640                    );
641                    empty_payload = Some(rx);
642                }
643            };
644        }
645
646        let fut = ResolveBestPayload {
647            best_payload,
648            maybe_better,
649            empty_payload: empty_payload.filter(|_| kind != PayloadKind::WaitForPending),
650        };
651
652        (fut, KeepPayloadJobAlive::No)
653    }
654}
655
656/// Represents the current state of a payload being built.
657#[derive(Debug, Clone)]
658pub enum PayloadState<P> {
659    /// No payload has been built yet.
660    Missing,
661    /// The best payload built so far, which may still be improved upon.
662    Best(P),
663    /// The payload is frozen and no further building should occur.
664    ///
665    /// Contains the final payload `P` that should be used.
666    Frozen(P),
667}
668
669impl<P> PayloadState<P> {
670    /// Checks if the payload is frozen.
671    pub const fn is_frozen(&self) -> bool {
672        matches!(self, Self::Frozen(_))
673    }
674
675    /// Returns the payload if it exists (either Best or Frozen).
676    pub const fn payload(&self) -> Option<&P> {
677        match self {
678            Self::Missing => None,
679            Self::Best(p) | Self::Frozen(p) => Some(p),
680        }
681    }
682}
683
684/// The future that returns the best payload to be served to the consensus layer.
685///
686/// This returns the payload that's supposed to be sent to the CL.
687///
688/// If payload has been built so far, it will return that, but it will check if there's a better
689/// payload available from an in progress build job. If so it will return that.
690///
691/// If no payload has been built so far, it will either return an empty payload or the result of the
692/// in progress build job, whatever finishes first.
693#[derive(Debug)]
694pub struct ResolveBestPayload<Payload> {
695    /// Best payload so far.
696    pub best_payload: Option<Payload>,
697    /// Regular payload job that's currently running that might produce a better payload.
698    pub maybe_better: Option<PendingPayload<Payload>>,
699    /// The empty payload building job in progress, if any.
700    pub empty_payload: Option<oneshot::Receiver<Result<Payload, PayloadBuilderError>>>,
701}
702
703impl<Payload> ResolveBestPayload<Payload> {
704    const fn is_empty(&self) -> bool {
705        self.best_payload.is_none() && self.maybe_better.is_none() && self.empty_payload.is_none()
706    }
707}
708
709impl<Payload> Future for ResolveBestPayload<Payload>
710where
711    Payload: Unpin,
712{
713    type Output = Result<Payload, PayloadBuilderError>;
714
715    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
716        let this = self.get_mut();
717
718        // check if there is a better payload before returning the best payload
719        if let Some(fut) = Pin::new(&mut this.maybe_better).as_pin_mut() &&
720            let Poll::Ready(res) = fut.poll(cx)
721        {
722            this.maybe_better = None;
723            if let Ok(Some(payload)) = res.map(|out| out.into_payload()).inspect_err(
724                |err| warn!(target: "payload_builder", %err, "failed to resolve pending payload"),
725            ) {
726                debug!(target: "payload_builder", "resolving better payload");
727                return Poll::Ready(Ok(payload))
728            }
729        }
730
731        if let Some(best) = this.best_payload.take() {
732            debug!(target: "payload_builder", "resolving best payload");
733            return Poll::Ready(Ok(best))
734        }
735
736        if let Some(fut) = Pin::new(&mut this.empty_payload).as_pin_mut() &&
737            let Poll::Ready(res) = fut.poll(cx)
738        {
739            this.empty_payload = None;
740            return match res {
741                Ok(res) => {
742                    if let Err(err) = &res {
743                        warn!(target: "payload_builder", %err, "failed to resolve empty payload");
744                    } else {
745                        debug!(target: "payload_builder", "resolving empty payload");
746                    }
747                    Poll::Ready(res)
748                }
749                Err(err) => Poll::Ready(Err(err.into())),
750            }
751        }
752
753        if this.is_empty() {
754            return Poll::Ready(Err(PayloadBuilderError::MissingPayload))
755        }
756
757        Poll::Pending
758    }
759}
760
761/// A future that resolves to the result of the block building job.
762#[derive(Debug)]
763pub struct PendingPayload<P> {
764    /// Cancels the job on drop and carries cooperative control signals.
765    cancel: CancelOnDrop,
766    /// The channel to send the result to.
767    payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
768}
769
770impl<P> PendingPayload<P> {
771    /// Constructs a `PendingPayload` future.
772    pub const fn new(
773        cancel: CancelOnDrop,
774        payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
775    ) -> Self {
776        Self { cancel, payload }
777    }
778}
779
780impl<P> Future for PendingPayload<P> {
781    type Output = Result<BuildOutcome<P>, PayloadBuilderError>;
782
783    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
784        let res = ready!(self.payload.poll_unpin(cx));
785        Poll::Ready(res.map_err(Into::into).and_then(|res| res))
786    }
787}
788
789/// Static config for how to build a payload.
790#[derive(Clone, Debug)]
791pub struct PayloadConfig<Attributes, Header = alloy_consensus::Header> {
792    /// The parent header.
793    pub parent_header: Arc<SealedHeader<Header>>,
794    /// Additional parent block information, if available.
795    pub parent_block_info: Option<PayloadParentBlockInfo>,
796    /// Requested attributes for the payload.
797    pub attributes: Attributes,
798    /// The payload id.
799    pub payload_id: PayloadId,
800}
801
802/// Additional information about the parent block.
803#[derive(Clone, Copy, Debug, PartialEq, Eq)]
804pub struct PayloadParentBlockInfo {
805    /// Number of transactions in the parent block.
806    pub transaction_count: usize,
807}
808
809impl<Attributes, Header> PayloadConfig<Attributes, Header>
810where
811    Attributes: PayloadAttributes,
812{
813    /// Create new payload config.
814    pub const fn new(
815        parent_header: Arc<SealedHeader<Header>>,
816        attributes: Attributes,
817        payload_id: PayloadId,
818    ) -> Self {
819        Self { parent_header, parent_block_info: None, attributes, payload_id }
820    }
821
822    /// Attaches cached parent block information.
823    pub const fn with_parent_block_info(
824        mut self,
825        parent_block_info: Option<PayloadParentBlockInfo>,
826    ) -> Self {
827        self.parent_block_info = parent_block_info;
828        self
829    }
830
831    /// Returns the payload id.
832    pub const fn payload_id(&self) -> PayloadId {
833        self.payload_id
834    }
835}
836
837/// The possible outcomes of a payload building attempt.
838#[derive(Debug)]
839pub enum BuildOutcome<Payload> {
840    /// Successfully built a better block.
841    Better {
842        /// The new payload that was built.
843        payload: Payload,
844        /// The cached reads that were used to build the payload.
845        cached_reads: CachedReads,
846    },
847    /// Aborted payload building because resulted in worse block wrt. fees.
848    Aborted {
849        /// The total fees associated with the attempted payload.
850        fees: U256,
851        /// The cached reads that were used to build the payload.
852        cached_reads: CachedReads,
853    },
854    /// Build job was cancelled
855    Cancelled,
856
857    /// The payload is final and no further building should occur
858    Freeze(Payload),
859}
860
861impl<Payload> BuildOutcome<Payload> {
862    /// Consumes the type and returns the payload if the outcome is `Better` or `Freeze`.
863    pub fn into_payload(self) -> Option<Payload> {
864        match self {
865            Self::Better { payload, .. } | Self::Freeze(payload) => Some(payload),
866            _ => None,
867        }
868    }
869
870    /// Consumes the type and returns the payload if the outcome is `Better` or `Freeze`.
871    pub const fn payload(&self) -> Option<&Payload> {
872        match self {
873            Self::Better { payload, .. } | Self::Freeze(payload) => Some(payload),
874            _ => None,
875        }
876    }
877
878    /// Returns true if the outcome is `Better`.
879    pub const fn is_better(&self) -> bool {
880        matches!(self, Self::Better { .. })
881    }
882
883    /// Returns true if the outcome is `Freeze`.
884    pub const fn is_frozen(&self) -> bool {
885        matches!(self, Self::Freeze { .. })
886    }
887
888    /// Returns true if the outcome is `Aborted`.
889    pub const fn is_aborted(&self) -> bool {
890        matches!(self, Self::Aborted { .. })
891    }
892
893    /// Returns true if the outcome is `Cancelled`.
894    pub const fn is_cancelled(&self) -> bool {
895        matches!(self, Self::Cancelled)
896    }
897
898    /// Applies a fn on the current payload.
899    pub fn map_payload<F, P>(self, f: F) -> BuildOutcome<P>
900    where
901        F: FnOnce(Payload) -> P,
902    {
903        match self {
904            Self::Better { payload, cached_reads } => {
905                BuildOutcome::Better { payload: f(payload), cached_reads }
906            }
907            Self::Aborted { fees, cached_reads } => BuildOutcome::Aborted { fees, cached_reads },
908            Self::Cancelled => BuildOutcome::Cancelled,
909            Self::Freeze(payload) => BuildOutcome::Freeze(f(payload)),
910        }
911    }
912}
913
914/// The possible outcomes of a payload building attempt without reused [`CachedReads`]
915#[derive(Debug)]
916pub enum BuildOutcomeKind<Payload> {
917    /// Successfully built a better block.
918    Better {
919        /// The new payload that was built.
920        payload: Payload,
921    },
922    /// Aborted payload building because resulted in worse block wrt. fees.
923    Aborted {
924        /// The total fees associated with the attempted payload.
925        fees: U256,
926    },
927    /// Build job was cancelled
928    Cancelled,
929    /// The payload is final and no further building should occur
930    Freeze(Payload),
931}
932
933impl<Payload> BuildOutcomeKind<Payload> {
934    /// Attaches the [`CachedReads`] to the outcome.
935    pub fn with_cached_reads(self, cached_reads: CachedReads) -> BuildOutcome<Payload> {
936        match self {
937            Self::Better { payload } => BuildOutcome::Better { payload, cached_reads },
938            Self::Aborted { fees } => BuildOutcome::Aborted { fees, cached_reads },
939            Self::Cancelled => BuildOutcome::Cancelled,
940            Self::Freeze(payload) => BuildOutcome::Freeze(payload),
941        }
942    }
943}
944
945/// A collection of arguments used for building payloads.
946///
947/// This struct encapsulates the essential components and configuration required for the payload
948/// building process. It holds references to the Ethereum client, transaction pool, cached reads,
949/// payload configuration, cancellation status, and the best payload achieved so far.
950#[derive(Debug)]
951pub struct BuildArguments<Attributes, Payload: BuiltPayload> {
952    /// Previously cached disk reads
953    pub cached_reads: CachedReads,
954    /// Optional execution cache shared with the engine.
955    pub execution_cache: Option<SavedCache>,
956    /// Optional state-root task handle, shared with the engine.
957    ///
958    /// A successful build returns its retained trie through the handle's completion callback,
959    /// associated with the built block's hash and state root.
960    pub state_root_handle: Option<PayloadStateRootHandle>,
961    /// How to configure the payload.
962    pub config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
963    /// A marker that can be used to cancel the job.
964    pub cancel: CancelOnDrop,
965    /// The best payload achieved so far.
966    pub best_payload: Option<Payload>,
967}
968
969impl<Attributes, Payload: BuiltPayload> BuildArguments<Attributes, Payload> {
970    /// Create new build arguments.
971    pub const fn new(
972        cached_reads: CachedReads,
973        execution_cache: Option<SavedCache>,
974        state_root_handle: Option<PayloadStateRootHandle>,
975        config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
976        cancel: CancelOnDrop,
977        best_payload: Option<Payload>,
978    ) -> Self {
979        Self { cached_reads, execution_cache, state_root_handle, config, cancel, best_payload }
980    }
981}
982
983/// A trait for building payloads that encapsulate Ethereum transactions.
984///
985/// This trait provides the `try_build` method to construct a transaction payload
986/// using `BuildArguments`. It returns a `Result` indicating success or a
987/// `PayloadBuilderError` if building fails.
988///
989/// Generic parameters `Pool` and `Client` represent the transaction pool and
990/// Ethereum client types.
991pub trait PayloadBuilder: Send + Sync + Clone {
992    /// The payload attributes type to accept for building.
993    type Attributes: PayloadAttributes;
994    /// The type of the built payload.
995    type BuiltPayload: BuiltPayload;
996
997    /// Tries to build a transaction payload using provided arguments.
998    ///
999    /// Constructs a transaction payload based on the given arguments,
1000    /// returning a `Result` indicating success or an error if building fails.
1001    ///
1002    /// # Arguments
1003    ///
1004    /// - `args`: Build arguments containing necessary components.
1005    ///
1006    /// # Returns
1007    ///
1008    /// A `Result` indicating the build outcome or an error.
1009    fn try_build(
1010        &self,
1011        args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
1012    ) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError>;
1013
1014    /// Invoked when the payload job is being resolved and there is no payload yet.
1015    ///
1016    /// This can happen if the CL requests a payload before the first payload has been built.
1017    fn on_missing_payload(
1018        &self,
1019        _args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
1020    ) -> MissingPayloadBehaviour<Self::BuiltPayload> {
1021        MissingPayloadBehaviour::RaceEmptyPayload
1022    }
1023
1024    /// Builds an empty payload without any transaction.
1025    fn build_empty_payload(
1026        &self,
1027        config: PayloadConfig<Self::Attributes, HeaderForPayload<Self::BuiltPayload>>,
1028    ) -> Result<Self::BuiltPayload, PayloadBuilderError>;
1029}
1030
1031/// Tells the payload builder how to react to payload request if there's no payload available yet.
1032///
1033/// This situation can occur if the CL requests a payload before the first payload has been built.
1034#[derive(Default)]
1035pub enum MissingPayloadBehaviour<Payload> {
1036    /// Await the regular scheduled payload process.
1037    AwaitInProgress,
1038    /// Race the in progress payload process with an empty payload.
1039    #[default]
1040    RaceEmptyPayload,
1041    /// Race the in progress payload process with this job.
1042    RacePayload(Box<dyn FnOnce() -> Result<Payload, PayloadBuilderError> + Send>),
1043}
1044
1045impl<Payload> fmt::Debug for MissingPayloadBehaviour<Payload> {
1046    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1047        match self {
1048            Self::AwaitInProgress => write!(f, "AwaitInProgress"),
1049            Self::RaceEmptyPayload => {
1050                write!(f, "RaceEmptyPayload")
1051            }
1052            Self::RacePayload(_) => write!(f, "RacePayload"),
1053        }
1054    }
1055}
1056
1057/// Checks if the new payload is better than the current best.
1058///
1059/// This compares the total fees of the blocks, higher is better.
1060#[inline(always)]
1061pub fn is_better_payload<T: BuiltPayload>(best_payload: Option<&T>, new_fees: U256) -> bool {
1062    best_payload.is_none_or(|best_payload| new_fees > best_payload.fees())
1063}
1064
1065/// Returns the duration until the given unix timestamp in seconds.
1066///
1067/// Returns `Duration::ZERO` if the given timestamp is in the past.
1068fn duration_until(unix_timestamp_secs: u64) -> Duration {
1069    let unix_now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
1070    let timestamp = Duration::from_secs(unix_timestamp_secs);
1071    timestamp.saturating_sub(unix_now)
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::*;
1077    use alloy_consensus::Header;
1078    use alloy_rpc_types_engine::PayloadAttributes as EthPayloadAttributes;
1079    use reth_ethereum_engine_primitives::EthBuiltPayload;
1080    use reth_provider::test_utils::MockEthProvider;
1081    use std::sync::atomic::{AtomicUsize, Ordering};
1082
1083    // Counts build attempts and never produces a payload.
1084    #[derive(Clone, Debug, Default)]
1085    struct CountingBuilder(Arc<AtomicUsize>);
1086
1087    impl PayloadBuilder for CountingBuilder {
1088        type Attributes = EthPayloadAttributes;
1089        type BuiltPayload = EthBuiltPayload;
1090
1091        fn try_build(
1092            &self,
1093            args: BuildArguments<EthPayloadAttributes, EthBuiltPayload>,
1094        ) -> Result<BuildOutcome<EthBuiltPayload>, PayloadBuilderError> {
1095            self.0.fetch_add(1, Ordering::SeqCst);
1096            Ok(BuildOutcome::Aborted { fees: U256::ZERO, cached_reads: args.cached_reads })
1097        }
1098
1099        fn build_empty_payload(
1100            &self,
1101            _config: PayloadConfig<EthPayloadAttributes, Header>,
1102        ) -> Result<EthBuiltPayload, PayloadBuilderError> {
1103            Err(PayloadBuilderError::MissingPayload)
1104        }
1105    }
1106
1107    #[tokio::test(flavor = "multi_thread")]
1108    async fn second_build_waits_one_interval() {
1109        let client = MockEthProvider::default();
1110        let parent = Header::default();
1111        let parent_hash = parent.hash_slow();
1112        client.add_header(parent_hash, parent);
1113        let builder = CountingBuilder::default();
1114        let config = BasicPayloadJobGeneratorConfig::default().interval(Duration::from_secs(3600));
1115        let generator = BasicPayloadJobGenerator::with_builder(
1116            client,
1117            Runtime::test(),
1118            config,
1119            builder.clone(),
1120        );
1121
1122        let input = BuildNewPayload {
1123            attributes: EthPayloadAttributes::default(),
1124            parent_hash,
1125            resources: Default::default(),
1126        };
1127        let mut job = generator.new_payload_job(input, PayloadId::new([0; 8])).unwrap();
1128
1129        // The first build ends well within the timeout; the next one must wait for the interval.
1130        assert!(tokio::time::timeout(Duration::from_millis(200), &mut job).await.is_err());
1131        assert_eq!(builder.0.load(Ordering::SeqCst), 1);
1132        assert!(job.pending_block.is_none());
1133    }
1134}