1use super::Result;
2use crate::Vm::Rpc;
3use alloy_primitives::{U256, map::AddressHashMap};
4use foundry_common::{ContractsByArtifact, fs::normalize_path};
5use foundry_compilers::{ArtifactId, ProjectPathsConfig, utils::canonicalize};
6use foundry_config::{
7 Config, FsPermissions, ResolvedRpcEndpoint, ResolvedRpcEndpoints, RpcEndpoint, RpcEndpointUrl,
8 cache::StorageCachingConfig, fs_permissions::FsAccessKind,
9};
10use foundry_evm_core::opts::EvmOpts;
11use foundry_evm_traces::identifier::ExternalIdentifierConfig;
12use itertools::Itertools;
13use std::{
14 path::{Path, PathBuf},
15 time::Duration,
16};
17
18#[derive(Clone, Debug)]
22pub struct CheatsConfig {
23 pub ffi: bool,
25 pub blocked_cheatcodes: Vec<[u8; 4]>,
27 pub always_use_create_2_factory: bool,
29 pub batch_rewrite_creates: bool,
31 pub prompt_timeout: Duration,
33 pub rpc_storage_caching: StorageCachingConfig,
35 pub no_storage_caching: bool,
37 pub rpc_endpoints: ResolvedRpcEndpoints,
39 pub paths: ProjectPathsConfig,
41 pub bind_json_path: PathBuf,
43 pub fs_permissions: FsPermissions,
45 pub root: PathBuf,
47 pub broadcast: PathBuf,
49 pub isolate: bool,
51 pub evm_opts: EvmOpts,
53 pub labels: AddressHashMap<String>,
55 pub available_artifacts: Option<ContractsByArtifact>,
59 pub artifact_lookup: Option<ContractsByArtifact>,
62 pub decode_external_storage: bool,
65 pub external_sources: ExternalIdentifierConfig,
68 pub running_artifact: Option<ArtifactId>,
70 pub assertions_revert: bool,
72 pub seed: Option<U256>,
74 pub internal_expect_revert: bool,
76}
77
78impl CheatsConfig {
79 pub fn new(
81 config: &Config,
82 evm_opts: EvmOpts,
83 available_artifacts: Option<ContractsByArtifact>,
84 running_artifact: Option<ArtifactId>,
85 batch_rewrite_creates: bool,
86 ) -> Self {
87 let rpc_endpoints = config.rpc_endpoints.clone().resolved();
88 trace!(?rpc_endpoints, "using resolved rpc endpoints");
89
90 let artifact_lookup = available_artifacts.clone();
91 let available_artifacts =
93 if config.unchecked_cheatcode_artifacts { None } else { available_artifacts };
94 let mut labels = config.labels.clone();
95 labels.extend(config.tracing.labels.clone());
96
97 Self {
98 ffi: evm_opts.ffi,
99 blocked_cheatcodes: Vec::new(),
100 always_use_create_2_factory: evm_opts.always_use_create_2_factory,
101 batch_rewrite_creates,
102 prompt_timeout: Duration::from_secs(config.prompt_timeout),
103 rpc_storage_caching: config.rpc_storage_caching.clone(),
104 no_storage_caching: config.no_storage_caching,
105 rpc_endpoints,
106 paths: config.project_paths(),
107 bind_json_path: config.bind_json.out.clone(),
108 fs_permissions: config.fs_permissions.clone().joined(config.root.as_ref()),
109 root: config.root.clone(),
110 broadcast: config.root.clone().join(&config.broadcast),
111 isolate: config.isolate,
112 evm_opts,
113 labels,
114 available_artifacts,
115 artifact_lookup,
116 decode_external_storage: config.decode_external_storage,
117 external_sources: ExternalIdentifierConfig::new(config),
118 running_artifact,
119 assertions_revert: config.assertions_revert,
120 seed: config.fuzz.seed,
121 internal_expect_revert: config.allow_internal_expect_revert,
122 }
123 }
124
125 pub fn clone_with(&self, config: &Config, evm_opts: EvmOpts) -> Self {
127 let mut cloned = Self::new(
128 config,
129 evm_opts,
130 self.artifact_lookup.clone().or_else(|| self.available_artifacts.clone()),
131 self.running_artifact.clone(),
132 self.batch_rewrite_creates,
133 );
134 cloned.blocked_cheatcodes.clone_from(&self.blocked_cheatcodes);
135 cloned
136 }
137
138 pub fn normalized_path(&self, path: impl AsRef<Path>) -> PathBuf {
142 let path = self.root.join(path);
143 canonicalize(&path).unwrap_or_else(|_| canonicalize_existing_ancestor(&path))
144 }
145
146 pub fn is_path_allowed(&self, path: impl AsRef<Path>, kind: FsAccessKind) -> bool {
153 self.is_normalized_path_allowed(&self.normalized_path(path), kind)
154 }
155
156 fn is_normalized_path_allowed(&self, path: &Path, kind: FsAccessKind) -> bool {
157 self.fs_permissions.is_path_allowed(path, kind)
158 }
159
160 pub fn ensure_path_allowed(
164 &self,
165 path: impl AsRef<Path>,
166 kind: FsAccessKind,
167 ) -> Result<PathBuf> {
168 let path = path.as_ref();
169 let normalized = self.normalized_path(path);
170 ensure!(
171 self.is_normalized_path_allowed(&normalized, kind),
172 "the path {} is not allowed to be accessed for {kind} operations",
173 normalized.strip_prefix(&self.root).unwrap_or(path).display()
174 );
175 Ok(normalized)
176 }
177
178 pub fn is_foundry_toml(&self, path: impl AsRef<Path>) -> bool {
182 let foundry_toml = self.root.join(Config::FILE_NAME);
187 Path::new(&foundry_toml.to_string_lossy().to_lowercase())
188 .starts_with(Path::new(&path.as_ref().to_string_lossy().to_lowercase()))
189 }
190
191 pub fn ensure_not_foundry_toml(&self, path: impl AsRef<Path>) -> Result<()> {
194 ensure!(!self.is_foundry_toml(path), "access to `foundry.toml` is not allowed");
195 Ok(())
196 }
197
198 pub fn rpc_endpoint(&self, url_or_alias: &str) -> Result<ResolvedRpcEndpoint> {
215 if self.evm_opts.no_network {
217 return Err(fmt_err!("network access is disabled"));
218 }
219 if let Some(endpoint) = self.rpc_endpoints.get(url_or_alias) {
220 Ok(endpoint.clone().try_resolve())
221 } else if let Ok(endpoint) = self
222 .rpc_endpoints
223 .values()
224 .map(|endpoint| endpoint.clone().try_resolve())
225 .filter(|endpoint| endpoint.endpoint.as_ref().is_ok_and(|url| url == url_or_alias))
226 .all_equal_value()
227 {
228 Ok(endpoint)
232 } else if let Some(builtin_url) = foundry_config::builtin_rpc_url(url_or_alias) {
233 let url = RpcEndpointUrl::Url(builtin_url.to_string());
234 Ok(RpcEndpoint::new(url).resolve())
235 } else {
236 if url_or_alias.starts_with("http") ||
238 url_or_alias.starts_with("ws") ||
239 Path::new(url_or_alias).exists()
241 {
242 let url = RpcEndpointUrl::Env(url_or_alias.to_string());
243 Ok(RpcEndpoint::new(url).resolve())
244 } else {
245 Err(fmt_err!("invalid rpc url: {url_or_alias}"))
246 }
247 }
248 }
249 pub fn rpc_urls(&self) -> Result<Vec<Rpc>> {
251 let mut urls = Vec::with_capacity(self.rpc_endpoints.len());
252 for alias in self.rpc_endpoints.keys() {
253 let url = self.rpc_endpoint(alias)?.url()?;
254 urls.push(Rpc { key: alias.clone(), url });
255 }
256 Ok(urls)
257 }
258}
259
260impl Default for CheatsConfig {
261 fn default() -> Self {
262 Self {
263 ffi: false,
264 blocked_cheatcodes: Vec::new(),
265 always_use_create_2_factory: false,
266 batch_rewrite_creates: false,
267 prompt_timeout: Duration::from_secs(120),
268 rpc_storage_caching: Default::default(),
269 no_storage_caching: false,
270 rpc_endpoints: Default::default(),
271 paths: ProjectPathsConfig::builder().build_with_root("./"),
272 fs_permissions: Default::default(),
273 root: Default::default(),
274 bind_json_path: PathBuf::default().join("utils").join("jsonBindings.sol"),
275 broadcast: Default::default(),
276 isolate: Config::default().isolate,
277 evm_opts: Default::default(),
278 labels: Default::default(),
279 available_artifacts: Default::default(),
280 artifact_lookup: Default::default(),
281 decode_external_storage: false,
282 external_sources: Default::default(),
283 running_artifact: Default::default(),
284 assertions_revert: true,
285 seed: None,
286 internal_expect_revert: false,
287 }
288 }
289}
290
291fn canonicalize_existing_ancestor(path: &Path) -> PathBuf {
292 let normalized = normalize_path(path);
293 let mut missing = Vec::new();
294 let mut ancestor = normalized.as_path();
295 while !ancestor.exists() {
296 let Some(name) = ancestor.file_name() else { return normalized };
297 missing.push(name.to_owned());
298 let Some(parent) = ancestor.parent() else { return normalized };
299 ancestor = parent;
300 }
301
302 let mut path = canonicalize(ancestor).unwrap_or_else(|_| ancestor.to_path_buf());
303 for component in missing.iter().rev() {
304 path.push(component);
305 }
306 path
307}
308
309#[cfg(test)]
310mod tests {
311
312 use super::*;
313 use alloy_primitives::Address;
314 use foundry_config::{RpcEndpoints, fs_permissions::PathPermission};
315 use tempfile::TempDir;
316
317 fn config(root: &Path, fs_permissions: FsPermissions) -> CheatsConfig {
318 CheatsConfig::new(
319 &Config { root: root.into(), fs_permissions, ..Default::default() },
320 Default::default(),
321 None,
322 None,
323 false,
324 )
325 }
326
327 #[test]
328 fn test_allowed_paths() {
329 let temp = TempDir::new().unwrap();
330 let root = temp.path().join("my/project/root");
331 std::fs::create_dir_all(&root).unwrap();
332 let config = config(&root, FsPermissions::new(vec![PathPermission::read_write("./")]));
333
334 assert!(config.ensure_path_allowed("./t.txt", FsAccessKind::Read).is_ok());
335 assert!(config.ensure_path_allowed("./t.txt", FsAccessKind::Write).is_ok());
336 assert!(config.ensure_path_allowed("../root/t.txt", FsAccessKind::Read).is_ok());
337 assert!(config.ensure_path_allowed("../root/t.txt", FsAccessKind::Write).is_ok());
338 assert!(config.ensure_path_allowed("../../root/t.txt", FsAccessKind::Read).is_err());
339 assert!(config.ensure_path_allowed("../../root/t.txt", FsAccessKind::Write).is_err());
340 }
341
342 #[test]
343 fn test_batch_rewrite_creates_flag_plumbing() {
344 assert!(!CheatsConfig::default().batch_rewrite_creates);
345
346 let on = CheatsConfig::new(&Config::default(), Default::default(), None, None, true);
347 assert!(on.batch_rewrite_creates);
348
349 let cloned = on.clone_with(&Config::default(), Default::default());
350 assert!(cloned.batch_rewrite_creates);
351 }
352
353 #[test]
354 fn unchecked_artifacts_retain_lookup_without_validation() {
355 let config = Config { unchecked_cheatcode_artifacts: true, ..Default::default() };
356 let cheats = CheatsConfig::new(
357 &config,
358 Default::default(),
359 Some(ContractsByArtifact::default()),
360 None,
361 false,
362 );
363
364 assert!(cheats.available_artifacts.is_none());
365 assert!(cheats.artifact_lookup.is_some());
366
367 let cloned = cheats.clone_with(&config, Default::default());
368 assert!(cloned.available_artifacts.is_none());
369 assert!(cloned.artifact_lookup.is_some());
370 }
371
372 #[test]
373 fn clone_with_preserves_available_artifacts_without_lookup() {
374 let cheats = CheatsConfig {
375 available_artifacts: Some(ContractsByArtifact::default()),
376 ..Default::default()
377 };
378
379 let cloned = cheats.clone_with(&Config::default(), Default::default());
380 assert!(cloned.available_artifacts.is_some());
381 assert!(cloned.artifact_lookup.is_some());
382 }
383
384 #[test]
385 fn tracing_labels_override_legacy_labels() {
386 let address = Address::with_last_byte(1);
387 let mut config = Config::default();
388 config.labels.insert(address, "legacy".to_string());
389 config.tracing.labels.insert(address, "canonical".to_string());
390
391 let config = CheatsConfig::new(&config, Default::default(), None, None, false);
392
393 assert_eq!(config.labels.get(&address).map(String::as_str), Some("canonical"));
394 }
395
396 #[test]
397 fn test_is_foundry_toml() {
398 let root = Path::new("/my/project/root/");
399 let config = config(root, FsPermissions::new(vec![PathPermission::read_write("./")]));
400
401 let f = root.join("foundry.toml");
402 assert!(config.is_foundry_toml(f));
403
404 let f = root.join("Foundry.toml");
405 assert!(config.is_foundry_toml(f));
406
407 let f = root.join("lib/other/foundry.toml");
408 assert!(!config.is_foundry_toml(f));
409 }
410
411 #[test]
412 fn test_rpc_endpoint_url_keeps_entry_config() {
413 let mut endpoint = RpcEndpoint::new(RpcEndpointUrl::Url("http://127.0.0.1:18429".into()));
414 endpoint.config.retries = Some(2);
415 endpoint.config.retry_backoff = Some(100);
416 let shared = || RpcEndpoint::new(RpcEndpointUrl::Url("http://127.0.0.1:18430".into()));
417 let mut retrying = shared();
418 retrying.config.retries = Some(5);
419 let mut same = RpcEndpoint::new(RpcEndpointUrl::Url("http://127.0.0.1:18431".into()));
420 same.config.retries = Some(3);
421 let config = Config {
422 rpc_endpoints: RpcEndpoints::new([
423 ("stub", endpoint),
424 ("plain", shared()),
425 ("retrying", retrying),
426 ("same_a", same.clone()),
427 ("same_b", same),
428 ]),
429 ..Default::default()
430 };
431 let config = CheatsConfig::new(&config, Default::default(), None, None, false);
432 let settings = |url_or_alias| {
433 let config = config.rpc_endpoint(url_or_alias).unwrap().config;
434 (config.retries, config.retry_backoff)
435 };
436
437 assert_eq!(settings("stub"), (Some(2), Some(100)));
438 assert_eq!(settings("http://127.0.0.1:18429"), (Some(2), Some(100)));
439 assert_eq!(settings("http://127.0.0.1:18430"), (None, None));
441 assert_eq!(settings("retrying"), (Some(5), None));
442 assert_eq!(settings("http://127.0.0.1:18431"), (Some(3), None));
444 assert_eq!(settings("http://127.0.0.1:18432"), (None, None));
445 }
446}