Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add state override for gas estimates #1358

Merged
merged 49 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
cff1757
feat: add state override for gas estimates
aon Mar 5, 2024
9b68b44
Merge branch 'main' into aon-add-override-estimate-gas-tracer
aon Mar 5, 2024
77f8d21
chore: run zk format
aon Mar 5, 2024
e2ad0f4
fix: change state overrides to use storage_view
aon Mar 6, 2024
aa58304
feat: improve `StateOverride` with custom serializer
aon Mar 7, 2024
0327102
fix: remove pub from hashmap
aon Mar 7, 2024
9f9e328
feat: add storage overrides struct
aon Mar 11, 2024
df87370
fix: read value on overrided state
aon Mar 11, 2024
c0b37c4
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 12, 2024
d1bee52
minor changes
Mar 12, 2024
dbab472
Merge branch 'aon-add-override-estimate-gas-tracer' of github.com:mat…
Mar 12, 2024
671689c
create new state_override file and add tests
Mar 13, 2024
0335fb2
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 14, 2024
a640cee
linter and spellcheck
Mar 14, 2024
f6db295
Merge branch 'aon-add-override-estimate-gas-tracer' of github.com:mat…
Mar 14, 2024
1a39ddd
Cargo lock
Mar 14, 2024
2deec8c
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 14, 2024
f62e51e
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 15, 2024
31384e4
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 15, 2024
dbc177e
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Mar 18, 2024
c32cf4f
fix merge conflicts
Jun 6, 2024
5c56d18
zk fmt
Jun 6, 2024
93aa395
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jun 6, 2024
945946f
Revert submodule update to match main
Jun 6, 2024
da57e99
contracts
Jun 6, 2024
fd8af63
fix CI
Jun 10, 2024
f6ee13d
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 10, 2024
7182490
change test function signature
Jun 10, 2024
422e69f
merge with main
Jun 13, 2024
b8b663f
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 17, 2024
4ac87e0
Move StorageOverrides inside StorageView
Jun 19, 2024
f4c0189
Apply earlier the storageOverrides
Jun 19, 2024
f023a17
fix spelling
Jun 19, 2024
8ec5256
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 24, 2024
20932d4
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 27, 2024
4fee27a
storageview implement overrideStorage trait
Jun 28, 2024
299f3f0
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jun 28, 2024
bc4b245
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Deniallugo Jul 1, 2024
9479f03
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 1, 2024
157577b
add logic for stateDiff and State with tests, and added state_overrid…
Jul 1, 2024
9649f59
remove toml
Jul 1, 2024
5cb963e
outdated comment
Jul 2, 2024
241991e
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 2, 2024
a0627cb
add logic for testing stateDiff and State differences and fix nits
Jul 11, 2024
33a83c8
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 11, 2024
cf7b8cb
fix error on merge
Jul 12, 2024
b074154
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jul 16, 2024
3685e54
fix tests
Jul 17, 2024
3d3c469
Merge branch 'main' into aon-add-override-estimate-gas-tracer
Jrigada Jul 22, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/lib/state/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod in_memory;
mod postgres;
mod rocksdb;
mod shadow_storage;
mod storage_overrides;
mod storage_view;
#[cfg(test)]
mod test_utils;
Expand All @@ -32,6 +33,7 @@ pub use self::{
postgres::{PostgresStorage, PostgresStorageCaches},
rocksdb::{RocksbStorageBuilder, RocksdbStorage},
shadow_storage::ShadowStorage,
storage_overrides::StorageOverrides,
storage_view::{StorageView, StorageViewMetrics},
witness::WitnessStorage,
};
Expand Down
145 changes: 145 additions & 0 deletions core/lib/state/src/storage_overrides.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
use std::{cell::RefCell, collections::HashMap, fmt, rc::Rc};

use zksync_types::{
api::{OverrideState, StateOverride},
get_code_key, get_nonce_key,
utils::{decompose_full_nonce, nonces_to_full_nonce, storage_key_for_eth_balance},
AccountTreeId, StorageKey, StorageValue, H256,
};
use zksync_utils::{bytecode::hash_bytecode, h256_to_u256, u256_to_h256};

use crate::{ReadStorage, StorageView, StorageViewMetrics, WriteStorage};

/// A storage view that allows to override some of the storage values.
#[derive(Debug)]
pub struct StorageOverrides<S> {
storage_view: StorageView<S>,
overrided_factory_deps: HashMap<H256, Vec<u8>>,
Jrigada marked this conversation as resolved.
Show resolved Hide resolved
overrided_account_state: HashMap<AccountTreeId, HashMap<H256, H256>>,
}
impl<S: ReadStorage + fmt::Debug> StorageOverrides<S> {
Jrigada marked this conversation as resolved.
Show resolved Hide resolved
/// Applies the state override to the storage.
pub fn apply_state_override(&mut self, state_override: StateOverride) {
for (account, overrides) in state_override.iter() {
if let Some(balance) = overrides.balance {
let balance_key = storage_key_for_eth_balance(&account);
self.set_value(balance_key, u256_to_h256(balance));
}

if let Some(nonce) = overrides.nonce {
let nonce_key = get_nonce_key(&account);

let full_nonce = self.read_value(&nonce_key);
let (_, deployment_nonce) = decompose_full_nonce(h256_to_u256(full_nonce));
let new_full_nonce = nonces_to_full_nonce(nonce, deployment_nonce);

self.set_value(nonce_key, u256_to_h256(new_full_nonce));
}

if let Some(code) = &overrides.code {
let code_key = get_code_key(account);
let code_hash = hash_bytecode(&code.0);

self.set_value(code_key, code_hash);
self.store_factory_dep(code_hash, code.0.clone());
}

match &overrides.state {
Some(OverrideState::State(state)) => {
self.override_account_state(AccountTreeId::new(account.clone()), state.clone());
}
Some(OverrideState::StateDiff(state_diff)) => {
for (key, value) in state_diff.iter() {
self.set_value(
StorageKey::new(AccountTreeId::new(account.clone()), key.clone()),
value.clone(),
);
}
}
None => {}
}
}
}
}

impl<S: ReadStorage + fmt::Debug> StorageOverrides<S> {
Deniallugo marked this conversation as resolved.
Show resolved Hide resolved
/// Creates a new storage view based on the underlying storage.
pub fn new(storage_view: StorageView<S>) -> Self {
Self {
storage_view,
overrided_factory_deps: HashMap::new(),
overrided_account_state: HashMap::new(),
}
}

/// Overrides a factory dep code.
pub fn store_factory_dep(&mut self, hash: H256, code: Vec<u8>) {
self.overrided_factory_deps.insert(hash, code);
}

/// Overrides an account entire state.
pub fn override_account_state(&mut self, account: AccountTreeId, state: HashMap<H256, H256>) {
self.overrided_account_state.insert(account, state);
}

/// Returns the current metrics.
pub fn metrics(&self) -> StorageViewMetrics {
self.storage_view.metrics()
}

/// Make a Rc RefCell ptr to the storage
pub fn to_rc_ptr(self) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(self))
}
}

impl<S: ReadStorage + fmt::Debug> Into<Rc<RefCell<Self>>> for StorageOverrides<S> {
fn into(self) -> Rc<RefCell<Self>> {
self.to_rc_ptr()
}
}

impl<S: ReadStorage + fmt::Debug> ReadStorage for StorageOverrides<S> {
fn read_value(&mut self, key: &StorageKey) -> StorageValue {
// If the account is overrided, return the overrided value if any or zero.
// Otherwise, return the value from the underlying storage.
self.overrided_account_state
.get(key.account())
.and_then(|state| match state.get(key.key()) {
Some(v) => Some(v.clone()),
None => Some(H256::zero()),
})
.unwrap_or_else(|| self.storage_view.read_value(key))
}

/// Only keys contained in the underlying storage will return `false`. If a key was
/// inserted using [`Self::set_value()`], it will still return `true`.
fn is_write_initial(&mut self, key: &StorageKey) -> bool {
self.storage_view.is_write_initial(key)
}

fn load_factory_dep(&mut self, hash: H256) -> Option<Vec<u8>> {
self.overrided_factory_deps
.get(&hash)
.cloned()
.or_else(|| self.storage_view.load_factory_dep(hash))
}

fn get_enumeration_index(&mut self, key: &StorageKey) -> Option<u64> {
self.storage_view.get_enumeration_index(key)
}
}

impl<S: ReadStorage + fmt::Debug> WriteStorage for StorageOverrides<S> {
fn set_value(&mut self, key: StorageKey, value: StorageValue) -> StorageValue {
self.storage_view.set_value(key, value)
Deniallugo marked this conversation as resolved.
Show resolved Hide resolved
}

fn modified_storage_keys(&self) -> &HashMap<StorageKey, StorageValue> {
self.storage_view.modified_storage_keys()
}

fn missed_storage_invocations(&self) -> usize {
self.storage_view.missed_storage_invocations()
}
}
66 changes: 66 additions & 0 deletions core/lib/types/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::{collections::HashMap, ops::Deref};

use chrono::{DateTime, Utc};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use strum::Display;
Expand Down Expand Up @@ -733,3 +735,67 @@ pub struct Proof {
pub address: Address,
pub storage_proof: Vec<StorageProof>,
}

/// Collection of overridden accounts, useful for `eth_estimateGas`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateOverride(HashMap<Address, OverrideAccount>);
Jrigada marked this conversation as resolved.
Show resolved Hide resolved

/// Account override for `eth_estimateGas`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OverrideAccount {
aon marked this conversation as resolved.
Show resolved Hide resolved
pub balance: Option<U256>,
pub nonce: Option<U256>,
pub code: Option<Bytes>,
#[serde(flatten, deserialize_with = "state_deserializer")]
pub state: Option<OverrideState>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OverrideState {
State(HashMap<H256, H256>),
StateDiff(HashMap<H256, H256>),
}

fn state_deserializer<'de, D>(deserializer: D) -> Result<Option<OverrideState>, D::Error>
where
D: Deserializer<'de>,
{
let val = serde_json::Value::deserialize(deserializer)?;
let state: Option<HashMap<H256, H256>> = match val.get("state") {
Some(val) => serde_json::from_value(val.clone()).map_err(serde::de::Error::custom)?,
None => None,
};
let state_diff: Option<HashMap<H256, H256>> = match val.get("stateDiff") {
Some(val) => serde_json::from_value(val.clone()).map_err(serde::de::Error::custom)?,
None => None,
};

match (state, state_diff) {
(Some(state), None) => Ok(Some(OverrideState::State(state))),
(None, Some(state_diff)) => Ok(Some(OverrideState::StateDiff(state_diff))),
(None, None) => Ok(None),
_ => Err(serde::de::Error::custom(
"Both 'state' and 'stateDiff' cannot be set simultaneously",
)),
}
}

impl StateOverride {
pub fn new(state: HashMap<Address, OverrideAccount>) -> Self {
Self(state)
}

pub fn get(&self, address: &Address) -> Option<&OverrideAccount> {
self.0.get(address)
}
}

impl Deref for StateOverride {
type Target = HashMap<Address, OverrideAccount>;

fn deref(&self) -> &Self::Target {
&self.0
}
}
4 changes: 3 additions & 1 deletion core/lib/types/src/transaction_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,9 @@ impl TransactionRequest {
}

// returns packed eth signature if it is present
fn get_packed_signature(&self) -> Result<PackedEthSignature, SerializationTransactionError> {
pub fn get_packed_signature(
&self,
) -> Result<PackedEthSignature, SerializationTransactionError> {
let packed_v = self
.v
.ok_or(SerializationTransactionError::IncompleteSignature)?
Expand Down
9 changes: 7 additions & 2 deletions core/lib/web3_decl/src/namespaces/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use jsonrpsee::{
proc_macros::rpc,
};
use zksync_types::{
api::{BlockId, BlockIdVariant, BlockNumber, Transaction, TransactionVariant},
api::{BlockId, BlockIdVariant, BlockNumber, StateOverride, Transaction, TransactionVariant},
transaction_request::CallRequest,
Address, H256,
};
Expand Down Expand Up @@ -36,7 +36,12 @@ pub trait EthNamespace {
async fn call(&self, req: CallRequest, block: Option<BlockIdVariant>) -> RpcResult<Bytes>;

#[method(name = "estimateGas")]
async fn estimate_gas(&self, req: CallRequest, _block: Option<BlockNumber>) -> RpcResult<U256>;
async fn estimate_gas(
&self,
req: CallRequest,
_block: Option<BlockNumber>,
state_override: Option<StateOverride>,
) -> RpcResult<U256>;

#[method(name = "gasPrice")]
async fn gas_price(&self) -> RpcResult<U256>;
Expand Down
1 change: 1 addition & 0 deletions core/lib/zksync_core/Cargo.toml
Jrigada marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ itertools = "0.10.3"
metrics = "0.21"
ctrlc = { version = "3.1", features = ["termination"] }
rand = "0.8"
rlp = "0.5"

tokio = { version = "1", features = ["time"] }
futures = { version = "0.3", features = ["compat"] }
Expand Down
36 changes: 27 additions & 9 deletions core/lib/zksync_core/src/api_server/execution_sandbox/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
//!
//! This module is intended to be blocking.

use std::time::{Duration, Instant};
use std::{
cell::RefCell,
rc::Rc,
time::{Duration, Instant},
};

use anyhow::Context as _;
use multivm::{
Expand All @@ -17,13 +21,15 @@ use multivm::{
};
use tokio::runtime::Handle;
use zksync_dal::{ConnectionPool, StorageProcessor};
use zksync_state::{PostgresStorage, ReadStorage, StoragePtr, StorageView, WriteStorage};
use zksync_state::{
PostgresStorage, ReadStorage, StorageOverrides, StoragePtr, StorageView, WriteStorage,
};
use zksync_system_constants::{
SYSTEM_CONTEXT_ADDRESS, SYSTEM_CONTEXT_CURRENT_L2_BLOCK_INFO_POSITION,
SYSTEM_CONTEXT_CURRENT_TX_ROLLING_HASH_POSITION, ZKPORTER_IS_AVAILABLE,
};
use zksync_types::{
api,
api::{self, StateOverride},
block::{pack_block_info, unpack_block_info, MiniblockHasher},
fee_model::BatchFeeInput,
get_nonce_key,
Expand All @@ -38,7 +44,7 @@ use super::{
BlockArgs, TxExecutionArgs, TxSharedArgs, VmPermit,
};

type BoxedVm<'a> = Box<VmInstance<StorageView<PostgresStorage<'a>>, HistoryDisabled>>;
type BoxedVm<'a> = Box<VmInstance<StorageOverrides<PostgresStorage<'a>>, HistoryDisabled>>;

#[derive(Debug)]
struct Sandbox<'a> {
Expand Down Expand Up @@ -259,7 +265,10 @@ impl<'a> Sandbox<'a> {
mut self,
tx: &Transaction,
adjust_pubdata_price: bool,
) -> (BoxedVm<'a>, StoragePtr<StorageView<PostgresStorage<'a>>>) {
) -> (
BoxedVm<'a>,
StoragePtr<StorageOverrides<PostgresStorage<'a>>>,
) {
self.setup_storage_view(tx);
let protocol_version = self.system_env.version;
if adjust_pubdata_price {
Expand All @@ -271,14 +280,15 @@ impl<'a> Sandbox<'a> {
);
};

let storage_view = self.storage_view.to_rc_ptr();
let storage_overrides: Rc<RefCell<StorageOverrides<PostgresStorage<'_>>>> =
StorageOverrides::new(self.storage_view).into();
let vm = Box::new(VmInstance::new_with_specific_version(
self.l1_batch_env,
self.system_env,
storage_view.clone(),
storage_overrides.clone(),
protocol_version.into_api_vm_version(),
));
(vm, storage_view)
(vm, storage_overrides)
}
}

Expand All @@ -294,8 +304,9 @@ pub(super) fn apply_vm_in_sandbox<T>(
connection_pool: &ConnectionPool,
tx: Transaction,
block_args: BlockArgs,
state_override: Option<StateOverride>,
apply: impl FnOnce(
&mut VmInstance<StorageView<PostgresStorage<'_>>, HistoryDisabled>,
&mut VmInstance<StorageOverrides<PostgresStorage<'_>>, HistoryDisabled>,
Transaction,
) -> T,
) -> anyhow::Result<T> {
Expand Down Expand Up @@ -328,6 +339,13 @@ pub(super) fn apply_vm_in_sandbox<T>(
tx.initiator_account(),
tx.nonce().unwrap_or(Nonce(0))
);

// Apply state override
if let Some(state_override) = state_override {
let mut storage_override = storage_view.as_ref().borrow_mut();
storage_override.apply_state_override(state_override);
}

let execution_latency = SANDBOX_METRICS.sandbox[&SandboxStage::Execution].start();
let result = apply(&mut vm, tx);
let vm_execution_took = execution_latency.observe();
Expand Down
Loading
Loading