Skip to content

Commit

Permalink
revamp the logic from ground up and align tests
Browse files Browse the repository at this point in the history
  • Loading branch information
itegulov committed Dec 12, 2024
1 parent a992885 commit e334c2f
Show file tree
Hide file tree
Showing 12 changed files with 289 additions and 182 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

This file was deleted.

78 changes: 38 additions & 40 deletions core/lib/dal/src/blocks_dal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ use zksync_db_connection::{
use zksync_types::{
aggregated_operations::AggregatedActionType,
block::{
L1BatchHeader, L1BatchStatistics, L1BatchTreeData, L2BlockHeader, StorageOracleInfo,
UnsealedL1BatchHeader,
CommonL1BatchHeader, L1BatchHeader, L1BatchStatistics, L1BatchTreeData, L2BlockHeader,
StorageOracleInfo, UnsealedL1BatchHeader,
},
commitment::{L1BatchCommitmentArtifacts, L1BatchWithMetadata},
fee_model::BatchFeeInput,
l2_to_l1_log::{BatchAndChainMerklePath, UserL2ToL1Log},
writes::TreeWrite,
Address, Bloom, L1BatchNumber, L2BlockNumber, ProtocolVersionId, SLChainId, H256, U256,
Expand All @@ -32,7 +31,8 @@ use crate::{
models::{
parse_protocol_version,
storage_block::{
StorageL1Batch, StorageL1BatchHeader, StorageL2BlockHeader, UnsealedStorageL1Batch,
CommonStorageL1BatchHeader, StorageL1Batch, StorageL1BatchHeader, StorageL2BlockHeader,
UnsealedStorageL1Batch,
},
storage_event::StorageL2ToL1Log,
storage_oracle_info::DbStorageOracleInfo,
Expand Down Expand Up @@ -103,6 +103,7 @@ impl BlocksDal<'_, '_> {
Ok(count == 0)
}

/// Returns the number of the last sealed L1 batch present in the DB, or `None` if there are no L1 batches.
pub async fn get_sealed_l1_batch_number(&mut self) -> DalResult<Option<L1BatchNumber>> {
let row = sqlx::query!(
r#"
Expand All @@ -122,6 +123,39 @@ impl BlocksDal<'_, '_> {
Ok(row.number.map(|num| L1BatchNumber(num as u32)))
}

/// Returns latest L1 batch's header (could be unsealed). The header contains fields that are
/// common for both unsealed and sealed batches. Returns `None` if there are no L1 batches.
pub async fn get_latest_l1_batch_header(&mut self) -> DalResult<Option<CommonL1BatchHeader>> {
let Some(header) = sqlx::query_as!(
CommonStorageL1BatchHeader,
r#"
SELECT
number,
is_sealed,
timestamp,
protocol_version,
fee_address,
l1_gas_price,
l2_fair_gas_price,
fair_pubdata_price
FROM
l1_batches
ORDER BY
number DESC
LIMIT
1
"#,
)
.instrument("get_latest_l1_batch_header")
.fetch_optional(self.storage)
.await?
else {
return Ok(None);
};

Ok(Some(header.into()))
}

pub async fn get_sealed_l2_block_number(&mut self) -> DalResult<Option<L2BlockNumber>> {
let row = sqlx::query!(
r#"
Expand Down Expand Up @@ -918,42 +952,6 @@ impl BlocksDal<'_, '_> {
Ok(())
}

/// Returns fee input as of the latest non-genesis L1 batch present in DB, where latest means:
/// * Current unsealed L1 batch if it exists
/// * Last sealed L1 batch if it does not (excluding genesis as it does not have valid fee input)
///
/// `None` if the only batch in DB is genesis or if there are no batches at all.
pub async fn get_latest_l1_batch_fee_input(&mut self) -> DalResult<Option<BatchFeeInput>> {
let row = sqlx::query!(
r#"
SELECT
l1_gas_price,
l2_fair_gas_price,
fair_pubdata_price
FROM
l1_batches
WHERE
number > 0
ORDER BY
number
LIMIT
1
"#
)
.instrument("get_latest_l1_batch_fee_input")
.fetch_optional(self.storage)
.await?;

let Some(row) = row else {
return Ok(None);
};
Ok(Some(BatchFeeInput::pubdata_independent(
row.l1_gas_price as u64,
row.l2_fair_gas_price as u64,
row.fair_pubdata_price as u64,
)))
}

pub async fn get_last_sealed_l2_block_header(&mut self) -> DalResult<Option<L2BlockHeader>> {
let header = sqlx::query_as!(
StorageL2BlockHeader,
Expand Down
35 changes: 34 additions & 1 deletion core/lib/dal/src/models/storage_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use thiserror::Error;
use zksync_contracts::BaseSystemContractsHashes;
use zksync_types::{
api,
block::{L1BatchHeader, L2BlockHeader, UnsealedL1BatchHeader},
block::{CommonL1BatchHeader, L1BatchHeader, L2BlockHeader, UnsealedL1BatchHeader},
commitment::{L1BatchCommitmentMode, L1BatchMetaParameters, L1BatchMetadata, PubdataParams},
fee_model::BatchFeeInput,
l2_to_l1_log::{L2ToL1Log, SystemL2ToL1Log, UserL2ToL1Log},
Expand Down Expand Up @@ -333,6 +333,39 @@ impl From<UnsealedStorageL1Batch> for UnsealedL1BatchHeader {
}
}

/// Partial projection of the columns common to both [`L1BatchHeader`] and [`UnsealedL1BatchHeader`].
pub(crate) struct CommonStorageL1BatchHeader {
pub number: i64,
pub is_sealed: bool,
pub timestamp: i64,
pub protocol_version: Option<i32>,
pub fee_address: Vec<u8>,
pub l1_gas_price: i64,
pub l2_fair_gas_price: i64,
pub fair_pubdata_price: Option<i64>,
}

impl From<CommonStorageL1BatchHeader> for CommonL1BatchHeader {
fn from(batch: CommonStorageL1BatchHeader) -> Self {
let protocol_version: Option<ProtocolVersionId> = batch
.protocol_version
.map(|v| (v as u16).try_into().unwrap());
Self {
number: L1BatchNumber(batch.number as u32),
is_sealed: batch.is_sealed,
timestamp: batch.timestamp as u64,
protocol_version,
fee_address: Address::from_slice(&batch.fee_address),
fee_input: BatchFeeInput::for_protocol_version(
protocol_version.unwrap_or_else(ProtocolVersionId::last_potentially_undefined),
batch.l2_fair_gas_price as u64,
batch.fair_pubdata_price.map(|p| p as u64),
batch.l1_gas_price as u64,
),
}
}
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub(crate) struct StorageBlockDetails {
pub number: i64,
Expand Down
18 changes: 18 additions & 0 deletions core/lib/types/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,14 @@ pub enum BlockId {
}

impl BlockId {
pub fn pending() -> Self {
Self::Number(BlockNumber::Pending)
}

pub fn latest() -> Self {
Self::Number(BlockNumber::Latest)
}

/// Extract block's id variant name.
pub fn extract_block_tag(&self) -> String {
match self {
Expand Down Expand Up @@ -145,6 +153,16 @@ pub enum BlockIdVariant {
BlockHashObject(BlockHashObject),
}

impl BlockIdVariant {
pub fn pending() -> Self {
Self::BlockNumber(BlockNumber::Pending)
}

pub fn latest() -> Self {
Self::BlockNumber(BlockNumber::Latest)
}
}

impl From<BlockIdVariant> for BlockId {
fn from(value: BlockIdVariant) -> BlockId {
match value {
Expand Down
11 changes: 11 additions & 0 deletions core/lib/types/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ impl L1BatchHeader {
}
}

/// Holder for the metadata that is relevant for unsealed batches.
#[derive(Debug, Clone, PartialEq)]
pub struct UnsealedL1BatchHeader {
pub number: L1BatchNumber,
Expand All @@ -87,6 +88,16 @@ pub struct UnsealedL1BatchHeader {
pub fee_input: BatchFeeInput,
}

/// Holder for the metadata that is relevant for both sealed and unsealed batches.
pub struct CommonL1BatchHeader {
pub number: L1BatchNumber,
pub is_sealed: bool,
pub timestamp: u64,
pub protocol_version: Option<ProtocolVersionId>,
pub fee_address: Address,
pub fee_input: BatchFeeInput,
}

/// Holder for the L2 block metadata that is not available from transactions themselves.
#[derive(Debug, Clone, PartialEq)]
pub struct L2BlockHeader {
Expand Down
Loading

0 comments on commit e334c2f

Please sign in to comment.