-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathblocks_dal.rs
2657 lines (2486 loc) · 84.7 KB
/
blocks_dal.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 std::{
collections::HashMap,
convert::{Into, TryInto},
ops,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::Context as _;
use bigdecimal::{BigDecimal, FromPrimitive, ToPrimitive};
use zksync_db_connection::{
connection::Connection,
error::{DalResult, SqlxContext},
instrument::{InstrumentExt, Instrumented},
interpolate_query, match_query_as,
};
use zksync_types::{
aggregated_operations::AggregatedActionType,
block::{
BlockGasCount, L1BatchHeader, L1BatchStatistics, L1BatchTreeData, L2BlockHeader,
StorageOracleInfo,
},
circuit::CircuitStatistic,
commitment::{L1BatchCommitmentArtifacts, L1BatchWithMetadata},
l2_to_l1_log::UserL2ToL1Log,
writes::TreeWrite,
Address, L1BatchNumber, L2BlockNumber, ProtocolVersionId, H256, U256,
};
pub use crate::models::storage_block::{L1BatchMetadataError, L1BatchWithOptionalMetadata};
use crate::{
models::{
parse_protocol_version,
storage_block::{StorageL1Batch, StorageL1BatchHeader, StorageL2BlockHeader},
storage_event::StorageL2ToL1Log,
storage_oracle_info::DbStorageOracleInfo,
},
Core, CoreDal,
};
#[derive(Debug)]
pub struct BlocksDal<'a, 'c> {
pub(crate) storage: &'a mut Connection<'c, Core>,
}
impl BlocksDal<'_, '_> {
pub async fn get_consistency_checker_last_processed_l1_batch(
&mut self,
) -> DalResult<L1BatchNumber> {
let row = sqlx::query!(
r#"
SELECT
last_processed_l1_batch AS "last_processed_l1_batch!"
FROM
consistency_checker_info
"#
)
.instrument("get_consistency_checker_last_processed_l1_batch")
.report_latency()
.fetch_one(self.storage)
.await?;
Ok(L1BatchNumber(row.last_processed_l1_batch as u32))
}
pub async fn set_consistency_checker_last_processed_l1_batch(
&mut self,
l1_batch_number: L1BatchNumber,
) -> DalResult<()> {
sqlx::query!(
r#"
UPDATE consistency_checker_info
SET
last_processed_l1_batch = $1,
updated_at = NOW()
"#,
l1_batch_number.0 as i32,
)
.instrument("set_consistency_checker_last_processed_l1_batch")
.report_latency()
.with_arg("l1_batch_number", &l1_batch_number)
.execute(self.storage)
.await?;
Ok(())
}
pub async fn is_genesis_needed(&mut self) -> DalResult<bool> {
let count = sqlx::query!(
r#"
SELECT
COUNT(*) AS "count!"
FROM
l1_batches
"#
)
.instrument("is_genesis_needed")
.fetch_one(self.storage)
.await?
.count;
Ok(count == 0)
}
pub async fn get_sealed_l1_batch_number(&mut self) -> DalResult<Option<L1BatchNumber>> {
let row = sqlx::query!(
r#"
SELECT
MAX(number) AS "number"
FROM
l1_batches
"#
)
.instrument("get_sealed_l1_batch_number")
.report_latency()
.fetch_one(self.storage)
.await?;
Ok(row.number.map(|num| L1BatchNumber(num as u32)))
}
pub async fn get_sealed_l2_block_number(&mut self) -> DalResult<Option<L2BlockNumber>> {
let row = sqlx::query!(
r#"
SELECT
MAX(number) AS "number"
FROM
miniblocks
"#
)
.instrument("get_sealed_l2_block_number")
.report_latency()
.fetch_one(self.storage)
.await?;
Ok(row.number.map(|number| L2BlockNumber(number as u32)))
}
/// Returns the number of the earliest L1 batch present in the DB, or `None` if there are no L1 batches.
pub async fn get_earliest_l1_batch_number(&mut self) -> DalResult<Option<L1BatchNumber>> {
let row = sqlx::query!(
r#"
SELECT
MIN(number) AS "number"
FROM
l1_batches
"#
)
.instrument("get_earliest_l1_batch_number")
.report_latency()
.fetch_one(self.storage)
.await?;
Ok(row.number.map(|num| L1BatchNumber(num as u32)))
}
pub async fn get_last_l1_batch_number_with_tree_data(
&mut self,
) -> DalResult<Option<L1BatchNumber>> {
let row = sqlx::query!(
r#"
SELECT
MAX(number) AS "number"
FROM
l1_batches
WHERE
hash IS NOT NULL
"#
)
.instrument("get_last_l1_batch_number_with_tree_data")
.report_latency()
.fetch_one(self.storage)
.await?;
Ok(row.number.map(|num| L1BatchNumber(num as u32)))
}
/// Gets a number of the earliest L1 batch that is ready for commitment generation (i.e., doesn't have commitment
/// yet, and has tree data).
pub async fn get_next_l1_batch_ready_for_commitment_generation(
&mut self,
) -> DalResult<Option<L1BatchNumber>> {
let row = sqlx::query!(
r#"
SELECT
number
FROM
l1_batches
WHERE
hash IS NOT NULL
AND commitment IS NULL
ORDER BY
number
LIMIT
1
"#
)
.instrument("get_next_l1_batch_ready_for_commitment_generation")
.report_latency()
.fetch_optional(self.storage)
.await?;
Ok(row.map(|row| L1BatchNumber(row.number as u32)))
}
/// Gets a number of the last L1 batch that is ready for commitment generation (i.e., doesn't have commitment
/// yet, and has tree data).
pub async fn get_last_l1_batch_ready_for_commitment_generation(
&mut self,
) -> DalResult<Option<L1BatchNumber>> {
let row = sqlx::query!(
r#"
SELECT
number
FROM
l1_batches
WHERE
hash IS NOT NULL
AND commitment IS NULL
ORDER BY
number DESC
LIMIT
1
"#
)
.instrument("get_last_l1_batch_ready_for_commitment_generation")
.report_latency()
.fetch_optional(self.storage)
.await?;
Ok(row.map(|row| L1BatchNumber(row.number as u32)))
}
/// Returns the number of the earliest L1 batch with metadata (= state hash) present in the DB,
/// or `None` if there are no such L1 batches.
pub async fn get_earliest_l1_batch_number_with_metadata(
&mut self,
) -> DalResult<Option<L1BatchNumber>> {
let row = sqlx::query!(
r#"
SELECT
MIN(number) AS "number"
FROM
l1_batches
WHERE
hash IS NOT NULL
"#
)
.instrument("get_earliest_l1_batch_number_with_metadata")
.report_latency()
.fetch_one(self.storage)
.await?;
Ok(row.number.map(|num| L1BatchNumber(num as u32)))
}
pub async fn get_l1_batches_statistics_for_eth_tx_id(
&mut self,
eth_tx_id: u32,
) -> DalResult<Vec<L1BatchStatistics>> {
Ok(sqlx::query!(
r#"
SELECT
number,
l1_tx_count,
l2_tx_count,
timestamp
FROM
l1_batches
WHERE
eth_commit_tx_id = $1
OR eth_prove_tx_id = $1
OR eth_execute_tx_id = $1
"#,
eth_tx_id as i32
)
.instrument("get_l1_batch_statistics_for_eth_tx_id")
.with_arg("eth_tx_id", ð_tx_id)
.fetch_all(self.storage)
.await?
.into_iter()
.map(|row| L1BatchStatistics {
number: L1BatchNumber(row.number as u32),
timestamp: row.timestamp as u64,
l2_tx_count: row.l2_tx_count as u32,
l1_tx_count: row.l1_tx_count as u32,
})
.collect())
}
async fn get_storage_l1_batch(
&mut self,
number: L1BatchNumber,
) -> DalResult<Option<StorageL1Batch>> {
sqlx::query_as!(
StorageL1Batch,
r#"
SELECT
number,
timestamp,
l1_tx_count,
l2_tx_count,
bloom,
priority_ops_onchain_data,
hash,
commitment,
l2_to_l1_messages,
used_contract_hashes,
compressed_initial_writes,
compressed_repeated_writes,
l2_l1_merkle_root,
rollup_last_leaf_index,
zkporter_is_available,
bootloader_code_hash,
default_aa_code_hash,
aux_data_hash,
pass_through_data_hash,
meta_parameters_hash,
protocol_version,
system_logs,
compressed_state_diffs,
events_queue_commitment,
bootloader_initial_content_commitment,
pubdata_input
FROM
l1_batches
LEFT JOIN commitments ON commitments.l1_batch_number = l1_batches.number
WHERE
number = $1
"#,
i64::from(number.0)
)
.instrument("get_storage_l1_batch")
.with_arg("number", &number)
.fetch_optional(self.storage)
.await
}
pub async fn get_l1_batch_header(
&mut self,
number: L1BatchNumber,
) -> DalResult<Option<L1BatchHeader>> {
let storage_l1_batch_header = sqlx::query_as!(
StorageL1BatchHeader,
r#"
SELECT
number,
l1_tx_count,
l2_tx_count,
timestamp,
l2_to_l1_messages,
bloom,
priority_ops_onchain_data,
used_contract_hashes,
bootloader_code_hash,
default_aa_code_hash,
protocol_version,
system_logs,
pubdata_input
FROM
l1_batches
WHERE
number = $1
"#,
i64::from(number.0)
)
.instrument("get_l1_batch_header")
.with_arg("number", &number)
.fetch_optional(self.storage)
.await?;
if let Some(storage_l1_batch_header) = storage_l1_batch_header {
let l2_to_l1_logs = self
.get_l2_to_l1_logs_for_batch::<UserL2ToL1Log>(number)
.await?;
return Ok(Some(
storage_l1_batch_header.into_l1_batch_header_with_logs(l2_to_l1_logs),
));
}
Ok(None)
}
/// Returns initial bootloader heap content for the specified L1 batch.
pub async fn get_initial_bootloader_heap(
&mut self,
number: L1BatchNumber,
) -> anyhow::Result<Option<Vec<(usize, U256)>>> {
let Some(row) = sqlx::query!(
r#"
SELECT
initial_bootloader_heap_content
FROM
l1_batches
WHERE
number = $1
"#,
i64::from(number.0)
)
.instrument("get_initial_bootloader_heap")
.report_latency()
.with_arg("number", &number)
.fetch_optional(self.storage)
.await?
else {
return Ok(None);
};
let heap = serde_json::from_value(row.initial_bootloader_heap_content)
.context("invalid value for initial_bootloader_heap_content in the DB")?;
Ok(Some(heap))
}
pub async fn get_storage_oracle_info(
&mut self,
number: L1BatchNumber,
) -> anyhow::Result<Option<StorageOracleInfo>> {
let storage_oracle_info = sqlx::query_as!(
DbStorageOracleInfo,
r#"
SELECT
storage_refunds,
pubdata_costs
FROM
l1_batches
WHERE
number = $1
"#,
i64::from(number.0)
)
.instrument("get_storage_refunds")
.report_latency()
.with_arg("number", &number)
.fetch_optional(self.storage)
.await?;
Ok(storage_oracle_info.and_then(DbStorageOracleInfo::into_optional_batch_oracle_info))
}
pub async fn set_eth_tx_id(
&mut self,
number_range: ops::RangeInclusive<L1BatchNumber>,
eth_tx_id: u32,
aggregation_type: AggregatedActionType,
) -> DalResult<()> {
match aggregation_type {
AggregatedActionType::Commit => {
let instrumentation = Instrumented::new("set_eth_tx_id#commit")
.with_arg("number_range", &number_range)
.with_arg("eth_tx_id", ð_tx_id);
let query = sqlx::query!(
r#"
UPDATE l1_batches
SET
eth_commit_tx_id = $1,
updated_at = NOW()
WHERE
number BETWEEN $2 AND $3
AND eth_commit_tx_id IS NULL
"#,
eth_tx_id as i32,
i64::from(number_range.start().0),
i64::from(number_range.end().0)
);
let result = instrumentation
.clone()
.with(query)
.execute(self.storage)
.await?;
if result.rows_affected() == 0 {
let err = instrumentation.constraint_error(anyhow::anyhow!(
"Update eth_commit_tx_id that is is not null is not allowed"
));
return Err(err);
}
}
AggregatedActionType::PublishProofOnchain => {
let instrumentation = Instrumented::new("set_eth_tx_id#prove")
.with_arg("number_range", &number_range)
.with_arg("eth_tx_id", ð_tx_id);
let query = sqlx::query!(
r#"
UPDATE l1_batches
SET
eth_prove_tx_id = $1,
updated_at = NOW()
WHERE
number BETWEEN $2 AND $3
AND eth_prove_tx_id IS NULL
"#,
eth_tx_id as i32,
i64::from(number_range.start().0),
i64::from(number_range.end().0)
);
let result = instrumentation
.clone()
.with(query)
.execute(self.storage)
.await?;
if result.rows_affected() == 0 {
let err = instrumentation.constraint_error(anyhow::anyhow!(
"Update eth_prove_tx_id that is is not null is not allowed"
));
return Err(err);
}
}
AggregatedActionType::Execute => {
let instrumentation = Instrumented::new("set_eth_tx_id#execute")
.with_arg("number_range", &number_range)
.with_arg("eth_tx_id", ð_tx_id);
let query = sqlx::query!(
r#"
UPDATE l1_batches
SET
eth_execute_tx_id = $1,
updated_at = NOW()
WHERE
number BETWEEN $2 AND $3
AND eth_execute_tx_id IS NULL
"#,
eth_tx_id as i32,
i64::from(number_range.start().0),
i64::from(number_range.end().0)
);
let result = instrumentation
.clone()
.with(query)
.execute(self.storage)
.await?;
if result.rows_affected() == 0 {
let err = instrumentation.constraint_error(anyhow::anyhow!(
"Update eth_execute_tx_id that is is not null is not allowed"
));
return Err(err);
}
}
}
Ok(())
}
pub async fn insert_l1_batch(
&mut self,
header: &L1BatchHeader,
initial_bootloader_contents: &[(usize, U256)],
predicted_block_gas: BlockGasCount,
storage_refunds: &[u32],
pubdata_costs: &[i32],
predicted_circuits_by_type: CircuitStatistic, // predicted number of circuits for each circuit type
) -> DalResult<()> {
let initial_bootloader_contents_len = initial_bootloader_contents.len();
let instrumentation = Instrumented::new("insert_l1_batch")
.with_arg("number", &header.number)
.with_arg(
"initial_bootloader_contents.len",
&initial_bootloader_contents_len,
);
let priority_onchain_data: Vec<Vec<u8>> = header
.priority_ops_onchain_data
.iter()
.map(|data| data.clone().into())
.collect();
let system_logs = header
.system_logs
.iter()
.map(|log| log.0.to_bytes().to_vec())
.collect::<Vec<Vec<u8>>>();
let pubdata_input = header.pubdata_input.clone();
let initial_bootloader_contents = serde_json::to_value(initial_bootloader_contents)
.map_err(|err| instrumentation.arg_error("initial_bootloader_contents", err))?;
let used_contract_hashes = serde_json::to_value(&header.used_contract_hashes)
.map_err(|err| instrumentation.arg_error("header.used_contract_hashes", err))?;
let storage_refunds: Vec<_> = storage_refunds.iter().copied().map(i64::from).collect();
let pubdata_costs: Vec<_> = pubdata_costs.iter().copied().map(i64::from).collect();
let query = sqlx::query!(
r#"
INSERT INTO
l1_batches (
number,
l1_tx_count,
l2_tx_count,
timestamp,
l2_to_l1_messages,
bloom,
priority_ops_onchain_data,
predicted_commit_gas_cost,
predicted_prove_gas_cost,
predicted_execute_gas_cost,
initial_bootloader_heap_content,
used_contract_hashes,
bootloader_code_hash,
default_aa_code_hash,
protocol_version,
system_logs,
storage_refunds,
pubdata_costs,
pubdata_input,
predicted_circuits_by_type,
created_at,
updated_at
)
VALUES
(
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16,
$17,
$18,
$19,
$20,
NOW(),
NOW()
)
"#,
i64::from(header.number.0),
i32::from(header.l1_tx_count),
i32::from(header.l2_tx_count),
header.timestamp as i64,
&header.l2_to_l1_messages,
header.bloom.as_bytes(),
&priority_onchain_data,
i64::from(predicted_block_gas.commit),
i64::from(predicted_block_gas.prove),
i64::from(predicted_block_gas.execute),
initial_bootloader_contents,
used_contract_hashes,
header.base_system_contracts_hashes.bootloader.as_bytes(),
header.base_system_contracts_hashes.default_aa.as_bytes(),
header.protocol_version.map(|v| v as i32),
&system_logs,
&storage_refunds,
&pubdata_costs,
pubdata_input,
serde_json::to_value(predicted_circuits_by_type).unwrap(),
);
let mut transaction = self.storage.start_transaction().await?;
instrumentation
.with(query)
.execute(&mut transaction)
.await?;
transaction.commit().await
}
pub async fn insert_l2_block(&mut self, l2_block_header: &L2BlockHeader) -> DalResult<()> {
let instrumentation =
Instrumented::new("insert_l2_block").with_arg("number", &l2_block_header.number);
let base_fee_per_gas =
BigDecimal::from_u64(l2_block_header.base_fee_per_gas).ok_or_else(|| {
instrumentation.arg_error(
"header.base_fee_per_gas",
anyhow::anyhow!("doesn't fit in u64"),
)
})?;
let query = sqlx::query!(
r#"
INSERT INTO
miniblocks (
number,
timestamp,
hash,
l1_tx_count,
l2_tx_count,
fee_account_address,
base_fee_per_gas,
l1_gas_price,
l2_fair_gas_price,
gas_per_pubdata_limit,
bootloader_code_hash,
default_aa_code_hash,
protocol_version,
virtual_blocks,
fair_pubdata_price,
gas_limit,
created_at,
updated_at
)
VALUES
(
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16,
NOW(),
NOW()
)
"#,
i64::from(l2_block_header.number.0),
l2_block_header.timestamp as i64,
l2_block_header.hash.as_bytes(),
i32::from(l2_block_header.l1_tx_count),
i32::from(l2_block_header.l2_tx_count),
l2_block_header.fee_account_address.as_bytes(),
base_fee_per_gas,
l2_block_header.batch_fee_input.l1_gas_price() as i64,
l2_block_header.batch_fee_input.fair_l2_gas_price() as i64,
l2_block_header.gas_per_pubdata_limit as i64,
l2_block_header
.base_system_contracts_hashes
.bootloader
.as_bytes(),
l2_block_header
.base_system_contracts_hashes
.default_aa
.as_bytes(),
l2_block_header.protocol_version.map(|v| v as i32),
i64::from(l2_block_header.virtual_blocks),
l2_block_header.batch_fee_input.fair_pubdata_price() as i64,
l2_block_header.gas_limit as i64,
);
instrumentation.with(query).execute(self.storage).await?;
Ok(())
}
pub async fn get_last_sealed_l2_block_header(&mut self) -> DalResult<Option<L2BlockHeader>> {
let header = sqlx::query_as!(
StorageL2BlockHeader,
r#"
SELECT
number,
timestamp,
hash,
l1_tx_count,
l2_tx_count,
fee_account_address AS "fee_account_address!",
base_fee_per_gas,
l1_gas_price,
l2_fair_gas_price,
gas_per_pubdata_limit,
bootloader_code_hash,
default_aa_code_hash,
protocol_version,
virtual_blocks,
fair_pubdata_price,
gas_limit
FROM
miniblocks
ORDER BY
number DESC
LIMIT
1
"#,
)
.instrument("get_last_sealed_l2_block_header")
.fetch_optional(self.storage)
.await?;
Ok(header.map(Into::into))
}
pub async fn get_l2_block_header(
&mut self,
l2_block_number: L2BlockNumber,
) -> DalResult<Option<L2BlockHeader>> {
let header = sqlx::query_as!(
StorageL2BlockHeader,
r#"
SELECT
number,
timestamp,
hash,
l1_tx_count,
l2_tx_count,
fee_account_address AS "fee_account_address!",
base_fee_per_gas,
l1_gas_price,
l2_fair_gas_price,
gas_per_pubdata_limit,
bootloader_code_hash,
default_aa_code_hash,
protocol_version,
virtual_blocks,
fair_pubdata_price,
gas_limit
FROM
miniblocks
WHERE
number = $1
"#,
i64::from(l2_block_number.0),
)
.instrument("get_l2_block_header")
.with_arg("l2_block_number", &l2_block_number)
.fetch_optional(self.storage)
.await?;
Ok(header.map(Into::into))
}
pub async fn mark_l2_blocks_as_executed_in_l1_batch(
&mut self,
l1_batch_number: L1BatchNumber,
) -> DalResult<()> {
sqlx::query!(
r#"
UPDATE miniblocks
SET
l1_batch_number = $1
WHERE
l1_batch_number IS NULL
"#,
l1_batch_number.0 as i32,
)
.instrument("mark_l2_blocks_as_executed_in_l1_batch")
.with_arg("l1_batch_number", &l1_batch_number)
.execute(self.storage)
.await?;
Ok(())
}
pub async fn save_l1_batch_tree_data(
&mut self,
number: L1BatchNumber,
tree_data: &L1BatchTreeData,
) -> anyhow::Result<()> {
let update_result = sqlx::query!(
r#"
UPDATE l1_batches
SET
hash = $1,
rollup_last_leaf_index = $2,
updated_at = NOW()
WHERE
number = $3
AND hash IS NULL
"#,
tree_data.hash.as_bytes(),
tree_data.rollup_last_leaf_index as i64,
i64::from(number.0),
)
.instrument("save_batch_tree_data")
.with_arg("number", &number)
.report_latency()
.execute(self.storage)
.await?;
if update_result.rows_affected() == 0 {
tracing::debug!("L1 batch #{number}: tree data wasn't updated as it's already present");
// Batch was already processed. Verify that the existing tree data matches.
let existing_tree_data = self.get_l1_batch_tree_data(number).await?;
anyhow::ensure!(
existing_tree_data.as_ref() == Some(tree_data),
"Root hash verification failed. Tree data for L1 batch #{number} does not match the expected value \
(expected: {tree_data:?}, existing: {existing_tree_data:?})",
);
}
Ok(())
}
pub async fn save_l1_batch_commitment_artifacts(
&mut self,
number: L1BatchNumber,
commitment_artifacts: &L1BatchCommitmentArtifacts,
) -> anyhow::Result<()> {
let mut transaction = self.storage.start_transaction().await?;
let update_result = sqlx::query!(
r#"
UPDATE l1_batches
SET
commitment = $1,
aux_data_hash = $2,
pass_through_data_hash = $3,
meta_parameters_hash = $4,
l2_l1_merkle_root = $5,
zkporter_is_available = $6,
compressed_state_diffs = $7,
compressed_initial_writes = $8,
compressed_repeated_writes = $9,
updated_at = NOW()
WHERE
number = $10
AND commitment IS NULL
"#,
commitment_artifacts.commitment_hash.commitment.as_bytes(),
commitment_artifacts.commitment_hash.aux_output.as_bytes(),
commitment_artifacts
.commitment_hash
.pass_through_data
.as_bytes(),
commitment_artifacts
.commitment_hash
.meta_parameters
.as_bytes(),
commitment_artifacts.l2_l1_merkle_root.as_bytes(),
commitment_artifacts.zkporter_is_available,
commitment_artifacts.compressed_state_diffs,
commitment_artifacts.compressed_initial_writes,
commitment_artifacts.compressed_repeated_writes,
i64::from(number.0),
)
.instrument("save_l1_batch_commitment_artifacts")
.with_arg("number", &number)
.report_latency()
.execute(&mut transaction)
.await?;
if update_result.rows_affected() == 0 {
tracing::debug!(
"L1 batch #{number}: commitment info wasn't updated as it's already present"
);
// Batch was already processed. Verify that existing commitment matches
let matched: i64 = sqlx::query!(
r#"
SELECT
COUNT(*) AS "count!"
FROM
l1_batches
WHERE
number = $1
AND commitment = $2
"#,
i64::from(number.0),
commitment_artifacts.commitment_hash.commitment.as_bytes(),
)
.instrument("get_matching_batch_commitment")
.with_arg("number", &number)
.report_latency()
.fetch_one(&mut transaction)
.await?
.count;
anyhow::ensure!(
matched == 1,
"Commitment verification failed. Commitment for L1 batch #{} does not match the expected value \
(expected commitment: {:?})",
number,
commitment_artifacts.commitment_hash.commitment
);
}
sqlx::query!(
r#"
INSERT INTO
commitments (l1_batch_number, events_queue_commitment, bootloader_initial_content_commitment)
VALUES
($1, $2, $3)
ON CONFLICT (l1_batch_number) DO NOTHING
"#,
i64::from(number.0),
commitment_artifacts.aux_commitments.map(|a| a.events_queue_commitment.0.to_vec()),
commitment_artifacts.aux_commitments
.map(|a| a.bootloader_initial_content_commitment.0.to_vec()),
)
.instrument("save_batch_aux_commitments")
.with_arg("number", &number)
.report_latency()
.execute(&mut transaction)
.await?;
transaction.commit().await?;
Ok(())
}
pub async fn get_last_committed_to_eth_l1_batch(
&mut self,
) -> DalResult<Option<L1BatchWithMetadata>> {
// We can get 0 batch for the first transaction
let batch = sqlx::query_as!(
StorageL1Batch,
r#"
SELECT
number,
timestamp,
l1_tx_count,
l2_tx_count,
bloom,