Skip to main content

foundry_cheatcodes/test/
assert.rs

1use crate::{CheatcodesExecutor, CheatsCtxt, Result, Vm::*};
2use alloy_primitives::{Address, B256, Bytes, I256, U256, U512, keccak256, uint};
3use alloy_sol_types::SolCall;
4use evm2::interpreter::{InstrStop, op, opcode::OpCode};
5use foundry_evm_core::{
6    abi::console::{format_units_int, format_units_uint},
7    backend::GLOBAL_FAIL_SLOT,
8    constants::CHEATCODE_ADDRESS,
9    decode::ASSERTION_FAILED_PREFIX,
10    evm::{FoundryEvmNetwork, InterpreterFor, MessageResultFor},
11};
12use itertools::Itertools;
13use std::{borrow::Cow, fmt};
14
15const EQ_REL_DELTA_RESOLUTION: U256 = uint!(18_U256);
16
17struct ComparisonAssertionError<'a, T> {
18    kind: AssertionKind,
19    left: &'a T,
20    right: &'a T,
21}
22
23#[derive(Clone, Copy)]
24enum AssertionKind {
25    Eq,
26    Ne,
27    Gt,
28    Ge,
29    Lt,
30    Le,
31}
32
33impl AssertionKind {
34    const fn inverse(self) -> Self {
35        match self {
36            Self::Eq => Self::Ne,
37            Self::Ne => Self::Eq,
38            Self::Gt => Self::Le,
39            Self::Ge => Self::Lt,
40            Self::Lt => Self::Ge,
41            Self::Le => Self::Gt,
42        }
43    }
44
45    const fn to_str(self) -> &'static str {
46        match self {
47            Self::Eq => "==",
48            Self::Ne => "!=",
49            Self::Gt => ">",
50            Self::Ge => ">=",
51            Self::Lt => "<",
52            Self::Le => "<=",
53        }
54    }
55}
56
57impl<T> ComparisonAssertionError<'_, T> {
58    fn format_values<D: fmt::Display>(&self, f: impl Fn(&T) -> D) -> String {
59        format!("{} {} {}", f(self.left), self.kind.inverse().to_str(), f(self.right))
60    }
61}
62
63impl<T: fmt::Display> ComparisonAssertionError<'_, T> {
64    fn format_for_values(&self) -> String {
65        self.format_values(T::to_string)
66    }
67}
68
69impl<T: fmt::Display> ComparisonAssertionError<'_, Vec<T>> {
70    fn format_for_arrays(&self) -> String {
71        self.format_values(|v| format!("[{}]", v.iter().format(", ")))
72    }
73}
74
75impl ComparisonAssertionError<'_, U256> {
76    fn format_with_decimals(&self, decimals: &U256) -> String {
77        self.format_values(|v| format_units_uint(v, decimals))
78    }
79}
80
81impl ComparisonAssertionError<'_, I256> {
82    fn format_with_decimals(&self, decimals: &U256) -> String {
83        self.format_values(|v| format_units_int(v, decimals))
84    }
85}
86
87#[derive(thiserror::Error, Debug)]
88#[error("{left} !~= {right} (max delta: {max_delta}, real delta: {real_delta})")]
89struct EqAbsAssertionError<T, D> {
90    left: T,
91    right: T,
92    max_delta: D,
93    real_delta: D,
94}
95
96impl EqAbsAssertionError<U256, U256> {
97    fn format_with_decimals(&self, decimals: &U256) -> String {
98        format!(
99            "{} !~= {} (max delta: {}, real delta: {})",
100            format_units_uint(&self.left, decimals),
101            format_units_uint(&self.right, decimals),
102            format_units_uint(&self.max_delta, decimals),
103            format_units_uint(&self.real_delta, decimals),
104        )
105    }
106}
107
108impl EqAbsAssertionError<I256, U256> {
109    fn format_with_decimals(&self, decimals: &U256) -> String {
110        format!(
111            "{} !~= {} (max delta: {}, real delta: {})",
112            format_units_int(&self.left, decimals),
113            format_units_int(&self.right, decimals),
114            format_units_uint(&self.max_delta, decimals),
115            format_units_uint(&self.real_delta, decimals),
116        )
117    }
118}
119
120fn format_delta_percent(delta: &U256) -> String {
121    format!("{}%", format_units_uint(delta, &(EQ_REL_DELTA_RESOLUTION - U256::from(2))))
122}
123
124#[derive(Debug)]
125enum EqRelDelta {
126    Defined(U256),
127    Undefined,
128}
129
130impl fmt::Display for EqRelDelta {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        match self {
133            Self::Defined(delta) => write!(f, "{}", format_delta_percent(delta)),
134            Self::Undefined => write!(f, "undefined"),
135        }
136    }
137}
138
139#[derive(thiserror::Error, Debug)]
140#[error(
141    "{left} !~= {right} (max delta: {}, real delta: {})",
142    format_delta_percent(max_delta),
143    real_delta
144)]
145struct EqRelAssertionFailure<T> {
146    left: T,
147    right: T,
148    max_delta: U256,
149    real_delta: EqRelDelta,
150}
151
152#[derive(thiserror::Error, Debug)]
153enum EqRelAssertionError<T> {
154    #[error(transparent)]
155    Failure(Box<EqRelAssertionFailure<T>>),
156    #[error("overflow in delta calculation")]
157    Overflow,
158}
159
160impl EqRelAssertionError<U256> {
161    fn format_with_decimals(&self, decimals: &U256) -> String {
162        match self {
163            Self::Failure(f) => format!(
164                "{} !~= {} (max delta: {}, real delta: {})",
165                format_units_uint(&f.left, decimals),
166                format_units_uint(&f.right, decimals),
167                format_delta_percent(&f.max_delta),
168                f.real_delta,
169            ),
170            Self::Overflow => self.to_string(),
171        }
172    }
173}
174
175impl EqRelAssertionError<I256> {
176    fn format_with_decimals(&self, decimals: &U256) -> String {
177        match self {
178            Self::Failure(f) => format!(
179                "{} !~= {} (max delta: {}, real delta: {})",
180                format_units_int(&f.left, decimals),
181                format_units_int(&f.right, decimals),
182                format_delta_percent(&f.max_delta),
183                f.real_delta,
184            ),
185            Self::Overflow => self.to_string(),
186        }
187    }
188}
189
190type ComparisonResult<'a, T> = Result<(), ComparisonAssertionError<'a, T>>;
191
192#[cold]
193fn handle_assertion_result<FEN: FoundryEvmNetwork, E>(
194    ccx: &mut CheatsCtxt<'_, '_, FEN>,
195    executor: &mut dyn CheatcodesExecutor<FEN>,
196    selector: [u8; 4],
197    err: E,
198    error_formatter: Option<&dyn Fn(&E) -> String>,
199    error_msg: Option<&str>,
200) -> Result {
201    let error_msg = error_msg.unwrap_or(ASSERTION_FAILED_PREFIX);
202    let msg = if let Some(error_formatter) = error_formatter {
203        Cow::Owned(format!("{error_msg}: {}", error_formatter(&err)))
204    } else {
205        Cow::Borrowed(error_msg)
206    };
207    let reverts = ccx.state.core.config.assertions_revert;
208    if let Some(trace) = &mut ccx.state.failure_trace {
209        let revert = reverts.then(|| keccak256(crate::Error::encode(msg.to_string())));
210        trace.record_assertion(selector, error_msg, revert);
211    }
212    if let Some(provenance) = &mut ccx.state.failure_provenance {
213        provenance.pending_assertion = Some(keccak256([&selector[..], msg.as_bytes()].concat()));
214    }
215    handle_assertion_result_mono(ccx, executor, msg)
216}
217
218fn handle_assertion_result_mono<FEN: FoundryEvmNetwork>(
219    ccx: &mut CheatsCtxt<'_, '_, FEN>,
220    executor: &mut dyn CheatcodesExecutor<FEN>,
221    msg: Cow<'_, str>,
222) -> Result {
223    ccx.state.failed_assertion.get_or_insert_with(|| msg.to_string());
224    if ccx.state.core.config.assertions_revert {
225        Err(msg.into_owned().into())
226    } else {
227        executor.console_log(&msg);
228        ccx.evm.state_mut().storage_slot(&CHEATCODE_ADDRESS, GLOBAL_FAIL_SLOT)?.set(U256::ONE);
229        Ok(Default::default())
230    }
231}
232
233/// Implements [crate::Cheatcode] for pairs of cheatcodes.
234///
235/// Accepts a list of pairs of cheatcodes, where the first cheatcode is the one that doesn't contain
236/// a custom error message, and the second one contains it at `err` field.
237///
238/// Passed `args` are the common arguments for both cheatcode structs (excluding `err` field).
239///
240/// Macro also accepts an optional closure that formats the error returned by the assertion.
241macro_rules! impl_assertions {
242    (|$($arg:ident),*| $body:expr, false, $(($no_error:ident, $with_error:ident)),* $(,)?) => {
243        impl_assertions! { @args_tt |($($arg),*)| $body, None, $(($no_error, $with_error)),* }
244    };
245    (|$($arg:ident),*| $body:expr, $(($no_error:ident, $with_error:ident)),* $(,)?) => {
246        impl_assertions! { @args_tt |($($arg),*)| $body, Some(&ToString::to_string), $(($no_error, $with_error)),* }
247    };
248    (|$($arg:ident),*| $body:expr, $error_formatter:expr, $(($no_error:ident, $with_error:ident)),* $(,)?) => {
249        impl_assertions! { @args_tt |($($arg),*)| $body, Some(&$error_formatter), $(($no_error, $with_error)),* }
250    };
251
252    // We convert args to `tt` and later expand them back into tuple to allow usage of expanded args inside of
253    // each assertion type context.
254    (@args_tt |$args:tt| $body:expr, $error_formatter:expr, $(($no_error:ident, $with_error:ident)),* $(,)?) => {
255        $(
256            impl_assertions! { @impl $no_error, $with_error, $args, $body, $error_formatter }
257        )*
258    };
259
260    (@impl $no_error:ident, $with_error:ident, ($($arg:ident),*), $body:expr, $error_formatter:expr) => {
261        impl crate::Cheatcode for $no_error {
262            fn apply_full<FEN: FoundryEvmNetwork>(
263                &self,
264                ccx: &mut CheatsCtxt<'_, '_, FEN>,
265                executor: &mut dyn CheatcodesExecutor<FEN>,
266            ) -> Result {
267                let Self { $($arg),* } = self;
268                match $body {
269                    Ok(()) => Ok(Default::default()),
270                    Err(err) => handle_assertion_result(
271                        ccx,
272                        executor,
273                        Self::SELECTOR,
274                        err,
275                        $error_formatter,
276                        None,
277                    ),
278                }
279            }
280        }
281
282        impl crate::Cheatcode for $with_error {
283            fn apply_full<FEN: FoundryEvmNetwork>(
284                &self,
285                ccx: &mut CheatsCtxt<'_, '_, FEN>,
286                executor: &mut dyn CheatcodesExecutor<FEN>,
287            ) -> Result {
288                let Self { $($arg,)* err } = self;
289                match $body {
290                    Ok(()) => Ok(Default::default()),
291                    Err(assertion_err) => handle_assertion_result(
292                        ccx,
293                        executor,
294                        Self::SELECTOR,
295                        assertion_err,
296                        $error_formatter,
297                        Some(err),
298                    ),
299                }
300            }
301        }
302    };
303}
304
305impl_assertions! {
306    |condition| assert_true(*condition),
307    false,
308    (assertTrue_0Call, assertTrue_1Call),
309}
310
311impl_assertions! {
312    |condition| assert_false(*condition),
313    false,
314    (assertFalse_0Call, assertFalse_1Call),
315}
316
317impl_assertions! {
318    |left, right| assert_eq(left, right),
319    ComparisonAssertionError::format_for_values,
320    (assertEq_0Call, assertEq_1Call),
321    (assertEq_2Call, assertEq_3Call),
322    (assertEq_4Call, assertEq_5Call),
323    (assertEq_6Call, assertEq_7Call),
324    (assertEq_8Call, assertEq_9Call),
325    (assertEq_10Call, assertEq_11Call),
326    (assertEq_12Call, assertEq_13Call),
327}
328
329impl_assertions! {
330    |left, right| assert_eq(left, right),
331    ComparisonAssertionError::format_for_arrays,
332    (assertEq_14Call, assertEq_15Call),
333    (assertEq_16Call, assertEq_17Call),
334    (assertEq_18Call, assertEq_19Call),
335    (assertEq_20Call, assertEq_21Call),
336    (assertEq_22Call, assertEq_23Call),
337    (assertEq_24Call, assertEq_25Call),
338    (assertEq_26Call, assertEq_27Call),
339}
340
341impl_assertions! {
342    |left, right, decimals| assert_eq(left, right),
343    |e| e.format_with_decimals(decimals),
344    (assertEqDecimal_0Call, assertEqDecimal_1Call),
345    (assertEqDecimal_2Call, assertEqDecimal_3Call),
346}
347
348impl_assertions! {
349    |left, right| assert_not_eq(left, right),
350    ComparisonAssertionError::format_for_values,
351    (assertNotEq_0Call, assertNotEq_1Call),
352    (assertNotEq_2Call, assertNotEq_3Call),
353    (assertNotEq_4Call, assertNotEq_5Call),
354    (assertNotEq_6Call, assertNotEq_7Call),
355    (assertNotEq_8Call, assertNotEq_9Call),
356    (assertNotEq_10Call, assertNotEq_11Call),
357    (assertNotEq_12Call, assertNotEq_13Call),
358}
359
360impl_assertions! {
361    |left, right| assert_not_eq(left, right),
362    ComparisonAssertionError::format_for_arrays,
363    (assertNotEq_14Call, assertNotEq_15Call),
364    (assertNotEq_16Call, assertNotEq_17Call),
365    (assertNotEq_18Call, assertNotEq_19Call),
366    (assertNotEq_20Call, assertNotEq_21Call),
367    (assertNotEq_22Call, assertNotEq_23Call),
368    (assertNotEq_24Call, assertNotEq_25Call),
369    (assertNotEq_26Call, assertNotEq_27Call),
370}
371
372impl_assertions! {
373    |left, right, decimals| assert_not_eq(left, right),
374    |e| e.format_with_decimals(decimals),
375    (assertNotEqDecimal_0Call, assertNotEqDecimal_1Call),
376    (assertNotEqDecimal_2Call, assertNotEqDecimal_3Call),
377}
378
379impl_assertions! {
380    |left, right| assert_gt(left, right),
381    ComparisonAssertionError::format_for_values,
382    (assertGt_0Call, assertGt_1Call),
383    (assertGt_2Call, assertGt_3Call),
384}
385
386impl_assertions! {
387    |left, right, decimals| assert_gt(left, right),
388    |e| e.format_with_decimals(decimals),
389    (assertGtDecimal_0Call, assertGtDecimal_1Call),
390    (assertGtDecimal_2Call, assertGtDecimal_3Call),
391}
392
393impl_assertions! {
394    |left, right| assert_ge(left, right),
395    ComparisonAssertionError::format_for_values,
396    (assertGe_0Call, assertGe_1Call),
397    (assertGe_2Call, assertGe_3Call),
398}
399
400impl_assertions! {
401    |left, right, decimals| assert_ge(left, right),
402    |e| e.format_with_decimals(decimals),
403    (assertGeDecimal_0Call, assertGeDecimal_1Call),
404    (assertGeDecimal_2Call, assertGeDecimal_3Call),
405}
406
407impl_assertions! {
408    |left, right| assert_lt(left, right),
409    ComparisonAssertionError::format_for_values,
410    (assertLt_0Call, assertLt_1Call),
411    (assertLt_2Call, assertLt_3Call),
412}
413
414impl_assertions! {
415    |left, right, decimals| assert_lt(left, right),
416    |e| e.format_with_decimals(decimals),
417    (assertLtDecimal_0Call, assertLtDecimal_1Call),
418    (assertLtDecimal_2Call, assertLtDecimal_3Call),
419}
420
421impl_assertions! {
422    |left, right| assert_le(left, right),
423    ComparisonAssertionError::format_for_values,
424    (assertLe_0Call, assertLe_1Call),
425    (assertLe_2Call, assertLe_3Call),
426}
427
428impl_assertions! {
429    |left, right, decimals| assert_le(left, right),
430    |e| e.format_with_decimals(decimals),
431    (assertLeDecimal_0Call, assertLeDecimal_1Call),
432    (assertLeDecimal_2Call, assertLeDecimal_3Call),
433}
434
435impl_assertions! {
436    |left, right, maxDelta| uint_assert_approx_eq_abs(*left, *right, *maxDelta),
437    (assertApproxEqAbs_0Call, assertApproxEqAbs_1Call),
438}
439
440impl_assertions! {
441    |left, right, maxDelta| int_assert_approx_eq_abs(*left, *right, *maxDelta),
442    (assertApproxEqAbs_2Call, assertApproxEqAbs_3Call),
443}
444
445impl_assertions! {
446    |left, right, decimals, maxDelta| uint_assert_approx_eq_abs(*left, *right, *maxDelta),
447    |e| e.format_with_decimals(decimals),
448    (assertApproxEqAbsDecimal_0Call, assertApproxEqAbsDecimal_1Call),
449}
450
451impl_assertions! {
452    |left, right, decimals, maxDelta| int_assert_approx_eq_abs(*left, *right, *maxDelta),
453    |e| e.format_with_decimals(decimals),
454    (assertApproxEqAbsDecimal_2Call, assertApproxEqAbsDecimal_3Call),
455}
456
457impl_assertions! {
458    |left, right, maxPercentDelta| uint_assert_approx_eq_rel(*left, *right, *maxPercentDelta),
459    (assertApproxEqRel_0Call, assertApproxEqRel_1Call),
460}
461
462impl_assertions! {
463    |left, right, maxPercentDelta| int_assert_approx_eq_rel(*left, *right, *maxPercentDelta),
464    (assertApproxEqRel_2Call, assertApproxEqRel_3Call),
465}
466
467impl_assertions! {
468    |left, right, decimals, maxPercentDelta| uint_assert_approx_eq_rel(*left, *right, *maxPercentDelta),
469    |e| e.format_with_decimals(decimals),
470    (assertApproxEqRelDecimal_0Call, assertApproxEqRelDecimal_1Call),
471}
472
473impl_assertions! {
474    |left, right, decimals, maxPercentDelta| int_assert_approx_eq_rel(*left, *right, *maxPercentDelta),
475    |e| e.format_with_decimals(decimals),
476    (assertApproxEqRelDecimal_2Call, assertApproxEqRelDecimal_3Call),
477}
478
479const fn assert_true(condition: bool) -> Result<(), ()> {
480    if condition { Ok(()) } else { Err(()) }
481}
482
483const fn assert_false(condition: bool) -> Result<(), ()> {
484    assert_true(!condition)
485}
486
487fn assert_eq<'a, T: PartialEq>(left: &'a T, right: &'a T) -> ComparisonResult<'a, T> {
488    if left == right {
489        Ok(())
490    } else {
491        Err(ComparisonAssertionError { kind: AssertionKind::Eq, left, right })
492    }
493}
494
495fn assert_not_eq<'a, T: PartialEq>(left: &'a T, right: &'a T) -> ComparisonResult<'a, T> {
496    if left == right {
497        Err(ComparisonAssertionError { kind: AssertionKind::Ne, left, right })
498    } else {
499        Ok(())
500    }
501}
502
503fn assert_gt<'a, T: PartialOrd>(left: &'a T, right: &'a T) -> ComparisonResult<'a, T> {
504    if left > right {
505        Ok(())
506    } else {
507        Err(ComparisonAssertionError { kind: AssertionKind::Gt, left, right })
508    }
509}
510
511fn assert_ge<'a, T: PartialOrd>(left: &'a T, right: &'a T) -> ComparisonResult<'a, T> {
512    if left >= right {
513        Ok(())
514    } else {
515        Err(ComparisonAssertionError { kind: AssertionKind::Ge, left, right })
516    }
517}
518
519fn assert_lt<'a, T: PartialOrd>(left: &'a T, right: &'a T) -> ComparisonResult<'a, T> {
520    if left < right {
521        Ok(())
522    } else {
523        Err(ComparisonAssertionError { kind: AssertionKind::Lt, left, right })
524    }
525}
526
527fn assert_le<'a, T: PartialOrd>(left: &'a T, right: &'a T) -> ComparisonResult<'a, T> {
528    if left <= right {
529        Ok(())
530    } else {
531        Err(ComparisonAssertionError { kind: AssertionKind::Le, left, right })
532    }
533}
534
535fn get_delta_int(left: I256, right: I256) -> U256 {
536    let (left_sign, left_abs) = left.into_sign_and_abs();
537    let (right_sign, right_abs) = right.into_sign_and_abs();
538
539    if left_sign == right_sign {
540        if left_abs > right_abs { left_abs - right_abs } else { right_abs - left_abs }
541    } else {
542        left_abs.wrapping_add(right_abs)
543    }
544}
545
546/// Calculates the relative delta for an absolute difference.
547///
548/// Avoids overflow in the multiplication by using [`U512`] to hold the intermediary result.
549fn calc_delta_full<T>(abs_diff: U256, right: U256) -> Result<U256, EqRelAssertionError<T>> {
550    let delta = U512::from(abs_diff) * U512::from(10).pow(U512::from(EQ_REL_DELTA_RESOLUTION))
551        / U512::from(right);
552    U256::checked_from_limbs_slice(delta.as_limbs()).ok_or(EqRelAssertionError::Overflow)
553}
554
555fn uint_assert_approx_eq_abs(
556    left: U256,
557    right: U256,
558    max_delta: U256,
559) -> Result<(), Box<EqAbsAssertionError<U256, U256>>> {
560    let delta = left.abs_diff(right);
561
562    if delta <= max_delta {
563        Ok(())
564    } else {
565        Err(Box::new(EqAbsAssertionError { left, right, max_delta, real_delta: delta }))
566    }
567}
568
569fn int_assert_approx_eq_abs(
570    left: I256,
571    right: I256,
572    max_delta: U256,
573) -> Result<(), Box<EqAbsAssertionError<I256, U256>>> {
574    let delta = get_delta_int(left, right);
575
576    if delta <= max_delta {
577        Ok(())
578    } else {
579        Err(Box::new(EqAbsAssertionError { left, right, max_delta, real_delta: delta }))
580    }
581}
582
583fn uint_assert_approx_eq_rel(
584    left: U256,
585    right: U256,
586    max_delta: U256,
587) -> Result<(), EqRelAssertionError<U256>> {
588    if right.is_zero() {
589        if left.is_zero() {
590            return Ok(());
591        }
592        return Err(EqRelAssertionError::Failure(Box::new(EqRelAssertionFailure {
593            left,
594            right,
595            max_delta,
596            real_delta: EqRelDelta::Undefined,
597        })));
598    }
599
600    let delta = calc_delta_full::<U256>(left.abs_diff(right), right)?;
601
602    if delta <= max_delta {
603        Ok(())
604    } else {
605        Err(EqRelAssertionError::Failure(Box::new(EqRelAssertionFailure {
606            left,
607            right,
608            max_delta,
609            real_delta: EqRelDelta::Defined(delta),
610        })))
611    }
612}
613
614fn int_assert_approx_eq_rel(
615    left: I256,
616    right: I256,
617    max_delta: U256,
618) -> Result<(), EqRelAssertionError<I256>> {
619    if right.is_zero() {
620        if left.is_zero() {
621            return Ok(());
622        }
623        return Err(EqRelAssertionError::Failure(Box::new(EqRelAssertionFailure {
624            left,
625            right,
626            max_delta,
627            real_delta: EqRelDelta::Undefined,
628        })));
629    }
630
631    let delta = calc_delta_full::<I256>(get_delta_int(left, right), right.unsigned_abs())?;
632
633    if delta <= max_delta {
634        Ok(())
635    } else {
636        Err(EqRelAssertionError::Failure(Box::new(EqRelAssertionFailure {
637            left,
638            right,
639            max_delta,
640            real_delta: EqRelDelta::Defined(delta),
641        })))
642    }
643}
644
645/// Records the failed assertions and frames of a call by value-independent call sites, so a
646/// minimizer can tell whether a smaller input fails the same way.
647#[derive(Clone, Debug, Default)]
648pub struct FailureTrace {
649    /// Site of the latest call made by an executing frame.
650    pending: B256,
651    /// Tracking of each executing frame, indexed by call depth.
652    frames: Vec<SiteFrame>,
653    /// Failed assertions and failed frames, in execution order.
654    events: Vec<FailureEvent>,
655    /// Whether a snapshot was restored or a cheatcode with effects outside the EVM was skipped,
656    /// which can make a different path look like this one.
657    pub(crate) unidentified: bool,
658}
659
660/// Call site tracking of one executing frame.
661#[derive(Clone, Debug, Default)]
662struct SiteFrame {
663    /// Site of the call that entered this frame.
664    entry: B256,
665    /// For each stack slot, the pc of the `PUSH` its value was copied from, if any.
666    pushed_at: Vec<Option<usize>>,
667    /// Address and code of this frame, to identify the instruction that halted it.
668    destination: Address,
669    /// See [`Self::destination`].
670    code: Bytes,
671    /// Whether this frame runs initcode.
672    is_create: bool,
673    /// Highest pc executed so far, used to hash the executed part of initcode.
674    max_pc: usize,
675    /// Pc of the latest instruction, which halted the frame if it halted.
676    last_pc: usize,
677    /// Pc of the latest `JUMPI`, taken or not.
678    last_jumpi: usize,
679    /// Number of failure events recorded before this frame started.
680    events_before: usize,
681    /// Site of the `REVERT` or `INVALID` instruction that failed this frame, if any.
682    failed_at: Option<B256>,
683}
684
685impl SiteFrame {
686    /// Returns the site of the instruction about to execute: the frame's entry, the executing
687    /// code and pc, and the return labels of the internal functions that led to it. Values that
688    /// are not pushed constants, such as inputs, are ignored.
689    fn site<FEN: FoundryEvmNetwork>(&self, interpreter: &InterpreterFor<'_, '_, FEN>) -> B256 {
690        let code = interpreter.original_bytecode_slice();
691        let mut preimage = self.entry.to_vec();
692        // Initcode embeds constructor arguments, so constructors only hash executed code, and
693        // their address can derive from those arguments, so the entry identifies them instead.
694        let code_hash = if self.is_create {
695            keccak256(code.get(..=self.max_pc).unwrap_or(code))
696        } else {
697            preimage.extend_from_slice(interpreter.message().destination.as_slice());
698            interpreter.original_bytecode_hash()
699        };
700        preimage.extend_from_slice(code_hash.as_slice());
701        preimage.extend_from_slice(&interpreter.pc().to_be_bytes());
702        for (value, pushed_at) in interpreter.stack().as_slice().iter().zip(&self.pushed_at) {
703            if let Some(pushed_at) = pushed_at
704                && is_return_label(code, value)
705            {
706                preimage.extend_from_slice(&pushed_at.to_be_bytes());
707            }
708        }
709        keccak256(preimage)
710    }
711
712    /// Returns the site of the latest instruction, which halted the frame, without the return
713    /// labels on its stack.
714    fn halt_site(&self) -> B256 {
715        let mut preimage = self.entry.to_vec();
716        let code_hash = if self.is_create {
717            keccak256(self.code.get(..=self.max_pc).unwrap_or(&self.code))
718        } else {
719            preimage.extend_from_slice(self.destination.as_slice());
720            keccak256(&self.code)
721        };
722        preimage.extend_from_slice(code_hash.as_slice());
723        preimage.extend_from_slice(&self.last_pc.to_be_bytes());
724        preimage.extend_from_slice(&self.last_jumpi.to_be_bytes());
725        keccak256(preimage)
726    }
727}
728
729/// A failure recorded by [`FailureTrace`].
730#[derive(Clone, Debug)]
731enum FailureEvent {
732    /// A failed assertion, identified by its call site, cheatcode and unformatted message, with
733    /// the hash of its revert data when assertions revert.
734    Assertion { identity: B256, revert: Option<B256> },
735    /// A call or create that reverted or halted, identified by the site where it failed, or of
736    /// the call when it ran no instructions, with the number of failure events recorded within it.
737    Frame { site: B256, stop: InstrStop, events: usize },
738}
739
740impl FailureTrace {
741    /// Starts tracking the frame of `interpreter` at `depth`.
742    pub(crate) fn enter_frame<FEN: FoundryEvmNetwork>(
743        &mut self,
744        interpreter: &InterpreterFor<'_, '_, FEN>,
745        depth: usize,
746    ) {
747        let frame = SiteFrame {
748            entry: self.pending,
749            events_before: self.events.len(),
750            ..Default::default()
751        };
752        // Frames entered without an interpreter, such as cheatcode calls, were entered at
753        // `pending` too.
754        self.frames.resize(depth, frame.clone());
755        self.frames.push(SiteFrame {
756            destination: interpreter.message().destination,
757            code: interpreter.original_bytecode(),
758            is_create: interpreter.message().kind.is_create(),
759            ..frame
760        });
761    }
762
763    /// Records the site of external calls and tracks which stack values are pushed constants.
764    pub(crate) fn step<FEN: FoundryEvmNetwork>(
765        &mut self,
766        interpreter: &mut InterpreterFor<'_, '_, FEN>,
767        depth: usize,
768    ) {
769        let Some(frame) = self.frames.get_mut(depth) else { return };
770        let height = interpreter.stack().len();
771        frame.pushed_at.resize(height, None);
772        let pc = interpreter.pc();
773        frame.max_pc = frame.max_pc.max(pc);
774        frame.last_pc = pc;
775        let opcode = interpreter.opcode();
776        match opcode {
777            op::PUSH0..=op::PUSH32 => return frame.pushed_at.push(Some(pc)),
778            op::DUP1..=op::DUP16 => {
779                let n = (opcode - op::DUP1 + 1) as usize;
780                if let Some(slot) = height.checked_sub(n) {
781                    frame.pushed_at.push(frame.pushed_at[slot]);
782                }
783                return;
784            }
785            op::SWAP1..=op::SWAP16 => {
786                let n = (opcode - op::SWAP1 + 1) as usize;
787                if let Some(slot) = height.checked_sub(n + 1) {
788                    frame.pushed_at.swap(slot, height - 1);
789                }
790                return;
791            }
792            // Their stack effect depends on an immediate, so stop trusting the tracked slots.
793            op::SWAPN | op::EXCHANGE => frame.pushed_at.fill(None),
794            op::CALL
795            | op::CALLCODE
796            | op::DELEGATECALL
797            | op::STATICCALL
798            | op::CREATE
799            | op::CREATE2 => self.pending = frame.site::<FEN>(interpreter),
800            op::JUMPI => frame.last_jumpi = pc,
801            op::REVERT | op::INVALID => {
802                // The optimizer shares revert blocks between checks, which the latest branch tells
803                // apart.
804                let site = frame.site::<FEN>(interpreter);
805                let preimage = [site.as_slice(), &frame.last_jumpi.to_be_bytes()].concat();
806                frame.failed_at = Some(keccak256(preimage));
807            }
808            _ => {}
809        }
810        if let Some(info) = OpCode::new(opcode) {
811            frame.pushed_at.truncate(height.saturating_sub(info.inputs() as usize));
812            frame.pushed_at.extend(std::iter::repeat_n(None, info.outputs() as usize));
813        }
814    }
815
816    /// Records a failed assertion, or a `fail()`, made by the latest call.
817    pub(crate) fn record_assertion(
818        &mut self,
819        selector: [u8; 4],
820        message: &str,
821        revert: Option<B256>,
822    ) {
823        let identity = keccak256([self.pending.as_slice(), &selector, message.as_bytes()].concat());
824        self.events.push(FailureEvent::Assertion { identity, revert });
825    }
826
827    /// Records the outcome of the frame at `depth` once all inspectors have finalized it.
828    pub fn finish_frame<FEN: FoundryEvmNetwork>(
829        &mut self,
830        depth: usize,
831        result: &MessageResultFor<FEN>,
832    ) {
833        if !result.stop.is_success() {
834            // Frames without an interpreter, such as cheatcode calls, were entered at `pending`.
835            let (site, events_before) =
836                self.frames.get(depth + 1).map_or((self.pending, self.events.len()), |frame| {
837                    (frame.failed_at.unwrap_or_else(|| frame.halt_site()), frame.events_before)
838                });
839            let events = self.events.len() - events_before;
840            self.events.push(FailureEvent::Frame { site, stop: result.stop, events });
841        }
842        self.frames.truncate(depth + 1);
843    }
844
845    /// Returns the value-independent identity of the finished call that stopped with `exit` and
846    /// returned `output`, and starts recording the next call.
847    ///
848    /// The identity is unknown when a snapshot restore discarded part of the history, when a
849    /// cheatcode with effects outside the EVM was skipped, when the call succeeded without a failed
850    /// assertion or `fail()`, such as after a legacy DSTest failure that only wrote its own flag,
851    /// or when several failed assertions could have produced the revert data.
852    pub fn take_identity(&mut self, exit: InstrStop, output: &[u8]) -> Option<B256> {
853        let Self { events, unidentified, .. } = std::mem::take(self);
854        if unidentified {
855            return None;
856        }
857        let mut preimage = vec![exit as u8];
858        for event in &events {
859            match event {
860                FailureEvent::Assertion { identity, .. } => {
861                    preimage.push(0);
862                    preimage.extend_from_slice(identity.as_slice());
863                }
864                FailureEvent::Frame { site, stop, events } => {
865                    preimage.push(1);
866                    preimage.extend_from_slice(site.as_slice());
867                    preimage.push(*stop as u8);
868                    preimage.extend_from_slice(&events.to_be_bytes());
869                }
870            }
871        }
872        if exit.is_success() {
873            if !events.iter().any(|event| matches!(event, FailureEvent::Assertion { .. })) {
874                return None;
875            }
876        } else {
877            // Revert data produced by exactly one failed assertion is identified by that
878            // assertion, without the values in its message. Other revert data is compared in full,
879            // as custom error arguments can tell apart failures raised from one `REVERT`, such as
880            // a failure code. Errors that carry the minimized values therefore do not shrink.
881            let output_hash = keccak256(output);
882            let mut sources = events.iter().enumerate().filter(|(_, event)| {
883                matches!(event, FailureEvent::Assertion { revert, .. } if *revert == Some(output_hash))
884            });
885            match (sources.next(), sources.next()) {
886                (Some((index, _)), None) => {
887                    preimage.push(2);
888                    preimage.extend_from_slice(&index.to_be_bytes());
889                }
890                (None, _) => {
891                    preimage.push(3);
892                    preimage.extend_from_slice(output_hash.as_slice());
893                }
894                (Some(_), Some(_)) => return None,
895            }
896        }
897        Some(keccak256(preimage))
898    }
899}
900
901/// Records where a call failed, cheaply enough to run during campaigns, so a replay of the same
902/// input can be checked to fail the same way, unlike its revert data, exit reason and gas, which
903/// other failure paths can reproduce.
904///
905/// Unlike [`FailureTrace`], sites include values such as return labels, so only runs of the same
906/// input are comparable.
907#[derive(Clone, Debug, Default)]
908pub struct FailureProvenance {
909    /// Frame index and site of the `REVERT` or `INVALID` instruction about to end a frame.
910    pending_revert: Option<(usize, B256)>,
911    /// Identity of the failed assertion made by the cheatcode call in progress.
912    pub(crate) pending_assertion: Option<B256>,
913    /// Hash of the failed assertions and failed frames so far, in execution order.
914    hash: B256,
915    /// Whether a frame halted at an instruction that is not recorded, so the call has no
916    /// provenance.
917    unknown: bool,
918    /// Sites of the calls that entered the frames in progress, by depth.
919    callers: Vec<B256>,
920    /// Pc of the latest `JUMPI` of each frame in progress, taken or not, by the depth
921    /// [`Self::record_revert`] receives.
922    jumpis: Vec<usize>,
923}
924
925impl FailureProvenance {
926    /// Returns the site of the instruction about to execute: the executing address, code and pc,
927    /// and the stack values that look like return labels of internal functions.
928    fn site<FEN: FoundryEvmNetwork>(interpreter: &InterpreterFor<'_, '_, FEN>) -> B256 {
929        let code = interpreter.original_bytecode_slice();
930        let mut preimage = interpreter.message().destination.to_vec();
931        preimage.extend_from_slice(interpreter.original_bytecode_hash().as_slice());
932        preimage.extend_from_slice(&interpreter.pc().to_be_bytes());
933        for value in interpreter.stack().as_slice() {
934            if is_return_label(code, value) {
935                preimage.extend_from_slice(&value.to_be_bytes::<32>());
936            }
937        }
938        keccak256(preimage)
939    }
940
941    /// Records the site of the `REVERT` or `INVALID` instruction about to execute in the frame at
942    /// `depth`.
943    pub(crate) fn record_revert<FEN: FoundryEvmNetwork>(
944        &mut self,
945        interpreter: &InterpreterFor<'_, '_, FEN>,
946        depth: usize,
947    ) {
948        // The optimizer shares revert blocks between checks, which the frame's latest branch
949        // tells apart.
950        let jumpi = self.jumpis.get(depth).copied().unwrap_or_default();
951        let site = Self::site::<FEN>(interpreter);
952        self.pending_revert =
953            Some((depth, keccak256([site.as_slice(), &jumpi.to_be_bytes()].concat())));
954    }
955
956    /// Records the `JUMPI` about to execute at `pc` in the frame at `depth`.
957    pub(crate) fn record_jumpi(&mut self, depth: usize, pc: usize) {
958        if self.jumpis.len() <= depth {
959            self.jumpis.resize(depth + 1, 0);
960        }
961        self.jumpis[depth] = pc;
962    }
963
964    /// Records the site of `interpreter`'s call that enters the frame at `depth`.
965    pub fn enter_frame<FEN: FoundryEvmNetwork>(
966        &mut self,
967        depth: usize,
968        interpreter: &InterpreterFor<'_, '_, FEN>,
969    ) {
970        self.callers.truncate(depth);
971        self.callers.push(Self::site::<FEN>(interpreter));
972        // The entered frame, stepped at `depth + 1`, has not branched yet.
973        self.jumpis.truncate(depth + 1);
974    }
975
976    /// Records the failed assertion of the finished cheatcode call, if any, by the sites of the
977    /// calls that led to it, so the same assertion reached through different callers differs.
978    pub(crate) fn finish_assertion(&mut self) {
979        if let Some(assertion) = self.pending_assertion.take() {
980            let site = keccak256(self.callers.concat());
981            self.fold(keccak256([site.as_slice(), assertion.as_slice()].concat()));
982        }
983    }
984
985    /// Records the outcome of the frame at `depth` once all inspectors have finalized it, by the
986    /// sites of the calls that led to it, given the interpreter of its caller, or of the frame
987    /// itself for the first frame.
988    pub fn finish_frame<FEN: FoundryEvmNetwork>(
989        &mut self,
990        depth: usize,
991        interpreter: &InterpreterFor<'_, '_, FEN>,
992        result: &MessageResultFor<FEN>,
993    ) {
994        let pending_revert = self.pending_revert.take();
995        // The same callee fails the same way when entered through different calls.
996        let callers = (!result.stop.is_success()).then(|| keccak256(self.callers.concat()));
997        self.callers.truncate(depth);
998        let Some(callers) = callers else { return };
999        let stop = result.stop as u8;
1000        let site = match pending_revert {
1001            Some((frame, site)) if frame == depth + 1 => site,
1002            // Halts such as invalid jumps or running out of gas can happen at any instruction,
1003            // which is not recorded.
1004            _ if result.stop != InstrStop::Revert => {
1005                self.unknown = true;
1006                return;
1007            }
1008            // Frames without instructions, such as cheatcode calls, are identified by the call
1009            // that entered them.
1010            _ => {
1011                let entry = if usize::from(interpreter.message().depth) < depth {
1012                    Self::site::<FEN>(interpreter)
1013                } else {
1014                    keccak256(interpreter.message().destination)
1015                };
1016                keccak256([entry.as_slice(), &[stop]].concat())
1017            }
1018        };
1019        let output = keccak256(&result.output);
1020        self.fold(keccak256(
1021            [callers.as_slice(), site.as_slice(), &[stop], output.as_slice()].concat(),
1022        ));
1023    }
1024
1025    /// Returns the provenance of the finished call, if known, and starts recording the next call.
1026    pub fn take(&mut self) -> Option<B256> {
1027        let this = std::mem::take(self);
1028        (!this.unknown).then_some(this.hash)
1029    }
1030
1031    /// Appends a failure event to the hash.
1032    fn fold(&mut self, event: B256) {
1033        self.hash = keccak256([self.hash.as_slice(), event.as_slice()].concat());
1034    }
1035}
1036
1037/// Returns whether `value` is the pc of a `JUMPDEST` right after a `JUMP` in `code`, as the
1038/// return label of an internal function call is.
1039fn is_return_label(code: &[u8], value: &U256) -> bool {
1040    usize::try_from(*value).is_ok_and(|label| {
1041        label > 0 && code.get(label) == Some(&op::JUMPDEST) && code[label - 1] == op::JUMP
1042    })
1043}