Skip to content

Commit

Permalink
use Box instead of Arc<Mutex<T>>
Browse files Browse the repository at this point in the history
  • Loading branch information
nbaztec committed Dec 17, 2024
1 parent 53d5d9a commit 1876c01
Show file tree
Hide file tree
Showing 29 changed files with 253 additions and 356 deletions.
9 changes: 4 additions & 5 deletions crates/cheatcodes/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use foundry_evm_core::opts::EvmOpts;
use semver::Version;
use std::{
path::{Path, PathBuf},
sync::{Arc, Mutex},
time::Duration,
};

Expand Down Expand Up @@ -58,7 +57,7 @@ pub struct CheatsConfig {
/// Version of the script/test contract which is currently running.
pub running_version: Option<Version>,
/// The behavior strategy.
pub strategy: Arc<Mutex<dyn CheatcodeInspectorStrategyExt>>,
pub strategy: Box<dyn CheatcodeInspectorStrategyExt>,
/// Whether to enable legacy (non-reverting) assertions.
pub assertions_revert: bool,
/// Optional seed for the RNG algorithm.
Expand All @@ -74,7 +73,7 @@ impl CheatsConfig {
available_artifacts: Option<ContractsByArtifact>,
running_contract: Option<String>,
running_version: Option<Version>,
strategy: Arc<Mutex<dyn CheatcodeInspectorStrategyExt>>,
strategy: Box<dyn CheatcodeInspectorStrategyExt>,
) -> Self {
let mut allowed_paths = vec![config.root.0.clone()];
allowed_paths.extend(config.libs.clone());
Expand Down Expand Up @@ -235,7 +234,7 @@ impl Default for CheatsConfig {
available_artifacts: Default::default(),
running_contract: Default::default(),
running_version: Default::default(),
strategy: Arc::new(Mutex::new(EvmCheatcodeInspectorStrategy::default())),
strategy: Box::new(EvmCheatcodeInspectorStrategy::default()),
assertions_revert: true,
seed: None,
}
Expand All @@ -254,7 +253,7 @@ mod tests {
None,
None,
None,
Arc::new(Mutex::new(EvmCheatcodeInspectorStrategy::default())),
Box::new(EvmCheatcodeInspectorStrategy::default()),
)
}

Expand Down
34 changes: 10 additions & 24 deletions crates/cheatcodes/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ impl Cheatcode for getNonce_0Call {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { account } = self;

let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_get_nonce(ccx, *account)
ccx.with_strategy(|strategy, ccx| strategy.cheatcode_get_nonce(ccx, *account))
}
}

Expand Down Expand Up @@ -352,9 +350,7 @@ impl Cheatcode for getBlobhashesCall {
impl Cheatcode for rollCall {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { newHeight } = self;
let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_roll(ccx, *newHeight)
ccx.with_strategy(|strategy, ccx| strategy.cheatcode_roll(ccx, *newHeight))
}
}

Expand All @@ -376,9 +372,7 @@ impl Cheatcode for txGasPriceCall {
impl Cheatcode for warpCall {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { newTimestamp } = self;
let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_warp(ccx, *newTimestamp)
ccx.with_strategy(|strategy, ccx| strategy.cheatcode_warp(ccx, *newTimestamp))
}
}

Expand Down Expand Up @@ -413,48 +407,40 @@ impl Cheatcode for dealCall {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { account: address, newBalance: new_balance } = *self;

let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_deal(ccx, address, new_balance)
ccx.with_strategy(|strategy, ccx| strategy.cheatcode_deal(ccx, address, new_balance))
}
}

impl Cheatcode for etchCall {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { target, newRuntimeBytecode } = self;

let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_etch(ccx, *target, newRuntimeBytecode)
ccx.with_strategy(|strategy, ccx| strategy.cheatcode_etch(ccx, *target, newRuntimeBytecode))
}
}

impl Cheatcode for resetNonceCall {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { account } = self;
let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_reset_nonce(ccx, *account)
ccx.with_strategy(|strategy, ccx| strategy.cheatcode_reset_nonce(ccx, *account))
}
}

impl Cheatcode for setNonceCall {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { account, newNonce } = *self;

let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_set_nonce(ccx, account, newNonce)
ccx.with_strategy(|strategy, ccx| strategy.cheatcode_set_nonce(ccx, account, newNonce))
}
}

impl Cheatcode for setNonceUnsafeCall {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { account, newNonce } = *self;

let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_set_nonce_unsafe(ccx, account, newNonce)
ccx.with_strategy(|strategy, ccx| {
strategy.cheatcode_set_nonce_unsafe(ccx, account, newNonce)
})
}
}

Expand Down
12 changes: 2 additions & 10 deletions crates/cheatcodes/src/evm/fork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,7 @@ impl Cheatcode for selectForkCall {
persist_caller(ccx);
check_broadcast(ccx.state)?;

ccx.state
.strategy
.lock()
.expect("failed acquiring strategy")
.zksync_select_fork_vm(ccx.ecx, *forkId);
ccx.with_strategy(|strategy, ccx| strategy.zksync_select_fork_vm(ccx.ecx, *forkId));
ccx.ecx.db.select_fork(*forkId, &mut ccx.ecx.env, &mut ccx.ecx.journaled_state)?;

Ok(Default::default())
Expand Down Expand Up @@ -285,11 +281,7 @@ fn create_select_fork(ccx: &mut CheatsCtxt, url_or_alias: &str, block: Option<u6

let fork = create_fork_request(ccx, url_or_alias, block)?;
let id = ccx.ecx.db.create_fork(fork)?;
ccx.state
.strategy
.lock()
.expect("failed acquiring strategy")
.zksync_select_fork_vm(ccx.ecx, id);
ccx.with_strategy(|strategy, ccx| strategy.zksync_select_fork_vm(ccx.ecx, id));
ccx.ecx.db.select_fork(id, &mut ccx.ecx.env, &mut ccx.ecx.journaled_state)?;
Ok(id.abi_encode())
}
Expand Down
12 changes: 6 additions & 6 deletions crates/cheatcodes/src/evm/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ impl Cheatcode for clearMockedCallsCall {
impl Cheatcode for mockCall_0Call {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { callee, data, returnData } = self;
let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_mock_call(ccx, *callee, data, returnData)
ccx.with_strategy(|strategy, ccx| {
strategy.cheatcode_mock_call(ccx, *callee, data, returnData)
})
}
}

Expand Down Expand Up @@ -85,9 +85,9 @@ impl Cheatcode for mockCalls_1Call {
impl Cheatcode for mockCallRevert_0Call {
fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
let Self { callee, data, revertData } = self;
let strategy = ccx.state.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
guard.cheatcode_mock_call_revert(ccx, *callee, data, revertData)
ccx.with_strategy(|strategy, ccx| {
strategy.cheatcode_mock_call_revert(ccx, *callee, data, revertData)
})
}
}

Expand Down
4 changes: 1 addition & 3 deletions crates/cheatcodes/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,7 @@ impl Cheatcode for getArtifactPathByDeployedCodeCall {
impl Cheatcode for getCodeCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self { artifactPath: path } = self;
let strategy = state.strategy.clone();
let guard = strategy.lock().expect("failed acquiring strategy");
guard.get_artifact_code(state, path, false)
state.with_strategy(|strategy, state| strategy.get_artifact_code(state, path, false))
}
}

Expand Down
65 changes: 35 additions & 30 deletions crates/cheatcodes/src/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,15 @@ use std::{
io::BufReader,
ops::Range,
path::PathBuf,
sync::{Arc, Mutex},
sync::Arc,
};

mod utils;
pub use utils::CommonCreateInput;

pub type Ecx<'a, 'b, 'c> = &'a mut EvmContext<&'b mut (dyn DatabaseExt + 'c)>;
pub type InnerEcx<'a, 'b, 'c> = &'a mut InnerEvmContext<&'b mut (dyn DatabaseExt + 'c)>;
pub type Strategy<'a> = &'a mut dyn CheatcodeInspectorStrategyExt;

/// Helper trait for obtaining complete [revm::Inspector] instance from mutable reference to
/// [Cheatcodes].
Expand Down Expand Up @@ -527,7 +528,7 @@ pub struct Cheatcodes {
pub wallets: Option<Wallets>,

/// The behavior strategy.
pub strategy: Arc<Mutex<dyn CheatcodeInspectorStrategyExt>>,
pub strategy: Option<Box<dyn CheatcodeInspectorStrategyExt>>,
}

impl Clone for Cheatcodes {
Expand Down Expand Up @@ -567,7 +568,7 @@ impl Clone for Cheatcodes {
arbitrary_storage: self.arbitrary_storage.clone(),
deprecated: self.deprecated.clone(),
wallets: self.wallets.clone(),
strategy: self.strategy.lock().expect("failed acquiring strategy").new_cloned_ext(),
strategy: self.strategy.as_ref().map(|s| s.new_cloned_ext()),
}
}
}
Expand All @@ -587,7 +588,7 @@ impl Cheatcodes {
Self {
fs_commit: true,
labels: config.labels.clone(),
strategy: config.strategy.clone(),
strategy: Some(config.strategy.clone()),
config,
block: Default::default(),
active_delegation: Default::default(),
Expand Down Expand Up @@ -762,16 +763,13 @@ impl Cheatcodes {
if ecx_inner.journaled_state.depth() == broadcast.depth {
input.set_caller(broadcast.new_origin);

self.strategy
.lock()
.expect("failed acquiring strategy")
.record_broadcastable_create_transactions(
self.config.clone(),
&input,
ecx_inner,
broadcast,
&mut self.broadcastable_transactions,
);
self.strategy.as_mut().unwrap().record_broadcastable_create_transactions(
self.config.clone(),
&input,
ecx_inner,
broadcast,
&mut self.broadcastable_transactions,
);

input.log_debug(self, &input.scheme().unwrap_or(CreateScheme::Create));
}
Expand Down Expand Up @@ -803,9 +801,9 @@ impl Cheatcodes {
}]);
}

let strategy = self.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
if let Some(result) = guard.zksync_try_create(self, ecx, &input, executor) {
if let Some(result) = self.with_strategy(|strategy, cheatcodes| {
strategy.zksync_try_create(cheatcodes, ecx, &input, executor)
}) {
return Some(result);
}

Expand Down Expand Up @@ -920,7 +918,7 @@ where {
}

self.strategy
.lock()
.as_mut()
.expect("failed acquiring strategy")
.zksync_record_create_address(&outcome);

Expand Down Expand Up @@ -966,7 +964,7 @@ where {
let nonce = prev.saturating_sub(1);
account.info.nonce = nonce;
self.strategy
.lock()
.as_mut()
.expect("failed acquiring strategy")
.zksync_sync_nonce(sender, nonce, ecx);

Expand Down Expand Up @@ -1003,7 +1001,7 @@ where {
}

self.strategy
.lock()
.as_mut()
.expect("failed acquiring strategy")
.zksync_set_deployer_call_input(call);

Expand Down Expand Up @@ -1140,7 +1138,7 @@ where {
}

self.strategy
.lock()
.as_mut()
.expect("failed acquiring strategy")
.record_broadcastable_call_transactions(
self.config.clone(),
Expand Down Expand Up @@ -1222,9 +1220,9 @@ where {
}]);
}

let strategy = self.strategy.clone();
let mut guard = strategy.lock().expect("failed acquiring strategy");
if let Some(result) = guard.zksync_try_call(self, ecx, call, executor) {
if let Some(result) = self.with_strategy(|strategy, cheatcodes| {
strategy.zksync_try_call(cheatcodes, ecx, call, executor)
}) {
return Some(result);
}

Expand Down Expand Up @@ -1266,6 +1264,17 @@ where {
None => false,
}
}

pub fn with_strategy<F, R>(&mut self, mut f: F) -> R
where
F: FnMut(Strategy, &mut Self) -> R,
{
let mut strategy = self.strategy.take();
let result = f(strategy.as_mut().expect("failed acquiring strategy").as_mut(), self);
self.strategy = strategy;

result
}
}

impl Inspector<&mut dyn DatabaseExt> for Cheatcodes {
Expand All @@ -1286,7 +1295,7 @@ impl Inspector<&mut dyn DatabaseExt> for Cheatcodes {
}

self.strategy
.lock()
.as_mut()
.expect("failed acquiring strategy")
.post_initialize_interp(interpreter, ecx);
}
Expand Down Expand Up @@ -1333,11 +1342,7 @@ impl Inspector<&mut dyn DatabaseExt> for Cheatcodes {

#[inline]
fn step_end(&mut self, interpreter: &mut Interpreter, ecx: Ecx) {
if self
.strategy
.try_lock()
.expect("failed acquiring strategy")
.pre_step_end(interpreter, ecx)
if self.strategy.as_mut().expect("failed acquiring strategy").pre_step_end(interpreter, ecx)
{
return;
}
Expand Down
12 changes: 12 additions & 0 deletions crates/cheatcodes/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ extern crate tracing;

use alloy_primitives::Address;
use foundry_evm_core::backend::DatabaseExt;
use inspector::Strategy;
use revm::{ContextPrecompiles, InnerEvmContext};
use spec::Status;

Expand Down Expand Up @@ -174,4 +175,15 @@ impl CheatsCtxt<'_, '_, '_, '_> {
pub(crate) fn is_precompile(&self, address: &Address) -> bool {
self.precompiles.contains(address)
}

pub(crate) fn with_strategy<F, R>(&mut self, mut f: F) -> R
where
F: FnMut(Strategy, &mut Self) -> R,
{
let mut strategy = self.state.strategy.take();
let result = f(strategy.as_mut().expect("failed acquiring strategy").as_mut(), self);
self.state.strategy = strategy;

result
}
}
Loading

0 comments on commit 1876c01

Please sign in to comment.