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_execution_cache::SavedCache;
18use reth_payload_builder::{
19    BuildNewPayload, KeepPayloadJobAlive, PayloadBuilderLease, PayloadId, PayloadJob,
20    PayloadJobGenerator,
21};
22use reth_payload_builder_primitives::PayloadBuilderError;
23use reth_payload_primitives::{BuiltPayload, PayloadAttributes, PayloadKind};
24use reth_primitives_traits::{HeaderTy, NodePrimitives, SealedHeader};
25use reth_revm::{cached::CachedReads, cancelled::CancelOnDrop};
26use reth_storage_api::{BlockReaderIdExt, StateProviderFactory};
27use reth_tasks::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, trace, warn};
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                .map_err(PayloadBuilderError::from)?
174                .ok_or_else(|| PayloadBuilderError::MissingParentHeader(B256::ZERO))?
175        } else {
176            // Fetch specific header by hash
177            self.client
178                .sealed_header_by_hash(parent_hash)
179                .map_err(PayloadBuilderError::from)?
180                .ok_or_else(|| PayloadBuilderError::MissingParentHeader(parent_hash))?
181        };
182
183        let parent_hash = parent_header.hash();
184        let cached_reads = self.maybe_pre_cached(parent_hash);
185        let parent_block_info = self.maybe_parent_block_info(parent_hash);
186
187        let config = PayloadConfig::new(Arc::new(parent_header), attributes, id)
188            .with_parent_block_info(parent_block_info);
189
190        let until = self.job_deadline(config.attributes.timestamp());
191        let deadline = Box::pin(tokio::time::sleep_until(until));
192
193        let mut job = BasicPayloadJob {
194            config,
195            executor: self.executor.clone(),
196            deadline,
197            // ticks immediately
198            interval: tokio::time::interval(self.config.interval),
199            best_payload: PayloadState::Missing,
200            pending_block: None,
201            cached_reads,
202            execution_cache: resources.take_execution_cache(),
203            state_root_handle: resources.take_state_root_handle(),
204            leases: resources.take_leases(),
205            payload_task_guard: self.payload_task_guard.clone(),
206            metrics: Default::default(),
207            builder: self.builder.clone(),
208        };
209
210        // start the first job right away
211        job.spawn_build_job();
212
213        Ok(job)
214    }
215
216    fn on_new_state<N: NodePrimitives>(&mut self, new_state: CanonStateNotification<N>) {
217        if !self.config.pre_cache_state {
218            self.pre_cached = None;
219            return
220        }
221
222        let mut cached = CachedReads::default();
223
224        // extract the state from the notification and put it into the cache
225        let committed = new_state.committed();
226        let new_execution_outcome = committed.execution_outcome();
227        for (addr, acc) in new_execution_outcome.bundle_accounts_iter() {
228            if let Some(info) = acc.info.clone() {
229                // we want pre cache existing accounts and their storage
230                // this only includes changed accounts and storage but is better than nothing
231                let storage =
232                    acc.storage.iter().map(|(key, slot)| (*key, slot.present_value)).collect();
233                cached.insert_account(addr, info, storage);
234            }
235        }
236
237        let tip = committed.tip();
238        let block = tip.hash();
239        let parent_block_info =
240            PayloadParentBlockInfo { transaction_count: tip.transaction_count() };
241
242        self.pre_cached = Some(PrecachedState { block, cached });
243        self.pre_cached_parent_block_info =
244            Some(PrecachedParentBlockInfo { block, parent_block_info });
245    }
246}
247
248/// Pre-filled [`CachedReads`] for a specific block.
249///
250/// This is extracted from the [`CanonStateNotification`] for the tip block.
251#[derive(Debug, Clone)]
252pub struct PrecachedState {
253    /// The block for which the state is pre-cached.
254    pub block: B256,
255    /// Cached state for the block.
256    pub cached: CachedReads,
257}
258
259/// Pre-filled parent block information for a specific block.
260#[derive(Debug, Clone, Copy)]
261struct PrecachedParentBlockInfo {
262    /// The block for which the parent block information is cached.
263    block: B256,
264    /// Cached parent block information.
265    parent_block_info: PayloadParentBlockInfo,
266}
267
268/// Restricts how many generator tasks can be executed at once.
269#[derive(Debug, Clone)]
270pub struct PayloadTaskGuard(Arc<Semaphore>);
271
272impl Deref for PayloadTaskGuard {
273    type Target = Semaphore;
274
275    fn deref(&self) -> &Self::Target {
276        &self.0
277    }
278}
279
280// === impl PayloadTaskGuard ===
281
282impl PayloadTaskGuard {
283    /// Constructs `Self` with a maximum task count of `max_payload_tasks`.
284    pub fn new(max_payload_tasks: usize) -> Self {
285        Self(Arc::new(Semaphore::new(max_payload_tasks)))
286    }
287
288    /// Acquires an owned permit for a payload build task.
289    async fn acquire_owned(&self) -> tokio::sync::OwnedSemaphorePermit {
290        self.0.clone().acquire_owned().await.expect("payload task semaphore closed")
291    }
292}
293
294/// Settings for the [`BasicPayloadJobGenerator`].
295#[derive(Debug, Clone)]
296pub struct BasicPayloadJobGeneratorConfig {
297    /// The interval at which the job should build a new payload after the last.
298    interval: Duration,
299    /// The deadline for when the payload builder job should resolve.
300    ///
301    /// By default this is [`SLOT_DURATION`]: 12s
302    deadline: Duration,
303    /// Maximum number of tasks to spawn for building a payload.
304    max_payload_tasks: usize,
305    /// Whether to pre-cache changed state from canonical state notifications.
306    pre_cache_state: bool,
307}
308
309// === impl BasicPayloadJobGeneratorConfig ===
310
311impl BasicPayloadJobGeneratorConfig {
312    /// Sets the interval at which the job should build a new payload after the last.
313    pub const fn interval(mut self, interval: Duration) -> Self {
314        self.interval = interval;
315        self
316    }
317
318    /// Sets the deadline when this job should resolve.
319    pub const fn deadline(mut self, deadline: Duration) -> Self {
320        self.deadline = deadline;
321        self
322    }
323
324    /// Sets the maximum number of tasks to spawn for building a payload(s).
325    ///
326    /// # Panics
327    ///
328    /// If `max_payload_tasks` is 0.
329    pub fn max_payload_tasks(mut self, max_payload_tasks: usize) -> Self {
330        assert!(max_payload_tasks > 0, "max_payload_tasks must be greater than 0");
331        self.max_payload_tasks = max_payload_tasks;
332        self
333    }
334
335    /// Sets whether to pre-cache changed state from canonical state notifications.
336    ///
337    /// This keeps the parent block's state changes in memory so payload jobs building on top of it
338    /// can reuse those reads.
339    pub const fn pre_cache_state(mut self, pre_cache_state: bool) -> Self {
340        self.pre_cache_state = pre_cache_state;
341        self
342    }
343}
344
345impl Default for BasicPayloadJobGeneratorConfig {
346    fn default() -> Self {
347        Self {
348            interval: Duration::from_secs(1),
349            // 12s slot time
350            deadline: SLOT_DURATION,
351            max_payload_tasks: 3,
352            pre_cache_state: true,
353        }
354    }
355}
356
357/// A basic payload job that continuously builds a payload with the best transactions from the pool.
358///
359/// This type is a [`PayloadJob`] and [`Future`] that terminates when the deadline is reached or
360/// when the job is resolved: [`PayloadJob::resolve`].
361///
362/// This basic job implementation will trigger new payload build task continuously until the job is
363/// resolved or the deadline is reached, or until the built payload is marked as frozen:
364/// [`BuildOutcome::Freeze`]. Once a frozen payload is returned, no additional payloads will be
365/// built and this future will wait to be resolved: [`PayloadJob::resolve`] or terminated if the
366/// deadline is reached.
367#[derive(Debug)]
368pub struct BasicPayloadJob<Builder>
369where
370    Builder: PayloadBuilder,
371{
372    /// The configuration for how the payload will be created.
373    config: PayloadConfig<Builder::Attributes, HeaderForPayload<Builder::BuiltPayload>>,
374    /// How to spawn building tasks
375    executor: Runtime,
376    /// The deadline when this job should resolve.
377    deadline: Pin<Box<Sleep>>,
378    /// The interval at which the job should build a new payload after the last.
379    interval: Interval,
380    /// The best payload so far and its state.
381    best_payload: PayloadState<Builder::BuiltPayload>,
382    /// Receiver for the block that is currently being built.
383    pending_block: Option<PendingPayload<Builder::BuiltPayload>>,
384    /// Restricts how many generator tasks can be executed at once.
385    payload_task_guard: PayloadTaskGuard,
386    /// Caches all disk reads for the state the new payloads builds on
387    ///
388    /// This is used to avoid reading the same state over and over again when new attempts are
389    /// triggered, because during the building process we'll repeatedly execute the transactions.
390    cached_reads: Option<CachedReads>,
391    /// Optional execution cache shared with the engine.
392    execution_cache: Option<SavedCache>,
393    /// Optional state-root task handle, shared with the engine.
394    state_root_handle: Option<PayloadStateRootHandle>,
395    /// Lifecycle leases shared with the payload-builder service.
396    ///
397    /// Every detached build task clones these so that the loaned resources remain available until
398    /// `try_build` completes, even if the payload job is resolved first.
399    leases: Vec<PayloadBuilderLease>,
400    /// metrics for this type
401    metrics: PayloadBuilderMetrics,
402    /// The type responsible for building payloads.
403    ///
404    /// See [`PayloadBuilder`]
405    builder: Builder,
406}
407
408impl<Builder> BasicPayloadJob<Builder>
409where
410    Builder: PayloadBuilder + Unpin + 'static,
411    Builder::Attributes: Unpin + Clone,
412    Builder::BuiltPayload: Unpin + Clone,
413{
414    /// Spawns a new payload build task.
415    fn spawn_build_job(&mut self) {
416        trace!(target: "payload_builder", id = %self.config.payload_id(), "spawn new payload build task");
417        let (tx, rx) = oneshot::channel();
418        let cancel = CancelOnDrop::default();
419        let pending_cancel = cancel.clone();
420        let guard = self.payload_task_guard.clone();
421        let payload_config = self.config.clone();
422        let best_payload = self.best_payload.payload().cloned();
423        self.metrics.inc_initiated_payload_builds();
424        let cached_reads = self.cached_reads.take().unwrap_or_default();
425        let execution_cache = self.execution_cache.clone();
426        let state_root_handle = self.state_root_handle.take();
427        let leases = self.leases.clone();
428        let builder = self.builder.clone();
429        let executor = self.executor.clone();
430        self.executor.spawn_task(async move {
431            // acquire the permit for executing the task
432            let permit = guard.acquire_owned().await;
433            executor.spawn_blocking_named_or_tokio(PAYLOAD_BUILDER_THREAD_NAME, move || {
434                let _permit = permit;
435                let args = BuildArguments {
436                    cached_reads,
437                    execution_cache,
438                    state_root_handle,
439                    config: payload_config,
440                    cancel,
441                    best_payload,
442                };
443                let result = builder.try_build(args);
444                drop(leases);
445                let _ = tx.send(result);
446            });
447        });
448
449        self.pending_block = Some(PendingPayload { cancel: pending_cancel, payload: rx });
450    }
451}
452
453impl<Builder> Future for BasicPayloadJob<Builder>
454where
455    Builder: PayloadBuilder + Unpin + 'static,
456    Builder::Attributes: Unpin + Clone,
457    Builder::BuiltPayload: Unpin + Clone,
458{
459    type Output = Result<(), PayloadBuilderError>;
460
461    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
462        let this = self.get_mut();
463
464        // check if the deadline is reached
465        if this.deadline.as_mut().poll(cx).is_ready() {
466            trace!(target: "payload_builder", "payload building deadline reached");
467            return Poll::Ready(Ok(()))
468        }
469
470        loop {
471            // Wait for any pending build to complete before polling the next tick.
472            //
473            // This avoids consuming interval ticks while a build is still in-flight,
474            // which would delay the follow-up build by a full interval even though
475            // the current attempt has already finished.
476            if let Some(mut fut) = this.pending_block.take() {
477                match fut.poll_unpin(cx) {
478                    Poll::Ready(Ok(outcome)) => match outcome {
479                        BuildOutcome::Better { payload, cached_reads } => {
480                            this.cached_reads = Some(cached_reads);
481                            debug!(target: "payload_builder", value = %payload.fees(), "built better payload");
482                            this.best_payload = PayloadState::Best(payload);
483                        }
484                        BuildOutcome::Freeze(payload) => {
485                            debug!(target: "payload_builder", "payload frozen, no further building will occur");
486                            this.best_payload = PayloadState::Frozen(payload);
487                        }
488                        BuildOutcome::Aborted { fees, cached_reads } => {
489                            this.cached_reads = Some(cached_reads);
490                            trace!(target: "payload_builder", worse_fees = %fees, "skipped payload build of worse block");
491                        }
492                        BuildOutcome::Cancelled => {
493                            unreachable!("the cancel signal never fired")
494                        }
495                    },
496                    Poll::Ready(Err(error)) => {
497                        // job failed, but we simply try again next interval
498                        debug!(target: "payload_builder", %error, "payload build attempt failed");
499                        this.metrics.inc_failed_payload_builds();
500                    }
501                    Poll::Pending => {
502                        this.pending_block = Some(fut);
503                        return Poll::Pending
504                    }
505                }
506            }
507
508            if this.best_payload.is_frozen() {
509                return Poll::Pending
510            }
511
512            // Wait for the next build interval tick.
513            //
514            // The loop is needed because `poll_tick` does not register a waker
515            // when it returns `Ready`, so we must loop back after spawning a job
516            // to reach a point that *does* register one (the pending block poll above).
517            ready!(this.interval.poll_tick(cx));
518            this.spawn_build_job()
519        }
520    }
521}
522
523impl<Builder> PayloadJob for BasicPayloadJob<Builder>
524where
525    Builder: PayloadBuilder + Unpin + 'static,
526    Builder::Attributes: Unpin + Clone,
527    Builder::BuiltPayload: Unpin + Clone,
528{
529    type PayloadAttributes = Builder::Attributes;
530    type ResolvePayloadFuture = ResolveBestPayload<Self::BuiltPayload>;
531    type BuiltPayload = Builder::BuiltPayload;
532
533    fn best_payload(&self) -> Result<Self::BuiltPayload, PayloadBuilderError> {
534        if let Some(payload) = self.best_payload.payload() {
535            Ok(payload.clone())
536        } else {
537            // No payload has been built yet, but we need to return something that the CL then
538            // can deliver, so we need to return an empty payload.
539            //
540            // Note: it is assumed that this is unlikely to happen, as the payload job is
541            // started right away and the first full block should have been
542            // built by the time CL is requesting the payload.
543            self.metrics.inc_requested_empty_payload();
544            self.builder.build_empty_payload(self.config.clone())
545        }
546    }
547
548    fn payload_attributes(&self) -> Result<Self::PayloadAttributes, PayloadBuilderError> {
549        Ok(self.config.attributes.clone())
550    }
551
552    fn payload_timestamp(&self) -> Result<u64, PayloadBuilderError> {
553        Ok(self.config.attributes.timestamp())
554    }
555
556    fn resolve_kind(
557        &mut self,
558        kind: PayloadKind,
559    ) -> (Self::ResolvePayloadFuture, KeepPayloadJobAlive) {
560        let best_payload = self.best_payload.payload().cloned();
561        if best_payload.is_none() && self.pending_block.is_none() {
562            // ensure we have a job scheduled if we don't have a best payload yet and none is active
563            self.spawn_build_job();
564        }
565
566        let maybe_better = self.pending_block.take();
567        let mut empty_payload = None;
568
569        if best_payload.is_none() {
570            if let Some(pending) = maybe_better.as_ref() {
571                pending.cancel.request_finalization();
572            }
573
574            debug!(target: "payload_builder", id=%self.config.payload_id(), "no best payload yet to resolve, building empty payload");
575
576            let args = BuildArguments {
577                cached_reads: self.cached_reads.take().unwrap_or_default(),
578                execution_cache: self.execution_cache.clone(),
579                state_root_handle: None,
580                config: self.config.clone(),
581                cancel: CancelOnDrop::default(),
582                best_payload: None,
583            };
584
585            match self.builder.on_missing_payload(args) {
586                MissingPayloadBehaviour::AwaitInProgress => {
587                    debug!(target: "payload_builder", id=%self.config.payload_id(), "awaiting in progress payload build job");
588                }
589                MissingPayloadBehaviour::RaceEmptyPayload => {
590                    debug!(target: "payload_builder", id=%self.config.payload_id(), "racing empty payload");
591
592                    // if no payload has been built yet
593                    self.metrics.inc_requested_empty_payload();
594                    // no payload built yet, so we need to return an empty payload
595                    let (tx, rx) = oneshot::channel();
596                    let config = self.config.clone();
597                    let builder = self.builder.clone();
598                    self.executor.spawn_blocking_named_or_tokio(
599                        PAYLOAD_BUILDER_THREAD_NAME,
600                        move || {
601                            let res = builder.build_empty_payload(config);
602                            let _ = tx.send(res);
603                        },
604                    );
605
606                    empty_payload = Some(rx);
607                }
608                MissingPayloadBehaviour::RacePayload(job) => {
609                    debug!(target: "payload_builder", id=%self.config.payload_id(), "racing fallback payload");
610                    // race the in progress job with this job
611                    let (tx, rx) = oneshot::channel();
612                    self.executor.spawn_blocking_named_or_tokio(
613                        PAYLOAD_BUILDER_THREAD_NAME,
614                        move || {
615                            let _ = tx.send(job());
616                        },
617                    );
618                    empty_payload = Some(rx);
619                }
620            };
621        }
622
623        let fut = ResolveBestPayload {
624            best_payload,
625            maybe_better,
626            empty_payload: empty_payload.filter(|_| kind != PayloadKind::WaitForPending),
627        };
628
629        (fut, KeepPayloadJobAlive::No)
630    }
631}
632
633/// Represents the current state of a payload being built.
634#[derive(Debug, Clone)]
635pub enum PayloadState<P> {
636    /// No payload has been built yet.
637    Missing,
638    /// The best payload built so far, which may still be improved upon.
639    Best(P),
640    /// The payload is frozen and no further building should occur.
641    ///
642    /// Contains the final payload `P` that should be used.
643    Frozen(P),
644}
645
646impl<P> PayloadState<P> {
647    /// Checks if the payload is frozen.
648    pub const fn is_frozen(&self) -> bool {
649        matches!(self, Self::Frozen(_))
650    }
651
652    /// Returns the payload if it exists (either Best or Frozen).
653    pub const fn payload(&self) -> Option<&P> {
654        match self {
655            Self::Missing => None,
656            Self::Best(p) | Self::Frozen(p) => Some(p),
657        }
658    }
659}
660
661/// The future that returns the best payload to be served to the consensus layer.
662///
663/// This returns the payload that's supposed to be sent to the CL.
664///
665/// If payload has been built so far, it will return that, but it will check if there's a better
666/// payload available from an in progress build job. If so it will return that.
667///
668/// If no payload has been built so far, it will either return an empty payload or the result of the
669/// in progress build job, whatever finishes first.
670#[derive(Debug)]
671pub struct ResolveBestPayload<Payload> {
672    /// Best payload so far.
673    pub best_payload: Option<Payload>,
674    /// Regular payload job that's currently running that might produce a better payload.
675    pub maybe_better: Option<PendingPayload<Payload>>,
676    /// The empty payload building job in progress, if any.
677    pub empty_payload: Option<oneshot::Receiver<Result<Payload, PayloadBuilderError>>>,
678}
679
680impl<Payload> ResolveBestPayload<Payload> {
681    const fn is_empty(&self) -> bool {
682        self.best_payload.is_none() && self.maybe_better.is_none() && self.empty_payload.is_none()
683    }
684}
685
686impl<Payload> Future for ResolveBestPayload<Payload>
687where
688    Payload: Unpin,
689{
690    type Output = Result<Payload, PayloadBuilderError>;
691
692    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
693        let this = self.get_mut();
694
695        // check if there is a better payload before returning the best payload
696        if let Some(fut) = Pin::new(&mut this.maybe_better).as_pin_mut() &&
697            let Poll::Ready(res) = fut.poll(cx)
698        {
699            this.maybe_better = None;
700            if let Ok(Some(payload)) = res.map(|out| out.into_payload()).inspect_err(
701                |err| warn!(target: "payload_builder", %err, "failed to resolve pending payload"),
702            ) {
703                debug!(target: "payload_builder", "resolving better payload");
704                return Poll::Ready(Ok(payload))
705            }
706        }
707
708        if let Some(best) = this.best_payload.take() {
709            debug!(target: "payload_builder", "resolving best payload");
710            return Poll::Ready(Ok(best))
711        }
712
713        if let Some(fut) = Pin::new(&mut this.empty_payload).as_pin_mut() &&
714            let Poll::Ready(res) = fut.poll(cx)
715        {
716            this.empty_payload = None;
717            return match res {
718                Ok(res) => {
719                    if let Err(err) = &res {
720                        warn!(target: "payload_builder", %err, "failed to resolve empty payload");
721                    } else {
722                        debug!(target: "payload_builder", "resolving empty payload");
723                    }
724                    Poll::Ready(res)
725                }
726                Err(err) => Poll::Ready(Err(err.into())),
727            }
728        }
729
730        if this.is_empty() {
731            return Poll::Ready(Err(PayloadBuilderError::MissingPayload))
732        }
733
734        Poll::Pending
735    }
736}
737
738/// A future that resolves to the result of the block building job.
739#[derive(Debug)]
740pub struct PendingPayload<P> {
741    /// Cancels the job on drop and carries cooperative control signals.
742    cancel: CancelOnDrop,
743    /// The channel to send the result to.
744    payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
745}
746
747impl<P> PendingPayload<P> {
748    /// Constructs a `PendingPayload` future.
749    pub const fn new(
750        cancel: CancelOnDrop,
751        payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
752    ) -> Self {
753        Self { cancel, payload }
754    }
755}
756
757impl<P> Future for PendingPayload<P> {
758    type Output = Result<BuildOutcome<P>, PayloadBuilderError>;
759
760    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
761        let res = ready!(self.payload.poll_unpin(cx));
762        Poll::Ready(res.map_err(Into::into).and_then(|res| res))
763    }
764}
765
766/// Static config for how to build a payload.
767#[derive(Clone, Debug)]
768pub struct PayloadConfig<Attributes, Header = alloy_consensus::Header> {
769    /// The parent header.
770    pub parent_header: Arc<SealedHeader<Header>>,
771    /// Additional parent block information, if available.
772    pub parent_block_info: Option<PayloadParentBlockInfo>,
773    /// Requested attributes for the payload.
774    pub attributes: Attributes,
775    /// The payload id.
776    pub payload_id: PayloadId,
777}
778
779/// Additional information about the parent block.
780#[derive(Clone, Copy, Debug, PartialEq, Eq)]
781pub struct PayloadParentBlockInfo {
782    /// Number of transactions in the parent block.
783    pub transaction_count: usize,
784}
785
786impl<Attributes, Header> PayloadConfig<Attributes, Header>
787where
788    Attributes: PayloadAttributes,
789{
790    /// Create new payload config.
791    pub const fn new(
792        parent_header: Arc<SealedHeader<Header>>,
793        attributes: Attributes,
794        payload_id: PayloadId,
795    ) -> Self {
796        Self { parent_header, parent_block_info: None, attributes, payload_id }
797    }
798
799    /// Attaches cached parent block information.
800    pub const fn with_parent_block_info(
801        mut self,
802        parent_block_info: Option<PayloadParentBlockInfo>,
803    ) -> Self {
804        self.parent_block_info = parent_block_info;
805        self
806    }
807
808    /// Returns the payload id.
809    pub const fn payload_id(&self) -> PayloadId {
810        self.payload_id
811    }
812}
813
814/// The possible outcomes of a payload building attempt.
815#[derive(Debug)]
816pub enum BuildOutcome<Payload> {
817    /// Successfully built a better block.
818    Better {
819        /// The new payload that was built.
820        payload: Payload,
821        /// The cached reads that were used to build the payload.
822        cached_reads: CachedReads,
823    },
824    /// Aborted payload building because resulted in worse block wrt. fees.
825    Aborted {
826        /// The total fees associated with the attempted payload.
827        fees: U256,
828        /// The cached reads that were used to build the payload.
829        cached_reads: CachedReads,
830    },
831    /// Build job was cancelled
832    Cancelled,
833
834    /// The payload is final and no further building should occur
835    Freeze(Payload),
836}
837
838impl<Payload> BuildOutcome<Payload> {
839    /// Consumes the type and returns the payload if the outcome is `Better` or `Freeze`.
840    pub fn into_payload(self) -> Option<Payload> {
841        match self {
842            Self::Better { payload, .. } | Self::Freeze(payload) => Some(payload),
843            _ => None,
844        }
845    }
846
847    /// Consumes the type and returns the payload if the outcome is `Better` or `Freeze`.
848    pub const fn payload(&self) -> Option<&Payload> {
849        match self {
850            Self::Better { payload, .. } | Self::Freeze(payload) => Some(payload),
851            _ => None,
852        }
853    }
854
855    /// Returns true if the outcome is `Better`.
856    pub const fn is_better(&self) -> bool {
857        matches!(self, Self::Better { .. })
858    }
859
860    /// Returns true if the outcome is `Freeze`.
861    pub const fn is_frozen(&self) -> bool {
862        matches!(self, Self::Freeze { .. })
863    }
864
865    /// Returns true if the outcome is `Aborted`.
866    pub const fn is_aborted(&self) -> bool {
867        matches!(self, Self::Aborted { .. })
868    }
869
870    /// Returns true if the outcome is `Cancelled`.
871    pub const fn is_cancelled(&self) -> bool {
872        matches!(self, Self::Cancelled)
873    }
874
875    /// Applies a fn on the current payload.
876    pub fn map_payload<F, P>(self, f: F) -> BuildOutcome<P>
877    where
878        F: FnOnce(Payload) -> P,
879    {
880        match self {
881            Self::Better { payload, cached_reads } => {
882                BuildOutcome::Better { payload: f(payload), cached_reads }
883            }
884            Self::Aborted { fees, cached_reads } => BuildOutcome::Aborted { fees, cached_reads },
885            Self::Cancelled => BuildOutcome::Cancelled,
886            Self::Freeze(payload) => BuildOutcome::Freeze(f(payload)),
887        }
888    }
889}
890
891/// The possible outcomes of a payload building attempt without reused [`CachedReads`]
892#[derive(Debug)]
893pub enum BuildOutcomeKind<Payload> {
894    /// Successfully built a better block.
895    Better {
896        /// The new payload that was built.
897        payload: Payload,
898    },
899    /// Aborted payload building because resulted in worse block wrt. fees.
900    Aborted {
901        /// The total fees associated with the attempted payload.
902        fees: U256,
903    },
904    /// Build job was cancelled
905    Cancelled,
906    /// The payload is final and no further building should occur
907    Freeze(Payload),
908}
909
910impl<Payload> BuildOutcomeKind<Payload> {
911    /// Attaches the [`CachedReads`] to the outcome.
912    pub fn with_cached_reads(self, cached_reads: CachedReads) -> BuildOutcome<Payload> {
913        match self {
914            Self::Better { payload } => BuildOutcome::Better { payload, cached_reads },
915            Self::Aborted { fees } => BuildOutcome::Aborted { fees, cached_reads },
916            Self::Cancelled => BuildOutcome::Cancelled,
917            Self::Freeze(payload) => BuildOutcome::Freeze(payload),
918        }
919    }
920}
921
922/// A collection of arguments used for building payloads.
923///
924/// This struct encapsulates the essential components and configuration required for the payload
925/// building process. It holds references to the Ethereum client, transaction pool, cached reads,
926/// payload configuration, cancellation status, and the best payload achieved so far.
927#[derive(Debug)]
928pub struct BuildArguments<Attributes, Payload: BuiltPayload> {
929    /// Previously cached disk reads
930    pub cached_reads: CachedReads,
931    /// Optional execution cache shared with the engine.
932    pub execution_cache: Option<SavedCache>,
933    /// Optional state-root task handle, shared with the engine.
934    ///
935    /// The preserved trie is shared with the engine, so a concurrent `newPayload` will
936    /// block until this task completes. The trie is anchored at the built block's state
937    /// root, so if the next `newPayload` is not on top of that block, the trie cache is
938    /// invalidated and cleared.
939    pub state_root_handle: Option<PayloadStateRootHandle>,
940    /// How to configure the payload.
941    pub config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
942    /// A marker that can be used to cancel the job.
943    pub cancel: CancelOnDrop,
944    /// The best payload achieved so far.
945    pub best_payload: Option<Payload>,
946}
947
948impl<Attributes, Payload: BuiltPayload> BuildArguments<Attributes, Payload> {
949    /// Create new build arguments.
950    pub const fn new(
951        cached_reads: CachedReads,
952        execution_cache: Option<SavedCache>,
953        state_root_handle: Option<PayloadStateRootHandle>,
954        config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
955        cancel: CancelOnDrop,
956        best_payload: Option<Payload>,
957    ) -> Self {
958        Self { cached_reads, execution_cache, state_root_handle, config, cancel, best_payload }
959    }
960}
961
962/// A trait for building payloads that encapsulate Ethereum transactions.
963///
964/// This trait provides the `try_build` method to construct a transaction payload
965/// using `BuildArguments`. It returns a `Result` indicating success or a
966/// `PayloadBuilderError` if building fails.
967///
968/// Generic parameters `Pool` and `Client` represent the transaction pool and
969/// Ethereum client types.
970pub trait PayloadBuilder: Send + Sync + Clone {
971    /// The payload attributes type to accept for building.
972    type Attributes: PayloadAttributes;
973    /// The type of the built payload.
974    type BuiltPayload: BuiltPayload;
975
976    /// Tries to build a transaction payload using provided arguments.
977    ///
978    /// Constructs a transaction payload based on the given arguments,
979    /// returning a `Result` indicating success or an error if building fails.
980    ///
981    /// # Arguments
982    ///
983    /// - `args`: Build arguments containing necessary components.
984    ///
985    /// # Returns
986    ///
987    /// A `Result` indicating the build outcome or an error.
988    fn try_build(
989        &self,
990        args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
991    ) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError>;
992
993    /// Invoked when the payload job is being resolved and there is no payload yet.
994    ///
995    /// This can happen if the CL requests a payload before the first payload has been built.
996    fn on_missing_payload(
997        &self,
998        _args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
999    ) -> MissingPayloadBehaviour<Self::BuiltPayload> {
1000        MissingPayloadBehaviour::RaceEmptyPayload
1001    }
1002
1003    /// Builds an empty payload without any transaction.
1004    fn build_empty_payload(
1005        &self,
1006        config: PayloadConfig<Self::Attributes, HeaderForPayload<Self::BuiltPayload>>,
1007    ) -> Result<Self::BuiltPayload, PayloadBuilderError>;
1008}
1009
1010/// Tells the payload builder how to react to payload request if there's no payload available yet.
1011///
1012/// This situation can occur if the CL requests a payload before the first payload has been built.
1013#[derive(Default)]
1014pub enum MissingPayloadBehaviour<Payload> {
1015    /// Await the regular scheduled payload process.
1016    AwaitInProgress,
1017    /// Race the in progress payload process with an empty payload.
1018    #[default]
1019    RaceEmptyPayload,
1020    /// Race the in progress payload process with this job.
1021    RacePayload(Box<dyn FnOnce() -> Result<Payload, PayloadBuilderError> + Send>),
1022}
1023
1024impl<Payload> fmt::Debug for MissingPayloadBehaviour<Payload> {
1025    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1026        match self {
1027            Self::AwaitInProgress => write!(f, "AwaitInProgress"),
1028            Self::RaceEmptyPayload => {
1029                write!(f, "RaceEmptyPayload")
1030            }
1031            Self::RacePayload(_) => write!(f, "RacePayload"),
1032        }
1033    }
1034}
1035
1036/// Checks if the new payload is better than the current best.
1037///
1038/// This compares the total fees of the blocks, higher is better.
1039#[inline(always)]
1040pub fn is_better_payload<T: BuiltPayload>(best_payload: Option<&T>, new_fees: U256) -> bool {
1041    if let Some(best_payload) = best_payload {
1042        new_fees > best_payload.fees()
1043    } else {
1044        true
1045    }
1046}
1047
1048/// Returns the duration until the given unix timestamp in seconds.
1049///
1050/// Returns `Duration::ZERO` if the given timestamp is in the past.
1051fn duration_until(unix_timestamp_secs: u64) -> Duration {
1052    let unix_now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
1053    let timestamp = Duration::from_secs(unix_timestamp_secs);
1054    timestamp.saturating_sub(unix_now)
1055}