Skip to content

Commit

Permalink
fix[ux]: fix compiler hang for large exponentiations (#3893)
Browse files Browse the repository at this point in the history
this commit fixes a UX bug where the compiler would hang while trying to
constant-fold large exponentiations. it does a loose check to see if the
output would be vastly out of bounds and fails fast if so.
  • Loading branch information
charles-cooper authored Mar 26, 2024
1 parent 1a40e93 commit 4595938
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions tests/functional/codegen/types/numbers/test_exponents.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@
from hypothesis import strategies as st

from vyper.codegen.arithmetic import calculate_largest_base, calculate_largest_power
from vyper.compiler import compile_code
from vyper.exceptions import InvalidLiteral


def test_compiler_hang():
code = """
@external
def f0():
lv0: uint256 = max_value(int128) ** max_value(int128)
"""
with pytest.raises(InvalidLiteral):
compile_code(code)


@pytest.mark.fuzzing
Expand Down
10 changes: 10 additions & 0 deletions vyper/ast/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import copy
import decimal
import functools
import math
import operator
import pickle
import sys
Expand Down Expand Up @@ -1080,6 +1081,15 @@ def _op(self, left, right):
raise TypeMismatch("Cannot perform exponentiation on decimal values.", self._parent)
if right < 0:
raise InvalidOperation("Cannot calculate a negative power", self._parent)
# prevent a compiler hang. we are ok with false positives at this
# stage since we are just trying to filter out inputs which can cause
# the compiler to hang. the others will get caught during constant
# folding or codegen.
# l**r > 2**256
# r * ln(l) > ln(2 ** 256)
# r > ln(2 ** 256) / ln(l)
if right > math.log(decimal.Decimal(2**257)) / math.log(decimal.Decimal(left)):
raise InvalidLiteral("Out of bounds", self)
return int(left**right)


Expand Down

0 comments on commit 4595938

Please sign in to comment.