-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathpayload_builder_vanilla.rs
1426 lines (1286 loc) · 51.7 KB
/
payload_builder_vanilla.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::generator::BlockPayloadJobGenerator;
use crate::generator::BuildArguments;
use crate::{
generator::{BlockCell, PayloadBuilder},
metrics::OpRBuilderMetrics,
tx_signer::Signer,
};
use alloy_consensus::constants::EMPTY_WITHDRAWALS;
use alloy_consensus::transaction::Recovered;
use alloy_consensus::{
Eip658Value, Header, Transaction, TxEip1559, Typed2718, EMPTY_OMMER_ROOT_HASH,
};
use alloy_eips::merge::BEACON_NONCE;
use alloy_primitives::private::alloy_rlp::Encodable;
use alloy_primitives::{Address, Bytes, TxHash, TxKind, B256, U256};
use alloy_rpc_types_engine::PayloadId;
use alloy_rpc_types_eth::Withdrawals;
use op_alloy_consensus::{OpDepositReceipt, OpTypedTransaction};
use reth::builder::{components::PayloadServiceBuilder, node::FullNodeTypes, BuilderContext};
use reth::core::primitives::InMemorySize;
use reth::payload::PayloadBuilderHandle;
use reth_basic_payload_builder::{
BasicPayloadJobGeneratorConfig, BuildOutcome, BuildOutcomeKind, PayloadConfig,
};
use reth_chain_state::{ExecutedBlock, ExecutedBlockWithTrieUpdates};
use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks};
use reth_evm::{
env::EvmEnv, system_calls::SystemCaller, ConfigureEvmEnv, ConfigureEvmFor, Database, Evm,
EvmError, InvalidTxError, NextBlockEnvAttributes,
};
use reth_execution_types::ExecutionOutcome;
use reth_node_api::NodePrimitives;
use reth_node_api::NodeTypesWithEngine;
use reth_node_api::TxTy;
use reth_optimism_chainspec::OpChainSpec;
use reth_optimism_consensus::calculate_receipt_root_no_memo_optimism;
use reth_optimism_evm::BasicOpReceiptBuilder;
use reth_optimism_evm::OpEvmConfig;
use reth_optimism_evm::{OpReceiptBuilder, ReceiptBuilderCtx};
use reth_optimism_forks::OpHardforks;
use reth_optimism_node::OpEngineTypes;
use reth_optimism_payload_builder::config::{OpBuilderConfig, OpDAConfig};
use reth_optimism_payload_builder::OpPayloadPrimitives;
use reth_optimism_payload_builder::{
error::OpPayloadBuilderError,
payload::{OpBuiltPayload, OpPayloadBuilderAttributes},
};
use reth_optimism_primitives::{
OpPrimitives, OpTransactionSigned, ADDRESS_L2_TO_L1_MESSAGE_PASSER,
};
use reth_payload_builder::PayloadBuilderService;
use reth_payload_builder_primitives::PayloadBuilderError;
use reth_payload_primitives::PayloadBuilderAttributes;
use reth_payload_util::BestPayloadTransactions;
use reth_payload_util::PayloadTransactions;
use reth_primitives::{transaction::SignedTransactionIntoRecoveredExt, BlockBody, SealedHeader};
use reth_primitives_traits::proofs;
use reth_primitives_traits::Block;
use reth_primitives_traits::RecoveredBlock;
use reth_primitives_traits::SignedTransaction;
use reth_provider::CanonStateSubscriptions;
use reth_provider::{
HashedPostStateProvider, ProviderError, StateProviderFactory, StateRootProvider,
StorageRootProvider,
};
use reth_revm::database::StateProviderDatabase;
use reth_transaction_pool::BestTransactionsAttributes;
use reth_transaction_pool::PoolTransaction;
use reth_transaction_pool::TransactionPool;
use revm::{
db::{states::bundle_state::BundleRetention, State},
primitives::{ExecutionResult, ResultAndState},
DatabaseCommit,
};
use std::collections::HashSet;
use std::error::Error as StdError;
use std::{fmt::Display, sync::Arc, time::Instant};
use tokio_util::sync::CancellationToken;
use tracing::{info, trace, warn};
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CustomOpPayloadBuilder {
builder_signer: Option<Signer>,
#[cfg(feature = "flashblocks")]
flashblocks_ws_url: String,
#[cfg(feature = "flashblocks")]
chain_block_time: u64,
#[cfg(feature = "flashblocks")]
flashblock_block_time: u64,
}
impl CustomOpPayloadBuilder {
#[cfg(feature = "flashblocks")]
pub fn new(
builder_signer: Option<Signer>,
flashblocks_ws_url: String,
chain_block_time: u64,
flashblock_block_time: u64,
) -> Self {
Self {
builder_signer,
flashblocks_ws_url,
chain_block_time,
flashblock_block_time,
}
}
#[cfg(not(feature = "flashblocks"))]
pub fn new(
builder_signer: Option<Signer>,
_flashblocks_ws_url: String,
_chain_block_time: u64,
_flashblock_block_time: u64,
) -> Self {
Self { builder_signer }
}
}
impl<Node, Pool> PayloadServiceBuilder<Node, Pool> for CustomOpPayloadBuilder
where
Node: FullNodeTypes<
Types: NodeTypesWithEngine<
Engine = OpEngineTypes,
ChainSpec = OpChainSpec,
Primitives = OpPrimitives,
>,
>,
Pool: TransactionPool<Transaction: PoolTransaction<Consensus = TxTy<Node::Types>>>
+ Unpin
+ 'static,
{
type PayloadBuilder = OpPayloadBuilderVanilla<Pool, Node::Provider, OpEvmConfig, OpPrimitives>;
async fn build_payload_builder(
&self,
ctx: &BuilderContext<Node>,
pool: Pool,
) -> eyre::Result<Self::PayloadBuilder> {
Ok(OpPayloadBuilderVanilla::new(
OpEvmConfig::new(ctx.chain_spec()),
self.builder_signer,
pool,
ctx.provider().clone(),
Arc::new(BasicOpReceiptBuilder::default()),
))
}
fn spawn_payload_builder_service(
self,
ctx: &BuilderContext<Node>,
payload_builder: Self::PayloadBuilder,
) -> eyre::Result<PayloadBuilderHandle<<Node::Types as NodeTypesWithEngine>::Engine>> {
tracing::info!("Spawning a custom payload builder");
let payload_job_config = BasicPayloadJobGeneratorConfig::default();
let payload_generator = BlockPayloadJobGenerator::with_builder(
ctx.provider().clone(),
ctx.task_executor().clone(),
payload_job_config,
payload_builder,
false,
);
let (payload_service, payload_builder) =
PayloadBuilderService::new(payload_generator, ctx.provider().canonical_state_stream());
ctx.task_executor()
.spawn_critical("custom payload builder service", Box::pin(payload_service));
tracing::info!("Custom payload service started");
Ok(payload_builder)
}
}
impl<Pool, Client, EvmConfig, N, Txs> reth_basic_payload_builder::PayloadBuilder
for OpPayloadBuilderVanilla<Pool, Client, EvmConfig, N, Txs>
where
Pool: Clone + Send + Sync,
Client: Clone + Send + Sync,
EvmConfig: Clone + Send + Sync,
N: NodePrimitives,
Txs: Clone + Send + Sync,
{
type Attributes = OpPayloadBuilderAttributes<N::SignedTx>;
type BuiltPayload = OpBuiltPayload<N>;
fn try_build(
&self,
_args: reth_basic_payload_builder::BuildArguments<Self::Attributes, Self::BuiltPayload>,
) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError> {
unimplemented!()
}
fn build_empty_payload(
&self,
_config: reth_basic_payload_builder::PayloadConfig<
Self::Attributes,
reth_basic_payload_builder::HeaderForPayload<Self::BuiltPayload>,
>,
) -> Result<Self::BuiltPayload, PayloadBuilderError> {
unimplemented!()
}
}
/// Optimism's payload builder
#[derive(Debug, Clone)]
pub struct OpPayloadBuilderVanilla<Pool, Client, EvmConfig, N: NodePrimitives, Txs = ()> {
/// The type responsible for creating the evm.
pub evm_config: EvmConfig,
/// The builder's signer key to use for an end of block tx
pub builder_signer: Option<Signer>,
/// The transaction pool
pub pool: Pool,
/// Node client
pub client: Client,
/// Settings for the builder, e.g. DA settings.
pub config: OpBuilderConfig,
/// The type responsible for yielding the best transactions for the payload if mempool
/// transactions are allowed.
pub best_transactions: Txs,
/// The metrics for the builder
pub metrics: OpRBuilderMetrics,
/// Node primitive types.
pub receipt_builder: Arc<dyn OpReceiptBuilder<N::SignedTx, Receipt = N::Receipt>>,
}
impl<Pool, Client, EvmConfig, N: NodePrimitives>
OpPayloadBuilderVanilla<Pool, Client, EvmConfig, N>
{
/// `OpPayloadBuilder` constructor.
pub fn new(
evm_config: EvmConfig,
builder_signer: Option<Signer>,
pool: Pool,
client: Client,
receipt_builder: Arc<dyn OpReceiptBuilder<N::SignedTx, Receipt = N::Receipt>>,
) -> Self {
Self::with_builder_config(
evm_config,
builder_signer,
pool,
client,
receipt_builder,
Default::default(),
)
}
pub fn with_builder_config(
evm_config: EvmConfig,
builder_signer: Option<Signer>,
pool: Pool,
client: Client,
receipt_builder: Arc<dyn OpReceiptBuilder<N::SignedTx, Receipt = N::Receipt>>,
config: OpBuilderConfig,
) -> Self {
Self {
pool,
client,
receipt_builder,
config,
evm_config,
best_transactions: (),
metrics: Default::default(),
builder_signer,
}
}
}
impl<EvmConfig, Pool, Client, N, Txs> PayloadBuilder
for OpPayloadBuilderVanilla<Pool, Client, EvmConfig, N, Txs>
where
Client: StateProviderFactory + ChainSpecProvider<ChainSpec: EthChainSpec + OpHardforks> + Clone,
N: OpPayloadPrimitives<_TX = OpTransactionSigned>,
Pool: TransactionPool<Transaction: PoolTransaction<Consensus = N::SignedTx>>,
EvmConfig: ConfigureEvmFor<N>,
Txs: OpPayloadTransactions<Pool::Transaction>,
{
type Attributes = OpPayloadBuilderAttributes<N::SignedTx>;
type BuiltPayload = OpBuiltPayload<N>;
fn try_build(
&self,
args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
best_payload: BlockCell<Self::BuiltPayload>,
) -> Result<(), PayloadBuilderError> {
let pool = self.pool.clone();
let block_build_start_time = Instant::now();
match self.build_payload(
args,
|attrs| {
#[allow(clippy::unit_arg)]
self.best_transactions
.best_transactions(pool.clone(), attrs)
},
|hashes| {
#[allow(clippy::unit_arg)]
self.best_transactions.remove_reverted(pool.clone(), hashes)
},
)? {
BuildOutcome::Better { payload, .. } => {
best_payload.set(payload);
self.metrics
.total_block_built_duration
.record(block_build_start_time.elapsed());
self.metrics.block_built_success.increment(1);
Ok(())
}
BuildOutcome::Freeze(payload) => {
best_payload.set(payload);
self.metrics
.total_block_built_duration
.record(block_build_start_time.elapsed());
Ok(())
}
BuildOutcome::Cancelled => {
tracing::warn!("Payload build cancelled");
Err(PayloadBuilderError::MissingPayload)
}
_ => {
tracing::warn!("No better payload found");
Err(PayloadBuilderError::MissingPayload)
}
}
}
}
impl<Pool, Client, EvmConfig, N, T> OpPayloadBuilderVanilla<Pool, Client, EvmConfig, N, T>
where
Pool: TransactionPool<Transaction: PoolTransaction<Consensus = N::SignedTx>>,
Client: StateProviderFactory + ChainSpecProvider<ChainSpec: EthChainSpec + OpHardforks>,
N: OpPayloadPrimitives<_TX = OpTransactionSigned>,
EvmConfig: ConfigureEvmFor<N>,
{
/// Constructs an Optimism payload from the transactions sent via the
/// Payload attributes by the sequencer. If the `no_tx_pool` argument is passed in
/// the payload attributes, the transaction pool will be ignored and the only transactions
/// included in the payload will be those sent through the attributes.
///
/// Given build arguments including an Optimism client, transaction pool,
/// and configuration, this function creates a transaction payload. Returns
/// a result indicating success with the payload or an error in case of failure.
fn build_payload<'a, Txs>(
&self,
args: BuildArguments<OpPayloadBuilderAttributes<N::SignedTx>, OpBuiltPayload<N>>,
best: impl FnOnce(BestTransactionsAttributes) -> Txs + Send + Sync + 'a,
remove_reverted: impl FnOnce(Vec<TxHash>),
) -> Result<BuildOutcome<OpBuiltPayload<N>>, PayloadBuilderError>
where
Txs: PayloadTransactions<Transaction: PoolTransaction<Consensus = N::SignedTx>>,
{
let evm_env = self
.evm_env(&args.config.attributes, &args.config.parent_header)
.map_err(PayloadBuilderError::other)?;
let BuildArguments {
mut cached_reads,
config,
cancel,
} = args;
let ctx = OpPayloadBuilderCtx {
evm_config: self.evm_config.clone(),
da_config: self.config.da_config.clone(),
chain_spec: self.client.chain_spec(),
config,
evm_env,
cancel,
receipt_builder: self.receipt_builder.clone(),
builder_signer: self.builder_signer,
metrics: Default::default(),
};
let builder = OpBuilder::new(best, remove_reverted);
let state_provider = self.client.state_by_block_hash(ctx.parent().hash())?;
let state = StateProviderDatabase::new(state_provider);
if ctx.attributes().no_tx_pool {
let db = State::builder()
.with_database(state)
.with_bundle_update()
.build();
builder.build(db, ctx)
} else {
// sequencer mode we can reuse cachedreads from previous runs
let db = State::builder()
.with_database(cached_reads.as_db_mut(state))
.with_bundle_update()
.build();
builder.build(db, ctx)
}
.map(|out| out.with_cached_reads(cached_reads))
}
/// Returns the configured [`EvmEnv`] for the targeted payload
/// (that has the `parent` as its parent).
pub fn evm_env(
&self,
attributes: &OpPayloadBuilderAttributes<N::SignedTx>,
parent: &Header,
) -> Result<EvmEnv<EvmConfig::Spec>, EvmConfig::Error> {
let next_attributes = NextBlockEnvAttributes {
timestamp: attributes.timestamp(),
suggested_fee_recipient: attributes.suggested_fee_recipient(),
prev_randao: attributes.prev_randao(),
gas_limit: attributes.gas_limit.unwrap_or(parent.gas_limit),
};
self.evm_config.next_evm_env(parent, next_attributes)
}
}
/// The type that builds the payload.
///
/// Payload building for optimism is composed of several steps.
/// The first steps are mandatory and defined by the protocol.
///
/// 1. first all System calls are applied.
/// 2. After canyon the forced deployed `create2deployer` must be loaded
/// 3. all sequencer transactions are executed (part of the payload attributes)
///
/// Depending on whether the node acts as a sequencer and is allowed to include additional
/// transactions (`no_tx_pool == false`):
/// 4. include additional transactions
///
/// And finally
/// 5. build the block: compute all roots (txs, state)
#[derive(derive_more::Debug)]
pub struct OpBuilder<'a, Txs> {
/// Yields the best transaction to include if transactions from the mempool are allowed.
best: Box<dyn FnOnce(BestTransactionsAttributes) -> Txs + 'a>,
/// Removes reverted transactions from the tx pool
#[debug(skip)]
remove_reverted: Box<dyn FnOnce(Vec<TxHash>) + 'a>,
}
impl<'a, Txs> OpBuilder<'a, Txs> {
fn new(
best: impl FnOnce(BestTransactionsAttributes) -> Txs + Send + Sync + 'a,
remove_reverted: impl FnOnce(Vec<TxHash>) + 'a,
) -> Self {
Self {
best: Box::new(best),
remove_reverted: Box::new(remove_reverted),
}
}
}
impl<Txs> OpBuilder<'_, Txs> {
/// Executes the payload and returns the outcome.
pub fn execute<EvmConfig, ChainSpec, N, DB, P>(
self,
state: &mut State<DB>,
ctx: &OpPayloadBuilderCtx<EvmConfig, ChainSpec, N>,
) -> Result<BuildOutcomeKind<ExecutedPayload<N>>, PayloadBuilderError>
where
N: OpPayloadPrimitives<_TX = OpTransactionSigned>,
Txs: PayloadTransactions<Transaction: PoolTransaction<Consensus = N::SignedTx>>,
EvmConfig: ConfigureEvmFor<N>,
ChainSpec: EthChainSpec + OpHardforks,
DB: Database<Error = ProviderError> + AsRef<P>,
P: StorageRootProvider,
{
let Self {
best,
remove_reverted,
} = self;
info!(target: "payload_builder", id=%ctx.payload_id(), parent_header = ?ctx.parent().hash(), parent_number = ctx.parent().number, "building new payload");
// 1. apply eip-4788 pre block contract call
ctx.apply_pre_beacon_root_contract_call(state)?;
// 2. ensure create2deployer is force deployed
ctx.ensure_create2_deployer(state)?;
let sequencer_tx_start_time = Instant::now();
// 3. execute sequencer transactions
let mut info = ctx.execute_sequencer_transactions(state)?;
ctx.metrics
.sequencer_tx_duration
.record(sequencer_tx_start_time.elapsed());
// 4. if mem pool transactions are requested we execute them
// gas reserved for builder tx
let message = format!("Block Number: {}", ctx.block_number())
.as_bytes()
.to_vec();
let builder_tx_gas = ctx
.builder_signer()
.map_or(0, |_| estimate_gas_for_builder_tx(message.clone()));
let block_gas_limit = ctx.block_gas_limit() - builder_tx_gas;
// Save some space in the block_da_limit for builder tx
let builder_tx_da_size = ctx
.estimate_builder_tx_da_size(state, builder_tx_gas, message.clone())
.unwrap_or(0);
let block_da_limit = ctx
.da_config
.max_da_block_size()
.map(|da_size| da_size - builder_tx_da_size as u64);
// Check that it's possible to create builder tx, considering max_da_tx_size, otherwise panic
if let Some(tx_da_limit) = ctx.da_config.max_da_tx_size() {
// Panic indicate max_da_tx_size misconfiguration
assert!(
tx_da_limit >= builder_tx_da_size as u64,
"The configured da_config.max_da_tx_size is too small to accommodate builder tx."
);
}
if !ctx.attributes().no_tx_pool {
let best_txs_start_time = Instant::now();
let best_txs = best(ctx.best_transaction_attributes());
ctx.metrics
.transaction_pool_fetch_duration
.record(best_txs_start_time.elapsed());
if ctx
.execute_best_transactions(
&mut info,
state,
best_txs,
block_gas_limit,
block_da_limit,
)?
.is_some()
{
return Ok(BuildOutcomeKind::Cancelled);
}
}
// Add builder tx to the block
ctx.add_builder_tx(&mut info, state, builder_tx_gas, message);
let state_merge_start_time = Instant::now();
// merge all transitions into bundle state, this would apply the withdrawal balance changes
// and 4788 contract call
state.merge_transitions(BundleRetention::Reverts);
ctx.metrics
.state_transition_merge_duration
.record(state_merge_start_time.elapsed());
ctx.metrics
.payload_num_tx
.record(info.executed_transactions.len() as f64);
let withdrawals_root = if ctx.is_isthmus_active() {
// withdrawals root field in block header is used for storage root of L2 predeploy
// `l2tol1-message-passer`
Some(
state
.database
.as_ref()
.storage_root(ADDRESS_L2_TO_L1_MESSAGE_PASSER, Default::default())?,
)
} else if ctx.is_canyon_active() {
Some(EMPTY_WITHDRAWALS)
} else {
None
};
remove_reverted(info.reverted_tx_hashes.iter().copied().collect());
let payload = ExecutedPayload {
info,
withdrawals_root,
};
Ok(BuildOutcomeKind::Better { payload })
}
/// Builds the payload on top of the state.
pub fn build<EvmConfig, ChainSpec, N, DB, P>(
self,
mut state: State<DB>,
ctx: OpPayloadBuilderCtx<EvmConfig, ChainSpec, N>,
) -> Result<BuildOutcomeKind<OpBuiltPayload<N>>, PayloadBuilderError>
where
EvmConfig: ConfigureEvmFor<N>,
ChainSpec: EthChainSpec + OpHardforks,
N: OpPayloadPrimitives<_TX = OpTransactionSigned>,
Txs: PayloadTransactions<Transaction: PoolTransaction<Consensus = N::SignedTx>>,
DB: Database<Error = ProviderError> + AsRef<P>,
P: StateRootProvider + HashedPostStateProvider + StorageRootProvider,
{
let ExecutedPayload {
info,
withdrawals_root,
} = match self.execute(&mut state, &ctx)? {
BuildOutcomeKind::Better { payload } | BuildOutcomeKind::Freeze(payload) => payload,
BuildOutcomeKind::Cancelled => return Ok(BuildOutcomeKind::Cancelled),
BuildOutcomeKind::Aborted { fees } => return Ok(BuildOutcomeKind::Aborted { fees }),
};
let block_number = ctx.block_number();
let execution_outcome = ExecutionOutcome::new(
state.take_bundle(),
vec![info.receipts],
block_number,
Vec::new(),
);
let receipts_root = execution_outcome
.generic_receipts_root_slow(block_number, |receipts| {
calculate_receipt_root_no_memo_optimism(
receipts,
&ctx.chain_spec,
ctx.attributes().timestamp(),
)
})
.expect("Number is in range");
let logs_bloom = execution_outcome
.block_logs_bloom(block_number)
.expect("Number is in range");
// calculate the state root
let state_root_start_time = Instant::now();
let state_provider = state.database.as_ref();
let hashed_state = state_provider.hashed_post_state(execution_outcome.state());
let (state_root, trie_output) = {
state
.database
.as_ref()
.state_root_with_updates(hashed_state.clone())
.inspect_err(|err| {
warn!(target: "payload_builder",
parent_header=%ctx.parent().hash(),
%err,
"failed to calculate state root for payload"
);
})?
};
ctx.metrics
.state_root_calculation_duration
.record(state_root_start_time.elapsed());
// create the block header
let transactions_root = proofs::calculate_transaction_root(&info.executed_transactions);
// OP doesn't support blobs/EIP-4844.
// https://specs.optimism.io/protocol/exec-engine.html#ecotone-disable-blob-transactions
// Need [Some] or [None] based on hardfork to match block hash.
let (excess_blob_gas, blob_gas_used) = ctx.blob_fields();
let extra_data = ctx.extra_data()?;
let header = Header {
parent_hash: ctx.parent().hash(),
ommers_hash: EMPTY_OMMER_ROOT_HASH,
beneficiary: ctx.evm_env.block_env.coinbase,
state_root,
transactions_root,
receipts_root,
withdrawals_root,
logs_bloom,
timestamp: ctx.attributes().payload_attributes.timestamp,
mix_hash: ctx.attributes().payload_attributes.prev_randao,
nonce: BEACON_NONCE.into(),
base_fee_per_gas: Some(ctx.base_fee()),
number: ctx.parent().number + 1,
gas_limit: ctx.block_gas_limit(),
difficulty: U256::ZERO,
gas_used: info.cumulative_gas_used,
extra_data,
parent_beacon_block_root: ctx.attributes().payload_attributes.parent_beacon_block_root,
blob_gas_used,
excess_blob_gas,
requests_hash: None,
};
// seal the block
let block = N::Block::new(
header,
BlockBody {
transactions: info.executed_transactions,
ommers: vec![],
withdrawals: ctx.withdrawals().cloned(),
},
);
let sealed_block = Arc::new(block.seal_slow());
info!(target: "payload_builder", id=%ctx.attributes().payload_id(), "sealed built block");
// create the executed block data
let executed: ExecutedBlockWithTrieUpdates<N> = ExecutedBlockWithTrieUpdates {
block: ExecutedBlock {
recovered_block: Arc::new(RecoveredBlock::new_sealed(
sealed_block.as_ref().clone(),
info.executed_senders,
)),
execution_output: Arc::new(execution_outcome),
hashed_state: Arc::new(hashed_state),
},
trie: Arc::new(trie_output),
};
let no_tx_pool = ctx.attributes().no_tx_pool;
let payload = OpBuiltPayload::new(
ctx.payload_id(),
sealed_block,
info.total_fees,
Some(executed),
);
ctx.metrics
.payload_byte_size
.record(payload.block().size() as f64);
if no_tx_pool {
// if `no_tx_pool` is set only transactions from the payload attributes will be included
// in the payload. In other words, the payload is deterministic and we can
// freeze it once we've successfully built it.
Ok(BuildOutcomeKind::Freeze(payload))
} else {
Ok(BuildOutcomeKind::Better { payload })
}
}
}
/// A type that returns a the [`PayloadTransactions`] that should be included in the pool.
pub trait OpPayloadTransactions<Transaction>: Clone + Send + Sync + Unpin + 'static {
/// Returns an iterator that yields the transaction in the order they should get included in the
/// new payload.
fn best_transactions<Pool: TransactionPool<Transaction = Transaction>>(
&self,
pool: Pool,
attr: BestTransactionsAttributes,
) -> impl PayloadTransactions<Transaction = Transaction>;
/// Removes reverted transactions from the tx pool
fn remove_reverted<Pool: TransactionPool<Transaction = Transaction>>(
&self,
pool: Pool,
hashes: Vec<TxHash>,
);
}
impl<T: PoolTransaction> OpPayloadTransactions<T> for () {
fn best_transactions<Pool: TransactionPool<Transaction = T>>(
&self,
pool: Pool,
attr: BestTransactionsAttributes,
) -> impl PayloadTransactions<Transaction = T> {
BestPayloadTransactions::new(pool.best_transactions_with_attributes(attr))
}
fn remove_reverted<Pool: TransactionPool<Transaction = T>>(
&self,
pool: Pool,
hashes: Vec<TxHash>,
) {
pool.remove_transactions(hashes);
}
}
/// Holds the state after execution
#[derive(Debug)]
pub struct ExecutedPayload<N: NodePrimitives> {
/// Tracked execution info
pub info: ExecutionInfo<N>,
/// Withdrawal hash.
pub withdrawals_root: Option<B256>,
}
/// This acts as the container for executed transactions and its byproducts (receipts, gas used)
#[derive(Default, Debug)]
pub struct ExecutionInfo<N: NodePrimitives> {
/// All executed transactions (unrecovered).
pub executed_transactions: Vec<N::SignedTx>,
/// The recovered senders for the executed transactions.
pub executed_senders: Vec<Address>,
/// The transaction receipts
pub receipts: Vec<N::Receipt>,
/// All gas used so far
pub cumulative_gas_used: u64,
/// Estimated DA size
pub cumulative_da_bytes_used: u64,
/// Tracks fees from executed mempool transactions
pub total_fees: U256,
/// Tracks the reverted transaction hashes to remove from the transaction pool
pub reverted_tx_hashes: HashSet<TxHash>,
}
impl<N: NodePrimitives> ExecutionInfo<N> {
/// Create a new instance with allocated slots.
pub fn with_capacity(capacity: usize) -> Self {
Self {
executed_transactions: Vec::with_capacity(capacity),
executed_senders: Vec::with_capacity(capacity),
receipts: Vec::with_capacity(capacity),
cumulative_gas_used: 0,
cumulative_da_bytes_used: 0,
total_fees: U256::ZERO,
reverted_tx_hashes: HashSet::new(),
}
}
/// Returns true if the transaction would exceed the block limits:
/// - block gas limit: ensures the transaction still fits into the block.
/// - tx DA limit: if configured, ensures the tx does not exceed the maximum allowed DA limit
/// per tx.
/// - block DA limit: if configured, ensures the transaction's DA size does not exceed the
/// maximum allowed DA limit per block.
pub fn is_tx_over_limits(
&self,
tx: &N::SignedTx,
block_gas_limit: u64,
tx_data_limit: Option<u64>,
block_data_limit: Option<u64>,
) -> bool {
if tx_data_limit.is_some_and(|da_limit| tx.length() as u64 > da_limit) {
return true;
}
if block_data_limit
.is_some_and(|da_limit| self.cumulative_da_bytes_used + (tx.length() as u64) > da_limit)
{
return true;
}
self.cumulative_gas_used + tx.gas_limit() > block_gas_limit
}
}
/// Container type that holds all necessities to build a new payload.
#[derive(Debug)]
pub struct OpPayloadBuilderCtx<EvmConfig: ConfigureEvmEnv, ChainSpec, N: NodePrimitives> {
/// The type that knows how to perform system calls and configure the evm.
pub evm_config: EvmConfig,
/// The DA config for the payload builder
pub da_config: OpDAConfig,
/// The chainspec
pub chain_spec: Arc<ChainSpec>,
/// How to build the payload.
pub config: PayloadConfig<OpPayloadBuilderAttributes<N::SignedTx>>,
/// Evm Settings
pub evm_env: EvmEnv<EvmConfig::Spec>,
/// Marker to check whether the job has been cancelled.
pub cancel: CancellationToken,
/// Receipt builder.
pub receipt_builder: Arc<dyn OpReceiptBuilder<N::SignedTx, Receipt = N::Receipt>>,
/// The builder signer
pub builder_signer: Option<Signer>,
/// The metrics for the builder
pub metrics: OpRBuilderMetrics,
}
impl<EvmConfig, ChainSpec, N> OpPayloadBuilderCtx<EvmConfig, ChainSpec, N>
where
EvmConfig: ConfigureEvmEnv,
ChainSpec: EthChainSpec + OpHardforks,
N: NodePrimitives,
{
/// Returns the parent block the payload will be build on.
pub fn parent(&self) -> &SealedHeader {
&self.config.parent_header
}
/// Returns the builder attributes.
pub const fn attributes(&self) -> &OpPayloadBuilderAttributes<N::SignedTx> {
&self.config.attributes
}
/// Returns the withdrawals if shanghai is active.
pub fn withdrawals(&self) -> Option<&Withdrawals> {
self.chain_spec
.is_shanghai_active_at_timestamp(self.attributes().timestamp())
.then(|| &self.attributes().payload_attributes.withdrawals)
}
/// Returns the block gas limit to target.
pub fn block_gas_limit(&self) -> u64 {
self.attributes()
.gas_limit
.unwrap_or_else(|| self.evm_env.block_env.gas_limit.saturating_to())
}
/// Returns the block number for the block.
pub fn block_number(&self) -> u64 {
self.evm_env.block_env.number.to()
}
/// Returns the current base fee
pub fn base_fee(&self) -> u64 {
self.evm_env.block_env.basefee.to()
}
/// Returns the current blob gas price.
pub fn get_blob_gasprice(&self) -> Option<u64> {
self.evm_env
.block_env
.get_blob_gasprice()
.map(|gasprice| gasprice as u64)
}
/// Returns the blob fields for the header.
///
/// This will always return `Some(0)` after ecotone.
pub fn blob_fields(&self) -> (Option<u64>, Option<u64>) {
// OP doesn't support blobs/EIP-4844.
// https://specs.optimism.io/protocol/exec-engine.html#ecotone-disable-blob-transactions
// Need [Some] or [None] based on hardfork to match block hash.
if self.is_ecotone_active() {
(Some(0), Some(0))
} else {
(None, None)
}
}
/// Returns the extra data for the block.
///
/// After holocene this extracts the extradata from the paylpad
pub fn extra_data(&self) -> Result<Bytes, PayloadBuilderError> {
if self.is_holocene_active() {
self.attributes()
.get_holocene_extra_data(
self.chain_spec.base_fee_params_at_timestamp(
self.attributes().payload_attributes.timestamp,
),
)
.map_err(PayloadBuilderError::other)
} else {
Ok(Default::default())
}
}
/// Returns the current fee settings for transactions from the mempool
pub fn best_transaction_attributes(&self) -> BestTransactionsAttributes {
BestTransactionsAttributes::new(self.base_fee(), self.get_blob_gasprice())
}
/// Returns the unique id for this payload job.
pub fn payload_id(&self) -> PayloadId {
self.attributes().payload_id()
}
/// Returns true if regolith is active for the payload.
pub fn is_regolith_active(&self) -> bool {
self.chain_spec
.is_regolith_active_at_timestamp(self.attributes().timestamp())
}
/// Returns true if ecotone is active for the payload.
pub fn is_ecotone_active(&self) -> bool {
self.chain_spec
.is_ecotone_active_at_timestamp(self.attributes().timestamp())
}
/// Returns true if canyon is active for the payload.
pub fn is_canyon_active(&self) -> bool {
self.chain_spec
.is_canyon_active_at_timestamp(self.attributes().timestamp())
}
/// Returns true if holocene is active for the payload.
pub fn is_holocene_active(&self) -> bool {
self.chain_spec
.is_holocene_active_at_timestamp(self.attributes().timestamp())
}
/// Returns true if isthmus is active for the payload.
pub fn is_isthmus_active(&self) -> bool {
self.chain_spec
.is_isthmus_active_at_timestamp(self.attributes().timestamp())
}
/// Returns the chain id
pub fn chain_id(&self) -> u64 {
self.chain_spec.chain_id()
}
/// Returns the builder signer
pub fn builder_signer(&self) -> Option<Signer> {
self.builder_signer
}
/// Ensure that the create2deployer is force-deployed at the canyon transition. Optimism
/// blocks will always have at least a single transaction in them (the L1 info transaction),
/// so we can safely assume that this will always be triggered upon the transition and that
/// the above check for empty blocks will never be hit on OP chains.
pub fn ensure_create2_deployer<DB>(&self, db: &mut State<DB>) -> Result<(), PayloadBuilderError>
where
DB: Database,
DB::Error: Display,
{
reth_optimism_evm::ensure_create2_deployer(
self.chain_spec.clone(),
self.attributes().payload_attributes.timestamp,
db,
)
.map_err(|err| {
warn!(target: "payload_builder", %err, "missing create2 deployer, skipping block.");
PayloadBuilderError::other(OpPayloadBuilderError::ForceCreate2DeployerFail)
})
}
}