Skip to main content

zksync_vm2/
lib.rs

1//! # High-Performance ZKsync Era VM
2//!
3//! This crate provides high-performance [`VirtualMachine`] for ZKsync Era.
4
5use std::hash::{DefaultHasher, Hash, Hasher};
6
7use primitive_types::{H160, U256};
8pub use zksync_vm2_interface as interface;
9use zksync_vm2_interface::Tracer;
10
11// Re-export missing modules if single instruction testing is enabled
12#[cfg(feature = "single_instruction_test")]
13pub(crate) use self::single_instruction_test::{heap, program, stack};
14pub use self::{
15    decommit::DecommitOpcodeOutcome,
16    fat_pointer::FatPointer,
17    instruction::{ExecutionEnd, Instruction},
18    mode_requirements::ModeRequirements,
19    predication::Predicate,
20    program::Program,
21    vm::{Settings, VirtualMachine},
22    world_diff::{Snapshot, StorageChange, StorageWriteEntry, WorldDiff},
23};
24use crate::precompiles::{LegacyPrecompiles, Precompiles};
25
26pub mod addressing_modes;
27#[cfg(not(feature = "single_instruction_test"))]
28mod bitset;
29mod callframe;
30mod decode;
31mod decommit;
32mod fat_pointer;
33#[cfg(not(feature = "single_instruction_test"))]
34mod heap;
35mod instruction;
36mod instruction_handlers;
37mod mode_requirements;
38mod page_ids;
39pub mod precompiles;
40mod predication;
41#[cfg(not(feature = "single_instruction_test"))]
42mod program;
43mod rollback;
44#[cfg(feature = "single_instruction_test")]
45pub mod single_instruction_test;
46#[cfg(not(feature = "single_instruction_test"))]
47mod stack;
48mod state;
49pub mod testonly;
50#[cfg(all(test, not(feature = "single_instruction_test")))]
51mod tests;
52mod tracing;
53mod vm;
54mod world_diff;
55
56/// Storage slot information returned from [`StorageInterface::read_storage()`].
57#[derive(Debug, Clone, Copy)]
58pub struct StorageSlot {
59    /// Value of the storage slot.
60    pub value: U256,
61    /// Whether a write to the slot would be considered an initial write. This influences refunds.
62    pub is_write_initial: bool,
63}
64
65impl StorageSlot {
66    /// Represents an empty storage slot.
67    pub const EMPTY: Self = Self {
68        value: U256([0; 4]),
69        is_write_initial: true,
70    };
71}
72
73/// VM storage access operations.
74pub trait StorageInterface {
75    /// Reads the specified slot from the storage.
76    ///
77    /// There is no write counterpart; [`WorldDiff::get_storage_changes()`] gives a list of all storage changes.
78    fn read_storage(&mut self, contract: H160, key: U256) -> StorageSlot;
79
80    /// Same as [`Self::read_storage()`], but doesn't request the initialness flag for the read slot.
81    ///
82    /// The default implementation uses `read_storage()`.
83    fn read_storage_value(&mut self, contract: H160, key: U256) -> U256 {
84        self.read_storage(contract, key).value
85    }
86
87    /// Computes the cost of writing a storage slot.
88    fn cost_of_writing_storage(&mut self, initial_slot: StorageSlot, new_value: U256) -> u32;
89
90    /// Returns if the storage slot is free both in terms of gas and pubdata.
91    fn is_free_storage_slot(&self, contract: &H160, key: &U256) -> bool;
92}
93
94/// Encapsulates VM interaction with the external world. This includes VM storage and decomitting (loading) bytecodes
95/// for execution.
96pub trait World<T: Tracer>: StorageInterface + Sized {
97    /// Loads a bytecode with the specified hash.
98    ///
99    /// This method will be called *every* time a contract is called. Caching and decoding is
100    /// the world implementor's job.
101    fn decommit(&mut self, hash: U256) -> Program<T, Self>;
102
103    /// Loads bytecode bytes for the `decommit` opcode.
104    fn decommit_code(&mut self, hash: U256) -> Vec<u8>;
105
106    /// Returns precompiles to be used.
107    fn precompiles(&self) -> &impl Precompiles {
108        &LegacyPrecompiles
109    }
110}
111
112/// Deterministic (across program runs and machines) hash that can be used for `Debug` implementations
113/// to concisely represent large amounts of data.
114#[cfg_attr(feature = "single_instruction_test", allow(dead_code))] // Currently used entirely in types overridden by `single_instruction_test` feature
115pub(crate) fn hash_for_debugging(value: &impl Hash) -> u64 {
116    let mut hasher = DefaultHasher::new();
117    value.hash(&mut hasher);
118    hasher.finish()
119}