Skip to content

Commit 6ed37b8

Browse files
authored
fix[ux]: fold keccak and sha256 of constant hexbytes (#4536)
This commit allows `keccak` and `sha256` of a constant hexbytes value to be folded.
1 parent 61d259a commit 6ed37b8

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

tests/functional/builtins/codegen/test_keccak256.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,17 @@ def foo() -> bytes32:
111111
"""
112112
c = get_contract(code)
113113
assert c.foo() == keccak(str_val.encode())
114+
115+
116+
def test_hash_constant_hexbytes(get_contract, keccak):
117+
hexbytes_val = "67363d3d37363d34f03d5260086018f3"
118+
code = f"""
119+
FOO: constant(Bytes[16]) = x"{hexbytes_val}"
120+
BAR: constant(bytes32) = keccak256(FOO)
121+
@external
122+
def foo() -> bytes32:
123+
x: bytes32 = BAR
124+
return x
125+
"""
126+
c = get_contract(code)
127+
assert c.foo() == keccak(bytes.fromhex(hexbytes_val))

tests/functional/builtins/codegen/test_sha256.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,17 @@ def foo() -> bytes32:
103103
"""
104104
c = get_contract(code)
105105
assert c.foo() == hashlib.sha256(str_val.encode()).digest()
106+
107+
108+
def test_sha256_constant_hexbytes(get_contract, keccak):
109+
hexbytes_val = "67363d3d37363d34f03d5260086018f3"
110+
code = f"""
111+
FOO: constant(Bytes[16]) = x"{hexbytes_val}"
112+
BAR: constant(bytes32) = sha256(FOO)
113+
@external
114+
def foo() -> bytes32:
115+
x: bytes32 = BAR
116+
return x
117+
"""
118+
c = get_contract(code)
119+
assert c.foo() == hashlib.sha256(bytes.fromhex(hexbytes_val)).digest()

vyper/builtins/functions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ class Keccak256(BuiltinFunctionT):
594594
def _try_fold(self, node):
595595
validate_call_args(node, 1)
596596
value = node.args[0].get_folded_value()
597-
if isinstance(value, vy_ast.Bytes):
597+
if isinstance(value, (vy_ast.Bytes, vy_ast.HexBytes)):
598598
value = value.value
599599
elif isinstance(value, vy_ast.Str):
600600
value = value.value.encode()
@@ -641,7 +641,7 @@ class Sha256(BuiltinFunctionT):
641641
def _try_fold(self, node):
642642
validate_call_args(node, 1)
643643
value = node.args[0].get_folded_value()
644-
if isinstance(value, vy_ast.Bytes):
644+
if isinstance(value, (vy_ast.Bytes, vy_ast.HexBytes)):
645645
value = value.value
646646
elif isinstance(value, vy_ast.Str):
647647
value = value.value.encode()

0 commit comments

Comments
 (0)