zksync_dal 0.1.0

ZKsync data access layer
Documentation
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
use std::convert::TryInto;

use anyhow::Context as _;
use zksync_contracts::{BaseSystemContracts, BaseSystemContractsHashes};
use zksync_db_connection::{
    connection::Connection,
    error::DalResult,
    instrument::{InstrumentExt, Instrumented},
};
use zksync_types::{
    protocol_upgrade::{ProtocolUpgradeTx, ProtocolVersion},
    protocol_version::{L1VerifierConfig, ProtocolSemanticVersion, VerifierParams, VersionPatch},
    ProtocolVersionId, H256,
};

use crate::{
    models::{
        parse_protocol_version,
        storage_protocol_version::{protocol_version_from_storage, StorageProtocolVersion},
    },
    Core, CoreDal,
};

#[derive(Debug)]
pub struct ProtocolVersionsDal<'a, 'c> {
    pub storage: &'a mut Connection<'c, Core>,
}

impl ProtocolVersionsDal<'_, '_> {
    pub async fn save_protocol_version(
        &mut self,
        version: ProtocolSemanticVersion,
        timestamp: u64,
        l1_verifier_config: L1VerifierConfig,
        base_system_contracts_hashes: BaseSystemContractsHashes,
        tx_hash: Option<H256>,
    ) -> DalResult<()> {
        let mut db_transaction = self.storage.start_transaction().await?;

        sqlx::query!(
            r#"
            INSERT INTO
                protocol_versions (
                    id,
                    timestamp,
                    bootloader_code_hash,
                    default_account_code_hash,
                    upgrade_tx_hash,
                    created_at
                )
            VALUES
                ($1, $2, $3, $4, $5, NOW())
            ON CONFLICT DO NOTHING
            "#,
            version.minor as i32,
            timestamp as i64,
            base_system_contracts_hashes.bootloader.as_bytes(),
            base_system_contracts_hashes.default_aa.as_bytes(),
            tx_hash.as_ref().map(H256::as_bytes),
        )
        .instrument("save_protocol_version#minor")
        .with_arg("minor", &version.minor)
        .with_arg(
            "base_system_contracts_hashes",
            &base_system_contracts_hashes,
        )
        .with_arg("tx_hash", &tx_hash)
        .execute(&mut db_transaction)
        .await?;

        sqlx::query!(
            r#"
            INSERT INTO
                protocol_patches (
                    minor,
                    patch,
                    recursion_scheduler_level_vk_hash,
                    recursion_node_level_vk_hash,
                    recursion_leaf_level_vk_hash,
                    recursion_circuits_set_vks_hash,
                    created_at
                )
            VALUES
                ($1, $2, $3, $4, $5, $6, NOW())
            ON CONFLICT DO NOTHING
            "#,
            version.minor as i32,
            version.patch.0 as i32,
            l1_verifier_config
                .recursion_scheduler_level_vk_hash
                .as_bytes(),
            l1_verifier_config
                .params
                .recursion_node_level_vk_hash
                .as_bytes(),
            l1_verifier_config
                .params
                .recursion_leaf_level_vk_hash
                .as_bytes(),
            l1_verifier_config
                .params
                .recursion_circuits_set_vks_hash
                .as_bytes(),
        )
        .instrument("save_protocol_version#patch")
        .with_arg("version", &version)
        .execute(&mut db_transaction)
        .await?;

        db_transaction.commit().await?;

        Ok(())
    }

    pub async fn save_protocol_version_with_tx(
        &mut self,
        version: &ProtocolVersion,
    ) -> DalResult<()> {
        let tx_hash = version.tx.as_ref().map(|tx| tx.common_data.hash());
        let mut db_transaction = self.storage.start_transaction().await?;
        if let Some(tx) = &version.tx {
            db_transaction
                .transactions_dal()
                .insert_system_transaction(tx)
                .await?;
        }

        db_transaction
            .protocol_versions_dal()
            .save_protocol_version(
                version.version,
                version.timestamp,
                version.l1_verifier_config,
                version.base_system_contracts_hashes,
                tx_hash,
            )
            .await?;
        db_transaction.commit().await
    }

    async fn save_genesis_upgrade_tx_hash(
        &mut self,
        id: ProtocolVersionId,
        tx_hash: Option<H256>,
    ) -> DalResult<()> {
        sqlx::query!(
            r#"
            UPDATE protocol_versions
            SET
                upgrade_tx_hash = $1
            WHERE
                id = $2
            "#,
            tx_hash.as_ref().map(H256::as_bytes),
            id as i32,
        )
        .instrument("save_genesis_upgrade_tx_hash")
        .with_arg("id", &id)
        .with_arg("tx_hash", &tx_hash)
        .execute(self.storage)
        .await?;
        Ok(())
    }

    /// Attaches a transaction used to set ChainId to the genesis protocol version.
    /// Also inserts that transaction into the database.
    pub async fn save_genesis_upgrade_with_tx(
        &mut self,
        id: ProtocolVersionId,
        tx: &ProtocolUpgradeTx,
    ) -> DalResult<()> {
        let tx_hash = Some(tx.common_data.hash());
        let mut db_transaction = self.storage.start_transaction().await?;
        db_transaction
            .transactions_dal()
            .insert_system_transaction(tx)
            .await?;
        db_transaction
            .protocol_versions_dal()
            .save_genesis_upgrade_tx_hash(id, tx_hash)
            .await?;
        db_transaction.commit().await
    }

    pub async fn protocol_version_id_by_timestamp(
        &mut self,
        current_timestamp: u64,
    ) -> sqlx::Result<ProtocolVersionId> {
        let row = sqlx::query!(
            r#"
            SELECT
                id
            FROM
                protocol_versions
            WHERE
                timestamp <= $1
            ORDER BY
                id DESC
            LIMIT
                1
            "#,
            current_timestamp as i64
        )
        .fetch_one(self.storage.conn())
        .await?;

        ProtocolVersionId::try_from(row.id as u16).map_err(|err| sqlx::Error::Decode(err.into()))
    }

    pub async fn load_base_system_contracts_by_version_id(
        &mut self,
        version_id: u16,
    ) -> anyhow::Result<Option<BaseSystemContracts>> {
        let row = sqlx::query!(
            r#"
            SELECT
                bootloader_code_hash,
                default_account_code_hash
            FROM
                protocol_versions
            WHERE
                id = $1
            "#,
            i32::from(version_id)
        )
        .fetch_optional(self.storage.conn())
        .await
        .context("cannot fetch system contract hashes")?;

        Ok(if let Some(row) = row {
            let contracts = self
                .storage
                .factory_deps_dal()
                .get_base_system_contracts(
                    H256::from_slice(&row.bootloader_code_hash),
                    H256::from_slice(&row.default_account_code_hash),
                )
                .await?;
            Some(contracts)
        } else {
            None
        })
    }

    pub async fn get_protocol_version_with_latest_patch(
        &mut self,
        version_id: ProtocolVersionId,
    ) -> DalResult<Option<ProtocolVersion>> {
        let maybe_row = sqlx::query_as!(
            StorageProtocolVersion,
            r#"
            SELECT
                protocol_versions.id AS "minor!",
                protocol_versions.timestamp,
                protocol_versions.bootloader_code_hash,
                protocol_versions.default_account_code_hash,
                protocol_patches.patch,
                protocol_patches.recursion_scheduler_level_vk_hash,
                protocol_patches.recursion_node_level_vk_hash,
                protocol_patches.recursion_leaf_level_vk_hash,
                protocol_patches.recursion_circuits_set_vks_hash
            FROM
                protocol_versions
                JOIN protocol_patches ON protocol_patches.minor = protocol_versions.id
            WHERE
                id = $1
            ORDER BY
                protocol_patches.patch DESC
            LIMIT
                1
            "#,
            version_id as i32
        )
        .instrument("get_protocol_version_with_latest_patch")
        .with_arg("version_id", &version_id)
        .fetch_optional(self.storage)
        .await?;

        let Some(row) = maybe_row else {
            return Ok(None);
        };
        let tx = self.get_protocol_upgrade_tx(version_id).await?;

        Ok(Some(protocol_version_from_storage(row, tx)))
    }

    pub async fn l1_verifier_config_for_version(
        &mut self,
        version: ProtocolSemanticVersion,
    ) -> Option<L1VerifierConfig> {
        let row = sqlx::query!(
            r#"
            SELECT
                recursion_scheduler_level_vk_hash,
                recursion_node_level_vk_hash,
                recursion_leaf_level_vk_hash,
                recursion_circuits_set_vks_hash
            FROM
                protocol_patches
            WHERE
                minor = $1
                AND patch = $2
            "#,
            version.minor as i32,
            version.patch.0 as i32
        )
        .fetch_optional(self.storage.conn())
        .await
        .unwrap()?;
        Some(L1VerifierConfig {
            params: VerifierParams {
                recursion_node_level_vk_hash: H256::from_slice(&row.recursion_node_level_vk_hash),
                recursion_leaf_level_vk_hash: H256::from_slice(&row.recursion_leaf_level_vk_hash),
                recursion_circuits_set_vks_hash: H256::from_slice(
                    &row.recursion_circuits_set_vks_hash,
                ),
            },
            recursion_scheduler_level_vk_hash: H256::from_slice(
                &row.recursion_scheduler_level_vk_hash,
            ),
        })
    }

    pub async fn get_patch_versions_for_vk(
        &mut self,
        minor_version: ProtocolVersionId,
        recursion_scheduler_level_vk_hash: H256,
    ) -> DalResult<Vec<VersionPatch>> {
        let rows = sqlx::query!(
            r#"
            SELECT
                patch
            FROM
                protocol_patches
            WHERE
                minor = $1
                AND recursion_scheduler_level_vk_hash = $2
            ORDER BY
                patch DESC
            "#,
            minor_version as i32,
            recursion_scheduler_level_vk_hash.as_bytes()
        )
        .instrument("get_patch_versions_for_vk")
        .fetch_all(self.storage)
        .await?;
        Ok(rows
            .into_iter()
            .map(|row| VersionPatch(row.patch as u32))
            .collect())
    }

    /// Returns first patch number for the minor version.
    /// Note, that some patch numbers can be skipped, so the result is not always 0.
    pub async fn first_patch_for_version(
        &mut self,
        version_id: ProtocolVersionId,
    ) -> DalResult<Option<VersionPatch>> {
        let row = sqlx::query!(
            r#"
            SELECT
                patch
            FROM
                protocol_patches
            WHERE
                minor = $1
            ORDER BY
                patch
            LIMIT
                1
            "#,
            version_id as i32,
        )
        .instrument("first_patch_for_version")
        .fetch_optional(self.storage)
        .await?;
        Ok(row.map(|row| VersionPatch(row.patch as u32)))
    }

    pub async fn latest_semantic_version(&mut self) -> DalResult<Option<ProtocolSemanticVersion>> {
        sqlx::query!(
            r#"
            SELECT
                minor,
                patch
            FROM
                protocol_patches
            ORDER BY
                minor DESC,
                patch DESC
            LIMIT
                1
            "#
        )
        .try_map(|row| {
            parse_protocol_version(row.minor).map(|minor| ProtocolSemanticVersion {
                minor,
                patch: (row.patch as u32).into(),
            })
        })
        .instrument("latest_semantic_version")
        .fetch_optional(self.storage)
        .await
    }

    pub async fn last_used_version_id(&mut self) -> Option<ProtocolVersionId> {
        let id = sqlx::query!(
            r#"
            SELECT
                protocol_version
            FROM
                l1_batches
            ORDER BY
                number DESC
            LIMIT
                1
            "#
        )
        .fetch_optional(self.storage.conn())
        .await
        .unwrap()?
        .protocol_version?;

        Some((id as u16).try_into().unwrap())
    }

    pub async fn all_versions(&mut self) -> Vec<ProtocolSemanticVersion> {
        let rows = sqlx::query!(
            r#"
            SELECT
                minor,
                patch
            FROM
                protocol_patches
            "#
        )
        .fetch_all(self.storage.conn())
        .await
        .unwrap();
        rows.into_iter()
            .map(|row| ProtocolSemanticVersion {
                minor: (row.minor as u16).try_into().unwrap(),
                patch: (row.patch as u32).into(),
            })
            .collect()
    }

    pub async fn get_protocol_upgrade_tx(
        &mut self,
        protocol_version_id: ProtocolVersionId,
    ) -> DalResult<Option<ProtocolUpgradeTx>> {
        let instrumentation = Instrumented::new("get_protocol_upgrade_tx")
            .with_arg("protocol_version_id", &protocol_version_id);
        let query = sqlx::query!(
            r#"
            SELECT
                upgrade_tx_hash
            FROM
                protocol_versions
            WHERE
                id = $1
            "#,
            protocol_version_id as i32
        );

        let maybe_row = instrumentation
            .with(query)
            .fetch_optional(self.storage)
            .await?;
        let Some(upgrade_tx_hash) = maybe_row.and_then(|row| row.upgrade_tx_hash) else {
            return Ok(None);
        };
        let upgrade_tx_hash = H256::from_slice(&upgrade_tx_hash);

        let instrumentation = Instrumented::new("get_protocol_upgrade_tx#get_tx")
            .with_arg("protocol_version_id", &protocol_version_id)
            .with_arg("upgrade_tx_hash", &upgrade_tx_hash);
        let tx = self
            .storage
            .transactions_dal()
            .get_tx_by_hash(upgrade_tx_hash)
            .await?
            .ok_or_else(|| {
                instrumentation.arg_error(
                    "upgrade_tx_hash",
                    anyhow::anyhow!("upgrade transaction is not present in storage"),
                )
            })?;
        let tx = tx
            .try_into()
            .map_err(|err| instrumentation.arg_error("tx", anyhow::Error::msg(err)))?;
        Ok(Some(tx))
    }
}