1use super::*;
2use alloy_sol_types::{Revert, SolError};
3use evm2::interpreter::gas::CALL_STIPEND;
4use foundry_common::contracts::ContractsByArtifact;
5use foundry_evm::{
6 core::backend::GLOBAL_FAIL_SLOT,
7 inspectors::cheatcodes::{Error, ExpectedCallType, expect_revert_mismatch},
8};
9use std::collections::BTreeSet;
10
11const MAX_BOUND_ANALYSIS_VISITS: usize = 256;
12
13#[derive(Clone, Debug)]
14pub(crate) struct PathState {
15 pub(crate) depth: usize,
16 pub(crate) call_depth: usize,
17 pub(crate) call_depth_base: usize,
20 pub(crate) origin: Address,
21 pub(crate) origin_word: SymExpr,
22 pub(crate) gas_price: SymExpr,
23 pub(crate) ffi_enabled: bool,
24 pub(crate) block: SymbolicBlock,
25 pub(crate) frame: CallFrame,
26 pub(crate) world: SymbolicWorld,
27 pub(crate) prank: SymbolicPrank,
28 pub(crate) root_pranks: HashMap<Address, SymbolicPrank>,
31 pub(crate) constraints: Vec<SymBoolExpr>,
32 pub(crate) witness_preferences: Vec<SymBoolExpr>,
34 pub(crate) next_symbol: usize,
35 pub(crate) svm_returns: Vec<SymReturnData>,
38 pub(crate) recorded_logs: Option<Vec<SymbolicLog>>,
39 pub(crate) recorded_logs_generation: u64,
42 pub(crate) access_record: Option<AccessRecord>,
43 pub(crate) root_calldata: Option<SymbolicCalldata>,
44 pub(crate) invariant_predicate: bool,
46 corpus_seed_models: Vec<Arc<SymbolicModel>>,
47 branch_target: Option<SymbolicBranchTarget>,
48 branch_target_reached: bool,
49 needs_feasibility_check: bool,
50 pub(crate) loop_jumps: HashMap<(usize, Vec<usize>), u32>,
52 pub(crate) expected_revert: Option<ExpectedRevert>,
53 pub(crate) outer_expected_revert: bool,
57 pub(crate) first_failed_callee: Option<Address>,
60 pub(crate) first_reverted_callee: Option<Address>,
63 pub(crate) assertion_failed: bool,
65 pub(crate) memory_halt_pc: Option<usize>,
67 pub(crate) assume_no_revert_next_call: Option<AssumeNoRevert>,
68 pub(crate) expected_emit: Option<ExpectedEmit>,
69 pub(crate) expected_calls: Vec<ExpectedCall>,
70 pub(crate) expected_creates: Vec<ExpectedCreate>,
71 pub(crate) call_mocks: Vec<CallMock>,
72 pub(crate) function_mocks: Vec<FunctionMock>,
73 pub(crate) persistent_accounts: HashSet<Address>,
74 pub(crate) wallets: IndexSet<Address>,
75 pub(crate) labels: HashMap<Address, String>,
76 pub(crate) storage_load_hooks: HashMap<Address, SymbolicStorageHook>,
77 pub(crate) storage_store_hooks: HashMap<Address, SymbolicStorageHook>,
78 pub(crate) mapping_storage_store_hooks: HashMap<(Address, U256), SymbolicStorageHook>,
79 pub(crate) mapping_hook_keccak_preimages: HashMap<(Address, SymExpr), Arc<[SymExpr]>>,
80 pub(crate) storage_hook_active: bool,
81 pub(crate) pending_storage_hook_revert: bool,
82 pub(crate) persistent_writes: Vec<PersistentWrite>,
84 pub(crate) unknown_calls: Vec<UnknownCall>,
86 pub(crate) unknown_world: Option<SymExpr>,
88}
89
90impl PathState {
91 pub(crate) fn new(
92 cx: &mut SymCx,
93 address: Address,
94 caller: Address,
95 callvalue: U256,
96 calldata: SymbolicCalldata,
97 ffi_enabled: bool,
98 ) -> Self {
99 let mut state = Self::empty(cx, address, caller, ffi_enabled);
100 let callvalue = SymExpr::constant(cx, callvalue);
101 let call_data = calldata.call_data(cx);
102 state.frame = CallFrame::new(cx, address, address, caller, callvalue, false, call_data);
103 state.constraints = calldata.constraints().to_vec();
104 state.root_calldata = Some(calldata);
105 state
106 }
107
108 pub(crate) fn empty(
109 cx: &mut SymCx,
110 address: Address,
111 caller: Address,
112 ffi_enabled: bool,
113 ) -> Self {
114 let origin_word = SymExpr::constant(cx, address_word(caller));
115 let gas_price = SymExpr::zero(cx);
116 let block = SymbolicBlock::new(cx);
117 let callvalue = SymExpr::zero(cx);
118 let calldata = SymBytes::empty(cx);
119 let calldata = SymCalldata::from_bytes(cx, calldata);
120 let frame = CallFrame::new(cx, address, address, caller, callvalue, false, calldata);
121 Self {
122 depth: 0,
123 call_depth: 0,
124 call_depth_base: 0,
125 origin: caller,
126 origin_word,
127 gas_price,
128 ffi_enabled,
129 block,
130 frame,
131 world: SymbolicWorld::default(),
132 prank: SymbolicPrank::default(),
133 root_pranks: HashMap::default(),
134 constraints: Vec::new(),
135 witness_preferences: Vec::new(),
136 next_symbol: 0,
137 svm_returns: Vec::new(),
138 recorded_logs: None,
139 recorded_logs_generation: 0,
140 access_record: None,
141 root_calldata: None,
142 invariant_predicate: false,
143 corpus_seed_models: Vec::new(),
144 branch_target: None,
145 branch_target_reached: false,
146 needs_feasibility_check: false,
147 loop_jumps: HashMap::default(),
148 expected_revert: None,
149 outer_expected_revert: false,
150 first_failed_callee: None,
151 first_reverted_callee: None,
152 assertion_failed: false,
153 memory_halt_pc: None,
154 assume_no_revert_next_call: None,
155 expected_emit: None,
156 expected_calls: Vec::new(),
157 expected_creates: Vec::new(),
158 call_mocks: Vec::new(),
159 function_mocks: Vec::new(),
160 persistent_accounts: HashSet::default(),
161 wallets: IndexSet::default(),
162 labels: HashMap::default(),
163 storage_load_hooks: HashMap::default(),
164 storage_store_hooks: HashMap::default(),
165 mapping_storage_store_hooks: HashMap::default(),
166 mapping_hook_keccak_preimages: HashMap::default(),
167 storage_hook_active: false,
168 pending_storage_hook_revert: false,
169 persistent_writes: Vec::new(),
170 unknown_calls: Vec::new(),
171 unknown_world: None,
172 }
173 }
174
175 pub(crate) fn apply_executor_env(
177 &mut self,
178 cx: &mut SymCx,
179 executor: &ExecutorView<'_>,
180 ) -> Result<(), SymbolicError> {
181 self.block = SymbolicBlock::from_executor(cx, executor);
182 self.gas_price = SymExpr::constant(cx, U256::from(executor.gas_price));
183 for &(target, overwrite) in &executor.arbitrary_storage_targets {
184 self.world.enable_arbitrary_storage(target, overwrite);
185 }
186 for &(target, source) in &executor.arbitrary_storage_copies {
187 Arc::make_mut(&mut self.world.state).arbitrary_storage_copies.insert(target, source);
188 }
189 self.storage_load_hooks.extend(executor.storage_load_hooks.iter().copied());
190 self.storage_store_hooks.extend(executor.storage_store_hooks.iter().copied());
191 self.mapping_storage_store_hooks
192 .extend(executor.mapping_storage_store_hooks.iter().copied());
193 if executor.expects_safe_memory {
194 return Err(SymbolicError::Unsupported(
195 "symbolic vm.expectSafeMemory inherited from setUp",
196 ));
197 }
198 self.persistent_accounts.extend(executor.persistent_accounts.iter().copied());
199
200 for prank in &executor.pranks {
202 if prank.depth != 1 || prank.delegate_call {
203 return Err(SymbolicError::Unsupported("symbolic prank inherited from setUp"));
204 }
205 let caller = (prank.new_caller, SymExpr::constant(cx, address_word(prank.new_caller)));
206 let origin = prank
207 .new_origin
208 .map(|origin| (origin, SymExpr::constant(cx, address_word(origin))));
209 let slot = if prank.prank_caller == self.address {
211 &mut self.prank
212 } else {
213 self.root_pranks.entry(prank.prank_caller).or_default()
214 };
215 if prank.single_call {
216 slot.set_next(caller, origin);
217 } else {
218 slot.set_persistent(caller, origin);
219 slot.persistent_used = prank.used;
221 }
222 }
223 if let Some(accesses) = executor.accesses
224 && (executor.recording_accesses || !accesses.reads.is_empty())
225 {
226 let slots = |cx: &mut SymCx, slots: &HashMap<Address, Vec<U256>>| {
227 slots
228 .iter()
229 .map(|(address, slots)| {
230 (*address, slots.iter().map(|slot| SymExpr::constant(cx, *slot)).collect())
231 })
232 .collect()
233 };
234 self.access_record = Some(AccessRecord {
235 reads: slots(cx, &accesses.reads),
236 writes: slots(cx, &accesses.writes),
237 stopped: !executor.recording_accesses,
238 });
239 }
240 let Some(cheats) = executor.cheatcodes else { return Ok(()) };
241 let mut mocked_calls = cheats.mocked_calls.iter().collect::<Vec<_>>();
242 mocked_calls.sort_by_key(|(callee, _)| **callee);
243 for (callee, mocks) in mocked_calls {
244 let callee = SymExpr::constant(cx, address_word(*callee));
245 for (mock, returns) in mocks {
246 let data = SymBytes::concrete(cx, mock.calldata.to_vec());
247 let reverts = returns.front().is_some_and(|data| data.reverts);
248 let returns = returns
249 .iter()
250 .map(|data| SymReturnData::from_concrete_bytes(cx, data.data.to_vec()))
251 .collect();
252 self.call_mocks.push(CallMock::new(
253 callee.clone(),
254 mock.value,
255 data,
256 returns,
257 reverts,
258 ));
259 }
260 }
261 for (callee, mocks) in &cheats.mocked_functions {
262 let callee = SymExpr::constant(cx, address_word(*callee));
263 for (data, target) in mocks {
264 let data = SymBytes::concrete(cx, data.to_vec());
265 self.function_mocks.push(FunctionMock::new(callee.clone(), *target, data));
266 }
267 }
268 if let Some(logs) = &cheats.recorded_logs {
269 let logs = logs
270 .iter()
271 .map(|log| {
272 let topics = log
273 .topics
274 .iter()
275 .map(|topic| SymExpr::constant(cx, (*topic).into()))
276 .collect();
277 let data_len = SymExpr::constant(cx, U256::from(log.data.len()));
278 let data = SymBytes::concrete(cx, log.data.to_vec());
279 SymbolicLog::new(topics, data_len, data, log.emitter)
280 })
281 .collect();
282 self.recorded_logs = Some(logs);
283 }
284 let mut expected_calls = cheats
285 .expected_calls
286 .iter()
287 .flat_map(|(callee, calls)| calls.iter().map(move |(key, call)| (callee, key, call)))
288 .collect::<Vec<_>>();
289 expected_calls.sort_by(|a, b| (a.0, &a.1.0).cmp(&(b.0, &b.1.0)));
290 for (callee, (data, scheme), (expected, observed)) in expected_calls {
291 if scheme.is_some() {
292 return Err(SymbolicError::Unsupported(
293 "symbolic vm.expectCall scheme inherited from setUp",
294 ));
295 }
296 self.expected_calls.push(ExpectedCall {
297 callee: SymExpr::constant(cx, address_word(*callee)),
298 value: expected.value,
299 gas: expected.gas,
300 min_gas: expected.min_gas,
301 data: SymBytes::concrete(cx, data.to_vec()),
302 expected: expected.count,
303 observed: *observed,
304 exact: expected.call_type == ExpectedCallType::Count,
305 });
306 }
307 if let Some(wallets) = &cheats.wallets {
308 let wallets = wallets
309 .signers()
310 .map_err(|_| SymbolicError::Unsupported("symbolic wallets inherited from setUp"))?;
311 self.wallets.extend(wallets);
312 }
313 self.labels.extend(cheats.labels.iter().map(|(address, label)| (*address, label.clone())));
314 Ok(())
315 }
316
317 pub(crate) fn child(&self, frame: CallFrame) -> Self {
318 let mut child = self.clone();
319 child.call_depth += 1;
320 child.frame = frame;
321 child.prank = SymbolicPrank::default();
324 child.loop_jumps.clear();
325 child.outer_expected_revert = self.outer_expected_revert || self.expected_revert.is_some();
326 child.expected_revert = None;
327 child.first_failed_callee = None;
328 child.first_reverted_callee = None;
329 child.assume_no_revert_next_call = None;
330 child
331 }
332
333 pub(crate) const fn starts_isolated_transaction(&self, executor: &ExecutorView<'_>) -> bool {
336 executor.isolate && self.call_depth == 0
337 }
338
339 pub(crate) const fn at_call_depth_limit(&self) -> bool {
341 self.call_depth - self.call_depth_base >= CALL_DEPTH_LIMIT as usize
342 }
343
344 pub(crate) fn storage_hook_child(&self, frame: CallFrame) -> Self {
345 let mut child = self.child(frame);
346 child.storage_hook_active = true;
347 child.outer_expected_revert = false;
348 child.recorded_logs = None;
349 child.access_record = None;
350 child.expected_emit = None;
351 child.expected_calls.clear();
352 child.expected_creates.clear();
353 child.call_mocks.clear();
354 child.function_mocks.clear();
355 child.set_branch_target(None);
356 child
357 }
358
359 pub(crate) fn copy_call_output_offset(
360 &mut self,
361 cx: &mut SymCx,
362 dest: SymExpr,
363 size: &BoundedCopySize,
364 ) -> Result<(), SymbolicError> {
365 let CallFrame { memory, return_data, .. } = &mut self.frame;
366 memory.copy_call_output_offset(cx, dest, size, return_data)
367 }
368
369 pub(crate) fn constrained_usize(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<usize> {
370 self.constrained_usize_checked(cx, expr).and_then(Result::ok)
371 }
372
373 pub(crate) fn constrained_usize_checked(
374 &self,
375 cx: &mut SymCx,
376 expr: &SymExpr,
377 ) -> Option<Result<usize, U256>> {
378 self.constrained_word(cx, expr).map(|value| usize::try_from(value).map_err(|_| value))
379 }
380
381 pub(crate) fn upper_bound_usize(&self, _cx: &mut SymCx, expr: &SymExpr) -> Option<usize> {
382 let mut bounds = HashMap::default();
383 let mut ordering = HashMap::default();
384 let mut remaining = MAX_BOUND_ANALYSIS_VISITS;
385 self.expr_upper_bound_usize_cached(expr, &mut bounds, &mut ordering, &mut remaining)
386 }
387
388 pub(crate) fn lower_bound_usize(&self, expr: &SymExpr) -> usize {
390 let mut lower_bounds = HashMap::default();
391 let mut upper_bounds = HashMap::default();
392 let mut ordering = HashMap::default();
393 let mut remaining = MAX_BOUND_ANALYSIS_VISITS;
394 self.expr_lower_bound_usize(
395 expr,
396 &mut lower_bounds,
397 &mut upper_bounds,
398 &mut ordering,
399 &mut remaining,
400 )
401 }
402
403 pub(crate) fn constrained_word(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<U256> {
404 expr.as_const().or_else(|| {
405 self.constraints
406 .iter()
407 .find_map(|constraint| {
408 constraint.forces_expr_const_with_context(expr, &self.constraints)
409 })
410 .or_else(|| self.constrained_expr_value(cx, expr))
411 })
412 }
413
414 pub(crate) fn constrained_expr_value(&self, cx: &mut SymCx, expr: &SymExpr) -> Option<U256> {
415 if let Some(value) = expr.eval() {
416 return Some(value);
417 }
418 if let Some(value) = expr.known_word() {
419 return Some(value);
420 }
421
422 let mut vars = SymbolicVars::default();
423 expr.collect_eval_vars(&mut vars);
424 let mut model = SymbolicModel::default();
425 for var in vars {
426 let var_expr = SymExpr::get_var(cx, var);
427 let value = self.constraints.iter().find_map(|constraint| {
428 constraint.forces_expr_const_with_context(&var_expr, &self.constraints)
429 })?;
430 model.insert(var, value);
431 }
432
433 expr.eval_model_recording_keccak_preimages(cx, &model).ok()
434 }
435
436 pub(crate) fn split_corpus_seed_models(
437 &self,
438 condition: &SymBoolExpr,
439 ) -> (Vec<Arc<SymbolicModel>>, Vec<Arc<SymbolicModel>>) {
440 let mut true_models = Vec::new();
441 let mut false_models = Vec::new();
442 for model in &self.corpus_seed_models {
443 match condition.eval_model_if_complete(model.as_ref()) {
444 Ok(Some(true)) => true_models.push(Arc::clone(model)),
445 Ok(Some(false)) => false_models.push(Arc::clone(model)),
446 Ok(None) | Err(_) => {
447 true_models.push(Arc::clone(model));
448 false_models.push(Arc::clone(model));
449 }
450 }
451 }
452 (true_models, false_models)
453 }
454
455 pub(crate) fn set_corpus_seed_models(&mut self, models: Vec<Arc<SymbolicModel>>) {
456 self.corpus_seed_models = models;
457 }
458
459 pub(crate) const fn corpus_seed_model_count(&self) -> usize {
460 self.corpus_seed_models.len()
461 }
462
463 pub(crate) const fn set_branch_target(&mut self, target: Option<SymbolicBranchTarget>) {
464 self.branch_target = target;
465 self.branch_target_reached = false;
466 }
467
468 pub(crate) const fn branch_target(&self) -> Option<SymbolicBranchTarget> {
469 self.branch_target
470 }
471
472 pub(crate) const fn mark_branch_target_reached(&mut self) {
473 self.branch_target_reached = true;
474 }
475
476 pub(crate) fn inherit_branch_target_progress(&mut self, child: &Self) {
477 if self.branch_target == child.branch_target && child.branch_target_reached {
478 self.mark_branch_target_reached();
479 }
480 }
481
482 pub(crate) fn take_noncommitting_check_state(&mut self, check: &mut Self) {
483 self.constraints = std::mem::take(&mut check.constraints);
484 self.witness_preferences = std::mem::take(&mut check.witness_preferences);
485 self.next_symbol = self.next_symbol.max(check.next_symbol);
486 self.svm_returns = std::mem::take(&mut check.svm_returns);
487 self.world.merge_replay_metadata_from(&check.world);
488 self.storage_load_hooks = std::mem::take(&mut check.storage_load_hooks);
489 self.storage_store_hooks = std::mem::take(&mut check.storage_store_hooks);
490 self.mapping_storage_store_hooks = std::mem::take(&mut check.mapping_storage_store_hooks);
491 }
492
493 pub(crate) fn take_call_outcome_state(&mut self, child: &mut Self) {
494 self.constraints = std::mem::take(&mut child.constraints);
495 self.witness_preferences = std::mem::take(&mut child.witness_preferences);
496 self.next_symbol = child.next_symbol;
497 self.svm_returns = std::mem::take(&mut child.svm_returns);
498 self.inherit_branch_target_progress(child);
499 self.storage_load_hooks = std::mem::take(&mut child.storage_load_hooks);
500 self.storage_store_hooks = std::mem::take(&mut child.storage_store_hooks);
501 self.mapping_storage_store_hooks = std::mem::take(&mut child.mapping_storage_store_hooks);
502 self.mapping_hook_keccak_preimages =
503 std::mem::take(&mut child.mapping_hook_keccak_preimages);
504 self.recorded_logs = child.recorded_logs.take();
505 self.recorded_logs_generation = child.recorded_logs_generation;
506 self.assertion_failed |= child.assertion_failed;
507 self.expected_emit = child.expected_emit.clone();
508 self.take_inspector_state(child);
509 self.persistent_writes = std::mem::take(&mut child.persistent_writes);
510 self.unknown_calls = std::mem::take(&mut child.unknown_calls);
512 self.unknown_world = child.unknown_world.take();
513 }
514
515 fn take_inspector_state(&mut self, other: &mut Self) {
517 self.access_record = other.access_record.take();
518 self.block = other.block.clone();
519 self.gas_price = other.gas_price.clone();
520 self.wallets = std::mem::take(&mut other.wallets);
521 self.labels = std::mem::take(&mut other.labels);
522 self.persistent_accounts = std::mem::take(&mut other.persistent_accounts);
523 self.expected_calls = std::mem::take(&mut other.expected_calls);
524 self.expected_creates = std::mem::take(&mut other.expected_creates);
525 self.call_mocks = std::mem::take(&mut other.call_mocks);
526 self.function_mocks = std::mem::take(&mut other.function_mocks);
527 }
528
529 pub(crate) fn discard_failed_call_logs(&mut self, len: usize, generation: u64) {
533 if let Some(logs) = &mut self.recorded_logs {
534 logs.truncate(if generation == self.recorded_logs_generation { len } else { 0 });
535 }
536 }
537
538 pub(crate) fn take_reverted_top_level_effects(&mut self, mut reverted: Self) {
539 let recorded_logs_len = self.recorded_logs.as_ref().map_or(0, Vec::len);
540 let recorded_logs_generation = self.recorded_logs_generation;
541 self.take_noncommitting_check_state(&mut reverted);
542 self.take_inspector_state(&mut reverted);
543 self.world.take_snapshots_from(&mut reverted.world);
544 self.recorded_logs = reverted.recorded_logs;
545 self.recorded_logs_generation = reverted.recorded_logs_generation;
546 self.discard_failed_call_logs(recorded_logs_len, recorded_logs_generation);
547 self.expected_revert = reverted.expected_revert;
548 self.first_failed_callee = reverted.first_failed_callee;
549 self.first_reverted_callee = reverted.first_reverted_callee;
550 self.assertion_failed = reverted.assertion_failed;
551 self.assume_no_revert_next_call = reverted.assume_no_revert_next_call;
552 self.expected_emit = reverted.expected_emit;
553 self.root_pranks = reverted.root_pranks;
556 if reverted.prank.has_active() {
557 self.root_pranks.insert(reverted.frame.address, reverted.prank);
558 }
559 self.prank = self.root_pranks.remove(&self.frame.address).unwrap_or_default();
560 }
561
562 pub(crate) fn can_materialize_seed(&self) -> bool {
567 !self.constraints.iter().any(SymBoolExpr::contains_gasleft)
568 }
569
570 pub(crate) const fn satisfies_branch_target(&self) -> bool {
571 self.branch_target.is_none() || self.branch_target_reached
572 }
573
574 pub(crate) const fn defer_feasibility_check(&mut self) {
575 self.needs_feasibility_check = true;
576 }
577
578 pub(crate) const fn take_deferred_feasibility_check(&mut self) -> bool {
579 let needs_check = self.needs_feasibility_check;
580 self.needs_feasibility_check = false;
581 needs_check
582 }
583
584 fn expr_upper_bound_usize_cached(
585 &self,
586 expr: &SymExpr,
587 bounds: &mut HashMap<SymExpr, Option<usize>>,
588 ordering: &mut HashMap<(SymExpr, SymExpr), bool>,
589 remaining: &mut usize,
590 ) -> Option<usize> {
591 if let Some(bound) = bounds.get(expr) {
592 return *bound;
593 }
594 if let Some(value) = expr.as_const() {
595 return usize::try_from(value).ok();
596 }
597
598 let constraint_bound = self.constraint_upper_bound_usize(expr);
599 let structural_bound = remaining.checked_sub(1).and_then(|next| {
600 *remaining = next;
601 match expr.kind() {
602 SymExprKind::Const(value) => usize::try_from(*value).ok(),
603 SymExprKind::Var(_)
604 | SymExprKind::GasLeft(_)
605 | SymExprKind::Keccak { .. }
606 | SymExprKind::Hash { .. } => None,
607 SymExprKind::Not(_) => None,
608 SymExprKind::TernOp(SymTernOp::MulDiv, _, _, _) => None,
609 SymExprKind::TernOp(_, _, _, modulus) => match modulus.as_const() {
610 Some(modulus) if modulus.is_zero() => Some(0),
611 Some(modulus) => usize::try_from(modulus - U256::ONE).ok(),
612 None => self
613 .expr_upper_bound_usize_cached(modulus, bounds, ordering, remaining)
614 .and_then(|bound| bound.checked_sub(1)),
615 },
616 SymExprKind::Ite(condition, left, right) => {
617 let left_bound =
618 self.expr_upper_bound_usize_cached(left, bounds, ordering, remaining);
619 let right_bound =
620 self.expr_upper_bound_usize_cached(right, bounds, ordering, remaining);
621 match (left_bound, right_bound) {
622 (Some(left_bound), Some(right_bound)) => Some(left_bound.max(right_bound)),
623 (None, Some(right_bound)) => condition
624 .implies_unsigned_less_or_equal(true, left, right, remaining)
625 .then_some(right_bound),
626 (Some(left_bound), None) => condition
627 .implies_unsigned_less_or_equal(false, right, left, remaining)
628 .then_some(left_bound),
629 (None, None) => None,
630 }
631 }
632 SymExprKind::BinOp(op, left, right) => match op {
633 SymBinOp::Add => self
634 .expr_upper_bound_usize_cached(left, bounds, ordering, remaining)?
635 .checked_add(
636 self.expr_upper_bound_usize_cached(right, bounds, ordering, remaining)?,
637 ),
638 SymBinOp::Mul => self
639 .expr_upper_bound_usize_cached(left, bounds, ordering, remaining)?
640 .checked_mul(
641 self.expr_upper_bound_usize_cached(right, bounds, ordering, remaining)?,
642 ),
643 SymBinOp::UDiv => {
644 let left =
645 self.expr_upper_bound_usize_cached(left, bounds, ordering, remaining)?;
646 match right.as_const()? {
647 divisor if divisor.is_zero() => Some(0),
648 divisor => Some(left / usize::try_from(divisor).ok()?),
649 }
650 }
651 SymBinOp::URem => match right.as_const() {
652 Some(divisor) if divisor.is_zero() => Some(0),
653 Some(divisor) => usize::try_from(divisor - U256::ONE).ok(),
654 None => {
655 self.expr_upper_bound_usize_cached(left, bounds, ordering, remaining)
656 }
657 },
658 SymBinOp::And => right
659 .as_const()
660 .and_then(|value| usize::try_from(value).ok())
661 .or_else(|| left.as_const().and_then(|value| usize::try_from(value).ok()))
662 .map(|mask| {
663 self.expr_upper_bound_usize_cached(left, bounds, ordering, remaining)
664 .or_else(|| {
665 self.expr_upper_bound_usize_cached(
666 right, bounds, ordering, remaining,
667 )
668 })
669 .map_or(mask, |bound| bound.min(mask))
670 }),
671 SymBinOp::Shr => {
672 let left =
673 self.expr_upper_bound_usize_cached(left, bounds, ordering, remaining)?;
674 let shift = usize::try_from(right.as_const()?).ok()?;
675 Some(if shift >= usize::BITS as usize { 0 } else { left >> shift })
676 }
677 SymBinOp::Sub => {
678 if let Some(difference) = left
679 .constant_difference(right)
680 .and_then(|difference| usize::try_from(difference).ok())
681 {
682 return Some(difference);
683 }
684 let left_bound =
685 self.expr_upper_bound_usize_cached(left, bounds, ordering, remaining)?;
686 self.expressions_are_unsigned_ordered(right, left, ordering, remaining)
687 .then_some(left_bound)
688 }
689 SymBinOp::Shl => match right.as_const() {
690 Some(shift) if shift >= U256::from(256) => Some(0),
691 Some(shift) => usize::try_from(shift).ok().and_then(|shift| {
692 let bound = self
693 .expr_upper_bound_usize_cached(left, bounds, ordering, remaining)?;
694 if bound == 0 {
695 return Some(0);
696 }
697 let factor = 1usize.checked_shl(u32::try_from(shift).ok()?)?;
698 bound.checked_mul(factor)
699 }),
700 None => None,
701 },
702 SymBinOp::SDiv
703 | SymBinOp::SRem
704 | SymBinOp::Or
705 | SymBinOp::Xor
706 | SymBinOp::Sar
707 | SymBinOp::MulHigh => None,
708 },
709 }
710 });
711
712 let bound = match (constraint_bound, structural_bound) {
713 (Some(left), Some(right)) => Some(left.min(right)),
714 (Some(bound), None) | (None, Some(bound)) => Some(bound),
715 (None, None) => None,
716 };
717 bounds.insert(expr.clone(), bound);
718 bound
719 }
720
721 fn expressions_are_unsigned_ordered(
722 &self,
723 left: &SymExpr,
724 right: &SymExpr,
725 ordering: &mut HashMap<(SymExpr, SymExpr), bool>,
726 remaining: &mut usize,
727 ) -> bool {
728 if left == right {
729 return true;
730 }
731 let key = (left.clone(), right.clone());
732 if let Some(ordered) = ordering.get(&key) {
733 return *ordered;
734 }
735 let Some(next) = remaining.checked_sub(1) else { return false };
736 *remaining = next;
737
738 let ordered = if let (Some(left), Some(right)) = (left.as_const(), right.as_const()) {
739 left <= right
740 } else if let SymExprKind::Ite(condition, then_value, else_value) = left.kind() {
741 let then_ordered = condition
742 .implies_unsigned_less_or_equal(true, then_value, right, remaining)
743 || self.expressions_are_unsigned_ordered(then_value, right, ordering, remaining);
744 let else_ordered = condition
745 .implies_unsigned_less_or_equal(false, else_value, right, remaining)
746 || self.expressions_are_unsigned_ordered(else_value, right, ordering, remaining);
747 then_ordered && else_ordered
748 } else if let SymExprKind::Ite(condition, then_value, else_value) = right.kind() {
749 let then_ordered = condition
750 .implies_unsigned_less_or_equal(true, left, then_value, remaining)
751 || self.expressions_are_unsigned_ordered(left, then_value, ordering, remaining);
752 let else_ordered = condition
753 .implies_unsigned_less_or_equal(false, left, else_value, remaining)
754 || self.expressions_are_unsigned_ordered(left, else_value, ordering, remaining);
755 then_ordered && else_ordered
756 } else {
757 false
758 };
759 ordering.insert(key, ordered);
760 ordered
761 }
762
763 fn expr_lower_bound_usize(
764 &self,
765 expr: &SymExpr,
766 lower_bounds: &mut HashMap<SymExpr, usize>,
767 upper_bounds: &mut HashMap<SymExpr, Option<usize>>,
768 ordering: &mut HashMap<(SymExpr, SymExpr), bool>,
769 remaining: &mut usize,
770 ) -> usize {
771 if let Some(bound) = lower_bounds.get(expr) {
772 return *bound;
773 }
774 if let Some(value) = expr.as_const().and_then(|value| usize::try_from(value).ok()) {
775 return value;
776 }
777 let Some(next) = remaining.checked_sub(1) else {
778 return 0;
779 };
780 *remaining = next;
781
782 let bound = match expr.kind() {
783 SymExprKind::Const(value) => usize::try_from(*value).unwrap_or_default(),
784 SymExprKind::Ite(_, left, right) => {
785 let left = self.expr_lower_bound_usize(
786 left,
787 lower_bounds,
788 upper_bounds,
789 ordering,
790 remaining,
791 );
792 let right = self.expr_lower_bound_usize(
793 right,
794 lower_bounds,
795 upper_bounds,
796 ordering,
797 remaining,
798 );
799 left.min(right)
800 }
801 SymExprKind::BinOp(SymBinOp::Add, left, right) => {
802 let no_wrap = self
803 .expr_upper_bound_usize_cached(left, upper_bounds, ordering, remaining)
804 .and_then(|left| {
805 self.expr_upper_bound_usize_cached(right, upper_bounds, ordering, remaining)
806 .and_then(|right| left.checked_add(right))
807 })
808 .is_some();
809 if no_wrap {
810 let left = self.expr_lower_bound_usize(
811 left,
812 lower_bounds,
813 upper_bounds,
814 ordering,
815 remaining,
816 );
817 let right = self.expr_lower_bound_usize(
818 right,
819 lower_bounds,
820 upper_bounds,
821 ordering,
822 remaining,
823 );
824 left.checked_add(right).unwrap_or_default()
825 } else {
826 0
827 }
828 }
829 SymExprKind::BinOp(SymBinOp::Sub, left, right) => left
830 .constant_difference(right)
831 .and_then(|difference| usize::try_from(difference).ok())
832 .unwrap_or_default(),
833 SymExprKind::BinOp(SymBinOp::Or, left, right) => {
834 let left = self.expr_lower_bound_usize(
835 left,
836 lower_bounds,
837 upper_bounds,
838 ordering,
839 remaining,
840 );
841 let right = self.expr_lower_bound_usize(
842 right,
843 lower_bounds,
844 upper_bounds,
845 ordering,
846 remaining,
847 );
848 left.max(right)
849 }
850 SymExprKind::Var(_)
851 | SymExprKind::GasLeft(_)
852 | SymExprKind::Keccak { .. }
853 | SymExprKind::Hash { .. }
854 | SymExprKind::Not(_)
855 | SymExprKind::BinOp(_, _, _)
856 | SymExprKind::TernOp(_, _, _, _) => 0,
857 };
858 lower_bounds.insert(expr.clone(), bound);
859 bound
860 }
861
862 pub(crate) fn constraint_upper_bound_usize(&self, expr: &SymExpr) -> Option<usize> {
863 let mut bound: Option<usize> = None;
864 for constraint in &self.constraints {
865 if let Some(candidate) = constraint.upper_bound_usize(expr) {
866 bound = Some(bound.map_or(candidate, |bound| bound.min(candidate)));
867 }
868 }
869 bound
870 }
871
872 pub(crate) fn expect_constrained_usize(
873 &self,
874 cx: &mut SymCx,
875 expr: SymExpr,
876 reason: &'static str,
877 ) -> Result<usize, SymbolicError> {
878 self.constrained_usize(cx, &expr).ok_or(SymbolicError::Unsupported(reason))
879 }
880
881 pub(crate) fn expect_constrained_word(
882 &self,
883 cx: &mut SymCx,
884 expr: SymExpr,
885 reason: &'static str,
886 ) -> Result<U256, SymbolicError> {
887 self.constrained_word(cx, &expr).ok_or(SymbolicError::Unsupported(reason))
888 }
889
890 pub(crate) fn bin_word(&mut self, cx: &mut SymCx, op: SymBinOp) -> Result<(), SymbolicError> {
891 let a = self.stack.pop()?;
892 let b = self.stack.pop()?;
893 self.stack.push(SymExpr::binop(cx, op, a, b))
894 }
895
896 pub(crate) fn bin_word_div_zero_guard(
897 &mut self,
898 cx: &mut SymCx,
899 op: SymBinOp,
900 ) -> Result<(), SymbolicError> {
901 let a = self.stack.pop()?;
902 let b = self.stack.pop()?;
903 let zero = SymExpr::zero(cx);
904 let condition = SymBoolExpr::eq(cx, b.clone(), zero.clone());
905 let expr = SymExpr::binop(cx, op, a, b);
906 self.stack.push(SymExpr::ite(cx, condition, zero, expr))
907 }
908
909 pub(crate) fn cmp_word_condition(
910 &mut self,
911 cx: &mut SymCx,
912 op: SymCmpOp,
913 ) -> Result<SymBoolExpr, SymbolicError> {
914 let a = self.stack.pop()?;
915 let b = self.stack.pop()?;
916 Ok(SymBoolExpr::cmp(cx, op, a, b))
917 }
918
919 pub(crate) fn shift_word(&mut self, cx: &mut SymCx, op: SymBinOp) -> Result<(), SymbolicError> {
920 let shift = self.stack.pop()?;
921 let value = self.stack.pop()?;
922 let expr = SymExpr::binop(cx, op, value, shift);
923 let result = expr.known_word().map(|word| SymExpr::constant(cx, word)).unwrap_or(expr);
924 self.stack.push(result)
925 }
926
927 pub(crate) fn exp_word(&mut self, cx: &mut SymCx) -> Result<(), SymbolicError> {
928 let base = self.stack.pop()?;
929 let exponent = self.stack.pop()?;
930 let base = if let Some(value) = self.constrained_word(cx, &base) {
932 SymExpr::constant(cx, value)
933 } else {
934 base
935 };
936 let result = if let Some(exponent) = self.constrained_word(cx, &exponent) {
937 if let Some(base_value) = base.as_const() {
938 SymExpr::constant(cx, base_value.wrapping_pow(exponent))
939 } else if exponent <= U256::from(SYMBOLIC_EXP_CONCRETE_EXPONENT_LIMIT) {
940 exp_expr_for_concrete_exponent(
941 cx,
942 base,
943 usize::try_from(exponent).expect("checked symbolic exponent"),
944 )
945 } else {
946 return Err(SymbolicError::Unsupported("symbolic EXP base"));
947 }
948 } else {
949 let exponent_limit = if base.as_const().is_some() {
950 CONCRETE_BASE_SYMBOLIC_EXPONENT_LIMIT
951 } else {
952 SYMBOLIC_EXP_CONCRETE_EXPONENT_LIMIT
953 };
954 let max_exponent = self
955 .upper_bound_usize(cx, &exponent)
956 .filter(|exponent| *exponent <= exponent_limit as usize)
957 .ok_or(SymbolicError::Unsupported("symbolic EXP exponent"))?;
958 let mut expr = SymExpr::zero(cx);
959 for candidate in (0..=max_exponent).rev() {
960 let candidate_expr = SymExpr::constant(cx, U256::from(candidate));
961 let condition = SymBoolExpr::eq(cx, exponent.clone(), candidate_expr);
962 let value = exp_expr_for_concrete_exponent(cx, base.clone(), candidate);
963 expr = SymExpr::ite(cx, condition, value, expr);
964 }
965 expr
966 };
967 self.stack.push(result)
968 }
969
970 pub(crate) fn balance(
971 &self,
972 cx: &mut SymCx,
973 executor: &ExecutorView<'_>,
974 address: Address,
975 ) -> Result<SymExpr, SymbolicError> {
976 self.world.balance_word_for_address(cx, executor, address)
977 }
978
979 pub(crate) fn balance_word(
980 &mut self,
981 cx: &mut SymCx,
982 executor: &ExecutorView<'_>,
983 address_expr: SymExpr,
984 ) -> Result<SymExpr, SymbolicError> {
985 self.world.balance_word(cx, executor, address_expr)
986 }
987
988 pub(crate) fn extcode_size_word(
989 &mut self,
990 cx: &mut SymCx,
991 executor: &ExecutorView<'_>,
992 address_expr: SymExpr,
993 ) -> Result<SymExpr, SymbolicError> {
994 self.world.extcode_size_word(cx, executor, address_expr)
995 }
996
997 pub(crate) fn extcode_hash_word(
998 &mut self,
999 cx: &mut SymCx,
1000 executor: &ExecutorView<'_>,
1001 address_expr: SymExpr,
1002 ) -> Result<SymExpr, SymbolicError> {
1003 self.world.extcode_hash_word(cx, executor, address_expr)
1004 }
1005
1006 pub(crate) fn extcode_bytes_word(
1007 &mut self,
1008 cx: &mut SymCx,
1009 executor: &ExecutorView<'_>,
1010 address_expr: SymExpr,
1011 offset: SymExpr,
1012 size: usize,
1013 ) -> Result<SymBytes, SymbolicError> {
1014 self.world.extcode_bytes_word(cx, executor, address_expr, offset, size)
1015 }
1016
1017 pub(crate) fn address_or_symbolic_slot(&mut self, cx: &mut SymCx, expr: SymExpr) -> Address {
1018 if let Some(value) = self.constrained_word(cx, &expr) {
1019 return word_to_address(value);
1020 }
1021 self.world.resolve_address(&expr).unwrap_or_else(|| self.world.symbolic_address_slot(expr))
1022 }
1023
1024 pub(crate) fn fresh_word(&mut self, cx: &mut SymCx, prefix: &'static str) -> SymExpr {
1025 let id = self.next_symbol;
1026 self.next_symbol += 1;
1027 SymExpr::var(cx, &format!("{prefix}_{id}"))
1028 }
1029
1030 pub(crate) fn fresh_gasleft(&mut self, cx: &mut SymCx) -> SymExpr {
1031 let id = self.next_symbol;
1032 self.next_symbol += 1;
1033 SymExpr::gas_left(cx, id)
1034 }
1035
1036 pub(crate) fn fresh_bounded_uint(&mut self, cx: &mut SymCx, bits: U256) -> SymExpr {
1037 if bits.is_zero() {
1039 return SymExpr::zero(cx);
1040 }
1041 let value = self.fresh_word(cx, "symbolic");
1042 if bits < U256::from(256) {
1043 let upper = U256::ONE << usize::try_from(bits).expect("checked bit width");
1044 self.constraints.push(SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &value, upper));
1045 }
1046 value
1047 }
1048
1049 pub(crate) fn fresh_bytes(&mut self, cx: &mut SymCx, len: usize) -> Vec<SymExpr> {
1050 (0..len).map(|_| self.fresh_bounded_uint(cx, U256::from(8))).collect()
1051 }
1052
1053 pub(crate) fn fresh_printable_ascii_bytes(
1054 &mut self,
1055 cx: &mut SymCx,
1056 len: usize,
1057 ) -> Vec<SymExpr> {
1058 (0..len)
1059 .map(|_| {
1060 let byte = self.fresh_bounded_uint(cx, U256::from(8));
1061 self.constraints.push(SymBoolExpr::cmp_word_const(
1062 cx,
1063 SymCmpOp::Uge,
1064 &byte,
1065 U256::from(0x20),
1066 ));
1067 self.constraints.push(SymBoolExpr::cmp_word_const(
1068 cx,
1069 SymCmpOp::Ule,
1070 &byte,
1071 U256::from(0x7e),
1072 ));
1073 byte
1074 })
1075 .collect()
1076 }
1077
1078 pub(crate) fn fresh_bounded_int(&mut self, cx: &mut SymCx, bits: U256) -> SymExpr {
1079 let value = self.fresh_word(cx, "symbolic");
1080 if bits.is_zero() {
1081 self.constraints.push(SymBoolExpr::eq_word_const(cx, &value, U256::ZERO));
1082 } else if bits < U256::from(256) {
1083 let magnitude = U256::ONE << (usize::try_from(bits).expect("checked bit width") - 1);
1084 let lt = SymBoolExpr::cmp_word_const(cx, SymCmpOp::Ult, &value, magnitude);
1085 let ge = SymBoolExpr::cmp_word_const(
1086 cx,
1087 SymCmpOp::Uge,
1088 &value,
1089 U256::ZERO.wrapping_sub(magnitude),
1090 );
1091 let condition = SymBoolExpr::or(cx, vec![lt, ge]);
1092 self.constraints.push(condition);
1093 }
1094 value
1095 }
1096
1097 pub(crate) fn prank_for_next_call(&mut self) -> (Address, SymExpr, Option<(Address, SymExpr)>) {
1098 if self.call_depth == 0 {
1101 self.root_pranks.retain(|_, prank| {
1102 prank.next_caller = None;
1103 prank.next_origin = None;
1104 prank.has_active()
1105 });
1106 }
1107 if let Some((caller, caller_word)) = self.prank.next_caller.take() {
1108 (caller, caller_word, self.prank.next_origin.take())
1109 } else {
1110 match self.prank.persistent_caller.clone() {
1111 Some((caller, caller_word)) => {
1112 self.prank.persistent_used = true;
1113 (caller, caller_word, self.prank.persistent_origin.clone())
1114 }
1115 None => {
1116 (self.address, self.address_word.clone(), self.prank.persistent_origin.clone())
1117 }
1118 }
1119 }
1120 }
1121
1122 pub(crate) fn resolve_prank_addresses(&mut self, cx: &mut SymCx) {
1125 let mut prank = std::mem::take(&mut self.prank);
1126 for (address, word) in [
1127 &mut prank.next_caller,
1128 &mut prank.next_origin,
1129 &mut prank.persistent_caller,
1130 &mut prank.persistent_origin,
1131 ]
1132 .into_iter()
1133 .flatten()
1134 {
1135 *address = self.address_or_symbolic_slot(cx, word.clone());
1136 }
1137 self.prank = prank;
1138 }
1139
1140 pub(crate) fn callers(&self) -> Option<(U256, SymExpr, SymExpr)> {
1143 let (mode, caller_word, origin) = if let Some((_, caller_word)) = &self.prank.next_caller {
1144 (U256::from(3), caller_word, &self.prank.next_origin)
1145 } else if let Some((_, caller_word)) = &self.prank.persistent_caller {
1146 (U256::from(4), caller_word, &self.prank.persistent_origin)
1147 } else {
1148 return self.prank.inherited.clone();
1149 };
1150 let origin_word = origin
1151 .as_ref()
1152 .map(|(_, origin_word)| origin_word.clone())
1153 .unwrap_or_else(|| self.origin_word.clone());
1154 Some((mode, caller_word.clone(), origin_word))
1155 }
1156
1157 pub(crate) fn read_callers_words(&self, cx: &mut SymCx) -> Vec<SymExpr> {
1158 let (mode, caller, origin) = self
1159 .callers()
1160 .unwrap_or_else(|| (U256::ZERO, self.origin_word.clone(), self.origin_word.clone()));
1161 vec![SymExpr::constant(cx, mode), caller, origin]
1162 }
1163
1164 pub(crate) fn record_log(&mut self, log: SymbolicLog) {
1165 if let Some(logs) = &mut self.recorded_logs {
1166 logs.push(log);
1167 }
1168 }
1169
1170 pub(crate) fn record_sload(&mut self, address: Address, slot: SymExpr) {
1171 if let Some(record) = &mut self.access_record
1172 && !record.stopped
1173 {
1174 record.read(address, slot);
1175 }
1176 }
1177
1178 pub(crate) fn record_sstore(&mut self, address: Address, slot: SymExpr) {
1179 if let Some(record) = &mut self.access_record
1180 && !record.stopped
1181 {
1182 record.write(address, slot);
1183 }
1184 }
1185
1186 pub(crate) fn check_expected_emit_after_call(&mut self, kind: CallKind) -> bool {
1193 if self.is_static || matches!(kind, CallKind::StaticCall) {
1194 return false;
1195 }
1196 let Some(expected) = &mut self.expected_emit else { return false };
1197 if expected.depth != self.call_depth {
1198 return false;
1199 }
1200 if expected.is_forbidden() {
1201 self.expected_emit = None;
1202 return false;
1203 }
1204 expected.failed = true;
1205 true
1206 }
1207
1208 pub(crate) fn expectations_satisfied(&self) -> bool {
1209 self.expected_revert.is_none()
1210 && self.expected_emit.as_ref().is_none_or(ExpectedEmit::is_forbidden)
1211 && self.expected_calls.iter().all(ExpectedCall::is_satisfied)
1212 && self.expected_creates.is_empty()
1213 }
1214
1215 pub(crate) fn set_persistent_balance(
1217 &mut self,
1218 cx: &mut SymCx,
1219 executor: &ExecutorView<'_>,
1220 address: Address,
1221 value: SymExpr,
1222 ) -> Result<(), SymbolicError> {
1223 let previous = self.world.balance_word_for_address(cx, executor, address)?;
1224 self.world.set_balance_word(address, value.clone());
1225 self.persistent_writes.push(PersistentWrite::Balance { address, balance: value, previous });
1226 Ok(())
1227 }
1228
1229 pub(crate) fn guard_free_address_write(
1234 &mut self,
1235 cx: &mut SymCx,
1236 executor: &ExecutorView<'_>,
1237 word: &SymExpr,
1238 ) -> Vec<(Address, SymBoolExpr)> {
1239 if self.constrained_word(cx, word).is_some() {
1240 return Vec::new();
1241 }
1242 let candidates = self.world.concrete_alias_candidates(executor);
1243 self.world.guard_symbolic_address(word, &candidates);
1244 candidates
1245 .into_iter()
1246 .map(|address| {
1247 let condition = SymBoolExpr::eq_word_const(cx, word, address_word(address));
1248 (address, condition)
1249 })
1250 .collect()
1251 }
1252
1253 pub(crate) fn set_persistent_nonce(
1255 &mut self,
1256 executor: &ExecutorView<'_>,
1257 address: Address,
1258 nonce: u64,
1259 ) -> Result<(), SymbolicError> {
1260 let previous = self.world.nonce(executor, address)?;
1261 self.world.set_nonce(address, nonce);
1262 let delta = i128::from(nonce) - i128::from(previous);
1263 self.persistent_writes.push(PersistentWrite::Nonce(address, delta));
1264 Ok(())
1265 }
1266
1267 pub(crate) fn replay_persistent_writes(
1277 &mut self,
1278 cx: &mut SymCx,
1279 executor: &ExecutorView<'_>,
1280 start: usize,
1281 ) -> Result<(), SymbolicError> {
1282 let mut balance_writes = Vec::<(Address, Vec<(SymExpr, SymExpr)>)>::new();
1285 let mut nonce_deltas = HashMap::<Address, i128>::default();
1286 let mut created = HashSet::<Address>::default();
1287 for write in self.persistent_writes.split_off(start) {
1288 match write {
1289 PersistentWrite::Balance { address, balance, previous } => {
1290 match balance_writes.iter_mut().find(|(account, _)| *account == address) {
1291 Some((_, writes)) => writes.push((balance, previous)),
1292 None => balance_writes.push((address, vec![(balance, previous)])),
1293 }
1294 }
1295 PersistentWrite::Nonce(address, delta) => {
1296 *nonce_deltas.entry(address).or_default() += delta;
1297 }
1298 PersistentWrite::Created(address) => {
1299 created.insert(address);
1300 }
1301 PersistentWrite::Restore => break,
1302 }
1303 }
1304 for (address, writes) in balance_writes {
1307 let reverted = self.world.balance_word_for_address(cx, executor, address)?;
1308 let mut low = reverted.clone();
1311 let mut high = SymExpr::zero(cx);
1312 for (balance, previous) in writes {
1313 let added = SymExpr::binop(cx, SymBinOp::Add, low.clone(), balance);
1314 let carry = SymBoolExpr::cmp(cx, SymCmpOp::Ult, added.clone(), low);
1315 let carry = SymExpr::bool_word(cx, carry);
1316 let borrow = SymBoolExpr::cmp(cx, SymCmpOp::Ult, added.clone(), previous.clone());
1317 let borrow = SymExpr::bool_word(cx, borrow);
1318 high = SymExpr::binop(cx, SymBinOp::Add, high, carry);
1319 high = SymExpr::binop(cx, SymBinOp::Sub, high, borrow);
1320 low = SymExpr::binop(cx, SymBinOp::Sub, added, previous);
1321 }
1322 let zero = SymExpr::zero(cx);
1323 let max = SymExpr::constant(cx, U256::MAX);
1324 let in_range = SymBoolExpr::eq(cx, high.clone(), zero.clone());
1325 let saturated = SymExpr::ite(cx, in_range, low, max);
1326 let negative = SymBoolExpr::cmp(cx, SymCmpOp::Slt, high, zero.clone());
1327 let balance = SymExpr::ite(cx, negative, zero, saturated);
1328 if balance != reverted {
1329 self.set_persistent_balance(cx, executor, address, balance)?;
1330 }
1331 }
1332 for (address, delta) in nonce_deltas {
1333 let previous = self.world.nonce(executor, address)?;
1334 let nonce = if created.contains(&address) {
1335 0
1336 } else {
1337 u64::try_from((i128::from(previous) + delta).max(0)).unwrap_or(u64::MAX)
1338 };
1339 if nonce != previous {
1340 self.set_persistent_nonce(executor, address, nonce)?;
1341 }
1342 }
1343 Ok(())
1344 }
1345}
1346
1347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1348pub(crate) struct SymbolicStorageHook {
1349 pub(crate) callback_target: Address,
1350 pub(crate) callback_selector: [u8; 4],
1351}
1352
1353#[derive(Clone, Debug)]
1358pub(crate) struct UnknownCall {
1359 pub(crate) opcode: u8,
1361 pub(crate) caller: Address,
1363 pub(crate) world: SymExpr,
1365 pub(crate) target: SymExpr,
1366 pub(crate) value: SymExpr,
1367 pub(crate) input_len: SymExpr,
1368 pub(crate) input: SymBytes,
1369 pub(crate) caller_world: SymbolicWorld,
1371 pub(crate) caller_balance: SymExpr,
1372 pub(crate) success: SymExpr,
1373 pub(crate) output_len: SymExpr,
1374 pub(crate) output: SymBytes,
1375 pub(crate) world_after: Option<SymExpr>,
1377 pub(crate) ether_in: Option<SymExpr>,
1379}
1380
1381#[derive(Clone, Debug, PartialEq, Eq)]
1382pub(crate) struct SymbolicLog {
1383 topics: Arc<[SymExpr]>,
1384 data_len: SymExpr,
1385 data: SymBytes,
1386 emitter: Address,
1387}
1388
1389impl SymbolicLog {
1390 pub(crate) fn new(
1391 topics: Vec<SymExpr>,
1392 data_len: SymExpr,
1393 data: SymBytes,
1394 emitter: Address,
1395 ) -> Self {
1396 Self { topics: topics.into(), data_len, data, emitter }
1397 }
1398
1399 pub(crate) fn into_parts(self) -> (Arc<[SymExpr]>, SymExpr, SymBytes, Address) {
1400 (self.topics, self.data_len, self.data, self.emitter)
1401 }
1402
1403 pub(crate) fn has_topics(&self) -> bool {
1404 !self.topics.is_empty()
1405 }
1406}
1407
1408#[derive(Clone, Debug, Default, PartialEq, Eq)]
1409pub(crate) struct AccessRecord {
1410 reads: HashMap<Address, Vec<SymExpr>>,
1411 writes: HashMap<Address, Vec<SymExpr>>,
1412 stopped: bool,
1414}
1415
1416impl AccessRecord {
1417 pub(crate) const fn stop(&mut self) {
1419 self.stopped = true;
1420 }
1421
1422 pub(crate) fn read(&mut self, address: Address, slot: SymExpr) {
1423 self.reads.entry(address).or_default().push(slot);
1424 }
1425
1426 pub(crate) fn write(&mut self, address: Address, slot: SymExpr) {
1427 self.read(address, slot.clone());
1428 self.writes.entry(address).or_default().push(slot);
1429 }
1430
1431 pub(crate) fn addresses(&self) -> Vec<Address> {
1432 let mut addresses = HashSet::<Address>::default();
1433 addresses.extend(self.reads.keys().copied());
1434 addresses.extend(self.writes.keys().copied());
1435 let mut addresses = addresses.into_iter().collect::<Vec<_>>();
1436 addresses.sort_unstable();
1437 addresses
1438 }
1439
1440 pub(crate) fn read_slots(&self, address: Address) -> Vec<SymExpr> {
1441 self.reads.get(&address).cloned().unwrap_or_default()
1442 }
1443
1444 pub(crate) fn write_slots(&self, address: Address) -> Vec<SymExpr> {
1445 self.writes.get(&address).cloned().unwrap_or_default()
1446 }
1447}
1448
1449#[derive(Clone, Debug, PartialEq, Eq)]
1450pub(crate) struct ExpectedRevert {
1451 data: ExpectedRevertData,
1452 reverter: Option<SymExpr>,
1453 count: u64,
1454 remaining: u64,
1455 deeper_frame_ran: bool,
1458}
1459
1460impl ExpectedRevert {
1461 pub(crate) fn new(data: ExpectedRevertData, reverter: Option<SymExpr>, count: u64) -> Self {
1462 let count = count.max(1);
1463 Self { data, reverter, count, remaining: count, deeper_frame_ran: false }
1464 }
1465
1466 pub(crate) const fn has_reverter(&self) -> bool {
1467 self.reverter.is_some()
1468 }
1469
1470 pub(crate) const fn consume_one(&mut self) -> bool {
1471 self.remaining = self.remaining.saturating_sub(1);
1472 self.remaining == 0
1473 }
1474
1475 pub(crate) const fn repeats_with_reverter(&self) -> bool {
1478 self.count > 1 && self.reverter.is_some()
1479 }
1480
1481 pub(crate) const fn reverted_by(
1485 &self,
1486 callee: Option<Address>,
1487 first_failed_callee: Option<Address>,
1488 ) -> Option<Address> {
1489 if self.count > 1 { callee } else { first_failed_callee }
1490 }
1491
1492 pub(crate) const fn matched_any(&self) -> bool {
1494 self.remaining < self.count
1495 }
1496
1497 pub(crate) fn match_condition(
1498 &self,
1499 cx: &mut SymCx,
1500 reverter: Option<Address>,
1501 return_data: &SymReturnData,
1502 ) -> Option<SymBoolExpr> {
1503 let mut conditions = Vec::new();
1504 if let Some(expected_reverter) = &self.reverter
1506 && let Some(reverter) = reverter
1507 {
1508 conditions.push(expected_reverter.address_match_condition(cx, reverter));
1509 }
1510 match &self.data {
1511 ExpectedRevertData::Any => {}
1512 ExpectedRevertData::Prefix(prefix) => {
1513 if return_data.len() < prefix.len() {
1514 return None;
1515 }
1516 let prefix_len = SymExpr::constant(cx, U256::from(prefix.len()));
1517 conditions.push(SymBoolExpr::cmp_word_expr(
1518 cx,
1519 SymCmpOp::Uge,
1520 &return_data.len_word,
1521 prefix_len,
1522 ));
1523 conditions.extend((0..prefix.len()).map(|offset| {
1524 let expected = prefix.byte(cx, offset);
1525 let actual = return_data.byte(cx, offset);
1526 SymBoolExpr::eq(cx, actual, expected)
1527 }));
1528 }
1529 ExpectedRevertData::Exact(data) => {
1530 let message = SymbolicAbiValue::String { bytes: data.clone() };
1533 let message = encode_sequence(cx, [&message]);
1534 let mut candidates = vec![data.clone()];
1535 for selector in [Revert::SELECTOR, Vm::CheatcodeError::SELECTOR] {
1536 let selector = SymBytes::concrete(cx, selector.to_vec());
1537 candidates.push(SymBytes::concat(cx, [selector, message.clone()]));
1538 }
1539 let mut matches = Vec::new();
1540 for candidate in candidates {
1541 if let Some(bytes_match) = return_data.bytes.prefix_condition(cx, &candidate) {
1542 let len = SymExpr::constant(cx, U256::from(candidate.len()));
1543 let len_match = SymBoolExpr::eq(cx, return_data.len_word.clone(), len);
1544 matches.push(SymBoolExpr::and(cx, vec![len_match, bytes_match]));
1545 }
1546 }
1547 if matches.is_empty() {
1548 return None;
1549 }
1550 conditions.push(SymBoolExpr::or(cx, matches));
1551 }
1552 }
1553 Some(SymBoolExpr::and(cx, conditions))
1554 }
1555
1556 pub(crate) fn mismatch_error(
1560 &self,
1561 reverted_by: Option<Address>,
1562 retdata: &Bytes,
1563 known_contracts: &Option<ContractsByArtifact>,
1564 ) -> Option<Error> {
1565 let (reason, partial_match) = match &self.data {
1566 ExpectedRevertData::Any => (None, false),
1567 ExpectedRevertData::Prefix(data) => (Some(data.as_concrete_slice()?), true),
1568 ExpectedRevertData::Exact(data) => (Some(data.as_concrete_slice()?), false),
1569 };
1570 let reverter = match &self.reverter {
1571 Some(reverter) => Some(word_to_address(reverter.as_const()?)),
1572 None => None,
1573 };
1574 expect_revert_mismatch(
1575 reason,
1576 partial_match,
1577 reverter,
1578 reverted_by,
1579 retdata,
1580 known_contracts,
1581 )
1582 }
1583
1584 pub(crate) const fn mark_deeper_frame_ran(&mut self) {
1585 self.deeper_frame_ran = true;
1586 }
1587
1588 pub(crate) const fn deeper_frame_ran(&self) -> bool {
1589 self.deeper_frame_ran
1590 }
1591}
1592
1593#[derive(Clone, Debug, PartialEq, Eq)]
1594pub(crate) enum ExpectedRevertData {
1595 Any,
1596 Prefix(SymBytes),
1597 Exact(SymBytes),
1598}
1599
1600#[derive(Clone, Debug, PartialEq, Eq)]
1601pub(crate) struct AssumeNoRevert {
1602 pub(crate) filters: Option<Vec<ExpectedRevert>>,
1603 pub(crate) reverted_by: Option<Address>,
1604}
1605
1606#[derive(Clone, Debug, PartialEq, Eq)]
1607pub(crate) struct ExpectedCall {
1608 callee: SymExpr,
1609 value: Option<U256>,
1610 gas: Option<u64>,
1611 min_gas: Option<u64>,
1612 data: SymBytes,
1613 expected: u64,
1614 observed: u64,
1615 exact: bool,
1616}
1617
1618#[derive(Clone, Debug, PartialEq, Eq)]
1619pub(crate) struct ExpectedCreate {
1620 bytecode: Vec<u8>,
1621 deployer: SymExpr,
1622 kind: CreateKind,
1623}
1624
1625impl ExpectedCreate {
1626 pub(crate) const fn new(bytecode: Vec<u8>, deployer: SymExpr, kind: CreateKind) -> Self {
1627 Self { bytecode, deployer, kind }
1628 }
1629
1630 pub(crate) fn match_condition(
1631 &self,
1632 cx: &mut SymCx,
1633 deployer: Address,
1634 kind: CreateKind,
1635 bytecode: &[u8],
1636 ) -> Option<SymBoolExpr> {
1637 if self.bytecode != bytecode {
1638 return None;
1639 }
1640 self.deployer_match_condition(cx, deployer, kind)
1641 }
1642
1643 pub(crate) fn deployer_match_condition(
1644 &self,
1645 cx: &mut SymCx,
1646 deployer: Address,
1647 kind: CreateKind,
1648 ) -> Option<SymBoolExpr> {
1649 (self.kind == kind).then(|| self.deployer.address_match_condition(cx, deployer))
1650 }
1651}
1652
1653impl ExpectedCall {
1654 pub(crate) fn new(
1655 callee: SymExpr,
1656 value: Option<U256>,
1657 gas: Option<u64>,
1658 min_gas: Option<u64>,
1659 data: SymBytes,
1660 count: Option<u64>,
1661 ) -> Self {
1662 let (gas, min_gas) = if value.is_some_and(|value| !value.is_zero()) {
1663 (
1664 gas.map(|gas| gas.saturating_add(CALL_STIPEND.into())),
1665 min_gas.map(|gas| gas.saturating_add(CALL_STIPEND.into())),
1666 )
1667 } else {
1668 (gas, min_gas)
1669 };
1670 Self {
1671 callee,
1672 value,
1673 gas,
1674 min_gas,
1675 data,
1676 expected: count.unwrap_or(1),
1677 observed: 0,
1678 exact: count.is_some(),
1679 }
1680 }
1681
1682 pub(crate) const fn value(&self) -> Option<U256> {
1683 self.value
1684 }
1685
1686 pub(crate) fn match_condition(
1687 &self,
1688 cx: &mut SymCx,
1689 callee: Address,
1690 value: Option<U256>,
1691 gas: &SymExpr,
1692 calldata: &SymBytes,
1693 ) -> Result<Option<SymBoolExpr>, SymbolicError> {
1694 if !self.value.is_none_or(|expected| value.is_some_and(|value| expected == value))
1695 || !self.gas_matches(gas, value)?
1696 {
1697 return Ok(None);
1698 }
1699 let Some(data_condition) = calldata.prefix_condition(cx, &self.data) else {
1700 return Ok(None);
1701 };
1702 let callee_condition = self.callee.address_match_condition(cx, callee);
1703 Ok(Some(SymBoolExpr::and(cx, vec![callee_condition, data_condition])))
1704 }
1705
1706 fn gas_matches(&self, gas: &SymExpr, value: Option<U256>) -> Result<bool, SymbolicError> {
1707 if self.gas.is_none() && self.min_gas.is_none() {
1708 return Ok(true);
1709 }
1710 let mut gas = gas.as_const_or("symbolic expected call gas")?;
1711 if value.is_some_and(|value| !value.is_zero()) {
1712 gas = gas.saturating_add(U256::from(CALL_STIPEND));
1713 }
1714 Ok(self.gas.is_none_or(|expected| gas == U256::from(expected))
1715 && self.min_gas.is_none_or(|expected| gas >= U256::from(expected)))
1716 }
1717
1718 pub(crate) const fn observe(&mut self) -> bool {
1719 if self.exact && self.observed >= self.expected {
1720 return false;
1721 }
1722 self.observed = self.observed.saturating_add(1);
1723 true
1724 }
1725
1726 pub(crate) const fn is_satisfied(&self) -> bool {
1727 if self.exact { self.observed == self.expected } else { self.observed >= self.expected }
1728 }
1729}
1730
1731pub(crate) fn register_expected_call(
1733 expected_calls: &mut Vec<ExpectedCall>,
1734 cx: &mut SymCx,
1735 expected: ExpectedCall,
1736) -> Result<(), &'static str> {
1737 if let Some(existing) = expected_calls
1738 .iter_mut()
1739 .find(|call| call.callee == expected.callee && call.data.same_bytes(cx, &expected.data))
1740 {
1741 if expected.exact {
1742 return Err("counted expected calls can only bet set once");
1743 }
1744 if existing.exact {
1745 return Err("cannot overwrite a counted expectCall with a non-counted expectCall");
1746 }
1747 existing.expected += 1;
1748 } else {
1749 expected_calls.push(expected);
1750 }
1751 Ok(())
1752}
1753
1754#[derive(Clone, Debug)]
1755pub(crate) struct CallMock {
1756 pub(crate) callee: SymExpr,
1757 value: Option<U256>,
1758 pub(crate) data: SymBytes,
1759 returns: Vec<SymReturnData>,
1760 reverts: bool,
1761 calls: usize,
1762}
1763
1764impl CallMock {
1765 pub(crate) const fn new(
1766 callee: SymExpr,
1767 value: Option<U256>,
1768 data: SymBytes,
1769 returns: Vec<SymReturnData>,
1770 reverts: bool,
1771 ) -> Self {
1772 Self { callee, value, data, returns, reverts, calls: 0 }
1773 }
1774
1775 pub(crate) const fn value(&self) -> Option<U256> {
1776 self.value
1777 }
1778
1779 pub(crate) fn specificity(&self) -> (usize, bool) {
1780 (self.data.len(), self.value.is_some())
1781 }
1782
1783 pub(crate) const fn answers(&self) -> bool {
1786 !self.returns.is_empty()
1787 }
1788
1789 pub(crate) fn match_condition(
1790 &self,
1791 cx: &mut SymCx,
1792 callee: Address,
1793 value: Option<U256>,
1794 calldata: &SymBytes,
1795 ) -> Option<SymBoolExpr> {
1796 if !self.value.is_none_or(|expected| value.is_some_and(|value| expected == value)) {
1797 return None;
1798 }
1799 let data_condition = calldata.prefix_condition(cx, &self.data)?;
1800 let callee_condition = self.callee.address_match_condition(cx, callee);
1801 Some(SymBoolExpr::and(cx, vec![callee_condition, data_condition]))
1802 }
1803
1804 pub(crate) fn next_outcome(&mut self, cx: &mut SymCx) -> CallMockOutcome {
1805 let idx = self.calls.min(self.returns.len().saturating_sub(1));
1806 self.calls = self.calls.saturating_add(1);
1807 CallMockOutcome {
1808 return_data: self.returns.get(idx).cloned().unwrap_or_else(|| SymReturnData::empty(cx)),
1809 reverts: self.reverts,
1810 }
1811 }
1812}
1813
1814#[derive(Clone, Debug)]
1815pub(crate) struct CallMockOutcome {
1816 return_data: SymReturnData,
1817 reverts: bool,
1818}
1819
1820impl CallMockOutcome {
1821 pub(crate) fn into_parts(self) -> (SymReturnData, bool) {
1822 (self.return_data, self.reverts)
1823 }
1824}
1825
1826#[derive(Clone, Debug, PartialEq, Eq)]
1827pub(crate) struct FunctionMock {
1828 callee: SymExpr,
1829 target: Address,
1830 data: SymBytes,
1831}
1832
1833impl FunctionMock {
1834 pub(crate) const fn new(callee: SymExpr, target: Address, data: SymBytes) -> Self {
1835 Self { callee, target, data }
1836 }
1837
1838 pub(crate) fn matches_definition(
1839 &self,
1840 cx: &mut SymCx,
1841 callee: &SymExpr,
1842 data: &SymBytes,
1843 ) -> bool {
1844 self.callee == *callee && self.data.same_bytes(cx, data)
1845 }
1846
1847 pub(crate) const fn set_target(&mut self, target: Address) {
1848 self.target = target;
1849 }
1850
1851 pub(crate) fn calldata_len(&self) -> usize {
1852 self.data.len()
1853 }
1854
1855 pub(crate) const fn target(&self) -> Address {
1856 self.target
1857 }
1858
1859 pub(crate) fn code_match_condition(
1862 &self,
1863 cx: &mut SymCx,
1864 code_address: &SymExpr,
1865 calldata: &SymBytes,
1866 ) -> Option<SymBoolExpr> {
1867 if self.data.len() != calldata.len() && self.data.len() != 4 {
1868 return None;
1869 }
1870 let data_condition = calldata.prefix_condition(cx, &self.data)?;
1871 let callee_condition = SymBoolExpr::eq(cx, self.callee.clone(), code_address.clone());
1872 Some(SymBoolExpr::and(cx, vec![callee_condition, data_condition]))
1873 }
1874
1875 pub(crate) fn match_condition(
1876 &self,
1877 cx: &mut SymCx,
1878 callee: Address,
1879 calldata: &SymBytes,
1880 ) -> Option<SymBoolExpr> {
1881 let data_condition = calldata.prefix_condition(cx, &self.data)?;
1882 let callee_condition = self.callee.address_match_condition(cx, callee);
1883 Some(SymBoolExpr::and(cx, vec![callee_condition, data_condition]))
1884 }
1885}
1886
1887#[derive(Clone, Debug, PartialEq, Eq)]
1888pub(crate) struct ExpectedEmit {
1889 checks: ExpectedEmitChecks,
1890 emitter: Option<SymExpr>,
1891 remaining: u64,
1892 template: Option<SymbolicLog>,
1893 anonymous: bool,
1895 depth: usize,
1897 failed: bool,
1899}
1900
1901impl ExpectedEmit {
1902 pub(crate) const fn new(
1903 checks: ExpectedEmitChecks,
1904 emitter: Option<SymExpr>,
1905 remaining: u64,
1906 anonymous: bool,
1907 depth: usize,
1908 ) -> Self {
1909 Self { checks, emitter, remaining, template: None, anonymous, depth, failed: false }
1910 }
1911
1912 pub(crate) const fn failed(&self) -> bool {
1914 self.failed
1915 }
1916
1917 pub(crate) const fn is_forbidden(&self) -> bool {
1922 self.remaining == 0
1923 }
1924
1925 pub(crate) const fn is_anonymous(&self) -> bool {
1927 self.anonymous
1928 }
1929
1930 pub(crate) const fn template(&self) -> Option<&SymbolicLog> {
1931 self.template.as_ref()
1932 }
1933
1934 pub(crate) fn set_template(&mut self, log: SymbolicLog) {
1935 self.template = Some(log);
1936 }
1937
1938 pub(crate) const fn consume_one(&mut self) -> bool {
1940 self.remaining = self.remaining.saturating_sub(1);
1941 self.remaining == 0
1942 }
1943
1944 pub(crate) fn match_condition(
1945 &self,
1946 cx: &mut SymCx,
1947 template: &SymbolicLog,
1948 actual: &SymbolicLog,
1949 ) -> Option<SymBoolExpr> {
1950 let mut conditions = Vec::new();
1951 if let Some(expected_emitter) = &self.emitter {
1952 conditions.push(expected_emitter.address_match_condition(cx, actual.emitter));
1953 }
1954 if template.topics.len() != actual.topics.len() {
1956 return Some(SymBoolExpr::constant(cx, false));
1957 }
1958 for ((left, right), check) in
1959 template.topics.iter().zip(actual.topics.iter()).zip(self.checks.topics)
1960 {
1961 if check {
1962 conditions.push(SymBoolExpr::eq(cx, left.clone(), right.clone()));
1963 }
1964 }
1965
1966 if self.checks.data {
1967 conditions.push(SymBoolExpr::eq(
1968 cx,
1969 template.data_len.clone(),
1970 actual.data_len.clone(),
1971 ));
1972 if template.data.len() != actual.data.len() {
1973 let concrete =
1976 template.data_len.as_const().is_some() && actual.data_len.as_const().is_some();
1977 return concrete.then(|| SymBoolExpr::constant(cx, false));
1978 }
1979 conditions.extend((0..template.data.len()).map(|idx| {
1980 let template = template.data.byte(cx, idx);
1981 let actual = actual.data.byte(cx, idx);
1982 SymBoolExpr::eq(cx, template, actual)
1983 }));
1984 }
1985
1986 Some(SymBoolExpr::and(cx, conditions))
1987 }
1988}
1989
1990#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1991pub(crate) struct ExpectedEmitChecks {
1992 topics: [bool; 4],
1993 data: bool,
1994}
1995
1996impl Default for ExpectedEmitChecks {
1997 fn default() -> Self {
1998 Self { topics: [true; 4], data: true }
1999 }
2000}
2001
2002impl ExpectedEmitChecks {
2003 pub(crate) fn from_non_anonymous_args(
2004 cx: &mut SymCx,
2005 memory: &SymMemory,
2006 args_offset: usize,
2007 ) -> Result<Self, SymbolicError> {
2008 Ok(Self {
2009 topics: [
2010 true,
2011 read_abi_bool_arg(cx, memory, args_offset, 0, "symbolic vm.expectEmit")?,
2012 read_abi_bool_arg(cx, memory, args_offset, 1, "symbolic vm.expectEmit")?,
2013 read_abi_bool_arg(cx, memory, args_offset, 2, "symbolic vm.expectEmit")?,
2014 ],
2015 data: read_abi_bool_arg(cx, memory, args_offset, 3, "symbolic vm.expectEmit")?,
2016 })
2017 }
2018
2019 pub(crate) fn from_anonymous_args(
2020 cx: &mut SymCx,
2021 memory: &SymMemory,
2022 args_offset: usize,
2023 ) -> Result<Self, SymbolicError> {
2024 Ok(Self {
2025 topics: [
2026 read_abi_bool_arg(cx, memory, args_offset, 0, "symbolic vm.expectEmitAnonymous")?,
2027 read_abi_bool_arg(cx, memory, args_offset, 1, "symbolic vm.expectEmitAnonymous")?,
2028 read_abi_bool_arg(cx, memory, args_offset, 2, "symbolic vm.expectEmitAnonymous")?,
2029 read_abi_bool_arg(cx, memory, args_offset, 3, "symbolic vm.expectEmitAnonymous")?,
2030 ],
2031 data: read_abi_bool_arg(cx, memory, args_offset, 4, "symbolic vm.expectEmitAnonymous")?,
2032 })
2033 }
2034}
2035
2036impl Deref for PathState {
2037 type Target = CallFrame;
2038
2039 fn deref(&self) -> &Self::Target {
2040 &self.frame
2041 }
2042}
2043
2044impl DerefMut for PathState {
2045 fn deref_mut(&mut self) -> &mut Self::Target {
2046 &mut self.frame
2047 }
2048}
2049
2050#[derive(Clone, Debug)]
2051pub(crate) struct CallFrame {
2052 pub(crate) pc: usize,
2053 pub(crate) address: Address,
2054 pub(crate) address_word: SymExpr,
2055 pub(crate) storage_address: Address,
2056 pub(crate) caller: Address,
2057 pub(crate) caller_word: SymExpr,
2058 pub(crate) callvalue: SymExpr,
2059 pub(crate) is_static: bool,
2060 pub(crate) is_constructor: bool,
2061 pub(crate) calldata: SymCalldata,
2062 pub(crate) stack: SymStack,
2063 pub(crate) memory: SymMemory,
2064 pub(crate) return_data: SymReturnData,
2065}
2066
2067impl CallFrame {
2068 pub(crate) fn new(
2069 cx: &mut SymCx,
2070 address: Address,
2071 storage_address: Address,
2072 caller: Address,
2073 callvalue: SymExpr,
2074 is_static: bool,
2075 calldata: SymCalldata,
2076 ) -> Self {
2077 Self {
2078 pc: 0,
2079 address,
2080 address_word: SymExpr::constant(cx, address_word(address)),
2081 storage_address,
2082 caller,
2083 caller_word: SymExpr::constant(cx, address_word(caller)),
2084 callvalue,
2085 is_static,
2086 is_constructor: false,
2087 calldata,
2088 stack: SymStack::default(),
2089 memory: SymMemory::default(),
2090 return_data: SymReturnData::empty(cx),
2091 }
2092 }
2093}
2094
2095#[derive(Clone, Debug, Default, PartialEq, Eq)]
2096pub(crate) struct SymbolicPrank {
2097 next_caller: Option<(Address, SymExpr)>,
2098 next_origin: Option<(Address, SymExpr)>,
2099 persistent_caller: Option<(Address, SymExpr)>,
2100 persistent_origin: Option<(Address, SymExpr)>,
2101 persistent_used: bool,
2103 pub(crate) inherited: Option<(U256, SymExpr, SymExpr)>,
2106}
2107
2108impl SymbolicPrank {
2109 pub(crate) fn set_next(
2110 &mut self,
2111 caller: (Address, SymExpr),
2112 origin: Option<(Address, SymExpr)>,
2113 ) {
2114 self.next_caller = Some(caller);
2115 self.next_origin = origin;
2116 }
2117
2118 pub(crate) fn set_persistent(
2119 &mut self,
2120 caller: (Address, SymExpr),
2121 origin: Option<(Address, SymExpr)>,
2122 ) {
2123 self.persistent_caller = Some(caller);
2124 self.persistent_origin = origin;
2125 self.persistent_used = false;
2126 }
2127
2128 pub(crate) const fn overwrite_error(&self, persistent: bool) -> Option<&'static str> {
2131 if self.next_caller.is_some() || (self.persistent_caller.is_some() && !self.persistent_used)
2132 {
2133 Some("cannot overwrite a prank until it is applied at least once")
2134 } else if self.persistent_caller.is_some() && !persistent {
2135 Some(
2136 "cannot override an ongoing prank with a single vm.prank; use vm.startPrank to \
2137 override the current prank",
2138 )
2139 } else {
2140 None
2141 }
2142 }
2143
2144 pub(crate) fn stop(&mut self) {
2146 *self = Self { inherited: self.inherited.take(), ..Self::default() };
2147 }
2148
2149 pub(crate) const fn has_active(&self) -> bool {
2150 self.next_caller.is_some()
2151 || self.next_origin.is_some()
2152 || self.persistent_caller.is_some()
2153 || self.persistent_origin.is_some()
2154 }
2155
2156 pub(crate) fn words(&self) -> impl Iterator<Item = &SymExpr> {
2158 [&self.next_caller, &self.next_origin, &self.persistent_caller, &self.persistent_origin]
2159 .into_iter()
2160 .flatten()
2161 .map(|(_, word)| word)
2162 }
2163}
2164
2165#[derive(Clone, Debug, PartialEq, Eq)]
2166pub(crate) struct StorageWrite {
2167 address: Address,
2168 key: SymExpr,
2169 value: SymExpr,
2170 guard: Option<SymBoolExpr>,
2173}
2174
2175impl StorageWrite {
2176 pub(crate) const fn new(address: Address, key: SymExpr, value: SymExpr) -> Self {
2177 Self { address, key, value, guard: None }
2178 }
2179
2180 pub(crate) fn select_from(
2181 cx: &mut SymCx,
2182 writes: &[Self],
2183 address: Address,
2184 key: SymExpr,
2185 base: SymExpr,
2186 ) -> SymExpr {
2187 let mut value = base;
2188 for write in writes.iter().filter(|write| write.address == address) {
2189 let write_value = match &write.guard {
2190 Some(guard) => SymExpr::ite(cx, guard.clone(), write.value.clone(), value.clone()),
2191 None => write.value.clone(),
2192 };
2193 value = key.clone().select_storage_write(cx, write.key.clone(), write_value, value);
2194 }
2195 value
2196 }
2197}
2198
2199#[derive(Clone, Debug, Default)]
2201pub(crate) struct SymbolicWorldState {
2202 storage: Vec<StorageWrite>,
2203 transient_storage: Vec<StorageWrite>,
2204 created_accounts: HashSet<Address>,
2205 current_transaction_created_accounts: HashSet<Address>,
2206 balances: HashMap<Address, SymExpr>,
2207 code_cache: HashMap<Address, SymCode>,
2208 written_code: HashSet<Address>,
2210 nonces: HashMap<Address, u64>,
2211 existing_accounts: HashSet<Address>,
2212 destroyed_accounts: HashSet<Address>,
2213 pending_selfdestructs: HashSet<Address>,
2214 arbitrary_storage_accounts: HashMap<Address, bool>,
2215 arbitrary_storage_copies: HashMap<Address, Address>,
2216 arbitrary_storage_all: bool,
2217 zero_init_symbolic_storage: bool,
2218 symbolic_key_base_reads: HashMap<(Address, SymExpr), SymExpr>,
2221 symbolic_accounts: bool,
2224 symbolic_address_aliases: HashMap<SymExpr, Address>,
2225 guarded_symbolic_addresses: HashMap<SymExpr, BTreeSet<Address>>,
2229 replay_storage_slots: HashMap<Symbol, Vec<SymbolicReplayStorageSlot>>,
2230 replay_symbolic_storage_keys: HashMap<Symbol, Vec<(Address, SymExpr)>>,
2231}
2232
2233#[derive(Clone, Debug)]
2234struct SymbolicReplayStorageSlot {
2235 address: Address,
2236 slot: U256,
2237}
2238
2239#[derive(Clone, Debug)]
2242struct SymbolicSnapshot {
2243 state: Arc<SymbolicWorldState>,
2244 block: SymbolicBlock,
2245 gas_price: SymExpr,
2246}
2247
2248#[derive(Clone, Debug, Default)]
2249pub(crate) struct SymbolicWorld {
2250 state: Arc<SymbolicWorldState>,
2251 snapshots: HashMap<U256, SymbolicSnapshot>,
2252 next_snapshot_id: u64,
2253}
2254
2255impl SymbolicWorldState {
2256 fn apply_pending_selfdestructs(&mut self, cx: &mut SymCx) {
2258 for address in std::mem::take(&mut self.pending_selfdestructs) {
2259 self.balances.insert(address, SymExpr::zero(cx));
2260 self.nonces.insert(address, 0);
2261 self.code_cache.insert(address, SymCode::empty(cx));
2262 self.written_code.insert(address);
2263 self.storage.retain(|write| write.address != address);
2264 self.transient_storage.retain(|write| write.address != address);
2265 self.created_accounts.insert(address);
2267 self.existing_accounts.remove(&address);
2268 self.destroyed_accounts.insert(address);
2269 }
2270 }
2271}
2272
2273impl Deref for SymbolicWorld {
2274 type Target = SymbolicWorldState;
2275
2276 fn deref(&self) -> &Self::Target {
2277 &self.state
2278 }
2279}
2280
2281impl SymbolicWorld {
2282 pub(crate) fn is_destroyed(&self, address: Address) -> bool {
2283 self.destroyed_accounts.contains(&address)
2284 }
2285
2286 pub(crate) fn set_storage_layout(&mut self, layout: SymbolicStorageLayout) {
2287 let state = Arc::make_mut(&mut self.state);
2288 state.arbitrary_storage_all = matches!(layout, SymbolicStorageLayout::Generic);
2289 state.zero_init_symbolic_storage = matches!(layout, SymbolicStorageLayout::ZeroInit);
2290 }
2291
2292 pub(crate) fn sload(
2293 &mut self,
2294 cx: &mut SymCx,
2295 executor: &ExecutorView<'_>,
2296 address: Address,
2297 key: SymExpr,
2298 concrete_key: Option<U256>,
2299 ) -> Result<SymExpr, SymbolicError> {
2300 let base = self.storage_base(cx, executor, address, &key, concrete_key)?;
2301 let read_key = concrete_key.map(|key| SymExpr::constant(cx, key)).unwrap_or(key);
2302 Ok(StorageWrite::select_from(cx, &self.storage, address, read_key, base))
2303 }
2304
2305 pub(crate) fn sstore(&mut self, address: Address, key: SymExpr, value: SymExpr) {
2306 Arc::make_mut(&mut self.state).storage.push(StorageWrite::new(address, key, value));
2307 }
2308
2309 pub(crate) fn guarded_sstore(
2311 &mut self,
2312 address: Address,
2313 key: SymExpr,
2314 value: SymExpr,
2315 guard: SymBoolExpr,
2316 ) {
2317 let write = StorageWrite { address, key, value, guard: Some(guard) };
2318 Arc::make_mut(&mut self.state).storage.push(write);
2319 }
2320
2321 pub(crate) fn global_fail_slot(
2323 &self,
2324 cx: &mut SymCx,
2325 executor: &ExecutorView<'_>,
2326 ) -> Result<SymExpr, SymbolicError> {
2327 let base = executor
2328 .backend
2329 .storage(CHEATCODE_ADDRESS, GLOBAL_FAIL_SLOT)
2330 .map(|value| SymExpr::constant(cx, value))
2331 .map_err(|err| SymbolicError::Backend(err.to_string()))?;
2332 let key = SymExpr::constant(cx, GLOBAL_FAIL_SLOT);
2333 Ok(StorageWrite::select_from(cx, &self.storage, CHEATCODE_ADDRESS, key, base))
2334 }
2335
2336 pub(crate) fn storage_write_keys(&self, address: Address) -> Vec<SymExpr> {
2338 let mut keys = Vec::new();
2339 for write in self.storage.iter().filter(|write| write.address == address) {
2340 if !keys.contains(&write.key) {
2341 keys.push(write.key.clone());
2342 }
2343 }
2344 keys
2345 }
2346
2347 pub(crate) fn balance_addresses(&self) -> Vec<Address> {
2349 let mut addresses = self.balances.keys().copied().collect::<Vec<_>>();
2350 for address in &self.destroyed_accounts {
2351 if !addresses.contains(address) {
2352 addresses.push(*address);
2353 }
2354 }
2355 addresses
2356 }
2357
2358 pub(crate) fn storage_write_addresses(&self) -> Vec<Address> {
2360 let mut addresses = Vec::new();
2361 for write in &self.storage {
2362 if !addresses.contains(&write.address) {
2363 addresses.push(write.address);
2364 }
2365 }
2366 addresses
2367 }
2368
2369 pub(crate) fn nonce_addresses(&self) -> Vec<Address> {
2371 self.nonces.keys().copied().collect()
2372 }
2373
2374 pub(crate) fn created_account_addresses(&self) -> Vec<Address> {
2376 self.created_accounts.iter().copied().collect()
2377 }
2378
2379 pub(crate) fn enable_symbolic_accounts(&mut self) {
2381 Arc::make_mut(&mut self.state).symbolic_accounts = true;
2382 }
2383
2384 pub(crate) fn alias_symbolic_address(&mut self, word: SymExpr, address: Address) {
2386 Arc::make_mut(&mut self.state).symbolic_address_aliases.insert(word, address);
2387 }
2388
2389 pub(crate) fn is_unknown_account(
2391 &mut self,
2392 cx: &mut SymCx,
2393 executor: &ExecutorView<'_>,
2394 address: Address,
2395 ) -> Result<bool, SymbolicError> {
2396 if !self.symbolic_accounts
2397 || self.created_accounts.contains(&address)
2398 || self.destroyed_accounts.contains(&address)
2399 || address == CHEATCODE_ADDRESS
2400 || address == SYMBOLIC_VM_COMPAT_ADDRESS
2401 || address == HARDHAT_CONSOLE_ADDRESS
2402 || is_precompile_for_spec(address, executor.spec_id)
2403 {
2404 return Ok(false);
2405 }
2406 Ok(self.extcode(cx, executor, address)?.is_empty())
2407 }
2408
2409 pub(crate) fn tload(&self, cx: &mut SymCx, address: Address, key: SymExpr) -> SymExpr {
2410 let base = SymExpr::zero(cx);
2411 StorageWrite::select_from(cx, &self.transient_storage, address, key, base)
2412 }
2413
2414 pub(crate) fn tstore(&mut self, address: Address, key: SymExpr, value: SymExpr) {
2415 Arc::make_mut(&mut self.state)
2416 .transient_storage
2417 .push(StorageWrite::new(address, key, value));
2418 }
2419
2420 pub(crate) fn clear_transaction_scoped_state(&mut self, cx: &mut SymCx) {
2422 let state = Arc::make_mut(&mut self.state);
2423 state.apply_pending_selfdestructs(cx);
2424 state.transient_storage.clear();
2425 state.current_transaction_created_accounts.clear();
2426 }
2427
2428 pub(crate) fn clear_transient_storage(&mut self) {
2430 if !self.transient_storage.is_empty() {
2431 Arc::make_mut(&mut self.state).transient_storage.clear();
2432 }
2433 }
2434
2435 pub(crate) fn restore_transient_storage(&mut self, outer: &Self) {
2437 if !self.transient_storage.is_empty() || !outer.transient_storage.is_empty() {
2438 Arc::make_mut(&mut self.state).transient_storage = outer.transient_storage.clone();
2439 }
2440 }
2441
2442 pub(crate) fn mark_current_transaction_created(&mut self, address: Address) {
2443 let state = Arc::make_mut(&mut self.state);
2444 state.created_accounts.insert(address);
2445 state.current_transaction_created_accounts.insert(address);
2446 }
2447
2448 pub(crate) fn was_created_in_current_transaction(&self, address: Address) -> bool {
2450 self.current_transaction_created_accounts.contains(&address)
2451 }
2452
2453 pub(crate) fn enable_arbitrary_storage(&mut self, address: Address, overwrite: bool) {
2454 Arc::make_mut(&mut self.state).arbitrary_storage_accounts.insert(address, overwrite);
2455 }
2456
2457 pub(crate) fn replay_storage_symbols(&self) -> SymbolicVars {
2458 self.replay_storage_slots
2459 .keys()
2460 .chain(self.replay_symbolic_storage_keys.keys())
2461 .copied()
2462 .collect()
2463 }
2464
2465 pub(crate) fn replay_storage_assignments(
2469 &self,
2470 model: &SymbolicModel,
2471 reject_aliases: bool,
2472 ) -> Result<Vec<SymbolicStorageAssignment>, SymbolicError> {
2473 let mut assignments = std::collections::BTreeMap::<(Address, U256), U256>::new();
2474 let mut assign = |address, slot, value, reject_conflict: bool| match assignments
2475 .entry((address, slot))
2476 {
2477 std::collections::btree_map::Entry::Vacant(entry) => {
2478 entry.insert(value);
2479 Ok(())
2480 }
2481 std::collections::btree_map::Entry::Occupied(entry)
2482 if *entry.get() == value || !reject_conflict =>
2483 {
2484 Ok(())
2485 }
2486 std::collections::btree_map::Entry::Occupied(_) => Err(SymbolicError::Solver(
2487 "conflicting symbolic storage replay assignments".to_string(),
2488 )),
2489 };
2490 for (symbol, slots) in &self.replay_storage_slots {
2491 let Some(value) = model.get(symbol).copied() else { continue };
2492 for slot in slots {
2493 assign(slot.address, slot.slot, value, true)?;
2494 }
2495 }
2496 for (symbol, reads) in &self.replay_symbolic_storage_keys {
2497 let Some(value) = model.get(symbol).copied() else { continue };
2498 for (address, key) in reads {
2499 if let Some(slot) = key.eval_model_if_complete(model)? {
2500 assign(*address, slot, value, reject_aliases)?;
2501 }
2502 }
2503 }
2504 Ok(assignments
2505 .into_iter()
2506 .map(|((address, slot), value)| SymbolicStorageAssignment { address, slot, value })
2507 .collect())
2508 }
2509
2510 pub(crate) fn resolve_address(&self, expr: &SymExpr) -> Option<Address> {
2511 expr.as_const().map(word_to_address).or_else(|| {
2512 self.alias_entry(expr)
2513 .filter(|(alias, _)| !self.guarded_symbolic_addresses.contains_key(*alias))
2514 .map(|(_, address)| address)
2515 })
2516 }
2517
2518 fn alias_entry(&self, expr: &SymExpr) -> Option<(&SymExpr, Address)> {
2520 self.symbolic_address_aliases
2521 .get_key_value(expr)
2522 .map(|(alias, address)| (alias, *address))
2523 .or_else(|| {
2524 self.symbolic_address_aliases
2525 .iter()
2526 .find(|(alias, _)| expr.symbolic_address_equivalent(alias))
2527 .map(|(alias, address)| (alias, *address))
2528 })
2529 }
2530
2531 pub(crate) fn symbolic_address_slot(&mut self, expr: SymExpr) -> Address {
2532 if let Some(address) = expr.as_const().map(word_to_address) {
2533 return address;
2534 }
2535 if let Some((_, address)) = self.alias_entry(&expr) {
2536 return address;
2537 }
2538 let address = expr.representative_symbolic_address();
2539 Arc::make_mut(&mut self.state).symbolic_address_aliases.insert(expr, address);
2540 address
2541 }
2542
2543 pub(crate) fn guard_symbolic_address(&mut self, expr: &SymExpr, candidates: &[Address]) {
2546 let Some((alias, _)) = self.alias_entry(expr) else { return };
2547 let alias = alias.clone();
2548 Arc::make_mut(&mut self.state)
2549 .guarded_symbolic_addresses
2550 .entry(alias)
2551 .or_default()
2552 .extend(candidates);
2553 }
2554
2555 pub(crate) fn has_guarded_addresses(&self) -> bool {
2557 !self.guarded_symbolic_addresses.is_empty()
2558 }
2559
2560 pub(crate) fn guarded_words_in(&self, expr: &SymExpr) -> Vec<(SymExpr, Vec<Address>)> {
2564 if !self.has_guarded_addresses() {
2565 return Vec::new();
2566 }
2567 let mut vars = SymbolicVars::default();
2568 expr.collect_eval_vars(&mut vars);
2569 if vars.is_empty() {
2570 return Vec::new();
2571 }
2572 let mut words = self
2573 .guarded_symbolic_addresses
2574 .iter()
2575 .filter(|(word, _)| {
2576 let mut word_vars = SymbolicVars::default();
2577 word.collect_eval_vars(&mut word_vars);
2578 word_vars.iter().any(|var| vars.contains(var))
2579 })
2580 .map(|(word, candidates)| {
2581 let representative = self.symbolic_address_aliases.get(word).copied();
2582 (representative, word.clone(), candidates.iter().copied().collect())
2583 })
2584 .collect::<Vec<_>>();
2585 words.sort_by_key(|(representative, ..)| *representative);
2586 words.into_iter().map(|(_, word, candidates)| (word, candidates)).collect()
2587 }
2588
2589 pub(crate) fn exclude_guarded_candidates(&mut self, expr: &SymExpr, excluded: &[Address]) {
2592 let Some((alias, _)) = self.alias_entry(expr) else { return };
2593 let alias = alias.clone();
2594 let state = Arc::make_mut(&mut self.state);
2595 let Some(guarded) = state.guarded_symbolic_addresses.get_mut(&alias) else { return };
2596 guarded.retain(|address| !excluded.contains(address));
2597 if guarded.is_empty() {
2598 state.guarded_symbolic_addresses.remove(&alias);
2599 }
2600 }
2601
2602 pub(crate) fn symbolic_word_for_address(&self, address: Address) -> Option<SymExpr> {
2603 self.symbolic_address_aliases
2604 .iter()
2605 .find_map(|(word, slot)| (*slot == address).then(|| word.clone()))
2606 }
2607
2608 pub(crate) fn symbolic_address_condition(
2613 &self,
2614 cx: &mut SymCx,
2615 expr: &SymExpr,
2616 address: Address,
2617 ) -> SymBoolExpr {
2618 let Some(word) = self.symbolic_word_for_address(address) else {
2619 let candidate = SymExpr::constant(cx, address_word(address));
2620 return SymBoolExpr::eq(cx, expr.clone(), candidate);
2621 };
2622 let mut conditions = vec![SymBoolExpr::eq(cx, expr.clone(), word.clone())];
2623 if let Some(guarded) = self.guarded_symbolic_addresses.get(&word) {
2624 let word = word.address_operand(cx);
2625 for candidate in guarded {
2626 let eq = SymBoolExpr::eq_word_const(cx, &word, address_word(*candidate));
2627 conditions.push(eq.not(cx));
2628 }
2629 }
2630 SymBoolExpr::and(cx, conditions)
2631 }
2632
2633 pub(crate) fn snapshot_state(&mut self, block: &SymbolicBlock, gas_price: &SymExpr) -> U256 {
2634 let id = U256::from(self.next_snapshot_id);
2635 self.next_snapshot_id = self.next_snapshot_id.saturating_add(1);
2636 let snapshot = SymbolicSnapshot {
2637 state: Arc::clone(&self.state),
2638 block: block.clone(),
2639 gas_price: gas_price.clone(),
2640 };
2641 self.snapshots.insert(id, snapshot);
2642 id
2643 }
2644
2645 pub(crate) fn restore_snapshot(&mut self, id: U256) -> Option<(SymbolicBlock, SymExpr)> {
2647 let snapshot = self.snapshots.get(&id)?;
2648 self.state = Arc::clone(&snapshot.state);
2649 Some((snapshot.block.clone(), snapshot.gas_price.clone()))
2650 }
2651
2652 pub(crate) fn delete_snapshot(&mut self, id: U256) -> bool {
2653 self.snapshots.remove(&id).is_some()
2654 }
2655
2656 pub(crate) fn delete_snapshots(&mut self) {
2657 self.snapshots.clear();
2658 }
2659
2660 pub(crate) fn take_snapshots_from(&mut self, other: &mut Self) {
2663 self.snapshots = std::mem::take(&mut other.snapshots);
2664 self.next_snapshot_id = other.next_snapshot_id;
2665 }
2666
2667 pub(crate) fn storage_base(
2668 &mut self,
2669 cx: &mut SymCx,
2670 executor: &ExecutorView<'_>,
2671 address: Address,
2672 key: &SymExpr,
2673 concrete_key: Option<U256>,
2674 ) -> Result<SymExpr, SymbolicError> {
2675 if let Some(base) = self.arbitrary_storage_base(cx, executor, address, key, concrete_key)? {
2676 return Ok(base);
2677 }
2678 if self.created_accounts.contains(&address) {
2679 return Ok(SymExpr::zero(cx));
2680 }
2681 if let Some(key) = concrete_key {
2682 return executor
2683 .backend
2684 .storage(address, key)
2685 .map(|value| SymExpr::constant(cx, value))
2686 .map_err(|err| SymbolicError::Backend(err.to_string()));
2687 }
2688 if let Some(key) = key.as_const() {
2689 executor
2690 .backend
2691 .storage(address, key)
2692 .map(|value| SymExpr::constant(cx, value))
2693 .map_err(|err| SymbolicError::Backend(err.to_string()))
2694 } else {
2695 if let Some(value) = self.symbolic_key_base_reads.get(&(address, key.clone())) {
2696 return Ok(value.clone());
2697 }
2698 let mut value = if self.zero_init_symbolic_storage {
2701 SymExpr::zero(cx)
2702 } else {
2703 let name = symbolic_storage_symbol(cx, address, key);
2704 SymExpr::get_var(cx, name)
2705 };
2706 for (slot, slot_value) in executor.backend.storage_slots(address) {
2707 if self.zero_init_symbolic_storage && slot_value.is_zero() {
2708 continue;
2709 }
2710 let slot = SymExpr::constant(cx, slot);
2711 let slot_value = SymExpr::constant(cx, slot_value);
2712 value = key.clone().select_storage_write(cx, slot, slot_value, value);
2713 }
2714 Arc::make_mut(&mut self.state)
2715 .symbolic_key_base_reads
2716 .insert((address, key.clone()), value.clone());
2717 Ok(value)
2718 }
2719 }
2720
2721 fn arbitrary_storage_base(
2722 &mut self,
2723 cx: &mut SymCx,
2724 executor: &ExecutorView<'_>,
2725 address: Address,
2726 key: &SymExpr,
2727 concrete_key: Option<U256>,
2728 ) -> Result<Option<SymExpr>, SymbolicError> {
2729 if let Some(slot) = concrete_key.or_else(|| key.as_const())
2730 && !self.arbitrary_storage_all
2731 {
2732 let overwrite_arbitrary_storage =
2733 self.arbitrary_storage_accounts.get(&address).copied();
2734 let has_arbitrary_storage = overwrite_arbitrary_storage.is_some();
2735 let is_copied_storage =
2736 !has_arbitrary_storage && self.arbitrary_storage_copies.contains_key(&address);
2737 let preserve_nonzero_slot =
2738 overwrite_arbitrary_storage == Some(false) || is_copied_storage;
2739 if preserve_nonzero_slot {
2740 let concrete = executor
2741 .backend
2742 .storage(address, slot)
2743 .map_err(|err| SymbolicError::Backend(err.to_string()))?;
2744 if !concrete.is_zero() {
2745 return Ok(Some(SymExpr::constant(cx, concrete)));
2746 }
2747 }
2748 }
2749
2750 Ok(self.unchecked_arbitrary_storage_base(cx, address, key, concrete_key))
2751 }
2752
2753 fn unchecked_arbitrary_storage_base(
2754 &mut self,
2755 cx: &mut SymCx,
2756 address: Address,
2757 key: &SymExpr,
2758 concrete_key: Option<U256>,
2759 ) -> Option<SymExpr> {
2760 let overwrite_arbitrary_storage = self.arbitrary_storage_accounts.get(&address).copied();
2761 let has_arbitrary_storage = overwrite_arbitrary_storage.is_some();
2762 let copied_source = (!has_arbitrary_storage)
2763 .then(|| self.arbitrary_storage_copies.get(&address).copied())
2764 .flatten();
2765 let symbol_address = if self.arbitrary_storage_all || has_arbitrary_storage {
2766 address
2767 } else {
2768 copied_source?
2769 };
2770 let symbol = symbolic_storage_symbol(cx, symbol_address, key);
2771 if let Some(slot) = concrete_key.or_else(|| key.as_const()) {
2772 if self.arbitrary_storage_all || has_arbitrary_storage {
2773 self.record_replay_storage_slot(symbol, address, slot);
2774 }
2775 if let Some(source) = copied_source {
2776 self.record_replay_storage_slot(symbol, source, slot);
2777 self.record_replay_storage_slot(symbol, address, slot);
2778 }
2779 } else if copied_source.is_none()
2780 && (self.arbitrary_storage_all || overwrite_arbitrary_storage == Some(true))
2781 {
2782 self.record_replay_symbolic_storage_key(symbol, address, key);
2784 }
2785 let value = SymExpr::get_var(cx, symbol);
2786 if let Some(source) = copied_source {
2787 self.sstore(source, key.clone(), value.clone());
2788 }
2789 Some(value)
2790 }
2791
2792 fn record_replay_storage_slot(&mut self, symbol: Symbol, address: Address, slot: U256) {
2793 if self.replay_storage_slots.get(&symbol).is_some_and(|slots| {
2794 slots.iter().any(|existing| existing.address == address && existing.slot == slot)
2795 }) {
2796 return;
2797 }
2798 Arc::make_mut(&mut self.state)
2799 .replay_storage_slots
2800 .entry(symbol)
2801 .or_default()
2802 .push(SymbolicReplayStorageSlot { address, slot });
2803 }
2804
2805 fn record_replay_symbolic_storage_key(
2806 &mut self,
2807 symbol: Symbol,
2808 address: Address,
2809 key: &SymExpr,
2810 ) {
2811 if self.replay_symbolic_storage_keys.get(&symbol).is_some_and(|reads| {
2812 reads.iter().any(|(existing, existing_key)| *existing == address && existing_key == key)
2813 }) {
2814 return;
2815 }
2816 Arc::make_mut(&mut self.state)
2817 .replay_symbolic_storage_keys
2818 .entry(symbol)
2819 .or_default()
2820 .push((address, key.clone()));
2821 }
2822
2823 pub(crate) fn merge_replay_metadata_from(&mut self, other: &Self) {
2824 for (symbol, slots) in &other.replay_storage_slots {
2825 for slot in slots {
2826 self.record_replay_storage_slot(*symbol, slot.address, slot.slot);
2827 }
2828 }
2829 for (symbol, reads) in &other.replay_symbolic_storage_keys {
2830 for (address, key) in reads {
2831 self.record_replay_symbolic_storage_key(*symbol, *address, key);
2832 }
2833 }
2834 let state = Arc::make_mut(&mut self.state);
2835 for (expr, address) in &other.symbolic_address_aliases {
2836 state.symbolic_address_aliases.entry(expr.clone()).or_insert(*address);
2837 }
2838 for (expr, candidates) in &other.guarded_symbolic_addresses {
2839 state.guarded_symbolic_addresses.entry(expr.clone()).or_default().extend(candidates);
2840 }
2841 }
2842
2843 pub(crate) fn backend_balance(
2844 &self,
2845 executor: &ExecutorView<'_>,
2846 address: Address,
2847 ) -> Result<U256, SymbolicError> {
2848 executor
2849 .backend
2850 .basic(address)
2851 .map_err(|err| SymbolicError::Backend(err.to_string()))
2852 .map(|account| account.map(|account| account.balance).unwrap_or_default())
2853 }
2854
2855 pub(crate) fn balance_word_for_address(
2856 &self,
2857 cx: &mut SymCx,
2858 executor: &ExecutorView<'_>,
2859 address: Address,
2860 ) -> Result<SymExpr, SymbolicError> {
2861 if self.destroyed_accounts.contains(&address) {
2862 return Ok(SymExpr::zero(cx));
2863 }
2864 if let Some(balance) = self.balances.get(&address) {
2865 return Ok(balance.clone());
2866 }
2867 if self.symbolic_accounts && !self.created_accounts.contains(&address) {
2868 return Ok(SymExpr::var(cx, &format!("balance_{address:?}")));
2869 }
2870 Ok(SymExpr::constant(cx, self.backend_balance(executor, address)?))
2871 }
2872
2873 pub(crate) fn balance_word(
2874 &mut self,
2875 cx: &mut SymCx,
2876 executor: &ExecutorView<'_>,
2877 address_expr: SymExpr,
2878 ) -> Result<SymExpr, SymbolicError> {
2879 self.select_symbolic_account(
2880 cx,
2881 executor,
2882 address_expr,
2883 |world, address| world.balances.contains_key(&address),
2884 |world, cx, address| world.balance_word_for_address(cx, executor, address),
2885 )
2886 }
2887
2888 pub(crate) fn set_balance_word(&mut self, address: Address, value: SymExpr) {
2889 let account_exists = !value.as_const().is_some_and(|value| value.is_zero());
2890 let state = Arc::make_mut(&mut self.state);
2891 state.balances.insert(address, value);
2892 if account_exists {
2893 state.existing_accounts.insert(address);
2894 state.destroyed_accounts.remove(&address);
2895 }
2896 }
2897
2898 pub(crate) fn transfer(
2901 &mut self,
2902 cx: &mut SymCx,
2903 executor: &ExecutorView<'_>,
2904 from: Address,
2905 to: Address,
2906 value: SymExpr,
2907 saturate: bool,
2908 ) -> Result<(), SymbolicError> {
2909 if from == to || value.as_const().is_some_and(|value| value.is_zero()) {
2910 return Ok(());
2911 }
2912 let from_balance = self.balance_word_for_address(cx, executor, from)?;
2913 let to_balance = self.balance_word_for_address(cx, executor, to)?;
2914 let from_balance = SymExpr::binop(cx, SymBinOp::Sub, from_balance, value.clone());
2915 let to_balance = if saturate {
2916 SymMemory::saturating_add_word(cx, to_balance, value)
2917 } else {
2918 SymExpr::binop(cx, SymBinOp::Add, to_balance, value)
2919 };
2920 self.set_balance_word(from, from_balance);
2921 self.set_balance_word(to, to_balance);
2922 Ok(())
2923 }
2924
2925 pub(crate) fn nonce(
2926 &self,
2927 executor: &ExecutorView<'_>,
2928 address: Address,
2929 ) -> Result<u64, SymbolicError> {
2930 if self.destroyed_accounts.contains(&address) {
2931 return Ok(self.nonces.get(&address).copied().unwrap_or_default());
2932 }
2933 if let Some(nonce) = self.nonces.get(&address) {
2934 return Ok(*nonce);
2935 }
2936 executor
2937 .backend
2938 .basic(address)
2939 .map_err(|err| SymbolicError::Backend(err.to_string()))
2940 .map(|account| account.map(|account| account.nonce).unwrap_or_default())
2941 }
2942
2943 pub(crate) fn nonce_word(
2944 &mut self,
2945 cx: &mut SymCx,
2946 executor: &ExecutorView<'_>,
2947 address_expr: SymExpr,
2948 ) -> Result<SymExpr, SymbolicError> {
2949 self.select_symbolic_account(
2950 cx,
2951 executor,
2952 address_expr,
2953 |world, address| world.nonces.contains_key(&address),
2954 |world, cx, address| {
2955 let nonce = world.nonce(executor, address)?;
2956 Ok(SymExpr::constant(cx, U256::from(nonce)))
2957 },
2958 )
2959 }
2960
2961 pub(crate) fn set_nonce(&mut self, address: Address, nonce: u64) {
2962 let state = Arc::make_mut(&mut self.state);
2963 state.nonces.insert(address, nonce);
2964 if nonce != 0 {
2965 state.existing_accounts.insert(address);
2966 state.destroyed_accounts.remove(&address);
2967 }
2968 }
2969
2970 pub(crate) fn increment_nonce(
2971 &mut self,
2972 executor: &ExecutorView<'_>,
2973 address: Address,
2974 ) -> Result<(), SymbolicError> {
2975 let nonce = self.nonce(executor, address)?;
2976 self.set_nonce(address, nonce.saturating_add(1));
2977 Ok(())
2978 }
2979
2980 pub(crate) fn has_code_or_nonce(
2981 &mut self,
2982 cx: &mut SymCx,
2983 executor: &ExecutorView<'_>,
2984 address: Address,
2985 ) -> Result<bool, SymbolicError> {
2986 if self.destroyed_accounts.contains(&address) {
2987 return Ok(false);
2988 }
2989 Ok(!self.extcode(cx, executor, address)?.is_empty() || self.nonce(executor, address)? != 0)
2990 }
2991
2992 pub(crate) fn install_code(&mut self, address: Address, code: SymCode) {
2993 let state = Arc::make_mut(&mut self.state);
2994 state.code_cache.insert(address, code);
2995 state.written_code.insert(address);
2996 state.existing_accounts.insert(address);
2997 state.destroyed_accounts.remove(&address);
2998 }
2999
3000 pub(crate) fn selfdestruct_legacy(
3004 &mut self,
3005 cx: &mut SymCx,
3006 executor: &ExecutorView<'_>,
3007 address: Address,
3008 beneficiary: Address,
3009 ) -> Result<(), SymbolicError> {
3010 let balance = self.balance_word_for_address(cx, executor, address)?;
3011 if beneficiary != address && !balance.as_const().is_some_and(|value| value.is_zero()) {
3012 let beneficiary_balance = self.balance_word_for_address(cx, executor, beneficiary)?;
3013 let beneficiary_balance =
3014 SymMemory::saturating_add_word(cx, beneficiary_balance, balance);
3015 self.set_balance_word(beneficiary, beneficiary_balance);
3016 }
3017 let zero = SymExpr::zero(cx);
3018 let state = Arc::make_mut(&mut self.state);
3019 state.balances.insert(address, zero);
3020 state.pending_selfdestructs.insert(address);
3021 Ok(())
3022 }
3023
3024 pub(crate) fn selfdestruct_cancun_existing(
3026 &mut self,
3027 cx: &mut SymCx,
3028 executor: &ExecutorView<'_>,
3029 address: Address,
3030 beneficiary: Address,
3031 ) -> Result<(), SymbolicError> {
3032 let balance = self.balance_word_for_address(cx, executor, address)?;
3033 if beneficiary != address && !balance.as_const().is_some_and(|value| value.is_zero()) {
3034 let beneficiary_balance = self.balance_word_for_address(cx, executor, beneficiary)?;
3035 let beneficiary_balance =
3038 SymMemory::saturating_add_word(cx, beneficiary_balance, balance);
3039 self.set_balance_word(beneficiary, beneficiary_balance);
3040 let zero = SymExpr::zero(cx);
3041 Arc::make_mut(&mut self.state).balances.insert(address, zero);
3042 }
3043 Ok(())
3044 }
3045
3046 pub(crate) fn extcode(
3047 &mut self,
3048 cx: &mut SymCx,
3049 executor: &ExecutorView<'_>,
3050 address: Address,
3051 ) -> Result<SymCode, SymbolicError> {
3052 if self.destroyed_accounts.contains(&address) {
3053 return Ok(SymCode::empty(cx));
3054 }
3055 if let Some(code) = self.code_cache.get(&address) {
3056 return Ok(code.clone());
3057 }
3058 let account = executor
3059 .backend
3060 .basic(address)
3061 .map_err(|err| SymbolicError::Backend(err.to_string()))?;
3062 if let Some(account) = account.as_ref()
3063 && (account.nonce != 0
3064 || !account.balance.is_zero()
3065 || account.code.as_ref().is_some_and(|code| !code.is_empty()))
3066 {
3067 Arc::make_mut(&mut self.state).existing_accounts.insert(address);
3068 }
3069 if address == CHEATCODE_ADDRESS
3070 && account.as_ref().is_none_or(|account| account.code.is_none())
3071 {
3072 let code = SymCode::concrete(cx, vec![0]);
3073 Arc::make_mut(&mut self.state).code_cache.insert(address, code.clone());
3074 return Ok(code);
3075 }
3076 let bytecode = account.as_ref().and_then(|account| account.code.as_ref());
3077 let code = bytecode
3078 .map(|bytecode| SymCode::from_bytecode(cx, bytecode))
3079 .unwrap_or_else(|| SymCode::empty(cx));
3080 Arc::make_mut(&mut self.state).code_cache.insert(address, code.clone());
3081 Ok(code)
3082 }
3083
3084 pub(crate) fn extcode_hash_for_address(
3085 &mut self,
3086 cx: &mut SymCx,
3087 executor: &ExecutorView<'_>,
3088 address: Address,
3089 ) -> Result<SymExpr, SymbolicError> {
3090 if self.is_unknown_account(cx, executor, address)? {
3091 return Ok(SymExpr::var(cx, &format!("codehash_{address:?}")));
3092 }
3093 if (address == CHEATCODE_ADDRESS || address == SYMBOLIC_VM_COMPAT_ADDRESS)
3096 && !self.written_code.contains(&address)
3097 && let Some(account) = executor
3098 .backend
3099 .basic(address)
3100 .map_err(|err| SymbolicError::Backend(err.to_string()))?
3101 {
3102 return Ok(SymExpr::constant(cx, account.code_hash.into()));
3103 }
3104 if self.destroyed_accounts.contains(&address) {
3105 return Ok(SymExpr::zero(cx));
3106 }
3107 let code = self.extcode(cx, executor, address)?;
3108 let bytes = code.read_byte_exprs(cx, 0, code.len());
3109 let hash = keccak_word(cx, bytes);
3110 if !code.is_empty() || self.nonce(executor, address)? != 0 {
3111 return Ok(hash);
3112 }
3113 let balance = self.balance_word_for_address(cx, executor, address)?;
3115 let empty = SymBoolExpr::eq_word_const(cx, &balance, U256::ZERO);
3116 let zero = SymExpr::zero(cx);
3117 Ok(SymExpr::ite(cx, empty, zero, hash))
3118 }
3119
3120 fn extcode_size_for_address(
3122 &mut self,
3123 cx: &mut SymCx,
3124 executor: &ExecutorView<'_>,
3125 address: Address,
3126 ) -> Result<SymExpr, SymbolicError> {
3127 if self.is_unknown_account(cx, executor, address)? {
3128 return Ok(SymExpr::var(cx, &format!("codesize_{address:?}")));
3129 }
3130 let len = self.extcode(cx, executor, address)?.len();
3131 Ok(SymExpr::constant(cx, U256::from(len)))
3132 }
3133
3134 pub(crate) fn extcode_size_word(
3135 &mut self,
3136 cx: &mut SymCx,
3137 executor: &ExecutorView<'_>,
3138 address_expr: SymExpr,
3139 ) -> Result<SymExpr, SymbolicError> {
3140 if address_expr.clone().address_operand(cx).as_const()
3144 == Some(address_word(SYMBOLIC_VM_COMPAT_ADDRESS))
3145 && self.extcode(cx, executor, SYMBOLIC_VM_COMPAT_ADDRESS)?.is_empty()
3146 {
3147 return Ok(SymExpr::constant(cx, U256::ONE));
3148 }
3149 self.select_symbolic_account(
3150 cx,
3151 executor,
3152 address_expr,
3153 |world, address| world.written_code.contains(&address),
3154 |world, cx, address| world.extcode_size_for_address(cx, executor, address),
3155 )
3156 }
3157
3158 pub(crate) fn extcode_hash_word(
3159 &mut self,
3160 cx: &mut SymCx,
3161 executor: &ExecutorView<'_>,
3162 address_expr: SymExpr,
3163 ) -> Result<SymExpr, SymbolicError> {
3164 self.select_symbolic_account(
3165 cx,
3166 executor,
3167 address_expr,
3168 |world, address| world.written_code.contains(&address),
3169 |world, cx, address| world.extcode_hash_for_address(cx, executor, address),
3170 )
3171 }
3172
3173 pub(crate) fn extcode_bytes_word(
3174 &mut self,
3175 cx: &mut SymCx,
3176 executor: &ExecutorView<'_>,
3177 address_expr: SymExpr,
3178 offset: SymExpr,
3179 size: usize,
3180 ) -> Result<SymBytes, SymbolicError> {
3181 let address_expr = address_expr.address_operand(cx);
3182 if let Some(address) = self.resolve_address(&address_expr) {
3183 if self.is_unknown_account(cx, executor, address)? {
3184 return Err(SymbolicError::Unsupported("EXTCODECOPY of unknown code"));
3185 }
3186 return Ok(self.extcode(cx, executor, address)?.read_bytes_offset(cx, offset, size));
3187 }
3188
3189 let expr = address_expr;
3190 let representative = expr.representative_symbolic_address();
3191 if self.is_unknown_account(cx, executor, representative)? {
3192 return Err(SymbolicError::Unsupported("EXTCODECOPY of unknown code"));
3193 }
3194 let mut result = self.extcode(cx, executor, representative)?.read_byte_exprs_offset(
3195 cx,
3196 offset.clone(),
3197 size,
3198 );
3199 let candidates = self
3200 .candidate_addresses(executor, |world, address| world.written_code.contains(&address));
3201 for address in candidates {
3202 let bytes = self.extcode(cx, executor, address)?.read_byte_exprs_offset(
3203 cx,
3204 offset.clone(),
3205 size,
3206 );
3207 let condition = self.symbolic_address_condition(cx, &expr, address);
3208 for (idx, byte) in bytes.into_iter().enumerate() {
3209 result[idx] = SymExpr::ite(cx, condition.clone(), byte, result[idx].clone());
3210 }
3211 }
3212
3213 Ok(SymBytes::exprs(cx, result))
3214 }
3215
3216 pub(crate) fn sload_word(
3217 &mut self,
3218 cx: &mut SymCx,
3219 executor: &ExecutorView<'_>,
3220 address_expr: SymExpr,
3221 key: SymExpr,
3222 concrete_key: Option<U256>,
3223 ) -> Result<SymExpr, SymbolicError> {
3224 self.select_symbolic_account(
3225 cx,
3226 executor,
3227 address_expr,
3228 |world, address| world.storage.iter().any(|write| write.address == address),
3229 |world, cx, address| world.sload(cx, executor, address, key.clone(), concrete_key),
3230 )
3231 }
3232
3233 fn select_symbolic_account(
3237 &mut self,
3238 cx: &mut SymCx,
3239 executor: &ExecutorView<'_>,
3240 address_expr: SymExpr,
3241 has_state: impl Fn(&Self, Address) -> bool,
3242 mut value_for: impl FnMut(&mut Self, &mut SymCx, Address) -> Result<SymExpr, SymbolicError>,
3243 ) -> Result<SymExpr, SymbolicError> {
3244 let address_expr = address_expr.address_operand(cx);
3245 if let Some(address) = self.resolve_address(&address_expr) {
3246 return value_for(self, cx, address);
3247 }
3248
3249 let representative = address_expr.representative_symbolic_address();
3250 let mut result = value_for(self, cx, representative)?;
3251 for address in self.candidate_addresses(executor, has_state) {
3252 let value = value_for(self, cx, address)?;
3253 let condition = self.symbolic_address_condition(cx, &address_expr, address);
3254 result = SymExpr::ite(cx, condition, value, result);
3255 }
3256 Ok(result)
3257 }
3258
3259 pub(crate) fn symbolic_call_targets(
3260 &mut self,
3261 cx: &mut SymCx,
3262 executor: &ExecutorView<'_>,
3263 ) -> Result<Vec<Address>, SymbolicError> {
3264 let mut targets = Vec::new();
3265 let candidates = self
3266 .candidate_addresses(executor, |world, address| world.written_code.contains(&address));
3267 for address in candidates {
3268 if is_precompile_for_spec(address, executor.spec_id)
3269 || address == CHEATCODE_ADDRESS
3270 || address == SYMBOLIC_VM_COMPAT_ADDRESS
3271 {
3272 continue;
3273 }
3274 if !self.extcode(cx, executor, address)?.is_empty() {
3275 targets.push(address);
3276 }
3277 }
3278 Ok(targets)
3279 }
3280
3281 pub(crate) fn concrete_alias_candidates(&self, executor: &ExecutorView<'_>) -> Vec<Address> {
3283 self.candidate_addresses(executor, |_, _| false)
3284 }
3285
3286 fn candidate_addresses(
3294 &self,
3295 executor: &ExecutorView<'_>,
3296 has_state: impl Fn(&Self, Address) -> bool,
3297 ) -> Vec<Address> {
3298 let mut addresses = self
3299 .code_cache
3300 .keys()
3301 .chain(self.balances.keys())
3302 .chain(&self.existing_accounts)
3303 .chain(&executor.account_addresses)
3304 .chain(self.storage.iter().map(|write| &write.address))
3305 .copied()
3306 .chain([CHEATCODE_ADDRESS])
3307 .filter(|address| {
3308 self.symbolic_word_for_address(*address).is_none() || has_state(self, *address)
3309 })
3310 .collect::<Vec<_>>();
3311 addresses.sort_unstable();
3312 addresses.dedup();
3313 addresses
3314 }
3315}
3316
3317fn symbolic_storage_symbol(cx: &mut SymCx, address: Address, key: &SymExpr) -> Symbol {
3318 stable_symbol(
3319 cx,
3320 "storage",
3321 format!("{address:?}:{:?}", ExpressionDigests::identity([key])).as_bytes(),
3322 )
3323}
3324
3325#[derive(Clone, Debug)]
3326pub(crate) struct SymbolicBlock {
3327 pub(crate) chain_id: SymExpr,
3328 pub(crate) coinbase: Address,
3329 pub(crate) coinbase_word: Option<SymExpr>,
3331 pub(crate) timestamp: SymExpr,
3332 pub(crate) number: SymExpr,
3333 pub(crate) difficulty: SymExpr,
3334 pub(crate) gaslimit: SymExpr,
3335 pub(crate) basefee: SymExpr,
3336 pub(crate) blob_basefee: SymExpr,
3337 pub(crate) slot_num: SymExpr,
3338 pub(crate) block_hashes: HashMap<U256, SymExpr>,
3339 pub(crate) blob_hashes: Vec<B256>,
3340}
3341
3342impl SymbolicBlock {
3343 pub(crate) fn new(cx: &mut SymCx) -> Self {
3344 Self {
3345 chain_id: SymExpr::one(cx),
3346 coinbase: Address::ZERO,
3347 coinbase_word: None,
3348 timestamp: SymExpr::zero(cx),
3349 number: SymExpr::zero(cx),
3350 difficulty: SymExpr::zero(cx),
3351 gaslimit: SymExpr::zero(cx),
3352 basefee: SymExpr::zero(cx),
3353 blob_basefee: SymExpr::zero(cx),
3354 slot_num: SymExpr::zero(cx),
3355 block_hashes: HashMap::default(),
3356 blob_hashes: Vec::new(),
3357 }
3358 }
3359
3360 pub(crate) fn from_executor(cx: &mut SymCx, executor: &ExecutorView<'_>) -> Self {
3361 let block = &executor.block;
3362 Self {
3363 chain_id: SymExpr::constant(cx, U256::from(executor.chain_id)),
3364 coinbase: block.coinbase,
3365 coinbase_word: None,
3366 timestamp: SymExpr::constant(cx, block.timestamp),
3367 number: SymExpr::constant(cx, block.number),
3368 difficulty: SymExpr::constant(cx, block.difficulty),
3369 gaslimit: SymExpr::constant(cx, block.gas_limit),
3370 basefee: SymExpr::constant(cx, block.basefee),
3371 blob_basefee: SymExpr::constant(cx, block.blob_basefee),
3372 slot_num: SymExpr::constant(cx, block.slot_num),
3373 block_hashes: HashMap::default(),
3374 blob_hashes: executor.blob_hashes.clone(),
3375 }
3376 }
3377
3378 pub(crate) fn set_block_hash(
3381 &mut self,
3382 block_number: U256,
3383 block_hash: SymExpr,
3384 ) -> Result<bool, SymbolicError> {
3385 let current = self.number.as_const_or("symbolic vm.setBlockhash current number")?;
3386 if block_number > current {
3387 return Ok(false);
3388 }
3389 self.block_hashes.insert(block_number, block_hash);
3390 Ok(true)
3391 }
3392
3393 pub(crate) fn block_hash(
3394 &self,
3395 cx: &mut SymCx,
3396 executor: &ExecutorView<'_>,
3397 block_number: U256,
3398 ) -> Result<SymExpr, SymbolicError> {
3399 let current = self.number.as_const_or("symbolic BLOCKHASH current number")?;
3400 if block_number >= current || current - block_number > U256::from(256) {
3401 return Ok(SymExpr::zero(cx));
3402 }
3403 if let Some(hash) = self.block_hashes.get(&block_number) {
3404 return Ok(hash.clone());
3405 }
3406 let hash = executor
3407 .backend
3408 .block_hash(block_number)
3409 .map_err(|err| SymbolicError::Backend(err.to_string()))?;
3410 Ok(SymExpr::constant(cx, U256::from_be_slice(hash.as_slice())))
3411 }
3412
3413 pub(crate) fn block_hash_word(
3414 &self,
3415 cx: &mut SymCx,
3416 executor: &ExecutorView<'_>,
3417 block_number: SymExpr,
3418 ) -> Result<SymExpr, SymbolicError> {
3419 if let Some(block_number) = block_number.as_const() {
3420 return self.block_hash(cx, executor, block_number);
3421 }
3422 let current = self.number.as_const_or("symbolic BLOCKHASH current number")?;
3423 if current.is_zero() {
3424 return Ok(SymExpr::zero(cx));
3425 }
3426
3427 let mut result = SymExpr::zero(cx);
3428 let max_distance =
3429 usize::try_from(current.min(U256::from(256))).expect("checked blockhash distance");
3430 for distance in (1..=max_distance).rev() {
3431 let candidate = current - U256::from(distance);
3432 let hash = self.block_hash(cx, executor, candidate)?;
3433 if hash.as_const().is_some_and(|hash| hash.is_zero()) {
3434 continue;
3435 }
3436 let candidate = SymExpr::constant(cx, candidate);
3437 let condition = SymBoolExpr::eq(cx, block_number.clone(), candidate);
3438 result = SymExpr::ite(cx, condition, hash, result);
3439 }
3440
3441 Ok(result)
3442 }
3443}
3444
3445#[derive(Clone, Debug)]
3448pub(crate) enum PersistentWrite {
3449 Balance { address: Address, balance: SymExpr, previous: SymExpr },
3451 Nonce(Address, i128),
3453 Created(Address),
3455 Restore,
3457}