-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathrunner.rs
More file actions
1691 lines (1510 loc) · 68.5 KB
/
Copy pathrunner.rs
File metadata and controls
1691 lines (1510 loc) · 68.5 KB
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 std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::vec;
use alloy_eips::eip2718::{Decodable2718, Encodable2718};
use alloy_primitives::{keccak256, Address, Bytes, TxHash, U256};
use anyhow::{anyhow, bail};
use backoff::future::retry as retry_backoff;
use backoff::ExponentialBackoffBuilder;
use citrea_common::backup::BackupManager;
use citrea_common::{InitParams, RollupPublicKeys, SequencerConfig};
use citrea_evm::system_events::{signed_system_transaction, SystemEvent};
use citrea_evm::{
create_initial_system_events, get_last_l1_height_in_light_client,
populate_deposit_system_events, populate_set_block_info_event, AccountInfo, CallMessage, Evm,
RlpEvmTransaction, MIN_TRANSACTION_GAS, SYSTEM_SIGNER,
};
use citrea_primitives::basefee::calculate_next_block_base_fee;
use citrea_primitives::forks::fork_from_block_number;
use citrea_primitives::merkle::{compute_tx_hashes, compute_tx_merkle_root};
use citrea_primitives::types::L2BlockHash;
use citrea_stf::runtime::{CitreaRuntime, DefaultContext};
use parking_lot::Mutex;
use reth_execution_types::{Chain, ExecutionOutcome};
use reth_primitives::{Receipt, RecoveredBlock, SealedBlock};
use reth_provider::{BlockReaderIdExt, CanonStateNotification};
use reth_tasks::shutdown::GracefulShutdown;
use reth_tasks::TaskExecutor;
use reth_transaction_pool::error::InvalidPoolTransactionError;
use reth_transaction_pool::{
BestTransactions, BestTransactionsAttributes, EthPooledTransaction, PoolTransaction,
ValidPoolTransaction,
};
use revm::database::{AccountStatus, BundleAccount, BundleState};
use revm::state::AccountInfo as ReVmAccountInfo;
use sov_accounts::Accounts;
use sov_accounts::Response::{AccountEmpty, AccountExists};
use sov_db::ledger_db::{LedgerDB, SequencerLedgerOps, SharedLedgerOps};
use sov_db::schema::types::{L2BlockNumber, SlotNumber};
use sov_keys::default_signature::k256_private_key::K256PrivateKey;
use sov_modules_api::hooks::HookL2BlockInfo;
use sov_modules_api::{
EncodeCall, L2Block, L2BlockModuleCallError, PrivateKey, SlotData, Spec, SpecId,
StateValueAccessor, WorkingSet,
};
use sov_modules_stf_blueprint::StfBlueprint;
use sov_prover_storage_manager::ProverStorageManager;
use sov_rollup_interface::block::{L2Header, SignedL2Header};
use sov_rollup_interface::da::{BlockHeaderTrait, DaSpec};
use sov_rollup_interface::fork::ForkManager;
use sov_rollup_interface::services::da::DaService;
use sov_rollup_interface::stf::{L2BlockResult, StateTransitionError};
use sov_rollup_interface::transaction::Transaction;
use sov_rollup_interface::zk::StorageRootHash;
use sov_state::storage::NativeStorage;
use sov_state::{ProverStorage, ReadWriteLog};
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::{broadcast, mpsc};
use tracing::level_filters::LevelFilter;
use tracing::{debug, error, info, trace, warn};
use tracing_subscriber::layer::SubscriberExt;
use crate::commitment::service::CommitmentService;
use crate::da::{da_block_monitor, fee_rate_monitor, get_finalized_block, DaBlockData};
use crate::db_provider::DbProvider;
use crate::deposit_data_mempool::{Deposit, DepositDataMempool};
use crate::mempool::CitreaMempool;
use crate::metrics::SEQUENCER_METRICS as SM;
use crate::types::SequencerRpcMessage;
use crate::utils::recover_raw_transaction;
/// Maximum number of DA blocks that can be missed per L2 block
pub const MAX_MISSED_DA_BLOCKS_PER_L2_BLOCK: u64 = 10;
/// The main sequencer implementation that manages block production and transaction processing
///
/// This struct is responsible for:
/// - Managing the transaction mempool
/// - Producing L2 blocks
/// - Processing system transactions
/// - Handling DA layer synchronization
/// - Managing state transitions
pub struct CitreaSequencer<Da>
where
Da: DaService,
{
/// Data availability service instance
da_service: Arc<Da>,
/// Transaction mempool
mempool: Arc<CitreaMempool>,
/// Private key for signing transactions
pub(crate) sov_tx_signer_priv_key: K256PrivateKey,
/// Channel for receiving messages from RPC.
rpc_message_rx: UnboundedReceiver<SequencerRpcMessage>,
/// Database provider for blockchain data access
db_provider: DbProvider,
/// Database for ledger operations
pub(crate) ledger_db: LedgerDB,
/// Sequencer configuration
pub(crate) config: SequencerConfig,
/// State transition function blueprint
pub(crate) stf: StfBlueprint<DefaultContext, Da::Spec, CitreaRuntime<DefaultContext, Da::Spec>>,
/// Mempool for deposit transactions
pub(crate) deposit_mempool: Arc<Mutex<DepositDataMempool>>,
/// Manager for prover storage
pub(crate) storage_manager: ProverStorageManager,
/// Current state root hash
pub(crate) state_root: StorageRootHash,
/// Current L2 block hash
pub(crate) l2_block_hash: L2BlockHash,
/// Sequencer's DA public key
sequencer_da_pub_key: Vec<u8>,
/// Manager for handling chain forks
pub(crate) fork_manager: ForkManager<'static>,
/// Channel for broadcasting L2 block updates
l2_block_tx: broadcast::Sender<u64>,
/// Manager for backup operations
backup_manager: Arc<BackupManager>,
/// Channel for sending canonical state notifications to mempool maintenance
canon_state_tx: mpsc::UnboundedSender<CanonStateNotification>,
/// Executor for spawning async tasks
task_executor: TaskExecutor,
}
impl<Da> CitreaSequencer<Da>
where
Da: DaService,
{
/// Creates a new CitreaSequencer instance
///
/// # Arguments
/// * `da_service` - Data availability service
/// * `config` - Sequencer configuration
/// * `init_params` - Initial parameters for sequencer setup
/// * `stf` - State transition function blueprint
/// * `storage_manager` - Manager for prover storage
/// * `public_keys` - Public keys for the rollup
/// * `ledger_db` - Database for ledger operations
/// * `db_provider` - Provider for database operations
/// * `mempool` - Transaction mempool
/// * `deposit_mempool` - Mempool for deposit transactions
/// * `fork_manager` - Manager for handling chain forks
/// * `l2_block_tx` - Channel for L2 block notifications
/// * `backup_manager` - Manager for backup operations
/// * `rpc_message_rx` - Channel for receiving messages from RPC
#[allow(clippy::too_many_arguments)]
pub fn new(
da_service: Arc<Da>,
config: SequencerConfig,
init_params: InitParams,
stf: StfBlueprint<DefaultContext, Da::Spec, CitreaRuntime<DefaultContext, Da::Spec>>,
storage_manager: ProverStorageManager,
public_keys: RollupPublicKeys,
ledger_db: LedgerDB,
db_provider: DbProvider,
mempool: Arc<CitreaMempool>,
deposit_mempool: Arc<Mutex<DepositDataMempool>>,
fork_manager: ForkManager<'static>,
l2_block_tx: broadcast::Sender<u64>,
backup_manager: Arc<BackupManager>,
rpc_message_rx: UnboundedReceiver<SequencerRpcMessage>,
canon_state_tx: mpsc::UnboundedSender<CanonStateNotification>,
task_executor: TaskExecutor,
) -> anyhow::Result<Self> {
let sov_tx_signer_priv_key =
K256PrivateKey::try_from(hex::decode(&config.private_key)?.as_slice())?;
Ok(Self {
da_service,
mempool,
sov_tx_signer_priv_key,
rpc_message_rx,
db_provider,
ledger_db,
config,
stf,
deposit_mempool,
storage_manager,
state_root: init_params.prev_state_root,
l2_block_hash: init_params.prev_l2_block_hash,
sequencer_da_pub_key: public_keys.sequencer_da_pub_key,
fork_manager,
l2_block_tx,
backup_manager,
canon_state_tx,
task_executor,
})
}
/// Performs a dry run of transactions to validate them before inclusion in a block
///
/// # Arguments
/// * `transactions` - Transactions to validate
/// * `prestate` - Initial state for the dry run
/// * `l2_block_info` - Block information for hooks
/// * `deposit_data` - Deposit transaction data
/// * `da_blocks` - Data availability blocks
///
/// # Returns
/// A tuple containing the validated transactions and their hashes
#[allow(clippy::too_many_arguments)]
async fn dry_run_transactions(
&mut self,
mut transactions: Box<
dyn BestTransactions<Item = Arc<ValidPoolTransaction<EthPooledTransaction>>>,
>,
prestate: ProverStorage,
l2_block_info: HookL2BlockInfo,
deposit_data: &[Deposit],
da_blocks: Vec<Da::FilteredBlock>,
) -> anyhow::Result<(
Vec<RlpEvmTransaction>,
Vec<TxHash>,
Vec<alloy_primitives::Address>,
)> {
let start = Instant::now();
// Disable logging during dry run to avoid noise
let silent_subscriber = tracing_subscriber::registry().with(LevelFilter::OFF);
tracing::subscriber::with_default(silent_subscriber, || {
let mut working_set_to_discard = WorkingSet::new(prestate.clone());
let mut nonce = self.get_nonce(&mut working_set_to_discard)?;
// Apply L2 block hook before processing transactions
if let Err(err) = self
.stf
.begin_l2_block(&mut working_set_to_discard, &l2_block_info)
{
warn!(
"DryRun: Failed to apply l2 block hook: {:?} \n reverting batch workspace",
err
);
bail!("DryRun: Failed to apply begin l2 block hook: {:?}", err)
}
let evm = citrea_evm::Evm::<DefaultContext>::default();
let start_dry_run_system_txs = Instant::now();
// Initially fill with system transactions if any
let (mut all_txs, mut working_set_to_discard) = self
.produce_and_run_system_transactions(
&l2_block_info,
&evm,
working_set_to_discard,
deposit_data,
da_blocks,
&mut nonce,
)?;
SM.dry_run_system_txs_duration_secs.set(
Instant::now()
.saturating_duration_since(start_dry_run_system_txs)
.as_secs_f64(),
);
// Track transactions that failed due to insufficient L1 fee balance
let mut l1_fee_failed_txs = vec![];
// Track senders for successfully validated transactions
let mut senders = vec![];
// using .next() instead of a for loop because its the intended
// behaviour for the BestTransactions implementations
// when we update reth we'll need to call transactions.mark_invalid()
#[allow(clippy::while_let_on_iterator)]
while let Some(evm_tx) = transactions.next() {
let start_tx = Instant::now();
let recovered = evm_tx.to_consensus();
let sender = recovered.signer();
let buf = recovered.into_inner().encoded_2718();
let rlp_tx = RlpEvmTransaction { rlp: buf };
let call_txs = CallMessage {
txs: vec![rlp_tx.clone()],
};
let raw_message = <CitreaRuntime<DefaultContext, Da::Spec> as EncodeCall<
citrea_evm::Evm<DefaultContext>,
>>::encode_call(call_txs);
let signed_tx = self.sign_tx(l2_block_info.current_spec, raw_message, nonce)?;
nonce += 1;
let txs = vec![signed_tx];
let mut working_set = working_set_to_discard.checkpoint().to_revertable();
if let Err(e) = self
.stf
.apply_l2_block_txs(&l2_block_info, &txs, &mut working_set)
{
// Decrement nonce if the transaction failed
nonce = nonce.saturating_sub(1);
match e {
// Since this is the sequencer, it should never get a soft confirmation error or a hook error
StateTransitionError::L2BlockError(l2_block_error) => {
panic!("L2 block error: {l2_block_error:?}")
}
StateTransitionError::HookError(soft_confirmation_hook_error) => {
panic!("Hook error: {soft_confirmation_hook_error:?}")
}
StateTransitionError::ModuleCallError(
soft_confirmation_module_call_error,
) => match soft_confirmation_module_call_error {
L2BlockModuleCallError::EvmGasUsedExceedsBlockGasLimit {
cumulative_gas,
tx_gas_used,
block_gas_limit,
} => {
if block_gas_limit - cumulative_gas < MIN_TRANSACTION_GAS {
break;
} else {
transactions.mark_invalid(
&evm_tx,
InvalidPoolTransactionError::ExceedsGasLimit(
tx_gas_used,
block_gas_limit - cumulative_gas,
),
);
working_set_to_discard = working_set.revert().to_revertable();
continue;
}
}
L2BlockModuleCallError::EvmTxTypeNotSupported(_) => {
panic!("got unsupported tx type")
}
L2BlockModuleCallError::EvmTransactionExecutionError(_) => {
transactions.mark_invalid(
&evm_tx,
// don't really have a way to know the underlying EVM error due to
// our APIs so passing a generic overdraft error
// as it doesn't matter (the kind field is never used)
InvalidPoolTransactionError::Overdraft {
cost: U256::from(1),
balance: U256::ZERO,
},
);
working_set_to_discard = working_set.revert().to_revertable();
continue;
}
L2BlockModuleCallError::EvmMisplacedSystemTx => {
panic!("tried to execute system transaction")
}
L2BlockModuleCallError::EvmNotEnoughFundsForL1Fee => {
l1_fee_failed_txs.push(*evm_tx.hash());
transactions.mark_invalid(
&evm_tx,
// don't really have a way to know the cost right now
// passing 1 & 0 as it doesn't matter (the kind field is never used)
InvalidPoolTransactionError::Overdraft {
cost: U256::from(1),
balance: U256::ZERO,
},
);
working_set_to_discard = working_set.revert().to_revertable();
continue;
}
L2BlockModuleCallError::EvmTxNotSerializable => {
panic!("Fed a non-serializable tx")
}
L2BlockModuleCallError::RuleEnforcerUnauthorized => unreachable!(),
L2BlockModuleCallError::ShortHeaderProofNotFound => unreachable!(),
L2BlockModuleCallError::ShortHeaderProofVerificationError => {
unreachable!()
}
L2BlockModuleCallError::EvmSystemTransactionPlacedAfterUserTx => {
panic!("System tx after user tx")
}
L2BlockModuleCallError::EvmSystemTxParseError => {
panic!("Sequencer produced incorrectly formatted system tx")
}
L2BlockModuleCallError::EvmSystemTransactionNotSuccessful => {
panic!("System tx failed")
}
L2BlockModuleCallError::ShortHeaderProofAllocationError(e) => {
panic!("Short header proof error: {e:?}");
}
},
}
};
// if no errors
// we can include the transaction in the block
working_set_to_discard = working_set.checkpoint().to_revertable();
all_txs.push(rlp_tx);
senders.push(sender);
SM.dry_run_single_tx_time.record(
Instant::now()
.saturating_duration_since(start_tx)
.as_secs_f64(),
);
}
let dry_run_execution_duration = Instant::now()
.saturating_duration_since(start)
.as_secs_f64();
SM.dry_run_execution.record(dry_run_execution_duration);
SM.dry_run_execution_gauge.set(dry_run_execution_duration);
SM.l1_fee_failed_txs_count
.set(l1_fee_failed_txs.len() as f64);
Ok((all_txs, l1_fee_failed_txs, senders))
})
}
/// Saves proofs for short headers from DA blocks
fn save_short_header_proofs(&self, da_blocks: Vec<Da::FilteredBlock>) {
debug!("Saving short header proofs to ledger db");
for da_block in da_blocks {
let short_header_proof: <<Da as DaService>::Spec as DaSpec>::ShortHeaderProof =
Da::block_to_short_header_proof(da_block.clone());
self.ledger_db
.put_short_header_proof_by_l1_hash(
&da_block.hash(),
borsh::to_vec(&short_header_proof)
.expect("Should serialize short header proof"),
)
.expect("Should save short header proof to ledger db");
info!(
"Saved short header proof for block: {}",
hex::encode(da_block.hash())
);
}
}
/// Produces a new L2 block with the given DA blocks.
/// Notifies subscribers of the new block height.
///
/// # Arguments
/// * `da_blocks` - Data availability blocks to process
/// * `l1_fee_rate` - Current L1 fee rate
/// * `last_used_l1_height` - Last processed L1 block height
async fn produce_l2_block(
&mut self,
mut da_blocks: Vec<Da::FilteredBlock>,
l1_fee_rate: u128,
last_used_l1_height: &mut u64,
) -> anyhow::Result<()> {
let start: Instant = Instant::now();
let l2_height = self.ledger_db.get_head_l2_block_height()?.unwrap_or(0) + 1;
self.fork_manager.register_block(l2_height)?;
let result = {
if da_blocks.len() == 1 && da_blocks[0].header().height() == *last_used_l1_height {
// If we are producing regular blocks, not for missed da blocks, and if the last used L1 block is the same as the last finalized block
// then there is no need to pass da data to the sequencer
da_blocks.clear();
}
self.produce_l2_block_inner(da_blocks, l1_fee_rate, l2_height, last_used_l1_height)
.await
};
match result {
Ok(l2_height) => {
// Only errors when there are no receivers
if let Err(_closed) = self.l2_block_tx.send(l2_height) {
debug!("l2_block_tx is closed");
}
}
Err(e) => {
error!("Sequencer error: {}", e);
}
}
let block_production_time = Instant::now()
.saturating_duration_since(start)
.as_secs_f64();
SM.block_production_execution.record(block_production_time);
SM.entire_block_production_duration_gauge
.set(block_production_time);
SM.l1_fee_rate.set(l1_fee_rate as f64);
SM.current_l2_block.set(l2_height as f64);
Ok(())
}
/// Inner implementation of L2 block production
///
/// # Arguments
/// * `da_blocks` - Data availability blocks to process
/// * `l1_fee_rate` - Current L1 fee rate
/// * `l2_height` - Height of the L2 block to produce
/// * `last_used_l1_height` - Last processed L1 block height
///
/// # Returns
/// The height of the produced L2 block
async fn produce_l2_block_inner(
&mut self,
da_blocks: Vec<Da::FilteredBlock>,
l1_fee_rate: u128,
l2_height: u64,
last_used_l1_height: &mut u64,
) -> anyhow::Result<u64> {
let start_dry_run_preparation = Instant::now();
let active_fork_spec = self.fork_manager.active_fork().spec_id;
// TODO: after L2Block refactor PR, we'll need to change native provider
// Save short header proof to ledger db for Native Short Header Proof Provider Service
self.save_short_header_proofs(da_blocks.clone());
let timestamp = chrono::Local::now().timestamp() as u64;
// Get pending deposits up to configured limit
let deposit_data = self
.deposit_mempool
.lock()
.fetch_deposits(self.config.deposit_mempool_fetch_limit);
let pub_key = self.sov_tx_signer_priv_key.pub_key();
let l2_block_info = HookL2BlockInfo {
l2_height,
pre_state_root: self.state_root,
current_spec: active_fork_spec,
sequencer_pub_key: pub_key.clone(),
l1_fee_rate,
timestamp,
};
// Create storage for the next L2 block
let prestate = self.storage_manager.create_storage_for_next_l2_height();
// Get best transactions from mempool based on gas price
let evm_txs = self.get_best_transactions(active_fork_spec)?;
let last_da_block_height = da_blocks.last().map(|b| b.header().height());
SM.dry_run_preparation_time.set(
Instant::now()
.saturating_duration_since(start_dry_run_preparation)
.as_secs_f64(),
);
// Dry running transactions would basically allow for figuring out a list of
// all transactions that would fit into the current block and the list of transactions
// which do not have enough balance to pay for the L1 fee.
let (txs_to_run, l1_fee_failed_txs, senders) = self
.dry_run_transactions(
evm_txs,
prestate.clone(),
l2_block_info.clone(),
&deposit_data,
da_blocks,
)
.await?;
let block_production_start = Instant::now();
let prestate = self.storage_manager.create_storage_for_next_l2_height();
assert_eq!(
prestate.version(),
l2_height,
"Prover storage version is corrupted"
);
let evm_txs_count = txs_to_run.len();
let mut working_set = WorkingSet::new(prestate.clone());
self.instrumented_begin_l2_block(&mut working_set, &l2_block_info)?;
let (signed_txs, blobs) = self.encode_and_sign_evm_txs_into_sov_txs(
&mut working_set,
&l2_block_info,
txs_to_run.clone(),
)?;
self.instrumented_apply_l2_block_txs(&l2_block_info, &signed_txs, &mut working_set)?;
self.instrumented_end_l2_block(l2_block_info, &mut working_set)?;
let receipts = self.extract_receipts_from_working_set(l2_height, &mut working_set);
assert_eq!(
receipts.len(),
evm_txs_count,
"Expected {} receipts but extracted {}",
evm_txs_count,
receipts.len()
);
let l2_block_result =
self.instrumented_finalize_l2_block(active_fork_spec, working_set, prestate);
// Calculate tx hashes and merkle root
let (tx_merkle_root, tx_hashes) =
self.calculate_txs_merkle_root(&signed_txs, active_fork_spec);
// create the l2 block header
let header = L2Header::new(
l2_height,
self.l2_block_hash,
l2_block_result.state_root_transition.final_root,
l1_fee_rate,
tx_merkle_root,
timestamp,
);
let signed_header = self.sign_l2_block_header(header)?;
// TODO: cleanup l2 block structure once we decide how to pull data from the running sequencer in the existing form
let l2_block = L2Block::new(signed_header, signed_txs);
info!(
"New block #{}, Tx count: #{}",
l2_block.height(),
evm_txs_count
);
// Extract account state changes for mempool maintenance
let start_extract_bundle = Instant::now();
let bundle_state = self.extract_bundle_state_from_state_log(&l2_block_result.state_log);
SM.mempool_extract_bundle_state_time.set(
Instant::now()
.saturating_duration_since(start_extract_bundle)
.as_secs_f64(),
);
// First set the state diff before committing the L2 block
// This prevents race conditions where the sequencer might shut down
// between committing the L2 block and saving the state diff
self.ledger_db
.set_state_diff(L2BlockNumber(l2_height), &l2_block_result.state_diff)?;
self.save_l2_block(l2_block, l2_block_result, tx_hashes, blobs)?;
// Remove successfully included deposits from the mempool
if !deposit_data.is_empty() {
let removed_count = self.deposit_mempool.lock().remove_deposits(&deposit_data);
debug!(
"Removed {} deposits from mempool after successful block production",
removed_count
);
}
// Build notification using in-memory data instead of reading from DB
let start_canonical_notification = Instant::now();
// Use the transactions we already have from dry_run (txs_to_run)
// and build block structure without DB reads
let (reth_block, reth_receipts, evm_block_hash) =
self.build_reth_block_data(l2_height, &txs_to_run, &senders, &receipts);
// Create the Chain notification with the produced block data
let chain = self.create_chain_notification(
l2_height,
evm_block_hash,
reth_block,
senders,
reth_receipts,
bundle_state,
);
// Send canonical state notification for mempool maintenance task
let _ = self.canon_state_tx.send(CanonStateNotification::Commit {
new: Arc::new(chain),
});
SM.mempool_canonical_notification_time.set(
Instant::now()
.saturating_duration_since(start_canonical_notification)
.as_secs_f64(),
);
// Handle L1 fee failed transactions and persistent storage cleanup
// Note: Mined transaction removal from mempool is handled by the maintenance task
self.maintain_mempool(l1_fee_failed_txs)
.expect("Maintain mempool should NOT fail");
SM.no_dry_run_block_production_duration_secs.set(
Instant::now()
.saturating_duration_since(block_production_start)
.as_secs_f64(),
);
SM.l2_block_tx_count.set(evm_txs_count as f64);
// Update last used l1 height if this is a new da block
if let Some(l1_height) = last_da_block_height {
*last_used_l1_height = l1_height;
// On the full node, "last scanned" means the L1 monitor processed that
// block; on the sequencer it means "last L1 block folded into an L2 block".
// This persisted height is informational only the sequencer recovers `last_used_l1_height`
// from the light client contract on restart.
// The L2 block is already committed at this point, so a
// failure here must not panic a successful block production.
if let Err(e) = self
.ledger_db
.set_last_scanned_l1_height(SlotNumber(l1_height))
{
error!("Failed to persist last scanned L1 height {l1_height}: {e}");
}
}
Ok(l2_height)
}
/// Calculates the transaction merkle root and records the time taken
fn calculate_txs_merkle_root(
&self,
txs: &[Transaction],
active_fork_spec: SpecId,
) -> ([u8; 32], Vec<[u8; 32]>) {
let start = Instant::now();
let tx_hashes = compute_tx_hashes(txs, active_fork_spec);
let merkle_root = compute_tx_merkle_root(&tx_hashes, active_fork_spec);
SM.calculate_tx_merkle_root_time.set(
Instant::now()
.saturating_duration_since(start)
.as_secs_f64(),
);
(merkle_root, tx_hashes)
}
/// Begins an L2 block and records the time taken
fn instrumented_begin_l2_block(
&mut self,
working_set: &mut WorkingSet<ProverStorage>,
l2_block_info: &HookL2BlockInfo,
) -> anyhow::Result<()> {
let start = Instant::now();
if let Err(err) = self.stf.begin_l2_block(working_set, l2_block_info) {
warn!(
"Failed to apply l2 block hook: {:?} \n reverting batch workspace",
err
);
bail!("Failed to apply begin l2 block hook: {:?}", err)
}
SM.begin_l2_block_time.set(
Instant::now()
.saturating_duration_since(start)
.as_secs_f64(),
);
Ok(())
}
/// Encodes and signs EVM transactions into Sov txs, and records the time taken
fn encode_and_sign_evm_txs_into_sov_txs(
&self,
working_set: &mut WorkingSet<<DefaultContext as Spec>::Storage>,
l2_block_info: &HookL2BlockInfo,
txs: Vec<RlpEvmTransaction>,
) -> anyhow::Result<(Vec<Transaction>, Vec<Vec<u8>>)> {
let start_encode_and_sign_sov_tx = Instant::now();
let mut blobs = vec![];
let mut signed_txs = vec![];
// if a batch failed need to refetch nonce
// so sticking to fetching from state makes sense
let nonce = self.get_nonce(working_set)?;
if !txs.is_empty() {
let call_txs = CallMessage { txs };
let raw_message = <CitreaRuntime<DefaultContext, Da::Spec> as EncodeCall<
citrea_evm::Evm<DefaultContext>,
>>::encode_call(call_txs);
let signed_tx = self.sign_tx(l2_block_info.current_spec, raw_message, nonce)?;
blobs.push(signed_tx.to_blob()?);
signed_txs.push(signed_tx);
}
SM.encode_and_sign_sov_tx_time.set(
Instant::now()
.saturating_duration_since(start_encode_and_sign_sov_tx)
.as_secs_f64(),
);
Ok((signed_txs, blobs))
}
/// Applies the L2 block transactions and records the time taken
fn instrumented_apply_l2_block_txs(
&mut self,
l2_block_info: &HookL2BlockInfo,
txs: &[Transaction],
working_set: &mut WorkingSet<ProverStorage>,
) -> anyhow::Result<()> {
let start = Instant::now();
self.stf
.apply_l2_block_txs(l2_block_info, txs, working_set)?;
SM.apply_l2_block_txs_time.set(
Instant::now()
.saturating_duration_since(start)
.as_secs_f64(),
);
Ok(())
}
/// Ends the L2 block and records the time taken
fn instrumented_end_l2_block(
&mut self,
l2_block_info: HookL2BlockInfo,
working_set: &mut WorkingSet<ProverStorage>,
) -> anyhow::Result<()> {
let start = Instant::now();
self.stf.end_l2_block(l2_block_info, working_set)?;
SM.end_l2_block_time.set(
Instant::now()
.saturating_duration_since(start)
.as_secs_f64(),
);
Ok(())
}
/// Extracts receipts from the working set's accessory cache after end_l2_block
fn extract_receipts_from_working_set(
&self,
_l2_height: u64,
working_set: &mut WorkingSet<ProverStorage>,
) -> Vec<reth_primitives::Receipt> {
let block = self
.db_provider
.evm
.get_head_block(working_set)
.expect("Head block must exist after end_l2_block");
let Range { start, end } = block.transaction_range();
let citrea_receipts =
self.db_provider
.evm
.get_block_receipts_range(start, end, working_set);
// Convert to reth receipts
citrea_receipts
.iter()
.map(|r| r.receipt.receipt.clone())
.collect()
}
/// Finalizes the L2 block and records the time taken
fn instrumented_finalize_l2_block(
&mut self,
active_fork_spec: SpecId,
working_set: WorkingSet<ProverStorage>,
prestate: ProverStorage,
) -> L2BlockResult<ProverStorage, sov_state::Witness, sov_state::ReadWriteLog> {
let start = Instant::now();
let result = self
.stf
.finalize_l2_block(active_fork_spec, working_set, prestate);
SM.finalize_l2_block_time.set(
Instant::now()
.saturating_duration_since(start)
.as_secs_f64(),
);
result
}
/// Saves an L2 block and its associated data to storage
///
/// # Arguments
/// * `l2_block` - The L2 block to save
/// * `l2_block_result` - Result of block execution
/// * `tx_hashes` - Transaction hashes in the block
/// * `blobs` - Associated blob data
pub(crate) fn save_l2_block(
&mut self,
l2_block: L2Block,
l2_block_result: L2BlockResult<ProverStorage, sov_state::Witness, sov_state::ReadWriteLog>,
tx_hashes: Vec<[u8; 32]>,
blobs: Vec<Vec<u8>>,
) -> anyhow::Result<()> {
let save_l2_block_start = Instant::now();
debug!("New L2 block with hash: {:?}", hex::encode(l2_block.hash()));
let state_root_transition = l2_block_result.state_root_transition;
// Check if state has actually changed
if state_root_transition.final_root.as_ref() == self.state_root.as_ref() {
bail!("Max L2 blocks per L1 is reached for the current L1 block. State root is the same as before, skipping");
}
trace!(
"State root after applying slot: {:?}",
state_root_transition.final_root,
);
let next_state_root = state_root_transition.final_root;
// Finalize storage changes from block execution
self.storage_manager
.finalize_storage(l2_block_result.change_set);
let l2_block_hash = l2_block.hash();
// Persist block data to storage
self.ledger_db
.commit_l2_block(l2_block, tx_hashes, Some(blobs))?;
// TODO: https://github.com/chainwayxyz/citrea/issues/1992
// // connect L1 and L2 height
// self.ledger_db.extend_l2_range_of_l1_slot(
// SlotNumber(da_block.header().height()),
// L2BlockNumber(l2_height),
// )?;
self.state_root = next_state_root;
self.l2_block_hash = l2_block_hash;
SM.save_l2_block_time.set(
Instant::now()
.saturating_duration_since(save_l2_block_start)
.as_secs_f64(),
);
Ok(())
}
/// Extracts EVM account changes from the state log to create a BundleState
fn extract_bundle_state_from_state_log(&self, state_log: &ReadWriteLog) -> BundleState {
let mut bundle_state = BundleState::default();
let mut account_id_to_address: HashMap<u64, alloy_primitives::Address> = HashMap::new();
let mut account_id_to_info: HashMap<u64, AccountInfo> = HashMap::new();
let mut account_id_to_status: HashMap<u64, AccountStatus> = HashMap::new();
// Parse reads for existing account mappings - these accounts are Loaded
for (cache_key, cache_value) in state_log.ordered_reads() {
if cache_key.key.starts_with(b"E/i/") {
if let Some(value) = cache_value {
let encoded_addr = &cache_key.key[4..];
let addr_bytes = borsh::from_slice::<[u8; 20]>(encoded_addr)
.expect("Failed to borsh deserialize address");
let address = Address::from_slice(&addr_bytes);
let account_id = borsh::from_slice::<u64>(&value.value)
.expect("Failed to borsh deserialize account ID");
account_id_to_address.insert(account_id, address);
}
}
}
// Parse writes for new mappings and account info changes - these override status to Changed
for (cache_key, cache_value) in state_log.iter_ordered_writes() {
if cache_key.key.starts_with(b"E/i/") {
if let Some(value) = cache_value {
let encoded_addr = &cache_key.key[4..];
let addr_bytes = borsh::from_slice::<[u8; 20]>(encoded_addr)
.expect("Failed to borsh deserialize address");
let address = Address::from_slice(&addr_bytes);
let account_id = borsh::from_slice::<u64>(&value.value)
.expect("Failed to borsh deserialize account ID");
account_id_to_address.insert(account_id, address);
}
} else if cache_key.key.starts_with(b"E/a/") {
if let Some(value) = cache_value {
let encoded_id = &cache_key.key[4..];
let account_id =
borsh::from_slice::<u64>(encoded_id).expect("Failed to parse account ID");
let account_info = borsh::from_slice::<AccountInfo>(&value.value)
.expect("Failed to borsh deserialize account info");
account_id_to_info.insert(account_id, account_info);
// Account was written to, so it's Changed (overrides Loaded if it was read)
account_id_to_status.insert(account_id, AccountStatus::Changed);
}
}
}
for (account_id, account_info) in account_id_to_info {
if let Some(&address) = account_id_to_address.get(&account_id) {
let revm_info = ReVmAccountInfo {
balance: account_info.balance,
nonce: account_info.nonce,
code_hash: account_info.code_hash.unwrap_or_else(|| keccak256([])),
code: None,
};
// Get the status for this account (will be Changed since we only process written accounts)
let status = account_id_to_status
.get(&account_id)
.copied()
.unwrap_or(AccountStatus::Changed);
let bundle_account = BundleAccount {
info: Some(revm_info),
storage: Default::default(),
original_info: None,
status,
};
bundle_state.state.insert(address, bundle_account);
}
}
bundle_state
}
/// Build block data from in-memory transactions without DB reads
fn build_reth_block_data(
&self,
l2_height: u64,
txs: &[RlpEvmTransaction],
_senders: &[alloy_primitives::Address],
receipts: &[reth_primitives::Receipt],
) -> (reth_primitives::Block, Vec<Receipt>, alloy_primitives::B256) {
// For now, we still need one DB read to get the block header
// In a future optimization, we could cache this in memory too
let mut working_set = WorkingSet::new(self.db_provider.storage.clone());
let citrea_block = self
.db_provider
.evm
.get_block_by_height(l2_height, &mut working_set)
.unwrap_or_else(|| panic!("Block {l2_height} must exist after saving"));
let evm_block_hash = citrea_block.header.hash();
let header = citrea_block.header.clone().unseal();
let reth_transactions: Vec<reth_primitives::TransactionSigned> = txs