Skip to main content

foundry_evm_symbolic/runtime/solver/normalize/
rounding.rs

1//! Rounding relations between a rounded multiple and its original dividend.
2//!
3//! These bounds describe mathematical differences, not wrapping EVM subtractions.
4//! They are consumed only where the sign or a non-wrapping product is established.
5
6use super::{
7    ConstraintContext, HashMap, MAX_LOCAL_ANALYSIS_NODES, SymBinOp, SymBoolExpr, SymBoolExprKind,
8    SymCmpOp, SymExpr, SymExprKind, U256, WordInterval, euclidean_sum_dividend,
9    word_division_operands,
10};
11
12/// `anchor - below <= rounded <= anchor + above` over mathematical integers.
13struct RoundingBounds<'a> {
14    anchor: &'a SymExpr,
15    below: U256,
16    above: U256,
17}
18
19impl ConstraintContext {
20    /// Matches `(dividend / d) * d` for a positive constant `d`.
21    pub(super) fn rounded_product_operands(expr: &SymExpr) -> Option<(&SymExpr, U256)> {
22        let (quotient, factor) = Self::constant_mul_operands(expr)?;
23        let (dividend, divisor) = quotient.udiv_operands()?;
24        (divisor.as_const() == Some(factor) && !factor.is_zero()).then_some((dividend, factor))
25    }
26
27    // Requesting an anchor preserves the raw dividend relation even when a safe
28    // offset also exposes a relation to the pre-offset value. With no requested
29    // anchor, prefer the shifted relation for quotient cancellation.
30    fn rounding_bounds<'a>(
31        &self,
32        expr: &'a SymExpr,
33        anchor: Option<&SymExpr>,
34    ) -> Option<RoundingBounds<'a>> {
35        let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
36        self.rounding_bounds_cached(expr, anchor, &mut HashMap::default(), &mut remaining)
37    }
38
39    fn rounding_bounds_cached<'a>(
40        &self,
41        expr: &'a SymExpr,
42        anchor: Option<&SymExpr>,
43        intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
44        remaining: &mut usize,
45    ) -> Option<RoundingBounds<'a>> {
46        let (dividend, divisor) = Self::rounded_product_operands(expr)?;
47        // Euclidean division: q*d = dividend - remainder, 0 <= remainder < d.
48        // In particular, q*d <= dividend <= MAX, so the rescaling cannot wrap.
49        let width = divisor - U256::ONE;
50        let raw = RoundingBounds { anchor: dividend, below: width, above: U256::ZERO };
51        if anchor == Some(dividend) {
52            return Some(raw);
53        }
54        let offset = match dividend.kind() {
55            SymExprKind::BinOp(SymBinOp::Add, anchor, bias)
56                if let Some(bias) = bias.as_const()
57                    && bias <= width =>
58            {
59                Some((anchor, bias, bias))
60            }
61            SymExprKind::BinOp(SymBinOp::Sub, sum, one)
62                if one.as_const() == Some(U256::ONE)
63                    && let SymExprKind::BinOp(SymBinOp::Add, anchor, bias) = sum.kind()
64                    && bias.as_const() == Some(divisor) =>
65            {
66                // Preserve the intermediate addition in `(anchor + d) - 1`.
67                Some((anchor, width, divisor))
68            }
69            _ => None,
70        };
71        if let Some((anchor, bias, addition)) = offset
72            && self
73                .interval_cached(anchor, intervals, remaining)
74                .is_some_and(|range| range.max.checked_add(addition).is_some())
75        {
76            // For dividend = anchor + bias, the error is bias - remainder.
77            return Some(RoundingBounds { anchor, below: width - bias, above: bias });
78        }
79        // An unproved offset remains opaque. A bound on a wrapped sum cannot
80        // justify removing that sum from the relation.
81        Some(raw)
82    }
83
84    /// A nonnegative rounding error smaller than a divisor preserves its quotient.
85    pub(super) fn quotient_of_rounded_product<'a>(&self, expr: &'a SymExpr) -> Option<&'a SymExpr> {
86        let (numerator, divisor) = expr.udiv_operands()?;
87        let bounds = self.rounding_bounds(numerator, None)?;
88        let minimum =
89            divisor.as_const().or_else(|| self.unsigned_lower_bounds.get(divisor).copied())?;
90        if !bounds.below.is_zero() || bounds.above >= minimum {
91            return None;
92        }
93        let SymExprKind::BinOp(SymBinOp::Mul, left, right) = bounds.anchor.kind() else {
94            return None;
95        };
96        let value = if left == divisor {
97            right
98        } else if right == divisor {
99            left
100        } else {
101            return None;
102        };
103        // The anchor is an EVM word. Cancelling a factor requires independent
104        // evidence that its mathematical product did not wrap.
105        self.mul_cannot_overflow_256(value, divisor).then_some(value)
106    }
107
108    pub(super) fn rounding_comparison_value(&self, expr: &SymBoolExpr) -> Option<bool> {
109        if let SymBoolExprKind::Not(inner) = expr.kind() {
110            return self.rounding_comparison_value(inner).map(|value| !value);
111        }
112        let SymBoolExprKind::Cmp(op, left, right) = expr.kind() else { return None };
113        for (rounded, anchor, op) in [
114            (left, right, *op),
115            (
116                right,
117                left,
118                match op {
119                    SymCmpOp::Ult => SymCmpOp::Ugt,
120                    SymCmpOp::Ule => SymCmpOp::Uge,
121                    SymCmpOp::Ugt => SymCmpOp::Ult,
122                    SymCmpOp::Uge => SymCmpOp::Ule,
123                    other => *other,
124                },
125            ),
126        ] {
127            if let Some(bounds) = self.rounding_bounds(rounded, Some(anchor))
128                && bounds.anchor == anchor
129            {
130                match op {
131                    SymCmpOp::Uge if bounds.below.is_zero() => return Some(true),
132                    SymCmpOp::Ult if bounds.below.is_zero() => return Some(false),
133                    SymCmpOp::Ule if bounds.above.is_zero() => return Some(true),
134                    SymCmpOp::Ugt if bounds.above.is_zero() => return Some(false),
135                    _ => {}
136                }
137            }
138        }
139        None
140    }
141
142    /// Decides a comparison between a division result and one of its operands.
143    ///
144    /// With a nonzero divisor, `a % d < d` and `a / d <= a`. For every divisor, `a % d <= a` and
145    /// `(a / d) * k <= a` once `k <= d`, and `x * y / k <= x` once `y <= k` and `x * y` cannot
146    /// wrap. With a nonzero `y + z` that cannot wrap, `x * y / (y + z) <= x`, strictly for nonzero
147    /// `x` and `z`. The Euclidean sum `(a / d) * d + a % d` is `a`, so each summand is at most the
148    /// other's complement. With a nonzero divisor, `a / d <= (a - 1) / d + 1`, also when selected
149    /// by `a != 0`, and `(x * y + c) / d <= x` once `y <= d`, `x * y` cannot wrap, and `c < d`.
150    /// Another conjunct's cross-multiplied `x * k <= y * l` also decides `x <= y` once `k` is
151    /// positive, `l <= k`, and `x * k` cannot wrap.
152    /// The shares `w * a / k + w * b / k <= w` once `a + b <= k`.
153    pub(super) fn division_comparison_value(&self, expr: &SymBoolExpr) -> Option<bool> {
154        if let SymBoolExprKind::Not(inner) = expr.kind() {
155            return self.division_comparison_value(inner).map(|value| !value);
156        }
157        let SymBoolExprKind::Cmp(op, left, right) = expr.kind() else { return None };
158        let mut intervals = HashMap::default();
159        let mut remaining = MAX_LOCAL_ANALYSIS_NODES;
160        let mut order = |small, large| {
161            self.division_order(small, large, &mut intervals, &mut remaining).or_else(|| {
162                self.asserts_scaled_order(small, large, &mut intervals, &mut remaining)
163                    .then_some(false)
164            })
165        };
166        if let Some(strict) = order(left, right) {
167            return match op {
168                SymCmpOp::Ule => Some(true),
169                SymCmpOp::Ugt => Some(false),
170                SymCmpOp::Ult if strict => Some(true),
171                SymCmpOp::Uge if strict => Some(false),
172                _ => None,
173            };
174        }
175        if let Some(strict) = order(right, left) {
176            return match op {
177                SymCmpOp::Uge => Some(true),
178                SymCmpOp::Ult => Some(false),
179                SymCmpOp::Ugt if strict => Some(true),
180                SymCmpOp::Ule if strict => Some(false),
181                _ => None,
182            };
183        }
184        None
185    }
186
187    /// Returns whether a division shape proves `small <= large`, and whether the order is strict.
188    ///
189    /// Intervals share the caller's cache and node budget, so a chain of nested subtractions is
190    /// analyzed once instead of once per level.
191    fn division_order(
192        &self,
193        small: &SymExpr,
194        large: &SymExpr,
195        intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
196        remaining: &mut usize,
197    ) -> Option<bool> {
198        // The overflow rewrite turns a checked `a + b` into `~a < b` before `d != 0` resolves the
199        // division guards, so a symbolic divisor's Euclidean sum is not folded to `x`. That sum is
200        // `x` and cannot wrap, so `b <= ~a`. Two shares of one whole cannot wrap either.
201        if let SymExprKind::Not(base) = large.kind()
202            && (euclidean_sum_dividend(base, small).is_some()
203                || self.shares_whole(base, small, None, intervals, remaining).is_some())
204        {
205            return Some(false);
206        }
207        // Two shares sum to at most their whole.
208        if let SymExprKind::BinOp(SymBinOp::Add, first, second) = small.kind()
209            && self.shares_whole(first, second, Some(large), intervals, remaining).is_some()
210        {
211            return Some(false);
212        }
213        let mut interval = |expr: &SymExpr| self.interval_cached(expr, intervals, remaining);
214        let nonzero = |range: Option<WordInterval>| range.is_some_and(|range| !range.min.is_zero());
215        match small.kind() {
216            SymExprKind::BinOp(SymBinOp::URem, dividend, divisor) => {
217                if dividend == large {
218                    return Some(false);
219                }
220                (divisor == large && nonzero(interval(divisor))).then_some(true)
221            }
222            SymExprKind::BinOp(SymBinOp::UDiv, dividend, divisor) => {
223                if dividend == large {
224                    return nonzero(interval(divisor)).then_some(false);
225                }
226                // `x / d <= (x - 1) / d + 1` for `d >= 1`, as in OpenZeppelin's `ceilDiv`: for
227                // `x >= 1` the quotients differ by at most one and the sum cannot wrap, and
228                // `0 / d` is zero. SMT's `x / 0` is all ones, so `d` must be nonzero.
229                let ceiling = match large.kind() {
230                    // OpenZeppelin v5 selects zero for `x == 0`, where `x / d` is zero too.
231                    SymExprKind::Ite(condition, value, zero)
232                        if zero.as_const() == Some(U256::ZERO)
233                            && let SymBoolExprKind::Not(inner) = condition.kind()
234                            && inner.zero_check_operand() == Some(dividend) =>
235                    {
236                        value
237                    }
238                    _ => large,
239                };
240                if let SymExprKind::BinOp(SymBinOp::Add, quotient, increment) = ceiling.kind()
241                    && increment.as_const() == Some(U256::ONE)
242                    && let Some((predecessor, other)) = quotient.udiv_operands()
243                    && other == divisor
244                    && let SymExprKind::BinOp(SymBinOp::Sub, value, decrement) = predecessor.kind()
245                    && decrement.as_const() == Some(U256::ONE)
246                    && value == dividend
247                {
248                    return nonzero(interval(divisor)).then_some(false);
249                }
250                // When `y + z` is nonzero and does not wrap, `x * y / (y + z) <= x`, strictly once
251                // `x` and `z` are nonzero, since `x * y < x * (y + z)`. A wrapped product only
252                // shrinks the dividend. `UDiv` by zero is all ones, so the divisor must be nonzero.
253                if let SymExprKind::BinOp(SymBinOp::Mul, left, right) = dividend.kind()
254                    && let SymExprKind::BinOp(SymBinOp::Add, a, b) = divisor.kind()
255                    && let Some(other) = [(left, right), (right, left)]
256                        .into_iter()
257                        .find_map(|(x, y)| (x == large).then_some(y))
258                    && let Some(rest) =
259                        [(a, b), (b, a)].into_iter().find_map(|(y, z)| (y == other).then_some(z))
260                    && let Some(other) = interval(other)
261                    && let Some(rest) = interval(rest)
262                    && other.max.checked_add(rest.max).is_some()
263                    && nonzero(interval(divisor))
264                {
265                    return Some(nonzero(interval(large)) && !rest.min.is_zero());
266                }
267                // Rounding up adds at most `d - 1`, so `(x * y + c) / d <= x` still holds once
268                // `c <= d - 1`; a wrapped sum only shrinks the dividend.
269                let mut bounded = |dividend: &SymExpr, addend: Option<&SymExpr>| {
270                    let SymExprKind::BinOp(SymBinOp::Mul, left, right) = dividend.kind() else {
271                        return false;
272                    };
273                    let other = if left == large {
274                        right
275                    } else if right == large {
276                        left
277                    } else {
278                        return false;
279                    };
280                    let Some(range) = interval(divisor).filter(|range| !range.min.is_zero()) else {
281                        return false;
282                    };
283                    addend.is_none_or(|addend| {
284                        matches!(addend.kind(), SymExprKind::BinOp(SymBinOp::Sub, value, one)
285                            if value == divisor && one.as_const() == Some(U256::ONE))
286                            || interval(addend).is_some_and(|addend| addend.max < range.min)
287                    }) && (other == divisor
288                        || interval(other).is_some_and(|other| other.max <= range.min)
289                        || self.asserts_less_or_equal(other, divisor))
290                        && self.mul_cannot_overflow_256(left, right)
291                };
292                // `round_down(n, t) <= n` (zero when `t == 0`), so dividing the rounded product
293                // is bounded by `n / d`. The EVM `DIV` may still carry its `t == 0` guard.
294                let peeled = match dividend.kind() {
295                    SymExprKind::BinOp(SymBinOp::Mul, left, right) => {
296                        [(left, right), (right, left)].into_iter().find_map(|(quotient, factor)| {
297                            word_division_operands(quotient)
298                                .and_then(|(n, t)| (t == factor).then_some(n))
299                        })
300                    }
301                    _ => None,
302                };
303                let rounded_up = match dividend.kind() {
304                    SymExprKind::BinOp(SymBinOp::Add, a, b) => [(a, b), (b, a)]
305                        .into_iter()
306                        .any(|(product, addend)| bounded(product, Some(addend))),
307                    // `(x * y + d) - 1`. A wrapped sum is smaller, and a sum that wraps to zero
308                    // gives `MAX == x * y + d - 1` exactly.
309                    SymExprKind::BinOp(SymBinOp::Sub, sum, one)
310                        if one.as_const() == Some(U256::ONE)
311                            && let SymExprKind::BinOp(SymBinOp::Add, a, b) = sum.kind()
312                            && let Some(product) =
313                                (a == divisor).then_some(b).or((b == divisor).then_some(a)) =>
314                    {
315                        bounded(product, None)
316                    }
317                    _ => false,
318                };
319                (rounded_up
320                    || peeled.is_some_and(|peeled| bounded(peeled, None))
321                    || bounded(dividend, None))
322                .then_some(false)
323            }
324            // `(x / d) * k <= (x / d) * d <= x` once `k <= d`, so the product cannot wrap; a zero
325            // `d` forces a zero product.
326            SymExprKind::BinOp(SymBinOp::Mul, left, right) => [(left, right), (right, left)]
327                .into_iter()
328                .any(|(quotient, factor)| {
329                    quotient.udiv_operands().is_some_and(|(dividend, divisor)| {
330                        dividend == large
331                            && (factor == divisor
332                                || interval(factor)
333                                    .zip(interval(divisor))
334                                    .is_some_and(|(factor, divisor)| factor.max <= divisor.min))
335                    })
336                })
337                .then_some(false),
338            _ => None,
339        }
340    }
341
342    /// Returns whether another conjunct asserts `small * k <= large * l` with `l <= k` and a
343    /// positive `k`, as in a cross-multiplied collateral check. When `small * k` does not wrap,
344    /// `small > large` would give `small * k > large * k >= large * l`, using `k > 0` and
345    /// `l <= k`, and a wrapped `large * l` is only smaller. The reverse, deciding a scaled fact
346    /// from `small <= large`, must never remove a conjunct, or the two could justify each other.
347    fn asserts_scaled_order(
348        &self,
349        small: &SymExpr,
350        large: &SymExpr,
351        intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
352        remaining: &mut usize,
353    ) -> bool {
354        let factor = |product: &'_ SymExpr, operand: &SymExpr| match product.kind() {
355            SymExprKind::BinOp(SymBinOp::Mul, left, right) if left == operand => {
356                Some(right.clone())
357            }
358            SymExprKind::BinOp(SymBinOp::Mul, left, right) if right == operand => {
359                Some(left.clone())
360            }
361            _ => None,
362        };
363        self.facts.iter().any(|fact| {
364            let (scaled_small, scaled_large) = match fact.kind() {
365                SymBoolExprKind::Cmp(SymCmpOp::Ult | SymCmpOp::Ule, left, right) => (left, right),
366                SymBoolExprKind::Not(inner) => match inner.kind() {
367                    SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right) => (right, left),
368                    _ => return false,
369                },
370                _ => return false,
371            };
372            let (Some(k), Some(l)) = (factor(scaled_small, small), factor(scaled_large, large))
373            else {
374                return false;
375            };
376            self.interval_cached(&k, intervals, remaining)
377                .zip(self.interval_cached(&l, intervals, remaining))
378                .is_some_and(|(k, l)| !k.min.is_zero() && l.max <= k.min)
379                && self.mul_cannot_overflow_256(small, &k)
380        })
381    }
382
383    /// Returns `w` for the shares `w * a / k` and `w * b / k` of a nonzero `k` once `a + b <= k`,
384    /// only matching `whole` when given. Their floors sum to at most `w * (a + b) / k <= w`, so the
385    /// sum cannot wrap, and a wrapped product only shrinks its share.
386    fn shares_whole<'a>(
387        &self,
388        first: &'a SymExpr,
389        second: &'a SymExpr,
390        whole: Option<&SymExpr>,
391        intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
392        remaining: &mut usize,
393    ) -> Option<&'a SymExpr> {
394        let (first, divisor) = first.udiv_operands()?;
395        let (second, other_divisor) = second.udiv_operands()?;
396        if divisor != other_divisor {
397            return None;
398        }
399        let (SymExprKind::BinOp(SymBinOp::Mul, w1, a1), SymExprKind::BinOp(SymBinOp::Mul, w2, b2)) =
400            (first.kind(), second.kind())
401        else {
402            return None;
403        };
404        let (found, a, b) =
405            [(w1, a1, w2, b2), (w1, a1, b2, w2), (a1, w1, w2, b2), (a1, w1, b2, w2)]
406                .into_iter()
407                .find_map(|(found, a, other, b)| {
408                    (found == other && whole.is_none_or(|whole| whole == found))
409                        .then_some((found, a, b))
410                })?;
411        let min = self.interval_cached(divisor, intervals, remaining)?.min;
412        if min.is_zero() {
413            return None;
414        }
415        // Whether another conjunct asserts `x <= y`, including strict `<`.
416        let asserted = |accept: &dyn Fn(&SymExpr, &SymExpr) -> bool| {
417            self.facts.iter().any(|fact| match fact.kind() {
418                SymBoolExprKind::Cmp(SymCmpOp::Ult | SymCmpOp::Ule, left, right) => {
419                    accept(left, right)
420                }
421                SymBoolExprKind::Not(inner) => matches!(
422                    inner.kind(),
423                    SymBoolExprKind::Cmp(SymCmpOp::Ult, left, right) if accept(right, left)
424                ),
425                _ => false,
426            })
427        };
428        // `a + b` must not wrap for `a + b <= k` to hold over the integers: from value ranges, or
429        // from a checked addition's `b <= ~a` guard.
430        let sum_max = self
431            .interval_cached(a, intervals, remaining)
432            .and_then(|a| a.max.checked_add(self.interval_cached(b, intervals, remaining)?.max));
433        let complement =
434            |x: &SymExpr, y: &SymExpr| matches!(y.kind(), SymExprKind::Not(inner) if inner == x);
435        if sum_max.is_none()
436            && !asserted(&|x, y| (x == b && complement(a, y)) || (x == a && complement(b, y)))
437        {
438            return None;
439        }
440        let is_sum = |expr: &SymExpr| {
441            matches!(expr.kind(), SymExprKind::BinOp(SymBinOp::Add, x, y)
442                if (x == a && y == b) || (x == b && y == a))
443        };
444        (sum_max.is_some_and(|max| max <= min)
445            || is_sum(divisor)
446            || asserted(&|x, y| is_sum(x) && y == divisor))
447        .then_some(found)
448    }
449
450    /// Returns whether other conjuncts assert `small <= large`, including strict `<`. An elapsed
451    /// `t - s` is at most `d` once `s <= t` and `t <= d + s`. A wrapped `d + s` would be below
452    /// `s <= t`, so the two facts cannot both hold.
453    fn asserts_less_or_equal(&self, small: &SymExpr, large: &SymExpr) -> bool {
454        if self.asserted_upper_bounds(small).contains(large) {
455            return true;
456        }
457        let SymExprKind::BinOp(SymBinOp::Sub, end, start) = small.kind() else { return false };
458        self.asserted_upper_bounds(start).contains(end)
459            && self.asserted_upper_bounds(end).iter().any(|sum| {
460                matches!(sum.kind(), SymExprKind::BinOp(SymBinOp::Add, a, b)
461                    if (a == large && b == start) || (a == start && b == large))
462            })
463    }
464
465    /// Bounds a subtraction only when the relation proves it cannot underflow.
466    pub(super) fn rounding_error_interval(
467        &self,
468        left: &SymExpr,
469        right: &SymExpr,
470        intervals: &mut HashMap<SymExpr, Option<WordInterval>>,
471        remaining: &mut usize,
472    ) -> Option<WordInterval> {
473        if let Some(bounds) = self.rounding_bounds_cached(left, Some(right), intervals, remaining)
474            && bounds.anchor == right
475            && bounds.below.is_zero()
476        {
477            return Some(WordInterval { min: U256::ZERO, max: bounds.above });
478        }
479        if let Some(bounds) = self.rounding_bounds_cached(right, Some(left), intervals, remaining)
480            && bounds.anchor == left
481            && bounds.above.is_zero()
482        {
483            return Some(WordInterval { min: U256::ZERO, max: bounds.below });
484        }
485        // A division shape such as `d - x % d` proves `right <= left`.
486        if self.division_order(right, left, intervals, remaining).is_some()
487            && let Some(left) = self.interval_cached(left, intervals, remaining)
488        {
489            return Some(WordInterval { min: U256::ZERO, max: left.max });
490        }
491        None
492    }
493}