1#![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
53pub type HeaderForPayload<P> = <<P as BuiltPayload>::Primitives as NodePrimitives>::BlockHeader;
55
56#[derive(Debug)]
58pub struct BasicPayloadJobGenerator<Client, Builder> {
59 client: Client,
61 executor: Runtime,
63 config: BasicPayloadJobGeneratorConfig,
65 payload_task_guard: PayloadTaskGuard,
67 builder: Builder,
71 pre_cached: Option<PrecachedState>,
73 pre_cached_parent_block_info: Option<PrecachedParentBlockInfo>,
75}
76
77impl<Client, Builder> BasicPayloadJobGenerator<Client, Builder> {
80 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 #[inline]
108 fn max_job_duration(&self, unix_timestamp: u64) -> Duration {
109 let duration_until_timestamp = duration_until(unix_timestamp);
110
111 let duration_until_timestamp = duration_until_timestamp.min(self.config.deadline * 3);
113
114 self.config.deadline + duration_until_timestamp
115 }
116
117 #[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 pub const fn tasks(&self) -> &Runtime {
126 &self.executor
127 }
128
129 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 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
148impl<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 self.client
172 .latest_header()?
173 .ok_or_else(|| PayloadBuilderError::MissingParentHeader(B256::ZERO))?
174 } else {
175 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 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 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 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 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#[derive(Debug, Clone)]
253pub struct PrecachedState {
254 pub block: B256,
256 pub cached: CachedReads,
258}
259
260#[derive(Debug, Clone, Copy)]
262struct PrecachedParentBlockInfo {
263 block: B256,
265 parent_block_info: PayloadParentBlockInfo,
267}
268
269#[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
281impl PayloadTaskGuard {
284 pub fn new(max_payload_tasks: usize) -> Self {
286 Self(Arc::new(Semaphore::new(max_payload_tasks)))
287 }
288
289 async fn acquire_owned(&self) -> tokio::sync::OwnedSemaphorePermit {
291 self.0.clone().acquire_owned().await.expect("payload task semaphore closed")
292 }
293}
294
295#[derive(Debug, Clone)]
297pub struct BasicPayloadJobGeneratorConfig {
298 interval: Duration,
300 deadline: Duration,
304 max_payload_tasks: usize,
306 pre_cache_state: bool,
308}
309
310impl BasicPayloadJobGeneratorConfig {
313 pub const fn interval(mut self, interval: Duration) -> Self {
315 self.interval = interval;
316 self
317 }
318
319 pub const fn deadline(mut self, deadline: Duration) -> Self {
321 self.deadline = deadline;
322 self
323 }
324
325 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 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 deadline: SLOT_DURATION,
352 max_payload_tasks: 3,
353 pre_cache_state: true,
354 }
355 }
356}
357
358#[derive(Debug)]
369pub struct BasicPayloadJob<Builder>
370where
371 Builder: PayloadBuilder,
372{
373 config: PayloadConfig<Builder::Attributes, HeaderForPayload<Builder::BuiltPayload>>,
375 executor: Runtime,
377 deadline: Pin<Box<Sleep>>,
379 interval: Interval,
381 best_payload: PayloadState<Builder::BuiltPayload>,
383 pending_block: Option<PendingPayload<Builder::BuiltPayload>>,
385 payload_task_guard: PayloadTaskGuard,
387 cached_reads: Option<CachedReads>,
392 execution_cache: Option<SavedCache>,
394 state_root_handle: Option<PayloadStateRootHandle>,
396 leases: Vec<PayloadBuilderLease>,
401 metrics: PayloadBuilderMetrics,
403 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 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 let permit = guard.acquire_owned().await;
437 executor.spawn_blocking_named_or_tokio(PAYLOAD_BUILDER_THREAD_NAME, move || {
438 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 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 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 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 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 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 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 self.metrics.inc_requested_empty_payload();
607 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 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#[derive(Debug, Clone)]
658pub enum PayloadState<P> {
659 Missing,
661 Best(P),
663 Frozen(P),
667}
668
669impl<P> PayloadState<P> {
670 pub const fn is_frozen(&self) -> bool {
672 matches!(self, Self::Frozen(_))
673 }
674
675 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#[derive(Debug)]
694pub struct ResolveBestPayload<Payload> {
695 pub best_payload: Option<Payload>,
697 pub maybe_better: Option<PendingPayload<Payload>>,
699 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 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#[derive(Debug)]
763pub struct PendingPayload<P> {
764 cancel: CancelOnDrop,
766 payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
768}
769
770impl<P> PendingPayload<P> {
771 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#[derive(Clone, Debug)]
791pub struct PayloadConfig<Attributes, Header = alloy_consensus::Header> {
792 pub parent_header: Arc<SealedHeader<Header>>,
794 pub parent_block_info: Option<PayloadParentBlockInfo>,
796 pub attributes: Attributes,
798 pub payload_id: PayloadId,
800}
801
802#[derive(Clone, Copy, Debug, PartialEq, Eq)]
804pub struct PayloadParentBlockInfo {
805 pub transaction_count: usize,
807}
808
809impl<Attributes, Header> PayloadConfig<Attributes, Header>
810where
811 Attributes: PayloadAttributes,
812{
813 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 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 pub const fn payload_id(&self) -> PayloadId {
833 self.payload_id
834 }
835}
836
837#[derive(Debug)]
839pub enum BuildOutcome<Payload> {
840 Better {
842 payload: Payload,
844 cached_reads: CachedReads,
846 },
847 Aborted {
849 fees: U256,
851 cached_reads: CachedReads,
853 },
854 Cancelled,
856
857 Freeze(Payload),
859}
860
861impl<Payload> BuildOutcome<Payload> {
862 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 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 pub const fn is_better(&self) -> bool {
880 matches!(self, Self::Better { .. })
881 }
882
883 pub const fn is_frozen(&self) -> bool {
885 matches!(self, Self::Freeze { .. })
886 }
887
888 pub const fn is_aborted(&self) -> bool {
890 matches!(self, Self::Aborted { .. })
891 }
892
893 pub const fn is_cancelled(&self) -> bool {
895 matches!(self, Self::Cancelled)
896 }
897
898 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#[derive(Debug)]
916pub enum BuildOutcomeKind<Payload> {
917 Better {
919 payload: Payload,
921 },
922 Aborted {
924 fees: U256,
926 },
927 Cancelled,
929 Freeze(Payload),
931}
932
933impl<Payload> BuildOutcomeKind<Payload> {
934 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#[derive(Debug)]
951pub struct BuildArguments<Attributes, Payload: BuiltPayload> {
952 pub cached_reads: CachedReads,
954 pub execution_cache: Option<SavedCache>,
956 pub state_root_handle: Option<PayloadStateRootHandle>,
961 pub config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
963 pub cancel: CancelOnDrop,
965 pub best_payload: Option<Payload>,
967}
968
969impl<Attributes, Payload: BuiltPayload> BuildArguments<Attributes, Payload> {
970 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
983pub trait PayloadBuilder: Send + Sync + Clone {
992 type Attributes: PayloadAttributes;
994 type BuiltPayload: BuiltPayload;
996
997 fn try_build(
1010 &self,
1011 args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
1012 ) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError>;
1013
1014 fn on_missing_payload(
1018 &self,
1019 _args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
1020 ) -> MissingPayloadBehaviour<Self::BuiltPayload> {
1021 MissingPayloadBehaviour::RaceEmptyPayload
1022 }
1023
1024 fn build_empty_payload(
1026 &self,
1027 config: PayloadConfig<Self::Attributes, HeaderForPayload<Self::BuiltPayload>>,
1028 ) -> Result<Self::BuiltPayload, PayloadBuilderError>;
1029}
1030
1031#[derive(Default)]
1035pub enum MissingPayloadBehaviour<Payload> {
1036 AwaitInProgress,
1038 #[default]
1040 RaceEmptyPayload,
1041 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#[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
1065fn 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 #[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 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}