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_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
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 .map_err(PayloadBuilderError::from)?
174 .ok_or_else(|| PayloadBuilderError::MissingParentHeader(B256::ZERO))?
175 } else {
176 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 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 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 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 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#[derive(Debug, Clone)]
252pub struct PrecachedState {
253 pub block: B256,
255 pub cached: CachedReads,
257}
258
259#[derive(Debug, Clone, Copy)]
261struct PrecachedParentBlockInfo {
262 block: B256,
264 parent_block_info: PayloadParentBlockInfo,
266}
267
268#[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
280impl PayloadTaskGuard {
283 pub fn new(max_payload_tasks: usize) -> Self {
285 Self(Arc::new(Semaphore::new(max_payload_tasks)))
286 }
287
288 async fn acquire_owned(&self) -> tokio::sync::OwnedSemaphorePermit {
290 self.0.clone().acquire_owned().await.expect("payload task semaphore closed")
291 }
292}
293
294#[derive(Debug, Clone)]
296pub struct BasicPayloadJobGeneratorConfig {
297 interval: Duration,
299 deadline: Duration,
303 max_payload_tasks: usize,
305 pre_cache_state: bool,
307}
308
309impl BasicPayloadJobGeneratorConfig {
312 pub const fn interval(mut self, interval: Duration) -> Self {
314 self.interval = interval;
315 self
316 }
317
318 pub const fn deadline(mut self, deadline: Duration) -> Self {
320 self.deadline = deadline;
321 self
322 }
323
324 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 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 deadline: SLOT_DURATION,
351 max_payload_tasks: 3,
352 pre_cache_state: true,
353 }
354 }
355}
356
357#[derive(Debug)]
368pub struct BasicPayloadJob<Builder>
369where
370 Builder: PayloadBuilder,
371{
372 config: PayloadConfig<Builder::Attributes, HeaderForPayload<Builder::BuiltPayload>>,
374 executor: Runtime,
376 deadline: Pin<Box<Sleep>>,
378 interval: Interval,
380 best_payload: PayloadState<Builder::BuiltPayload>,
382 pending_block: Option<PendingPayload<Builder::BuiltPayload>>,
384 payload_task_guard: PayloadTaskGuard,
386 cached_reads: Option<CachedReads>,
391 execution_cache: Option<SavedCache>,
393 state_root_handle: Option<PayloadStateRootHandle>,
395 leases: Vec<PayloadBuilderLease>,
400 metrics: PayloadBuilderMetrics,
402 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 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 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 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 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 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 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 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 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 self.metrics.inc_requested_empty_payload();
594 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 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#[derive(Debug, Clone)]
635pub enum PayloadState<P> {
636 Missing,
638 Best(P),
640 Frozen(P),
644}
645
646impl<P> PayloadState<P> {
647 pub const fn is_frozen(&self) -> bool {
649 matches!(self, Self::Frozen(_))
650 }
651
652 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#[derive(Debug)]
671pub struct ResolveBestPayload<Payload> {
672 pub best_payload: Option<Payload>,
674 pub maybe_better: Option<PendingPayload<Payload>>,
676 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 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#[derive(Debug)]
740pub struct PendingPayload<P> {
741 cancel: CancelOnDrop,
743 payload: oneshot::Receiver<Result<BuildOutcome<P>, PayloadBuilderError>>,
745}
746
747impl<P> PendingPayload<P> {
748 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#[derive(Clone, Debug)]
768pub struct PayloadConfig<Attributes, Header = alloy_consensus::Header> {
769 pub parent_header: Arc<SealedHeader<Header>>,
771 pub parent_block_info: Option<PayloadParentBlockInfo>,
773 pub attributes: Attributes,
775 pub payload_id: PayloadId,
777}
778
779#[derive(Clone, Copy, Debug, PartialEq, Eq)]
781pub struct PayloadParentBlockInfo {
782 pub transaction_count: usize,
784}
785
786impl<Attributes, Header> PayloadConfig<Attributes, Header>
787where
788 Attributes: PayloadAttributes,
789{
790 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 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 pub const fn payload_id(&self) -> PayloadId {
810 self.payload_id
811 }
812}
813
814#[derive(Debug)]
816pub enum BuildOutcome<Payload> {
817 Better {
819 payload: Payload,
821 cached_reads: CachedReads,
823 },
824 Aborted {
826 fees: U256,
828 cached_reads: CachedReads,
830 },
831 Cancelled,
833
834 Freeze(Payload),
836}
837
838impl<Payload> BuildOutcome<Payload> {
839 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 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 pub const fn is_better(&self) -> bool {
857 matches!(self, Self::Better { .. })
858 }
859
860 pub const fn is_frozen(&self) -> bool {
862 matches!(self, Self::Freeze { .. })
863 }
864
865 pub const fn is_aborted(&self) -> bool {
867 matches!(self, Self::Aborted { .. })
868 }
869
870 pub const fn is_cancelled(&self) -> bool {
872 matches!(self, Self::Cancelled)
873 }
874
875 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#[derive(Debug)]
893pub enum BuildOutcomeKind<Payload> {
894 Better {
896 payload: Payload,
898 },
899 Aborted {
901 fees: U256,
903 },
904 Cancelled,
906 Freeze(Payload),
908}
909
910impl<Payload> BuildOutcomeKind<Payload> {
911 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#[derive(Debug)]
928pub struct BuildArguments<Attributes, Payload: BuiltPayload> {
929 pub cached_reads: CachedReads,
931 pub execution_cache: Option<SavedCache>,
933 pub state_root_handle: Option<PayloadStateRootHandle>,
940 pub config: PayloadConfig<Attributes, HeaderTy<Payload::Primitives>>,
942 pub cancel: CancelOnDrop,
944 pub best_payload: Option<Payload>,
946}
947
948impl<Attributes, Payload: BuiltPayload> BuildArguments<Attributes, Payload> {
949 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
962pub trait PayloadBuilder: Send + Sync + Clone {
971 type Attributes: PayloadAttributes;
973 type BuiltPayload: BuiltPayload;
975
976 fn try_build(
989 &self,
990 args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
991 ) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError>;
992
993 fn on_missing_payload(
997 &self,
998 _args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
999 ) -> MissingPayloadBehaviour<Self::BuiltPayload> {
1000 MissingPayloadBehaviour::RaceEmptyPayload
1001 }
1002
1003 fn build_empty_payload(
1005 &self,
1006 config: PayloadConfig<Self::Attributes, HeaderForPayload<Self::BuiltPayload>>,
1007 ) -> Result<Self::BuiltPayload, PayloadBuilderError>;
1008}
1009
1010#[derive(Default)]
1014pub enum MissingPayloadBehaviour<Payload> {
1015 AwaitInProgress,
1017 #[default]
1019 RaceEmptyPayload,
1020 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#[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
1048fn 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}