-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathl1_committer.rs
More file actions
1359 lines (1204 loc) · 50.8 KB
/
l1_committer.rs
File metadata and controls
1359 lines (1204 loc) · 50.8 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 crate::{
BlockProducerConfig, CommitterConfig, EthConfig, SequencerConfig,
based::sequencer_state::{SequencerState, SequencerStatus},
sequencer::{
errors::CommitterError,
utils::{
self, batch_checkpoint_name, fetch_blocks_with_respective_fee_configs,
get_git_commit_hash, system_now_ms,
},
},
};
use bytes::Bytes;
use ethrex_blockchain::{
Blockchain, BlockchainOptions, BlockchainType, L2Config, error::ChainError, vm::StoreVmDatabase,
};
use ethrex_common::{
Address, H256, U256,
types::{
AccountUpdate, BLOB_BASE_FEE_UPDATE_FRACTION, BlobsBundle, Block, BlockNumber, Fork,
Genesis, MIN_BASE_FEE_PER_BLOB_GAS, TxType, batch::Batch, blobs_bundle,
fake_exponential_checked,
},
};
use ethrex_l2_common::{
calldata::Value,
l1_messages::{get_block_l1_messages, get_l1_message_hash},
merkle_tree::compute_merkle_root,
privileged_transactions::{
PRIVILEGED_TX_BUDGET, compute_privileged_transactions_hash,
get_block_privileged_transactions,
},
prover::ProverInputData,
state_diff::{StateDiff, prepare_state_diff},
};
use ethrex_l2_rpc::signer::{Signer, SignerHealth};
use ethrex_l2_sdk::{
build_generic_tx, calldata::encode_calldata, get_l1_active_fork, get_last_committed_batch,
send_tx_bump_gas_exponential_backoff,
};
#[cfg(feature = "metrics")]
use ethrex_metrics::l2::metrics::{METRICS, MetricsBlockType};
use ethrex_metrics::metrics;
use ethrex_rlp::encode::RLPEncode;
use ethrex_rpc::{
clients::eth::{EthClient, Overrides},
types::block_identifier::{BlockIdentifier, BlockTag},
};
use ethrex_storage::EngineType;
use ethrex_storage::Store;
use ethrex_storage_rollup::StoreRollup;
use ethrex_vm::{BlockExecutionResult, Evm};
use rand::Rng;
use serde::Serialize;
use std::{
collections::{BTreeMap, HashMap},
fs::remove_dir_all,
path::{Path, PathBuf},
sync::Arc,
};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, trace, warn};
use super::{errors::BlobEstimationError, utils::random_duration};
use spawned_concurrency::tasks::{
CallResponse, CastResponse, GenServer, GenServerHandle, send_after,
};
const COMMIT_FUNCTION_SIGNATURE_BASED: &str =
"commitBatch(uint256,bytes32,bytes32,bytes32,bytes32,bytes[])";
const COMMIT_FUNCTION_SIGNATURE: &str = "commitBatch(uint256,bytes32,bytes32,bytes32,bytes32)";
/// Default wake up time for the committer to check if it should send a commit tx
const COMMITTER_DEFAULT_WAKE_TIME_MS: u64 = 60_000;
#[derive(Clone)]
pub enum CallMessage {
Stop,
/// time to wait in ms before sending commit
Start(u64),
Health,
}
#[derive(Clone)]
pub enum InMessage {
Commit,
}
#[derive(Clone)]
pub enum OutMessage {
Done,
Error(String),
Stopped,
Started,
Health(Box<L1CommitterHealth>),
}
pub struct L1Committer {
eth_client: EthClient,
blockchain: Arc<Blockchain>,
on_chain_proposer_address: Address,
store: Store,
rollup_store: StoreRollup,
commit_time_ms: u64,
batch_gas_limit: Option<u64>,
arbitrary_base_blob_gas_price: u64,
validium: bool,
signer: Signer,
based: bool,
sequencer_state: SequencerState,
/// Time to wait before checking if it should send a new batch
committer_wake_up_ms: u64,
/// Timestamp of last successful committed batch
last_committed_batch_timestamp: u128,
/// Last succesful committed batch number
last_committed_batch: u64,
/// Cancellation token for the next inbound InMessage::Commit
cancellation_token: Option<CancellationToken>,
/// Timestamp for Osaka activation on L1. This is used to determine which fork to use when generating blobs proofs.
osaka_activation_time: Option<u64>,
/// Elasticity multiplier for prover input generation
elasticity_multiplier: u64,
/// Git commit hash of the build
git_commit_hash: String,
/// Store containing the state checkpoint at the last committed batch.
///
/// It is used to ensure state availability for batch preparation and
/// witness generation.
current_checkpoint_store: Store,
/// Blockchain instance using the current checkpoint store.
///
/// It is used for witness generation.
current_checkpoint_blockchain: Arc<Blockchain>,
/// Network genesis.
///
/// It is used for creating checkpoints.
genesis: Genesis,
/// Directory where checkpoints are stored.
checkpoints_dir: PathBuf,
}
#[derive(Clone, Serialize)]
pub struct L1CommitterHealth {
rpc_healthcheck: BTreeMap<String, serde_json::Value>,
commit_time_ms: u64,
arbitrary_base_blob_gas_price: u64,
validium: bool,
based: bool,
sequencer_state: String,
committer_wake_up_ms: u64,
last_committed_batch_timestamp: u128,
last_committed_batch: u64,
signer_status: SignerHealth,
running: bool,
on_chain_proposer_address: Address,
}
impl L1Committer {
#[expect(clippy::too_many_arguments)]
pub async fn new(
committer_config: &CommitterConfig,
proposer_config: &BlockProducerConfig,
eth_config: &EthConfig,
blockchain: Arc<Blockchain>,
store: Store,
rollup_store: StoreRollup,
based: bool,
sequencer_state: SequencerState,
genesis: Genesis,
checkpoints_dir: PathBuf,
) -> Result<Self, CommitterError> {
let eth_client = EthClient::new_with_config(
eth_config.rpc_url.clone(),
eth_config.max_number_of_retries,
eth_config.backoff_factor,
eth_config.min_retry_delay,
eth_config.max_retry_delay,
Some(eth_config.maximum_allowed_max_fee_per_gas),
Some(eth_config.maximum_allowed_max_fee_per_blob_gas),
)?;
let last_committed_batch =
get_last_committed_batch(ð_client, committer_config.on_chain_proposer_address)
.await?;
let (current_checkpoint_store, current_checkpoint_blockchain) =
Self::get_checkpoint_from_path(
genesis.clone(),
blockchain.options.clone(),
&checkpoints_dir.join(batch_checkpoint_name(last_committed_batch)),
&rollup_store,
)
.await?;
Ok(Self {
eth_client,
blockchain,
on_chain_proposer_address: committer_config.on_chain_proposer_address,
store,
rollup_store,
commit_time_ms: committer_config.commit_time_ms,
batch_gas_limit: committer_config.batch_gas_limit,
arbitrary_base_blob_gas_price: committer_config.arbitrary_base_blob_gas_price,
validium: committer_config.validium,
signer: committer_config.signer.clone(),
based,
sequencer_state,
committer_wake_up_ms: committer_config
.commit_time_ms
.min(COMMITTER_DEFAULT_WAKE_TIME_MS),
last_committed_batch_timestamp: 0,
last_committed_batch,
cancellation_token: None,
osaka_activation_time: eth_config.osaka_activation_time,
elasticity_multiplier: proposer_config.elasticity_multiplier,
git_commit_hash: get_git_commit_hash(),
current_checkpoint_store,
current_checkpoint_blockchain,
genesis,
checkpoints_dir,
})
}
pub async fn spawn(
store: Store,
blockchain: Arc<Blockchain>,
rollup_store: StoreRollup,
cfg: SequencerConfig,
sequencer_state: SequencerState,
genesis: Genesis,
checkpoints_dir: PathBuf,
) -> Result<GenServerHandle<L1Committer>, CommitterError> {
let state = Self::new(
&cfg.l1_committer,
&cfg.block_producer,
&cfg.eth,
blockchain,
store.clone(),
rollup_store.clone(),
cfg.based.enabled,
sequencer_state,
genesis,
checkpoints_dir,
)
.await?;
// NOTE: we spawn as blocking due to `generate_blobs_bundle` and
// `send_tx_bump_gas_exponential_backoff` blocking for more than 40ms
let l1_committer = state.start_blocking();
if let OutMessage::Error(reason) = l1_committer
.clone()
.call(CallMessage::Start(cfg.l1_committer.first_wake_up_time_ms))
.await?
{
Err(CommitterError::UnexpectedError(format!(
"Failed to send first wake up message to committer {reason}"
)))
} else {
Ok(l1_committer)
}
}
async fn commit_next_batch_to_l1(&mut self) -> Result<(), CommitterError> {
info!("Running committer main loop");
// Get the batch to commit
let last_committed_batch_number =
get_last_committed_batch(&self.eth_client, self.on_chain_proposer_address).await?;
let batch_to_commit = last_committed_batch_number + 1;
let l1_fork = get_l1_active_fork(&self.eth_client, self.osaka_activation_time)
.await
.map_err(CommitterError::EthClientError)?;
let batch = match self
.rollup_store
.get_batch(batch_to_commit, l1_fork)
.await?
{
Some(batch) => batch,
None => {
let Some(batch) = self.produce_batch(batch_to_commit).await? else {
// The batch is empty (there's no new blocks from last batch)
return Ok(());
};
batch
}
};
info!(
first_block = batch.first_block,
last_block = batch.last_block,
"Sending commitment for batch {}",
batch.number,
);
match self.send_commitment(&batch).await {
Ok(commit_tx_hash) => {
metrics!(
let _ = METRICS
.set_block_type_and_block_number(
MetricsBlockType::LastCommittedBlock,
batch.last_block,
)
.inspect_err(|e| {
tracing::error!(
"Failed to set metric: last committed block {}",
e.to_string()
)
});
);
self.rollup_store
.store_commit_tx_by_batch(batch.number, commit_tx_hash)
.await?;
info!(
"Commitment sent for batch {}, with tx hash {commit_tx_hash:#x}.",
batch.number
);
Ok(())
}
Err(error) => Err(CommitterError::FailedToSendCommitment(format!(
"Failed to send commitment for batch {}. first_block: {} last_block: {}: {error}",
batch.number, batch.first_block, batch.last_block
))),
}
}
async fn produce_batch(&mut self, batch_number: u64) -> Result<Option<Batch>, CommitterError> {
let last_committed_blocks = self
.rollup_store
.get_block_numbers_by_batch(batch_number-1)
.await?
.ok_or(
CommitterError::RetrievalError(format!("Failed to get batch with batch number {}. Batch is missing when it should be present. This is a bug", batch_number))
)?;
let last_block = last_committed_blocks
.last()
.ok_or(CommitterError::RetrievalError(format!(
"Last committed batch ({}) doesn't have any blocks. This is probably a bug.",
batch_number
)))?;
let first_block_to_commit = last_block + 1;
// We need to guarantee that the checkpoint path is new
// to avoid causing a lock error under rocksdb feature.
let new_checkpoint_path = self
.checkpoints_dir
.join(batch_checkpoint_name(batch_number));
// For re-execution we need to use a checkpoint to the previous state
// (i.e. checkpoint of the state to the latest block from the previous
// batch, or the state of the genesis if this is the first batch).
// We already have this initial checkpoint as part of the L1Committer
// struct, but we need to create a one-time copy of it because
// we still need to use the current checkpoint store later for witness
// generation.
let (new_checkpoint_store, new_checkpoint_blockchain) = self
.create_checkpoint(
&self.current_checkpoint_store,
&new_checkpoint_path,
&self.rollup_store,
)
.await?;
// Try to prepare batch
let result = self
.prepare_batch_from_block(
*last_block,
batch_number,
new_checkpoint_store.clone(),
new_checkpoint_blockchain.clone(),
)
.await;
let (
blobs_bundle,
new_state_root,
message_hashes,
privileged_transactions_hash,
last_block_of_batch,
) = result?;
if *last_block == last_block_of_batch {
debug!("No new blocks to commit, skipping");
return Ok(None);
}
let batch = Batch {
number: batch_number,
first_block: first_block_to_commit,
last_block: last_block_of_batch,
state_root: new_state_root,
privileged_transactions_hash,
message_hashes,
blobs_bundle,
commit_tx: None,
verify_tx: None,
};
self.rollup_store.seal_batch(batch.clone()).await?;
debug!(
first_block = batch.first_block,
last_block = batch.last_block,
"Batch {} stored in database",
batch.number
);
info!(
first_block = batch.first_block,
last_block = batch.last_block,
"Generating and storing witness for batch {}",
batch.number,
);
self.generate_and_store_batch_prover_input(&batch).await?;
// We need to update the current checkpoint after generating the witness
// with it, and before sending the commitment.
// The actual checkpoint store directory is not pruned until the batch
// it served in is verified on L1.
// The reference to the previous checkpoint is lost after this operation,
// but the directory is not deleted until the batch it serves in is verified
// on L1.
self.current_checkpoint_store = new_checkpoint_store;
self.current_checkpoint_blockchain = new_checkpoint_blockchain;
Ok(Some(batch))
}
async fn prepare_batch_from_block(
&mut self,
mut last_added_block_number: BlockNumber,
batch_number: u64,
checkpoint_store: Store,
checkpoint_blockchain: Arc<Blockchain>,
) -> Result<(BlobsBundle, H256, Vec<H256>, H256, BlockNumber), CommitterError> {
let first_block_of_batch = last_added_block_number + 1;
let mut blobs_bundle = BlobsBundle::default();
let mut acc_messages = vec![];
let mut acc_privileged_txs = vec![];
let mut acc_account_updates: HashMap<Address, AccountUpdate> = HashMap::new();
let mut message_hashes = vec![];
let mut privileged_transactions_hashes = vec![];
let mut new_state_root = H256::default();
let mut acc_gas_used = 0_u64;
let mut blocks = vec![];
#[cfg(feature = "metrics")]
let mut tx_count = 0_u64;
#[cfg(feature = "metrics")]
let mut blob_size = 0_usize;
#[cfg(feature = "metrics")]
let mut batch_gas_used = 0_u64;
info!("Preparing state diff from block {first_block_of_batch}, {batch_number}");
loop {
let block_to_commit_number = last_added_block_number + 1;
// Get potential block to include in the batch
// Here it is ok to fetch the blocks from the main store and not from
// the checkpoint because the blocks will be available. We only need
// the checkpoint for re-execution, this is during witness generation
// in generate_and_store_batch_prover_input and for later in this
// function.
let potential_batch_block = {
let Some(block_to_commit_body) = self
.store
.get_block_body(block_to_commit_number)
.await
.map_err(CommitterError::from)?
else {
debug!("No new block to commit, skipping..");
break;
};
let block_to_commit_header = self
.store
.get_block_header(block_to_commit_number)
.map_err(CommitterError::from)?
.ok_or(CommitterError::FailedToGetInformationFromStorage(
"Failed to get_block_header() after get_block_body()".to_owned(),
))?;
Block::new(block_to_commit_header, block_to_commit_body)
};
let current_block_gas_used = potential_batch_block.header.gas_used;
// Check if adding this block would exceed the batch gas limit
if self.batch_gas_limit.is_some_and(|batch_gas_limit| {
acc_gas_used + current_block_gas_used > batch_gas_limit
}) {
debug!(
"Batch gas limit reached. Any remaining blocks will be processed in the next batch"
);
break;
}
// Get block transactions and receipts
let mut txs = vec![];
let mut receipts = vec![];
for (index, tx) in potential_batch_block.body.transactions.iter().enumerate() {
let receipt = self
.store
.get_receipt(block_to_commit_number, index.try_into()?)
.await?
.ok_or(CommitterError::RetrievalError(
"Transactions in a block should have a receipt".to_owned(),
))?;
txs.push(tx.clone());
receipts.push(receipt);
}
metrics!(
tx_count += txs
.len()
.try_into()
.inspect_err(|_| tracing::error!("Failed to collect metric tx count"))
.unwrap_or(0);
batch_gas_used += potential_batch_block.header.gas_used;
);
// Get block messages and privileged transactions
let messages = get_block_l1_messages(&receipts);
let privileged_transactions = get_block_privileged_transactions(&txs);
// Get block account updates.
let account_updates = if let Some(account_updates) = self
.rollup_store
.get_account_updates_by_block_number(block_to_commit_number)
.await?
{
account_updates
} else {
warn!(
"Could not find execution cache result for block {}, falling back to re-execution",
last_added_block_number + 1
);
let parent_header = self
.store
.get_block_header_by_hash(potential_batch_block.header.parent_hash)?
.ok_or(CommitterError::ChainError(ChainError::ParentNotFound))?;
// Here we use the checkpoint store because we need the previous
// state available (i.e. not pruned) for re-execution.
let vm_db = StoreVmDatabase::new(checkpoint_store.clone(), parent_header);
let fee_config = self
.rollup_store
.get_fee_config_by_block(block_to_commit_number)
.await?
.ok_or(CommitterError::FailedToGetInformationFromStorage(
"Failed to get fee config for re-execution".to_owned(),
))?;
let mut vm = Evm::new_for_l2(vm_db, fee_config)?;
vm.execute_block(&potential_batch_block)?;
vm.get_state_transitions()?
};
// The checkpoint store's state corresponds to the parent state of
// the first block of the batch. Therefore, we need to apply the
// account updates of each block as we go, to be able to continue
// re-executing the next blocks in the batch.
{
let account_updates_list = checkpoint_store
.apply_account_updates_batch(
potential_batch_block.header.parent_hash,
&account_updates,
)?
.ok_or(CommitterError::FailedToGetInformationFromStorage(
"no account updated".to_owned(),
))?;
checkpoint_blockchain.store_block(
potential_batch_block.clone(),
account_updates_list,
BlockExecutionResult {
receipts,
requests: vec![],
},
)?;
}
// Accumulate block data with the rest of the batch.
acc_messages.extend(messages.clone());
acc_privileged_txs.extend(privileged_transactions.clone());
for account in account_updates {
let address = account.address;
if let Some(existing) = acc_account_updates.get_mut(&address) {
existing.merge(account);
} else {
acc_account_updates.insert(address, account);
}
}
// It is safe to retrieve this from the main store because blocks
// are available there. What's not available is the state
let parent_block_hash = self
.store
.get_block_header(first_block_of_batch)?
.ok_or(CommitterError::FailedToGetInformationFromStorage(
"Failed to get_block_header() of the last added block".to_owned(),
))?
.parent_hash;
let parent_header = self
.store
.get_block_header_by_hash(parent_block_hash)?
.ok_or(CommitterError::ChainError(ChainError::ParentNotFound))?;
// Again, here the VM database should be instantiated from the checkpoint
// store to have access to the previous state
let parent_db = StoreVmDatabase::new(checkpoint_store.clone(), parent_header);
let acc_privileged_txs_len: u64 = acc_privileged_txs.len().try_into()?;
if acc_privileged_txs_len > PRIVILEGED_TX_BUDGET {
warn!(
"Privileged transactions budget exceeded. Any remaining blocks will be processed in the next batch."
);
// Break loop. Use the previous generated blobs_bundle.
break;
}
let result = if !self.validium {
// Prepare current state diff.
let state_diff: StateDiff = prepare_state_diff(
potential_batch_block.header.clone(),
&parent_db,
&acc_messages,
&acc_privileged_txs,
acc_account_updates.clone().into_values().collect(),
)?;
let l1_fork = get_l1_active_fork(&self.eth_client, self.osaka_activation_time)
.await
.map_err(CommitterError::EthClientError)?;
generate_blobs_bundle(&state_diff, l1_fork)
} else {
Ok((BlobsBundle::default(), 0_usize))
};
let Ok((bundle, latest_blob_size)) = result else {
if block_to_commit_number == first_block_of_batch {
return Err(CommitterError::Unreachable(
"Not enough blob space for a single block batch. This means a block was incorrectly produced.".to_string(),
));
}
warn!(
"Batch size limit reached. Any remaining blocks will be processed in the next batch."
);
// Break loop. Use the previous generated blobs_bundle.
break;
};
trace!("Got bundle, latest blob size {latest_blob_size}");
// Save current blobs_bundle and continue to add more blocks.
blobs_bundle = bundle;
metrics!(
blob_size = latest_blob_size;
);
privileged_transactions_hashes.extend(
privileged_transactions
.iter()
.filter_map(|tx| tx.get_privileged_hash())
.collect::<Vec<H256>>(),
);
message_hashes.extend(messages.iter().map(get_l1_message_hash));
new_state_root = checkpoint_store
.state_trie(potential_batch_block.hash())?
.ok_or(CommitterError::FailedToGetInformationFromStorage(
"Failed to get state root from storage".to_owned(),
))?
.hash_no_commit();
last_added_block_number += 1;
acc_gas_used += current_block_gas_used;
blocks.push((last_added_block_number, potential_batch_block.hash()));
} // end loop
metrics!(if let (Ok(privileged_transaction_count), Ok(messages_count)) = (
privileged_transactions_hashes.len().try_into(),
message_hashes.len().try_into()
) {
let _ = self
.rollup_store
.update_operations_count(tx_count, privileged_transaction_count, messages_count)
.await
.inspect_err(|e| {
tracing::error!("Failed to update operations metric: {}", e.to_string())
});
}
#[allow(clippy::as_conversions)]
let blob_usage_percentage = blob_size as f64 * 100_f64 / ethrex_common::types::BYTES_PER_BLOB_F64;
let batch_gas_used = batch_gas_used.try_into()?;
let batch_size = (last_added_block_number - first_block_of_batch).try_into()?;
let tx_count = tx_count.try_into()?;
METRICS.set_blob_usage_percentage(blob_usage_percentage);
METRICS.set_batch_gas_used(batch_number, batch_gas_used)?;
METRICS.set_batch_size(batch_number, batch_size)?;
METRICS.set_batch_tx_count(batch_number, tx_count)?;
);
info!(
"Added {} privileged transactions to the batch",
privileged_transactions_hashes.len()
);
let privileged_transactions_hash =
compute_privileged_transactions_hash(privileged_transactions_hashes)?;
let last_block_hash = blocks
.last()
.ok_or(CommitterError::Unreachable(
"There should always be blocks".to_string(),
))?
.1;
checkpoint_store
.forkchoice_update(
Some(blocks),
last_added_block_number,
last_block_hash,
None,
None,
)
.await?;
Ok((
blobs_bundle,
new_state_root,
message_hashes,
privileged_transactions_hash,
last_added_block_number,
))
}
async fn generate_and_store_batch_prover_input(
&self,
batch: &Batch,
) -> Result<(), CommitterError> {
if self
.rollup_store
.get_prover_input_by_batch_and_version(batch.number, &self.git_commit_hash)
.await?
.is_some()
{
info!(
"Prover input for batch {} and version {} already exists, skipping generation",
batch.number, self.git_commit_hash
);
return Ok(());
}
let (blocks, fee_configs) = fetch_blocks_with_respective_fee_configs::<CommitterError>(
batch.number,
&self.store,
&self.rollup_store,
)
.await?;
let rand_suffix: u32 = rand::thread_rng().r#gen();
let one_time_checkpoint_path = self.checkpoints_dir.join(format!(
"temp_checkpoint_witness_{}_{rand_suffix}",
batch.number
));
// We need to create a one-time checkpoint copy because if witness generation fails the checkpoint would be modified
let (_, one_time_checkpoint_blockchain) = self
.create_checkpoint(
&self.current_checkpoint_store,
&one_time_checkpoint_path,
&self.rollup_store,
)
.await?;
let result = one_time_checkpoint_blockchain
.generate_witness_for_blocks_with_fee_configs(&blocks, Some(&fee_configs))
.await
.map_err(CommitterError::FailedToGenerateBatchWitness);
if one_time_checkpoint_path.exists() {
let _ = remove_dir_all(&one_time_checkpoint_path).inspect_err(|e| {
error!(
"Failed to remove one-time checkpoint directory at path {one_time_checkpoint_path:?}. Should be removed manually. Error: {}", e.to_string()
)
});
}
let batch_witness = result?;
// We still need to differentiate the validium case because for validium
// we are generating the BlobsBundle with BlobsBundle::default which
// sets the commitments and proofs to empty vectors.
let (blob_commitment, blob_proof) = if self.validium {
([0; 48], [0; 48])
} else {
let BlobsBundle {
commitments,
proofs,
blobs,
..
} = &batch.blobs_bundle;
let l1_fork = get_l1_active_fork(&self.eth_client, self.osaka_activation_time)
.await
.map_err(CommitterError::EthClientError)?;
let commitment = commitments
.last()
.cloned()
.ok_or_else(|| CommitterError::MissingBlob(batch.number))?;
// The prover takes a single proof even for Osaka type proofs, so if
// the committer generated Osaka type proofs (cell proofs), we need
// to create a BlobsBundle from the blobs specifying a pre-Osaka
// fork to get a single proof for the entire blob.
// If we are pre-Osaka, we already have a single proof in the
// previously generated bundle
let proof = if l1_fork < Fork::Osaka {
proofs
.first()
.cloned()
.ok_or_else(|| CommitterError::MissingBlob(batch.number))?
} else {
BlobsBundle::create_from_blobs(blobs, Some(0))?
.proofs
.first()
.cloned()
.ok_or_else(|| CommitterError::MissingBlob(batch.number))?
};
(commitment, proof)
};
let prover_input = ProverInputData {
blocks,
execution_witness: batch_witness,
elasticity_multiplier: self.elasticity_multiplier,
blob_commitment,
blob_proof,
fee_configs,
};
self.rollup_store
.store_prover_input_by_batch_and_version(
batch.number,
&self.git_commit_hash,
prover_input,
)
.await?;
Ok(())
}
/// Creates a checkpoint of the given store at the specified path.
///
/// This function performs the following steps:
/// 1. Creates a checkpoint of the provided store at the specified path.
/// 2. Initializes a new store and blockchain for the checkpoint.
/// 3. Regenerates the head state in the checkpoint store.
/// 4. TODO: Validates that the checkpoint contains the needed state root.
async fn create_checkpoint(
&self,
checkpointee: &Store,
path: &Path,
rollup_store: &StoreRollup,
) -> Result<(Store, Arc<Blockchain>), CommitterError> {
checkpointee.create_checkpoint(&path).await?;
Self::get_checkpoint_from_path(
self.genesis.clone(),
self.blockchain.options.clone(),
path,
rollup_store,
)
.await
}
/// Returns a checkpoint store and blockchain from the given path.
/// If the path does not exist, it creates a new store with the genesis state (this,
/// should only happen on the very first run).
async fn get_checkpoint_from_path(
genesis: Genesis,
mut blockchain_opts: BlockchainOptions,
path: &Path,
rollup_store: &StoreRollup,
) -> Result<(Store, Arc<Blockchain>), CommitterError> {
#[cfg(feature = "rocksdb")]
let engine_type = EngineType::RocksDB;
#[cfg(not(feature = "rocksdb"))]
let engine_type = EngineType::InMemory;
if !path.exists() {
info!("Creating genesis checkpoint at path {path:?}");
}
let checkpoint_store = {
let mut checkpoint_store_inner = Store::new(path, engine_type)?;
checkpoint_store_inner.add_initial_state(genesis).await?;
checkpoint_store_inner
};
// Here we override the blockchain type with a default config
// to avoid using the same `Arc<Mutex>` from the main blockchain.
// It is fine to use the default L2Config since the corresponding
// one for each block is fetched from the rollup store during head state regeneration.
blockchain_opts.r#type = BlockchainType::L2(L2Config::default());
let checkpoint_blockchain =
Arc::new(Blockchain::new(checkpoint_store.clone(), blockchain_opts));
regenerate_head_state(&checkpoint_store, rollup_store, &checkpoint_blockchain).await?;
Ok((checkpoint_store, checkpoint_blockchain))
}
async fn send_commitment(&mut self, batch: &Batch) -> Result<H256, CommitterError> {
let messages_merkle_root = compute_merkle_root(&batch.message_hashes);
let last_block_hash = get_last_block_hash(&self.store, batch.last_block)?;
let mut calldata_values = vec![
Value::Uint(U256::from(batch.number)),
Value::FixedBytes(batch.state_root.0.to_vec().into()),
Value::FixedBytes(messages_merkle_root.0.to_vec().into()),
Value::FixedBytes(batch.privileged_transactions_hash.0.to_vec().into()),
Value::FixedBytes(last_block_hash.0.to_vec().into()),
];
let (commit_function_signature, values) = if self.based {
let mut encoded_blocks: Vec<Bytes> = Vec::new();
let (blocks, _) = fetch_blocks_with_respective_fee_configs::<CommitterError>(
batch.number,
&self.store,
&self.rollup_store,
)
.await?;
for block in blocks {
encoded_blocks.push(block.encode_to_vec().into());
}
calldata_values.push(Value::Array(
encoded_blocks.into_iter().map(Value::Bytes).collect(),
));
(COMMIT_FUNCTION_SIGNATURE_BASED, calldata_values)
} else {
(COMMIT_FUNCTION_SIGNATURE, calldata_values)
};
let calldata = encode_calldata(commit_function_signature, &values)?;
let gas_price = self
.eth_client
.get_gas_price_with_extra(20)
.await?
.try_into()
.map_err(|_| {
CommitterError::ConversionError("Failed to convert gas_price to a u64".to_owned())
})?;
// Validium: EIP1559 Transaction.
// Rollup: EIP4844 Transaction -> For on-chain Data Availability.
let tx = if !self.validium {
info!("L2 is in rollup mode, sending EIP-4844 (including blob) tx to commit block");
let le_bytes = estimate_blob_gas(
&self.eth_client,
self.arbitrary_base_blob_gas_price,
20, // 20% of headroom
)
.await?
.to_le_bytes();
let gas_price_per_blob = U256::from_little_endian(&le_bytes);
build_generic_tx(
&self.eth_client,
TxType::EIP4844,
self.on_chain_proposer_address,
self.signer.address(),
calldata.into(),
Overrides {
from: Some(self.signer.address()),
gas_price_per_blob: Some(gas_price_per_blob),
max_fee_per_gas: Some(gas_price),
max_priority_fee_per_gas: Some(gas_price),
blobs_bundle: Some(batch.blobs_bundle.clone()),
wrapper_version: Some(batch.blobs_bundle.version),
..Default::default()
},
)
.await
.map_err(CommitterError::from)?
} else {