repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_migrated_valid_invalid.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_migrated_valid_invalid.py
""" EOF validation tests for EIP-3540 migrated from ethereum/tests/src/EOFTestsFiller/EIP3540/validInvalidFiller.yml. """ import pytest from ethereum_test_exceptions.exceptions import EOFExceptionInstanceOrList from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import Container, Section from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "eof_code,exception", [ pytest.param( # Deployed code without data section Container( name="EOF1V3540_0001", sections=[ Section.Code(code=Op.PUSH1[0] + Op.POP + Op.STOP), ], ), None, id="EOF1V3540_0001_deployed_code_without_data_section", ), pytest.param( # Deployed code with data section Container( name="EOF1V3540_0002", sections=[ Section.Code(code=Op.PUSH1[0] + Op.POP + Op.STOP), Section.Data("aabbccdd"), ], ), None, id="EOF1V3540_0002_deployed_code_with_data_section", ), pytest.param( # Empty code section with non-empty data section Container( sections=[Section.Code(code_outputs=0), Section.Data("aabb")], expected_bytecode="ef00010100040200010000ff00020000000000aabb", ), EOFException.ZERO_SECTION_SIZE, id="EOF1I3540_0012_empty_code_section_with_non_empty_data_section", ), pytest.param( # No section terminator after data section size Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff0002")), EOFException.MISSING_HEADERS_TERMINATOR, id="EOF1I3540_0020_no_section_terminator_after_data_section_size", ), pytest.param( # No type section contents Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff000200")), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0021_no_type_section_contents", ), pytest.param( # Type section contents (no outputs and max stack) Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff00020000")), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0022_invalid_type_section_no_outputs_and_max_stack", ), pytest.param( # Type section contents (no max stack) Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff0002000000")), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0023_invalid_type_section_no_max_stack", ), pytest.param( # Type section contents (max stack incomplete) Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff000200000000")), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0024_invalid_type_section_max_stack_incomplete", ), pytest.param( # No code section contents Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff00020000000000")), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0025_no_code_section_contents", ), pytest.param( # Code section contents incomplete Container(raw_bytes=bytes.fromhex("ef00010100040200010029ff000000000000027f")), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0026_code_section_contents_incomplete", ), pytest.param( # Trailing bytes after code section Container( raw_bytes=bytes.fromhex("ef0001 010004 0200010001 ff0000 00 00800000 fe aabbcc") ), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0027_trailing_bytes_after_code_section", ), pytest.param( # Trailing bytes after code section with wrong first section type Container( raw_bytes=bytes.fromhex("ef0001 010004 0200010001 ff0000 00 00000000 fe aabbcc") ), [EOFException.INVALID_FIRST_SECTION_TYPE, EOFException.INVALID_SECTION_BODIES_SIZE], id="EOF1I3540_0027_trailing_bytes_after_code_section_with_wrong_first_section_type", ), pytest.param( # Empty code section Container(raw_bytes=bytes.fromhex("ef00010100040200010000ff00000000000000")), EOFException.ZERO_SECTION_SIZE, id="EOF1I3540_0028_empty_code_section", ), pytest.param( # Code section preceding type section Container(raw_bytes=bytes.fromhex("ef00010200010001010004ff00020000000000feaabb")), [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0030_code_section_preceding_type_section", ), pytest.param( # Data section preceding type section Container(raw_bytes=bytes.fromhex("ef0001ff000201000402000100010000000000feaabb")), [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0031_data_section_preceding_type_section", ), pytest.param( # Data section preceding code section Container(raw_bytes=bytes.fromhex("ef0001010004ff000202000100010000000000feaabb")), [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0032_data_section_preceding_code_section", ), pytest.param( # Data section without code section Container(raw_bytes=bytes.fromhex("ef0001010004ff00020000000000aabb")), [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0033_data_section_without_code_section", ), pytest.param( # No data section Container(raw_bytes=bytes.fromhex("ef000101000402000100010000000000fe")), [EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0034_no_data_section", ), pytest.param( # Trailing bytes after data section Container( sections=[ Section.Code(Op.INVALID), Section.Data("aabb"), ], extra="ccdd", expected_bytecode="ef0001 010004 0200010001 ff0002 00 00800000 fe aabbccdd", ), EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1I3540_0035_trailing_bytes_after_data_section", ), pytest.param( # Trailing bytes after data section with wrong first section type Container( raw_bytes=bytes.fromhex("ef0001 010004 0200010001 ff0002 00 00000000 fe aabbccdd") ), [EOFException.INVALID_FIRST_SECTION_TYPE, EOFException.INVALID_SECTION_BODIES_SIZE], id="EOF1I3540_0035_trailing_bytes_after_data_section_with_wrong_first_section_type", ), pytest.param( # Multiple data sections Container( raw_bytes=bytes.fromhex("ef00010100040200010001ff0002ff00020000000000feaabbaabb") ), [EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0036_multiple_data_sections", ), pytest.param( # Multiple code and data sections Container( raw_bytes=bytes.fromhex( "ef000101000802000200010001ff0002ff0002000000000000000000fefeaabbaabb" ) ), [EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0037_multiple_code_and_data_sections", ), pytest.param( # Unknown section ID (at the beginning) Container(raw_bytes=bytes.fromhex("ef00010400010100040200010001ff00000000000000fe")), [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0038_unknown_section_id_at_the_beginning_05", ), pytest.param( # Unknown section ID (at the beginning) Container(raw_bytes=bytes.fromhex("ef00010500010100040200010001ff00000000000000fe")), [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0039_unknown_section_id_at_the_beginning_06", ), pytest.param( # Unknown section ID (at the beginning) Container(raw_bytes=bytes.fromhex("ef0001fe00010100040200010001ff00000000000000fe")), [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0040_unknown_section_id_at_the_beginning_ff", ), pytest.param( # Unknown section ID (after types section) Container(raw_bytes=bytes.fromhex("ef00010100040400010200010001ff00000000000000fe")), [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0041_unknown_section_id_after_types_section_05", ), pytest.param( # Unknown section ID (after types section) Container(raw_bytes=bytes.fromhex("ef00010100040500010200010001ff00000000000000fe")), [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0042_unknown_section_id_after_types_section_06", ), pytest.param( # Unknown section ID (after types section) Container(raw_bytes=bytes.fromhex("ef0001010004fe00010200010001ff00000000000000fe")), [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0043_unknown_section_id_after_types_section_ff", ), pytest.param( # Unknown section ID (after code section) Container(raw_bytes=bytes.fromhex("ef00010100040200010001050001ff00000000000000fe")), [EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0044_unknown_section_id_after_code_section_05", ), pytest.param( # Unknown section ID (after code section) Container(raw_bytes=bytes.fromhex("ef00010100040200010001060001ff00000000000000fe")), [EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0045_unknown_section_id_after_code_section_06", ), pytest.param( # Unknown section ID (after code section) Container(raw_bytes=bytes.fromhex("ef00010100040200010001040001ff00000000000000fe")), [EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0046_unknown_section_id_after_code_section_04", ), pytest.param( # Unknown section ID (after data section) Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff00000500010000000000fe")), [EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0047_unknown_section_id_after_data_section_05", ), pytest.param( # Unknown section ID (after data section) Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff00000600010000000000fe")), [EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0048_unknown_section_id_after_data_section_06", ), pytest.param( # Unknown section ID (after data section) Container(raw_bytes=bytes.fromhex("ef00010100040200010001ff00000400010000000000fe")), [EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], id="EOF1I3540_0049_unknown_section_id_after_data_section_04", ), pytest.param( Container( name="EOF1I3540_0002 (Invalid) Invalid magic", raw_bytes="ef01010100040200010001ff00000000000000fe", ), EOFException.INVALID_MAGIC, id="EOF1I3540_0002_invalid_incorrect_magic_01", ), pytest.param( Container( name="EOF1I3540_0003", raw_bytes="ef02010100040200010001ff00000000000000fe", ), EOFException.INVALID_MAGIC, id="EOF1I3540_0003_invalid_incorrect_magic_02", ), pytest.param( Container( name="EOF1I3540_0004", raw_bytes="efff010100040200010001ff00000000000000fe", ), EOFException.INVALID_MAGIC, id="EOF1I3540_0004_invalid_incorrect_magic_ff", ), pytest.param( Container( name="EOF1I3540_0006 (Invalid) Invalid version", raw_bytes="ef00000100040200010001ff00000000000000fe", ), EOFException.INVALID_VERSION, id="EOF1I3540_0006_invalid_incorrect_version_00", ), pytest.param( Container( name="EOF1I3540_0007", raw_bytes="ef00020100040200010001ff00000000000000fe", ), EOFException.INVALID_VERSION, id="EOF1I3540_0007_invalid_incorrect_version_02", ), pytest.param( Container( name="EOF1I3540_0008", raw_bytes="ef00ff0100040200010001ff00000000000000fe", ), EOFException.INVALID_VERSION, id="EOF1I3540_0008_invalid_incorrect_version_ff", ), ], ) def test_migrated_valid_invalid( eof_test: EOFTestFiller, eof_code: Container, exception: EOFExceptionInstanceOrList | None, ) -> None: """Verify EOF container construction and exception.""" eof_test( container=eof_code, expect_exception=exception, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_all_opcodes_in_container.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_all_opcodes_in_container.py
""" EOF Container: check how every opcode behaves in the middle of the valid eof container code. """ import itertools from typing import Any, Dict, Generator, List, Tuple import pytest from ethereum_test_tools import EOFException, EOFTestFiller, Opcode, UndefinedOpcodes from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.constants import MAX_RUNTIME_STACK_HEIGHT from ethereum_test_types.eof.v1 import Container, ContainerKind, Section from ethereum_test_types.eof.v1.constants import MAX_STACK_INCREASE_LIMIT from ethereum_test_vm import Bytecode from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) all_opcodes = set(Op) undefined_opcodes = set(UndefinedOpcodes) # Invalid Opcodes will produce EOFException.UNDEFINED_INSTRUCTION when used in # EOFContainer invalid_eof_opcodes = { Op.CODESIZE, Op.SELFDESTRUCT, Op.CREATE2, Op.CODECOPY, Op.EXTCODESIZE, Op.EXTCODECOPY, Op.EXTCODEHASH, Op.JUMP, Op.JUMPI, Op.PC, Op.GAS, Op.CREATE, Op.CALL, Op.CALLCODE, Op.DELEGATECALL, Op.STATICCALL, } valid_eof_opcodes = all_opcodes - invalid_eof_opcodes # Halting the execution opcodes can be placed without STOP instruction at the # end halting_opcodes = { Op.STOP, Op.RETURNCODE, Op.RETURN, Op.REVERT, Op.INVALID, } # Opcodes that end the code section and can be placed without STOP instruction # at the end section_terminating_opcodes = { Op.RETF, Op.JUMPF, } data_portion_opcodes = {op for op in all_opcodes if op.has_data_portion()} # NOTE: `sorted` is used to ensure that the tests are collected in a # deterministic order. @pytest.mark.parametrize( "opcode", sorted((all_opcodes | undefined_opcodes) - {Op.RETF}), ) def test_all_opcodes_in_container( eof_test: EOFTestFiller, opcode: Opcode, ) -> None: """ Test all opcodes inside valid container 257 because 0x5B is duplicated. """ data_portion = 1 if opcode == Op.CALLF else 0 opcode_with_data_portion = opcode[data_portion] if opcode.has_data_portion() else opcode # opcode_with_data_portion has the correct minimum stack height bytecode = Op.PUSH0 * opcode_with_data_portion.min_stack_height + opcode_with_data_portion if opcode not in (halting_opcodes | section_terminating_opcodes): bytecode += Op.STOP sections = [Section.Code(code=bytecode)] match opcode: case Op.EOFCREATE | Op.RETURNCODE: sections.append( Section.Container( container=Container( sections=[ Section.Code(code=Op.REVERT(0, 0)), ] ) ) ) case Op.CALLF: sections.append( Section.Code( code=Op.RETF, code_outputs=0, ) ) sections.append(Section.Data("1122334455667788" * 4)) if opcode == Op.RETURNCODE: eof_code = Container(sections=sections, kind=ContainerKind.INITCODE) else: eof_code = Container(sections=sections) eof_test( container=eof_code, expect_exception=( None if opcode in valid_eof_opcodes else EOFException.UNDEFINED_INSTRUCTION ), ) @pytest.mark.parametrize( "opcode", sorted(invalid_eof_opcodes | undefined_opcodes), ) @pytest.mark.parametrize( "terminating_opcode", sorted(halting_opcodes) + [Op.RJUMP], ) def test_invalid_opcodes_after_stop( eof_test: EOFTestFiller, opcode: Opcode, terminating_opcode: Opcode, ) -> None: """ Test that an invalid opcode placed after STOP (terminating instruction) invalidates EOF. """ terminating_code = Bytecode(terminating_opcode) match terminating_opcode: # Enhance the code for complex opcodes. case Op.RETURNCODE: terminating_code = Op.RETURNCODE[0] case Op.RETURN | Op.REVERT: terminating_code = Op.PUSH0 + Op.PUSH0 + terminating_opcode case Op.RJUMP: terminating_code = Op.RJUMP[-3] eof_code = Container( kind=ContainerKind.INITCODE if terminating_opcode == Op.RETURNCODE else ContainerKind.RUNTIME, sections=[ Section.Code(code=terminating_code + opcode), Section.Data("00" * 32), ] + ( [Section.Container(container=Container.Code(Op.INVALID))] if terminating_opcode == Op.RETURNCODE else [] ), ) eof_test( container=eof_code, expect_exception=EOFException.UNDEFINED_INSTRUCTION, ) @pytest.mark.parametrize( "opcode", sorted( valid_eof_opcodes - halting_opcodes - section_terminating_opcodes - {Op.RJUMP, Op.RJUMPI, Op.RJUMPV} ), ) def test_all_invalid_terminating_opcodes( eof_test: EOFTestFiller, opcode: Opcode, ) -> None: """Test all opcodes that are invalid as the last opcode in a container.""" if opcode.has_data_portion(): # Add the appropriate data portion to the opcode by using the get_item # method. On the CALLF opcode we need to reference the second code # section, hence the [1] index. opcode = opcode[0] if opcode != Op.CALLF else opcode[1] bytecode = (Op.PUSH0 * opcode.min_stack_height) + opcode sections = [Section.Code(code=bytecode)] if opcode == Op.CALLF[1]: sections += [Section.Code(code=Op.RETF, code_outputs=0)] elif opcode == Op.EOFCREATE[0]: sections += [ Section.Container( container=Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0, 0)), Section.Container(Container.Code(code=Op.STOP)), ] ) ) ] sections += [Section.Data(b"\0" * 32)] eof_test( container=Container( sections=sections, ), expect_exception=EOFException.MISSING_STOP_OPCODE, ) @pytest.mark.parametrize( "opcode", sorted(halting_opcodes | section_terminating_opcodes), ) def test_all_unreachable_terminating_opcodes_after_stop( eof_test: EOFTestFiller, opcode: Opcode, ) -> None: """Test all terminating opcodes after stop.""" match opcode: case Op.STOP: sections = [Section.Code(code=Op.STOP + Op.STOP)] case Op.RETF: sections = [ Section.Code(code=Op.CALLF[1] + Op.STOP), Section.Code(code=Op.STOP + Op.RETF, code_outputs=0), ] case Op.JUMPF: sections = [ Section.Code(code=Op.STOP + Op.JUMPF[1]), Section.Code(code=Op.STOP), ] case Op.RETURNCODE: sections = [ Section.Code(code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container( container=Container( sections=[ Section.Code(code=Op.STOP + Op.RETURNCODE[0](0, 0)), Section.Container(Container.Code(code=Op.STOP)), ] ) ), ] case Op.RETURN | Op.REVERT | Op.INVALID: sections = [ Section.Code(code=Op.PUSH0 + Op.PUSH0 + Op.STOP + opcode), ] case _: raise NotImplementedError(f"Opcode {opcode} is not implemented") eof_test( container=Container( sections=sections, ), expect_exception=EOFException.UNREACHABLE_INSTRUCTIONS if opcode != Op.RETURNCODE else EOFException.INCOMPATIBLE_CONTAINER_KIND, ) @pytest.mark.parametrize( "opcode", sorted((halting_opcodes | section_terminating_opcodes) - {Op.STOP}), ) def test_all_unreachable_terminating_opcodes_before_stop( eof_test: EOFTestFiller, opcode: Opcode, ) -> None: """Test all opcodes terminating opcodes before.""" match opcode: case Op.RETF: sections = [ Section.Code(code=Op.CALLF[1] + Op.STOP), Section.Code(code=Op.RETF + Op.STOP, code_outputs=0), ] case Op.JUMPF: sections = [ Section.Code(code=Op.JUMPF[1] + Op.STOP), Section.Code(code=Op.STOP), ] case Op.RETURNCODE: sections = [ Section.Code(code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container( container=Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0, 0) + Op.STOP), Section.Container(Container.Code(code=Op.STOP)), ] ) ), ] case Op.RETURN | Op.REVERT | Op.INVALID: sections = [ Section.Code(code=Op.PUSH1(0) + Op.PUSH1(0) + opcode + Op.STOP), ] case _: raise NotImplementedError(f"Opcode {opcode} is not implemented") eof_test( container=Container( sections=sections, ), expect_exception=EOFException.UNREACHABLE_INSTRUCTIONS if opcode != Op.RETURNCODE else EOFException.INCOMPATIBLE_CONTAINER_KIND, ) @pytest.mark.parametrize( "opcode", sorted(op for op in valid_eof_opcodes if op.pushed_stack_items > op.popped_stack_items) + [ Op.DUPN[0xFF], ], ) @pytest.mark.parametrize( "exception", # We test two types of exceptions here: # 1. Invalid max stack height, where we modify the `max_stack_height` # field of the code section to the maximum stack height allowed by # the EIP-3540, so the code still has to be checked for stack overflow. # # 2. Max stack height above limit, where we don't modify the # `max_stack_height` field of the code section, so the actual # code doesn't have to be verified for the stack overflow. [EOFException.INVALID_MAX_STACK_INCREASE, EOFException.MAX_STACK_INCREASE_ABOVE_LIMIT], ) def test_all_opcodes_stack_overflow( eof_test: EOFTestFiller, opcode: Opcode, exception: EOFException, ) -> None: """ Test stack overflow on all opcodes that push more items than they pop. """ opcode = opcode[0] if opcode.has_data_portion() else opcode assert opcode.pushed_stack_items - opcode.popped_stack_items == 1 opcode_count = MAX_RUNTIME_STACK_HEIGHT - opcode.min_stack_height bytecode = Op.PUSH0 * opcode.min_stack_height bytecode += opcode * opcode_count bytecode += Op.STOP kwargs: Dict[str, Any] = {"code": bytecode} if exception == EOFException.INVALID_MAX_STACK_INCREASE: # Lie about the max stack height to make the code be checked for stack # overflow. kwargs["max_stack_height"] = MAX_STACK_INCREASE_LIMIT sections = [Section.Code(**kwargs)] if opcode == Op.DATALOADN[0]: sections.append(Section.Data(b"\0" * 32)) eof_code = Container(sections=sections) eof_test( container=eof_code, expect_exception=exception, ) def valid_opcode_combinations( compute_max_stack_height_options: List[bool], truncate_all_options: List[bool], opcodes: List[Opcode], ) -> Generator[Tuple[bool, bool, Opcode], None, None]: """ Create valid parameter combinations for test_truncated_data_portion_opcodes(). """ for opcode, truncate_all, compute_max_stack_height in itertools.product( opcodes, truncate_all_options, compute_max_stack_height_options ): opcode_with_data_portion: bytes = bytes(opcode[1]) # Skip invalid or redundant combinations to avoid using pytest.skip in # the test if len(opcode_with_data_portion) == 2 and truncate_all: continue if ( compute_max_stack_height and max(opcode.min_stack_height, opcode.pushed_stack_items) == 0 ): continue yield compute_max_stack_height, truncate_all, opcode @pytest.mark.parametrize( "compute_max_stack_height, truncate_all, opcode", valid_opcode_combinations([False, True], [False, True], sorted(data_portion_opcodes)), ) def test_truncated_data_portion_opcodes( eof_test: EOFTestFiller, opcode: Opcode, truncate_all: bool, compute_max_stack_height: bool, ) -> None: """ Test that an instruction with data portion and truncated immediate bytes (therefore a terminating instruction is also missing) invalidates EOF. """ opcode_with_data_portion: bytes = bytes(opcode[1]) # Compose instruction bytes with empty imm bytes (truncate_all) or 1 byte # shorter imm bytes. opcode_bytes = opcode_with_data_portion[0:1] if truncate_all else opcode_with_data_portion[:-1] if opcode.min_stack_height > 0: opcode_bytes = bytes(Op.PUSH0 * opcode.min_stack_height) + opcode_bytes max_stack_height = ( max(opcode.min_stack_height, opcode.pushed_stack_items) if compute_max_stack_height else 0 ) eof_code = Container( sections=[ Section.Code(opcode_bytes, max_stack_height=max_stack_height), # Provide data section potentially confused with missing imm bytes. Section.Data(b"\0" * 64), ] ) eof_test( container=eof_code, expect_exception=EOFException.TRUNCATED_INSTRUCTION, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_container_size.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_container_size.py
"""EOF validation tests for EIP-3540 container size.""" import pytest from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_INITCODE_SIZE from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "6b313505c75afa49a4f34de39c609ebebc7be87f" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) VALID_CONTAINER = Container(sections=[Section.Code(code=Op.STOP)]) @pytest.mark.parametrize( "over_limit", [0, 1, 2, 2**16 - MAX_INITCODE_SIZE], ) @pytest.mark.eof_test_only def test_max_size( eof_test: EOFTestFiller, over_limit: int, ) -> None: """Verify EOF container valid at maximum size, invalid above.""" # Expand the minimal EOF code by more noop code, reaching the desired # target container size. code = Container( sections=[ Section.Code( code=Op.JUMPDEST * (MAX_INITCODE_SIZE - len(VALID_CONTAINER) + over_limit) + Op.STOP ) ] ) assert len(code) == MAX_INITCODE_SIZE + over_limit eof_test( container=code, expect_exception=None if over_limit == 0 else EOFException.CONTAINER_SIZE_ABOVE_LIMIT, ) @pytest.mark.parametrize( "size", [MAX_INITCODE_SIZE + 1, MAX_INITCODE_SIZE * 2], ) @pytest.mark.eof_test_only def test_above_max_size_raw( eof_test: EOFTestFiller, size: int, ) -> None: """ Verify EOF container invalid above maximum size, regardless of header contents. """ code = Op.INVALID * size eof_test( container=Container(raw_bytes=code), expect_exception=EOFException.CONTAINER_SIZE_ABOVE_LIMIT, ) @pytest.mark.parametrize( "code", [ pytest.param( Container(sections=[Section.Code(code=Op.STOP, custom_size=MAX_INITCODE_SIZE)]), id="1st_code_section", ), pytest.param( Container( sections=[ Section.Code(code=Op.STOP), Section.Code(code=Op.STOP, custom_size=MAX_INITCODE_SIZE), ] ), id="2nd_code_section", ), pytest.param( Container( sections=[ Section.Code(code=Op.STOP), Section.Container(container=Op.STOP, custom_size=MAX_INITCODE_SIZE), ] ), id="1st_container_section", ), pytest.param( Container( sections=[ Section.Code(code=Op.STOP), Section.Container(container=Op.STOP), Section.Container(container=Op.STOP, custom_size=MAX_INITCODE_SIZE), ] ), id="2nd_container_section", ), ], ) def test_section_after_end_of_container( eof_test: EOFTestFiller, code: Container, ) -> None: """ Verify EOF container is invalid if any of sections declares above container size. """ eof_test( container=code, expect_exception=EOFException.INVALID_SECTION_BODIES_SIZE, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_section_order.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_section_order.py
"""Different variations of EOF sections displacement.""" from enum import Enum from typing import List import pytest from ethereum_test_exceptions.exceptions import EOFExceptionInstanceOrList from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import AutoSection, Container, Section, SectionKind from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) class SectionTest(Enum): """Enum for the test type.""" MISSING = 1 WRONG_ORDER = 2 class CasePosition(Enum): """Enum for the test position.""" BODY = 1 HEADER = 2 BODY_AND_HEADER = 3 def get_expected_code_exception( section_kind: SectionKind, section_test: SectionTest, test_position: CasePosition ) -> tuple[str, EOFExceptionInstanceOrList | None]: """ Verification vectors with code and exception based on test combinations. """ match (section_kind, section_test, test_position): case (SectionKind.TYPE, SectionTest.MISSING, CasePosition.HEADER): return ( "ef00010200010003ff00010000800001305000ef", [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.TYPE, SectionTest.MISSING, CasePosition.BODY): return ( "ef00010100040200010003ff000100305000ef", [ EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.INVALID_FIRST_SECTION_TYPE, ], ) case (SectionKind.TYPE, SectionTest.MISSING, CasePosition.BODY_AND_HEADER): return ( "ef00010200010003ff000100305000ef", [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.TYPE, SectionTest.WRONG_ORDER, CasePosition.HEADER): return ( "ef00010200010003010004ff00010000800001305000ef", [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.TYPE, SectionTest.WRONG_ORDER, CasePosition.BODY): return ( "ef00010100040200010003ff00010030500000800001ef", # TODO why invalid first section type? it should say that the # body incorrect EOFException.INVALID_FIRST_SECTION_TYPE, ) case (SectionKind.TYPE, SectionTest.WRONG_ORDER, CasePosition.BODY_AND_HEADER): return ( "ef00010200010003010004ff00010030500000800001ef", [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.CODE, SectionTest.MISSING, CasePosition.HEADER): return ( "ef0001010004ff00010000800001305000ef", [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.CODE, SectionTest.MISSING, CasePosition.BODY): return ( "ef00010100040200010003ff00010000800001ef", # TODO should be an exception of empty code bytes, because it # can understand that last byte is data section byte [EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.CODE, SectionTest.MISSING, CasePosition.BODY_AND_HEADER): return ( "ef0001010004ff00010000800001ef", [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.CODE, SectionTest.WRONG_ORDER, CasePosition.HEADER): return ( "ef0001010004ff000102000100030000800001305000ef", [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.CODE, SectionTest.WRONG_ORDER, CasePosition.BODY): return ( "ef00010100040200010003ff00010000800001ef305000", EOFException.UNDEFINED_INSTRUCTION, ) case (SectionKind.CODE, SectionTest.WRONG_ORDER, CasePosition.BODY_AND_HEADER): return ( "ef0001010004ff000102000100030000800001ef305000", [EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.DATA, SectionTest.MISSING, CasePosition.HEADER): return ( "ef000101000402000100030000800001305000ef", [EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.DATA, SectionTest.MISSING, CasePosition.BODY): return ( "ef00010100040200010003ff00010000800001305000", EOFException.TOPLEVEL_CONTAINER_TRUNCATED, ) case (SectionKind.DATA, SectionTest.MISSING, CasePosition.BODY_AND_HEADER): return ( "ef000101000402000100030000800001305000", [EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.DATA, SectionTest.WRONG_ORDER, CasePosition.HEADER): return ( "ef0001ff000101000402000100030000800001305000ef", [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) case (SectionKind.DATA, SectionTest.WRONG_ORDER, CasePosition.BODY): return ( "ef00010100040200010003ff000100ef00800001305000", EOFException.INVALID_FIRST_SECTION_TYPE, ) case (SectionKind.DATA, SectionTest.WRONG_ORDER, CasePosition.BODY_AND_HEADER): return ( "ef0001ff0001010004020001000300ef00800001305000", [EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ) return "", None @pytest.mark.parametrize("section_kind", [SectionKind.TYPE, SectionKind.CODE, SectionKind.DATA]) @pytest.mark.parametrize("section_test", [SectionTest.MISSING, SectionTest.WRONG_ORDER]) @pytest.mark.parametrize( "test_position", [CasePosition.BODY, CasePosition.HEADER, CasePosition.BODY_AND_HEADER] ) def test_section_order( eof_test: EOFTestFiller, section_kind: SectionKind, section_test: SectionTest, test_position: CasePosition, ) -> None: """Test sections order and it appearance in body and header.""" def calculate_skip_flag(kind: SectionKind, position: CasePosition) -> bool: return ( False if (section_kind != kind) else ( True if section_test == SectionTest.MISSING and (test_position == position or test_position == CasePosition.BODY_AND_HEADER) else False ) ) def make_section_order(kind: SectionKind) -> List[Section]: if section_test != SectionTest.WRONG_ORDER: return [section_type, section_code, section_data] if kind == SectionKind.TYPE: return [section_code, section_type, section_data] if kind == SectionKind.CODE: return [section_type, section_data, section_code] if kind == SectionKind.DATA: return [section_data, section_type, section_code] return [section_type, section_code, section_data] section_code = Section.Code( code=Op.ADDRESS + Op.POP + Op.STOP, skip_header_listing=calculate_skip_flag(SectionKind.CODE, CasePosition.HEADER), skip_body_listing=calculate_skip_flag(SectionKind.CODE, CasePosition.BODY), ) section_type = Section( kind=SectionKind.TYPE, data=bytes.fromhex("00800001"), custom_size=4, skip_header_listing=calculate_skip_flag(SectionKind.TYPE, CasePosition.HEADER), skip_body_listing=calculate_skip_flag(SectionKind.TYPE, CasePosition.BODY), ) section_data = Section.Data( "ef", skip_header_listing=calculate_skip_flag(SectionKind.DATA, CasePosition.HEADER), skip_body_listing=calculate_skip_flag(SectionKind.DATA, CasePosition.BODY), ) expected_code, expected_exception = get_expected_code_exception( section_kind, section_test, test_position ) eof_code = Container( sections=make_section_order(section_kind), auto_type_section=AutoSection.NONE, auto_sort_sections=( AutoSection.AUTO if section_test != SectionTest.WRONG_ORDER else ( AutoSection.ONLY_BODY if test_position == CasePosition.HEADER else ( AutoSection.ONLY_HEADER if test_position == CasePosition.BODY else AutoSection.NONE ) ) ), expected_bytecode=expected_code, ) eof_test( container=eof_code, expect_exception=expected_exception, ) @pytest.mark.parametrize("container_position", range(4)) @pytest.mark.parametrize( "test_position", [CasePosition.BODY, CasePosition.HEADER, CasePosition.BODY_AND_HEADER] ) def test_container_section_order( eof_test: EOFTestFiller, container_position: int, test_position: CasePosition, ) -> None: """ Test containers section being out of order in the header and/or body. This extends and follows the convention of the test_section_order() for the optional container section. """ if container_position == 2: pytest.skip("Skip valid container section position") section_code = Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) # TODO: Migrated tests had the following infinite loop, so it is kept # here to equalize code coverage. + Op.RJUMP[0] + Op.STOP() ) section_type = Section(kind=SectionKind.TYPE, data=bytes.fromhex("00800004")) section_data = Section.Data("ef") section_container = Section.Container(Container.Code(Op.INVALID)) sections = [section_type, section_code, section_data] sections.insert(container_position, section_container) eof_code = Container( sections=sections, auto_type_section=AutoSection.NONE, auto_sort_sections=( AutoSection.ONLY_BODY if test_position == CasePosition.HEADER else ( AutoSection.ONLY_HEADER if test_position == CasePosition.BODY else AutoSection.NONE ) ), ) def get_expected_exception() -> EOFExceptionInstanceOrList | None: match container_position, test_position: case 2, _: return None # Valid containers section position case 0, CasePosition.BODY: # Messes up with the type section return EOFException.INVALID_FIRST_SECTION_TYPE case 1, CasePosition.BODY: # Messes up with the code section return EOFException.UNDEFINED_INSTRUCTION case 3, CasePosition.BODY: # Data section messes up with the # container section return EOFException.INVALID_MAGIC case 0, CasePosition.HEADER | CasePosition.BODY_AND_HEADER: return EOFException.MISSING_TYPE_HEADER case 1, CasePosition.HEADER | CasePosition.BODY_AND_HEADER: return EOFException.MISSING_CODE_HEADER case 3, CasePosition.HEADER | CasePosition.BODY_AND_HEADER: return EOFException.MISSING_TERMINATOR case _: return None eof_test( container=eof_code, expect_exception=get_expected_exception(), )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_section_header_body_mismatch.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_section_header_body_mismatch.py
"""EOF Container construction test.""" import pytest from ethereum_test_exceptions.exceptions import EOFExceptionInstanceOrList from ethereum_test_tools import EOFException, EOFTestFiller, extend_with_defaults from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import Container, Section from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( **extend_with_defaults( defaults={ # second section is mentioned in code header array "skip_header_listing": False, # second section code is in container's body "skip_body_listing": False, # code input bytes not listed in container's body "skip_types_body_listing": False, # code input bytes size not added to types section size "skip_types_header_listing": False, "expected_code": "", "expected_exception": None, }, cases=[ pytest.param( { "skip_header_listing": True, "skip_body_listing": True, "expected_code": "ef00010100080200010003ff0004000080000" "1000000003050000bad60A7", "expected_exception": [ EOFException.INVALID_TYPE_SECTION_SIZE, EOFException.INVALID_SECTION_BODIES_SIZE, ], }, id="drop_code_section_and_header", ), pytest.param( { "skip_header_listing": True, "skip_body_listing": False, "expected_code": "ef00010100080200010003ff0004000080000" "1000000003050003050000bad60A7", "expected_exception": [ EOFException.INVALID_TYPE_SECTION_SIZE, EOFException.INVALID_SECTION_BODIES_SIZE, ], }, id="drop_code_header", ), pytest.param( { "skip_header_listing": False, "skip_body_listing": True, "expected_code": "ef000101000802000200030003ff000400008" "00001000000003050000bad60A7", "expected_exception": [ EOFException.UNREACHABLE_CODE_SECTIONS, EOFException.TOPLEVEL_CONTAINER_TRUNCATED, ], }, id="drop_code_section", ), pytest.param( { "skip_header_listing": False, "skip_body_listing": False, "expected_code": "ef000101000802000200030003ff000400008" "00001000000003050003050000bad60A7", "expected_exception": EOFException.UNREACHABLE_CODE_SECTIONS, }, id="layout_ok_code_bad", ), pytest.param( { "skip_header_listing": True, "skip_body_listing": True, "skip_types_body_listing": True, "expected_code": "ef00010100080200010003ff000400008000013050000bad60a7", "expected_exception": [ EOFException.INVALID_TYPE_SECTION_SIZE, EOFException.INVALID_SECTION_BODIES_SIZE, ], }, id="drop_types_header", ), pytest.param( { "skip_header_listing": True, "skip_body_listing": True, "skip_types_body_listing": True, "skip_types_header_listing": True, "expected_code": "ef00010100040200010003ff000400008000013050000bad60a7", "expected_exception": None, }, id="drop_everything", ), ], ) ) def test_code_section_header_body_mismatch( eof_test: EOFTestFiller, skip_header_listing: bool, skip_body_listing: bool, skip_types_body_listing: bool, skip_types_header_listing: bool, expected_code: str, expected_exception: EOFExceptionInstanceOrList | None, ) -> None: """Inconsistent number of code sections (between types and code).""" eof_code = Container( name="EOF1I0018", sections=[ Section.Code( code=Op.ADDRESS + Op.POP + Op.STOP, ), Section.Code( code=Op.ADDRESS + Op.POP + Op.STOP, code_inputs=0, code_outputs=0, max_stack_height=0, # whether to not mention it in code section header list skip_header_listing=skip_header_listing, # whether to not print its code in containers body skip_body_listing=skip_body_listing, # whether to not print its input bytes in containers body skip_types_body_listing=skip_types_body_listing, # whether to not calculate its input bytes size in types # section's header skip_types_header_listing=skip_types_header_listing, ), Section.Data("0x0bad60A7"), ], ) # TODO remove this after Container class implementation is reliable assert bytes(eof_code).hex() == bytes.fromhex(expected_code).hex() eof_test( container=eof_code, expect_exception=expected_exception, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_opcodes_in_legacy.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_opcodes_in_legacy.py
"""Tests all EOF-only opcodes in legacy contracts and expects failure.""" import pytest from ethereum_test_base_types import Account from ethereum_test_specs import StateTestFiller from ethereum_test_tools import Initcode from ethereum_test_tools import Opcodes as Op from ethereum_test_types import Alloc, Environment, Transaction from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7692.md" REFERENCE_SPEC_VERSION = "f0e7661ee0d16e612e0931ec88b4c9f208e9d513" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) slot_code_executed = b"EXEC" slot_code_worked = b"WORK" slot_create_address = b"ADDR" value_code_executed = b"exec" value_code_worked = b"work" value_non_execution_canary = b"brid" value_create_failed = 0 eof_opcode_blocks = [ pytest.param(Op.PUSH0 + Op.DUPN[0], id="DUPN"), pytest.param(Op.PUSH0 + Op.PUSH0 + Op.SWAPN[0], id="SWAPN"), pytest.param(Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.EXCHANGE[2, 3], id="EXCHANGE"), pytest.param(Op.RJUMP[0], id="RJUMP"), pytest.param(Op.PUSH0 + Op.RJUMPI[0], id="RJUMPI"), pytest.param(Op.PUSH0 + Op.RJUMPV[0, 0], id="RJUMPI"), pytest.param(Op.CALLF[1], id="CALLF"), pytest.param(Op.RETF, id="RETF"), pytest.param(Op.JUMPF[0], id="JUMPF"), pytest.param(Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1(2) + Op.EXTCALL, id="EXTCALL"), pytest.param( Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1(2) + Op.EXTDELEGATECALL, id="EXTDELEGATECALL" ), pytest.param( Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1(2) + Op.EXTSTATICCALL, id="EXTSTATICCALL" ), pytest.param(Op.DATALOAD(0), id="DATALOAD"), pytest.param(Op.DATALOADN[0], id="DATALOADN"), pytest.param(Op.DATASIZE, id="DATASIZE"), pytest.param(Op.DATACOPY(0, 0, 32), id="DATACOPY"), pytest.param(Op.EOFCREATE[0](0, 0, 0, 0), id="EOFCREATE"), # pytest.param(Op.TXCREATE(0, 0, 0, 0, 0), id="TXCREATE"), not EOF-only # anymore pytest.param(Op.RETURNCODE[0], id="RETURNCODE"), ] @pytest.mark.parametrize( "code", eof_opcode_blocks, ) def test_opcodes_in_legacy(state_test: StateTestFiller, pre: Alloc, code: Opcodes) -> None: """Test all EOF only opcodes in legacy contracts and expects failure.""" env = Environment() address_test_contract = pre.deploy_contract( code=code + Op.SSTORE(slot_code_executed, value_code_executed), storage={slot_code_executed: value_non_execution_canary}, ) post = { # assert the canary is not over-written. If it was written then the EOF # opcode was valid address_test_contract: Account(storage={slot_code_executed: value_non_execution_canary}), } sender = pre.fund_eoa() tx = Transaction( sender=sender, to=address_test_contract, gas_limit=5_000_000, gas_price=10, protected=False, data="", ) state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "code", eof_opcode_blocks, ) def test_opcodes_in_create_tx(state_test: StateTestFiller, pre: Alloc, code: Opcodes) -> None: """Test all EOF only opcodes in create tx and expects failure.""" env = Environment() sender = pre.fund_eoa() tx = Transaction( sender=sender, to=None, gas_limit=5_000_000, gas_price=10, protected=False, data=code, ) post = { # Should revert in initcode, which results in no contract created tx.created_contract: Account.NONEXISTENT } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "legacy_create_opcode", [ pytest.param(Op.CREATE, id="CREATE"), pytest.param(Op.CREATE2, id="CREATE2"), ], ) @pytest.mark.parametrize( "code", eof_opcode_blocks, ) def test_opcodes_in_create_operation( state_test: StateTestFiller, pre: Alloc, code: Opcodes, legacy_create_opcode: Opcodes, ) -> None: """Test opcodes in create operation.""" env = Environment() init_code = Initcode(initcode_prefix=code, deploy_code=Op.RETURN(0, 0)) factory_code = ( Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_create_address, legacy_create_opcode(size=Op.CALLDATASIZE)) + Op.SSTORE(slot_code_worked, value_code_worked) ) sender = pre.fund_eoa() contract_address = pre.deploy_contract(code=factory_code) post = { contract_address: Account( storage={slot_create_address: value_create_failed, slot_code_worked: value_code_worked} ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, data=init_code, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize( ("ext_call_opcode"), [ pytest.param(Op.EXTCALL, id="EXTCALL"), pytest.param(Op.EXTDELEGATECALL, id="EXTDELEGATECALL"), pytest.param(Op.EXTSTATICCALL, id="EXTSTATICCALL"), ], ) @pytest.mark.parametrize( "code", eof_opcode_blocks, ) def test_opcodes_in_eof_calling_legacy( state_test: StateTestFiller, pre: Alloc, code: Opcodes, ext_call_opcode: Op, ) -> None: """Test all opcodes in eof calling legacy and expects failure.""" env = Environment() address_test_contract = pre.deploy_contract( code=code + Op.SSTORE(slot_code_executed, value_code_executed), storage={slot_code_executed: value_non_execution_canary}, ) address_entry_contract = pre.deploy_contract( code=Container( sections=[ Section.Code( ext_call_opcode(address=address_test_contract) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) ] ), storage={slot_code_executed: value_non_execution_canary}, ) post = { # assert the canary is not over-written. If it was written then the EOF # opcode was valid address_test_contract: Account(storage={slot_code_executed: value_non_execution_canary}), address_entry_contract: Account( storage={ slot_code_executed: value_non_execution_canary, slot_code_worked: value_code_worked, } ), } sender = pre.fund_eoa() tx = Transaction( sender=sender, to=address_entry_contract, gas_limit=5_000_000, gas_price=10, protected=False, data="", ) state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_container_validation.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_container_validation.py
"""EOF validation tests for EIP-3540 container format.""" import itertools import pytest from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_types.eof.v1 import ( AutoSection, Container, ContainerKind, Section, SectionKind, ) from ethereum_test_types.eof.v1.constants import ( MAX_CODE_INPUTS, MAX_CODE_OUTPUTS, MAX_CODE_SECTIONS, MAX_STACK_INCREASE_LIMIT, ) from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) VALID_CONTAINER = Container(sections=[Section.Code(code=Op.STOP)]) @pytest.mark.parametrize( "container", [ Container( name="single_code_section_max_stack_size", sections=[ Section.Code( code=(Op.CALLER * MAX_STACK_INCREASE_LIMIT) + (Op.POP * MAX_STACK_INCREASE_LIMIT) + Op.STOP, max_stack_height=MAX_STACK_INCREASE_LIMIT, ), ], ), Container( name="code_section_with_inputs_outputs", sections=[ Section.Code( code=(Op.PUSH0 + Op.CALLF[1] + Op.STOP), ), Section.Code( code=Op.POP + Op.PUSH0 + Op.RETF, code_inputs=1, code_outputs=1, ), ], ), Container( name="code_section_input_maximum", sections=[ Section.Code( code=((Op.PUSH0 * MAX_CODE_INPUTS) + Op.CALLF[1] + Op.STOP), max_stack_height=MAX_CODE_INPUTS, ), Section.Code( code=(Op.POP * MAX_CODE_INPUTS) + Op.RETF, code_inputs=MAX_CODE_INPUTS, code_outputs=0, max_stack_height=MAX_CODE_INPUTS, ), ], ), Container( name="code_section_output_maximum", sections=[ Section.Code( code=(Op.CALLF[1] + Op.STOP), max_stack_height=MAX_CODE_OUTPUTS, ), Section.Code( code=(Op.PUSH0 * MAX_CODE_OUTPUTS) + Op.RETF, code_inputs=0, code_outputs=MAX_CODE_OUTPUTS, max_stack_height=MAX_CODE_OUTPUTS, ), ], ), Container( name="multiple_code_sections", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( code=Op.RETF, code_inputs=0, code_outputs=0, ), ], ), Container( name="multiple_code_sections_max_inputs_max_outputs", sections=[ Section.Code( (Op.PUSH0 * MAX_CODE_OUTPUTS) + Op.CALLF[1] + Op.STOP, max_stack_height=MAX_CODE_OUTPUTS, ), Section.Code( code=Op.RETF, code_inputs=MAX_CODE_INPUTS, code_outputs=MAX_CODE_OUTPUTS, max_stack_height=MAX_CODE_INPUTS, ), ], ), Container( name="single_subcontainer_without_data", sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container(Container.Code(Op.INVALID)), ], ), Container( name="single_subcontainer_with_data", sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container(Container.Code(Op.INVALID)), Section.Data(data="0xAA"), ], ), ], ids=lambda c: c.name, ) def test_valid_containers( eof_test: EOFTestFiller, container: Container, ) -> None: """Test various types of valid containers.""" assert container.validity_error is None, ( f"Valid container with validity error: {container.validity_error}" ) eof_test(container=container) @pytest.mark.parametrize( "container", [ Container( name="empty_container", raw_bytes=b"", validity_error=[ EOFException.INVALID_MAGIC, ], ), Container( name="single_code_section_no_data_section", sections=[ Section.Code(Op.STOP), ], auto_data_section=False, validity_error=[ EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND, ], ), Container( name="incomplete_magic", raw_bytes="ef", validity_error=EOFException.INVALID_MAGIC, ), Container( name="no_version", raw_bytes="ef00", validity_error=[EOFException.INVALID_VERSION, EOFException.INVALID_MAGIC], ), Container( name="no_type_header", raw_bytes="ef00 01", validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="no_type_section_size", raw_bytes="ef00 01 01", validity_error=[ EOFException.MISSING_HEADERS_TERMINATOR, EOFException.INVALID_TYPE_SECTION_SIZE, ], ), Container( name="incomplete_type_section_size", raw_bytes="ef00010100", validity_error=[ EOFException.INCOMPLETE_SECTION_SIZE, EOFException.INVALID_TYPE_SECTION_SIZE, ], ), Container( name="no_code_header", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04]), validity_error=[ EOFException.MISSING_CODE_HEADER, EOFException.MISSING_HEADERS_TERMINATOR, ], ), Container( name="no_code_header_2", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0xFE]), validity_error=[EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_code_header_3", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x00]), validity_error=[EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_code_header_4", sections=[ Section(kind=SectionKind.TYPE, data="00800000"), Section.Data("da"), ], expected_bytecode="ef0001 010004 ff0001 00 00800000 da", validity_error=[EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="code_section_count_missing", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02]), validity_error=EOFException.INCOMPLETE_SECTION_NUMBER, ), Container( name="code_section_count_incomplete", raw_bytes="ef00 01 01 0004 02 00", validity_error=EOFException.INCOMPLETE_SECTION_NUMBER, ), Container( name="code_section_size_missing", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02, 0x00, 0x01]), validity_error=[ EOFException.MISSING_HEADERS_TERMINATOR, EOFException.ZERO_SECTION_SIZE, ], ), Container( name="code_section_size_incomplete", raw_bytes="ef00 01 01 0004 02 0001 00", validity_error=[EOFException.INCOMPLETE_SECTION_SIZE, EOFException.ZERO_SECTION_SIZE], ), Container( name="code_section_count_0x8000_truncated", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02, 0x80, 0x00]), validity_error=EOFException.TOO_MANY_CODE_SECTIONS, ), Container( name="code_section_count_0xFFFF_truncated", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02, 0xFF, 0xFF]), validity_error=EOFException.TOO_MANY_CODE_SECTIONS, ), pytest.param( Container( name="code_section_count_0x8000", raw_bytes=bytes( [0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02, 0x80, 0x00] + [0x00, 0x01] * 0x8000 ), validity_error=EOFException.CONTAINER_SIZE_ABOVE_LIMIT, ), marks=pytest.mark.eof_test_only(reason="initcode too large"), ), pytest.param( Container( name="code_section_count_0xFFFF", raw_bytes=bytes( [0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02, 0xFF, 0xFF] + [0x00, 0x01] * 0xFFFF ), validity_error=EOFException.CONTAINER_SIZE_ABOVE_LIMIT, ), marks=pytest.mark.eof_test_only(reason="initcode too large"), ), Container( name="code_section_size_0x8000_truncated", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02, 0x00, 0x01, 0x80, 0x00]), validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="code_section_size_0xFFFF_truncated", raw_bytes=bytes([0xEF, 0x00, 0x01, 0x01, 0x00, 0x04, 0x02, 0x00, 0x01, 0xFF, 0xFF]), validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="terminator_incomplete", header_terminator=b"", sections=[ Section(kind=SectionKind.TYPE, data=b"", custom_size=4), Section.Code(code=b"", custom_size=0x01), ], expected_bytecode="ef00 01 01 0004 02 0001 0001 ff 0000", validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="truncated_header_data_section", raw_bytes="ef00 01 01 0004 02 0001 0001", validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="no_data_section_size", raw_bytes="ef00 01 01 0004 02 0001 0001 ff", validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="data_section_size_incomplete", raw_bytes="ef00 01 01 0004 02 0001 0001 ff 00", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="no_container_section_count", raw_bytes="ef00 01 01 0004 02 0001 0001 03", validity_error=EOFException.INCOMPLETE_SECTION_NUMBER, ), Container( name="incomplete_container_section_count", raw_bytes="ef00 01 01 0004 02 0001 0001 03 00", validity_error=EOFException.INCOMPLETE_SECTION_NUMBER, ), Container( name="zero_container_section_count", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0000 ff 0000 00 00800000 00", validity_error=EOFException.ZERO_SECTION_SIZE, ), Container( name="no_container_section_size", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001", validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="incomplete_container_section_size", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001 00", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="incomplete_container_section_size_2", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001 0000", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="incomplete_container_section_size_3", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001 000000", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="incomplete_container_section_size_4", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0002 00000001", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="incomplete_container_section_size_5", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0002 00000001 00", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="incomplete_container_section_size_6", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0002 00000001 0000", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="incomplete_container_section_size_7", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0002 00000001 000000", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( name="zero_size_container_section", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001 00000000 ff 0000 00 00800000 00", validity_error=EOFException.ZERO_SECTION_SIZE, ), Container( name="container_section_size_2bytes", raw_bytes="ef00 01 01 0004 02 0001 000b 03 0001 0014 ff 0000 00 00800004" "6000600060006000ec0000" "ef00 01 01 0004 02 0001 0001 ff 0000 00 00800000 fe", validity_error=EOFException.MISSING_DATA_SECTION, ), Container( name="truncated_header_data_section_with_container_section", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001 00000001", validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="no_data_section_size_with_container_section", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001 00000001 ff", validity_error=EOFException.MISSING_HEADERS_TERMINATOR, ), Container( name="data_section_size_incomplete_with_container_section", raw_bytes="ef00 01 01 0004 02 0001 0001 03 0001 00000001 ff 00", validity_error=EOFException.INCOMPLETE_SECTION_SIZE, ), Container( # EOF code missing mandatory type section name="EOF1I4750_0001", raw_bytes="ef00010200010001ff00000000800000fe", validity_error=EOFException.MISSING_TYPE_HEADER, ), Container( # EOF code containing multiple type headers name="multiple_type_headers_1", # EOF1I4750_0002 raw_bytes="ef0001010004010004ff00000000800000fe", validity_error=EOFException.MISSING_CODE_HEADER, ), Container( # EOF code containing multiple type headers, second one matches # code length name="multiple_type_headers_2", raw_bytes="ef0001010004010001ff00000000800000fe", validity_error=EOFException.MISSING_CODE_HEADER, ), Container( # EOF code containing multiple type headers followed by 2 code # sections name="multiple_type_headers_3", sections=[ Section(kind=SectionKind.TYPE, data="00800000"), Section(kind=SectionKind.TYPE, data="00800000"), Section.Code(Op.JUMPF[1]), Section.Code(Op.INVALID), ], validity_error=EOFException.MISSING_CODE_HEADER, ), Container( # EOF code containing type section size (Size 1) name="EOF1I4750_0003", raw_bytes="ef00010100010200010001ff00000000800000fe", validity_error=[ EOFException.INVALID_TYPE_SECTION_SIZE, EOFException.INVALID_SECTION_BODIES_SIZE, ], ), Container( # EOF code containing type section size (Size 8 - 1 Code section) name="EOF1I4750_0004", raw_bytes="ef00010100080200010001ff00000000800000fe", validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( # EOF code containing type section size (Size 8 - 3 Code sections) name="EOF1I4750_0005", raw_bytes="ef0001010008020003000100010001ff0000000080000000800000fefefe", validity_error=EOFException.INVALID_TYPE_SECTION_SIZE, ), Container( name="no_sections", sections=[], auto_data_section=False, auto_type_section=AutoSection.NONE, expected_bytecode="ef0001 00", validity_error=[EOFException.MISSING_TYPE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_code_section_header", sections=[ Section(kind=SectionKind.TYPE, data=b"\0\x80\0\0"), Section.Data("0x00"), ], expected_bytecode="ef00 01 01 0004 ff 0001 00 00800000 00", auto_type_section=AutoSection.NONE, validity_error=[EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="too_many_code_sections", sections=[ Section.Code(Op.JUMPF[i + 1] if i < MAX_CODE_SECTIONS else Op.STOP) for i in range(MAX_CODE_SECTIONS + 1) ], validity_error=EOFException.TOO_MANY_CODE_SECTIONS, ), Container( name="zero_code_sections_header", raw_bytes="ef00 01 01 0004 02 0000 ff 0000 00 00800000", validity_error=[ EOFException.ZERO_SECTION_SIZE, EOFException.INCOMPLETE_SECTION_NUMBER, ], ), Container( name="zero_code_sections_header_empty_type_section", raw_bytes="ef00 01 01 0000 02 0000 ff 0000 00", validity_error=[ EOFException.ZERO_SECTION_SIZE, EOFException.INCOMPLETE_SECTION_NUMBER, ], ), # The basic `no_section_terminator` cases just remove the terminator # and the `00` for zeroth section inputs looks like one. Error is # because the sections are wrongly sized. Container( name="no_section_terminator", header_terminator=bytes(), sections=[Section.Code(code=Op.STOP)], validity_error=[ EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.INVALID_FIRST_SECTION_TYPE, ], ), Container( name="no_section_terminator_1", header_terminator=bytes(), sections=[Section.Code(code=Op.STOP, custom_size=2)], validity_error=[ EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.INVALID_FIRST_SECTION_TYPE, ], ), Container( name="no_section_terminator_2", header_terminator=bytes(), sections=[Section.Code(code="0x", custom_size=3)], validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="no_section_terminator_3", header_terminator=bytes(), sections=[Section.Code(code=Op.PUSH1(0) + Op.STOP)], validity_error=[ EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.INVALID_FIRST_SECTION_TYPE, ], ), # The following cases just remove the terminator and the `00` for # zeroth section inputs looks like one. Section bodies are as the size # prescribes here, so the error is about the inputs of zeroth section. Container( name="no_section_terminator_section_bodies_ok_1", header_terminator=bytes(), sections=[Section.Code(code=Op.JUMPDEST + Op.STOP, custom_size=1)], validity_error=EOFException.INVALID_FIRST_SECTION_TYPE, ), Container( name="no_section_terminator_section_bodies_ok_2", header_terminator=bytes(), sections=[Section.Code(code=Op.JUMPDEST * 2 + Op.STOP, custom_size=2)], validity_error=EOFException.INVALID_FIRST_SECTION_TYPE, ), # Here the terminator is missing but made to look like a different # section or arbitrary byte Container( name="no_section_terminator_nonzero", header_terminator=b"01", sections=[Section.Code(code=Op.STOP)], validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_section_terminator_nonzero_1", header_terminator=b"02", sections=[Section.Code(code=Op.STOP, custom_size=2)], validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_section_terminator_nonzero_2", header_terminator=b"03", sections=[Section.Code(code="0x", custom_size=3)], validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_section_terminator_nonzero_3", header_terminator=b"04", sections=[Section.Code(code=Op.PUSH1(0) + Op.STOP)], validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_section_terminator_nonzero_4", header_terminator=b"fe", sections=[Section.Code(code=Op.PUSH1(0) + Op.STOP)], validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="truncated_before_type_section", sections=[ Section(kind=SectionKind.TYPE, data=b"", custom_size=4), Section.Code(code=b"", custom_size=0x01), ], expected_bytecode="ef00 01 01 0004 02 0001 0001 ff 0000 00", validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="truncated_type_section_before_outputs", sections=[ Section(kind=SectionKind.TYPE, data=b"\0", custom_size=4), Section.Code(code=b"", custom_size=0x01), ], expected_bytecode="ef00 01 01 0004 02 0001 0001 ff 0000 00 00", validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="truncated_type_section_before_max_stack_height", sections=[ Section(kind=SectionKind.TYPE, data=b"\0\x80", custom_size=4), Section.Code(code=b"", custom_size=0x01), ], expected_bytecode="ef00 01 01 0004 02 0001 0001 ff 0000 00 0080", validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="truncated_type_section_truncated_max_stack_height", sections=[ Section(kind=SectionKind.TYPE, data=b"\0\x80\0", custom_size=4), Section.Code(code=b"", custom_size=0x01), ], expected_bytecode="ef00 01 01 0004 02 0001 0001 ff 0000 00 008000", validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="no_code_section_contents", sections=[Section.Code(code="0x", custom_size=0x01)], validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="incomplete_code_section_contents", sections=[ Section.Code(code=Op.STOP, custom_size=0x02), ], validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="trailing_bytes_after_code_section", sections=[Section.Code(code=Op.PUSH1(0) + Op.STOP)], extra=bytes([0xDE, 0xAD, 0xBE, 0xEF]), validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="empty_code_section", sections=[Section.Code(code="0x")], # TODO the exception must be about code section # EOFException.INVALID_CODE_SECTION, validity_error=EOFException.ZERO_SECTION_SIZE, ), Container( name="empty_code_section_with_non_empty_data", sections=[ Section.Code(code="0x"), Section.Data(data="0xDEADBEEF"), ], # TODO the exception must be about code section # EOFException.INVALID_CODE_SECTION, validity_error=EOFException.ZERO_SECTION_SIZE, ), Container( name="no_container_section_contents", sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section(kind=SectionKind.CONTAINER, data=b"", custom_size=20), ], validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="no_container_section_contents_with_data", sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section(kind=SectionKind.CONTAINER, data=b"", custom_size=20), Section.Data(b"\0" * 20), ], validity_error=EOFException.TOPLEVEL_CONTAINER_TRUNCATED, ), Container( name="no_data_section_contents", sections=[ Section.Code(Op.STOP), Section.Data(data="0x", custom_size=1), ], code="ef0001 010004 0200010001 ff0001 00 00800000 00", validity_error=EOFException.TOPLEVEL_CONTAINER_TRUNCATED, ), Container( name="data_section_contents_incomplete", sections=[ Section.Code(Op.STOP), Section.Data(data="0xAABBCC", custom_size=4), ], validity_error=EOFException.TOPLEVEL_CONTAINER_TRUNCATED, ), Container( name="data_section_preceding_code_section", auto_data_section=False, auto_sort_sections=AutoSection.NONE, sections=[ Section.Data(data="0xDEADBEEF"), Section.Code(Op.STOP), ], validity_error=[EOFException.MISSING_CODE_HEADER, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="data_section_without_code_section", sections=[Section.Data(data="0xDEADBEEF")], # TODO the actual exception should be # EOFException.MISSING_CODE_HEADER validity_error=[EOFException.ZERO_SECTION_SIZE, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="no_section_terminator_3a", header_terminator=bytes(), sections=[Section.Code(code="0x030004")], # TODO the exception must be about terminator validity_error=[ EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.INVALID_FIRST_SECTION_TYPE, ], ), Container( name="no_section_terminator_4a", header_terminator=bytes(), sections=[ Section.Code(Op.STOP), Section.Data(data="0xAABBCCDD"), ], # TODO: The error of this validation can be random. validity_error=EOFException.INVALID_FIRST_SECTION_TYPE, ), Container( name="trailing_bytes_after_data_section", extra=bytes([0xEE]), sections=[ Section.Code(code=Op.PUSH1(0) + Op.STOP), Section.Data(data="0xAABBCCDD"), ], # TODO should be more specific exception about trailing bytes validity_error=EOFException.INVALID_SECTION_BODIES_SIZE, ), Container( name="multiple_data_sections", sections=[ Section.Code(code=Op.PUSH1(0) + Op.STOP), Section.Data(data="0xAABBCC"), Section.Data(data="0xAABBCC"), ], expected_bytecode=( "ef00 01 01 0004 02 0001 0003 ff 0003 ff 0003 00 00800001 600000 AABBCC AABBCC" ), validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="multiple_code_headers", sections=[ Section.Code(Op.JUMPF[1]), Section.Data(data="0xAA"), Section.Code(Op.STOP), ], auto_sort_sections=AutoSection.ONLY_BODY, expected_bytecode=( "ef00 01 01 0008 02 0001 0003 ff 0001 02 0001 0001 00" "00800000 00800000 E50001 00 AA" ), validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="multiple_code_headers_2", sections=[ Section.Code(Op.JUMPF[1]), Section.Code(Op.STOP), Section.Data(data="0xAA"), ], skip_join_concurrent_sections_in_header=True, expected_bytecode=( "ef00 01 01 0008 02 0001 0003 02 0001 0001 ff 0001 00" "00800000 00800000 E50001 00 AA" ), validity_error=[ EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND, ], ), Container( name="duplicated_code_header", sections=[ Section.Code(Op.STOP), Section.Code( b"", custom_size=1, skip_types_header_listing=True, skip_types_body_listing=True, ), Section.Data(data="0xAA"), ], skip_join_concurrent_sections_in_header=True, expected_bytecode=( "ef00 01 01 0004 02 0001 0001 02 0001 0001 ff 0001 00 00800000 00 AA" ), validity_error=[ EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND, ], ), Container( name="multiple_code_and_data_sections", sections=[ Section.Code(Op.JUMPF[1]), Section.Code(Op.STOP), Section.Data(data="0xAA"), Section.Data(data="0xAA"), ], expected_bytecode=( "ef00 01 01 0008 02 0002 0003 0001 ff 0001 ff 0001 00" "00800000 00800000 E50001 00 AA AA" ), validity_error=[EOFException.MISSING_TERMINATOR, EOFException.UNEXPECTED_HEADER_KIND], ), Container( name="multiple_code_and_data_sections_2", sections=[ Section.Code(Op.JUMPF[1]), Section.Code(Op.STOP), Section.Data(data="0xAA"), Section.Data(data="0xAA"), ], skip_join_concurrent_sections_in_header=True, expected_bytecode=( "ef00 01 01 0008 02 0001 0003 02 0001 0001 ff 0001 ff 0001 00" "00800000 00800000 E50001 00 AA AA" ), validity_error=[ EOFException.MISSING_DATA_SECTION, EOFException.UNEXPECTED_HEADER_KIND, ], ), Container( name="multiple_container_headers", sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.EOFCREATE[1](0, 0, 0, 0) + Op.STOP), Section.Container(Container.Code(code=Op.INVALID)), Section.Data(data="0xAA"), Section.Container(Container.Code(code=Op.INVALID)), ], auto_sort_sections=AutoSection.ONLY_BODY, expected_bytecode=(
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
true
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_extcode.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_extcode.py
"""test execution semantics changes.""" import pytest from ethereum_test_tools import ( Account, Alloc, Environment, StateTestFiller, Storage, Transaction, keccak256, ) from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import Container from .. import EOF_FORK_NAME pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-4750.md" REFERENCE_SPEC_VERSION = "90f716078d0b08ce508a1e57803f885cc2f2e15e" def test_legacy_calls_eof_sstore( state_test: StateTestFiller, pre: Alloc, ) -> None: """Test EXTCODE* opcodes calling EOF and legacy contracts.""" env = Environment() eof_code = Container.Code(Op.RJUMP[0] + Op.STOP) address_eof_contract = pre.deploy_contract(eof_code) legacy_code = Op.PUSH1(2) + Op.JUMPDEST + Op.STOP address_legacy_contract = pre.deploy_contract(legacy_code) storage_test = Storage() test_contract_code = ( Op.SSTORE(storage_test.store_next(4), Op.EXTCODESIZE(address_legacy_contract)) + Op.EXTCODECOPY(address_legacy_contract, 0, 0, Op.EXTCODESIZE(address_legacy_contract)) + Op.SSTORE( storage_test.store_next(bytes(legacy_code).ljust(32, b"\0")), Op.MLOAD(0), ) + Op.SSTORE( storage_test.store_next(legacy_code.keccak256()), Op.EXTCODEHASH(address_legacy_contract), ) + Op.SSTORE(storage_test.store_next(2), Op.EXTCODESIZE(address_eof_contract)) + Op.EXTCODECOPY(address_eof_contract, 0x20, 0, 6) + Op.SSTORE(storage_test.store_next(b"\xef".ljust(32, b"\0")), Op.MLOAD(0x20)) + Op.MSTORE(0x40, b"\xcc" * 32) # clobber memory slot + Op.EXTCODECOPY(address_eof_contract, 0x40, len(eof_code) - 4, 8) # out-of-bounds "read" + Op.SSTORE(storage_test.store_next(b"\xcc" * 24), Op.MLOAD(0x40)) + Op.SSTORE( storage_test.store_next(keccak256(b"\xef\x00")), Op.EXTCODEHASH(address_eof_contract), ) ) address_test_contract = pre.deploy_contract(test_contract_code) sender = pre.fund_eoa() tx = Transaction( sender=sender, to=address_test_contract, gas_limit=50_000_000, gas_price=10, protected=False, data="", ) post = { address_test_contract: Account(storage=storage_test), } state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/__init__.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/__init__.py
""" EOF - EVM Object Format v1 tests. Test cases for [EIP-3540: EOF - EVM Object Format v1](https://eips.ethereum.org/EIPS/eip-3540). EIP-3540 introduces a structured format for EVM bytecode, with separate sections for code and data. Opcodes introduced: None (defines a new bytecode structure but no new opcodes). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_execution.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_execution.py
"""Execution of basic EOF containers.""" import pytest from ethereum_test_base_types import Storage from ethereum_test_tools import Account, Alloc, Environment, StateTestFiller, Transaction from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) EXPECTED_STORAGE = (bytes.fromhex("EF"), bytes.fromhex("BADDCAFE")) """Expected storage (key => value) to be produced by the EOF containers""" @pytest.mark.parametrize( "container", ( Container( name="store_from_push", sections=[Section.Code(Op.SSTORE(*EXPECTED_STORAGE) + Op.STOP)], ), Container( name="store_with_data", sections=[ Section.Code(Op.SSTORE(Op.DATALOADN[0], Op.DATALOADN[32]) + Op.STOP), Section.Data( EXPECTED_STORAGE[0].rjust(32, b"\x00") + EXPECTED_STORAGE[1].rjust(32, b"\x00") ), ], ), ), ids=lambda x: x.name, ) def test_eof_execution( state_test: StateTestFiller, pre: Alloc, container: Container, ) -> None: """Test simple contracts that are expected to succeed on call.""" env = Environment() storage = Storage() sender = pre.fund_eoa() container_address = pre.deploy_contract(container) caller_contract = Op.SSTORE( storage.store_next(1), Op.CALL(Op.GAS, container_address, 0, 0, 0, 0, 0) ) caller_address = pre.deploy_contract(caller_contract) tx = Transaction( to=caller_address, gas_limit=1_000_000, gas_price=10, protected=False, sender=sender, ) post = { caller_address: Account(storage=storage), container_address: Account(storage=dict([EXPECTED_STORAGE])), } state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_section_size.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_section_size.py
"""EOF Container, test custom_size field for sections.""" from enum import IntEnum import pytest from ethereum_test_exceptions.exceptions import EOFExceptionInstanceOrList from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import Container, Section, SectionKind from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) class SectionSize(IntEnum): """Enum for the section size.""" NORMAL = -1 ZERO = 0 UNDERSIZE = 2 OVERSIZE = 100 HUGE = 0x8000 MAX = 0xFFFF CONTAINER_BIG = 0x00010000 CONTAINER_MAX = 0xFFFFFFFF def __str__(self) -> str: """Return string representation of the section kind.""" return self.name @pytest.mark.parametrize( "section_kind, section_size, exception", [ pytest.param(SectionKind.DATA, SectionSize.NORMAL, None), pytest.param(SectionKind.DATA, SectionSize.ZERO, EOFException.INVALID_SECTION_BODIES_SIZE), pytest.param( SectionKind.DATA, SectionSize.UNDERSIZE, EOFException.INVALID_SECTION_BODIES_SIZE ), pytest.param( SectionKind.DATA, SectionSize.OVERSIZE, EOFException.TOPLEVEL_CONTAINER_TRUNCATED ), pytest.param( SectionKind.DATA, SectionSize.HUGE, EOFException.TOPLEVEL_CONTAINER_TRUNCATED ), pytest.param(SectionKind.DATA, SectionSize.MAX, EOFException.TOPLEVEL_CONTAINER_TRUNCATED), pytest.param( SectionKind.CODE, SectionSize.NORMAL, None, marks=pytest.mark.skip(reason="duplicate") ), pytest.param(SectionKind.CODE, SectionSize.ZERO, EOFException.ZERO_SECTION_SIZE), pytest.param( SectionKind.CODE, SectionSize.UNDERSIZE, EOFException.INVALID_SECTION_BODIES_SIZE ), pytest.param( SectionKind.CODE, SectionSize.OVERSIZE, EOFException.INVALID_SECTION_BODIES_SIZE ), pytest.param(SectionKind.CODE, SectionSize.HUGE, EOFException.INVALID_SECTION_BODIES_SIZE), pytest.param(SectionKind.CODE, SectionSize.MAX, EOFException.INVALID_SECTION_BODIES_SIZE), pytest.param( SectionKind.TYPE, SectionSize.NORMAL, None, marks=pytest.mark.skip(reason="duplicate") ), pytest.param( SectionKind.TYPE, SectionSize.ZERO, [EOFException.ZERO_SECTION_SIZE, EOFException.INVALID_SECTION_BODIES_SIZE], id="type_size_zero", ), pytest.param( SectionKind.TYPE, SectionSize.UNDERSIZE, [EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.INVALID_TYPE_SECTION_SIZE], id="type_size_undersize", ), pytest.param( SectionKind.TYPE, SectionSize.OVERSIZE, EOFException.INVALID_SECTION_BODIES_SIZE ), pytest.param(SectionKind.TYPE, SectionSize.HUGE, EOFException.INVALID_SECTION_BODIES_SIZE), pytest.param( SectionKind.TYPE, SectionSize.MAX, [EOFException.INVALID_SECTION_BODIES_SIZE, EOFException.INVALID_TYPE_SECTION_SIZE], id="type_size_max", ), pytest.param( SectionKind.CONTAINER, SectionSize.NORMAL, None, marks=pytest.mark.skip(reason="duplicate"), ), pytest.param(SectionKind.CONTAINER, SectionSize.ZERO, EOFException.ZERO_SECTION_SIZE), pytest.param( SectionKind.CONTAINER, SectionSize.UNDERSIZE, EOFException.INVALID_SECTION_BODIES_SIZE ), pytest.param( SectionKind.CONTAINER, SectionSize.OVERSIZE, EOFException.INVALID_SECTION_BODIES_SIZE ), pytest.param( SectionKind.CONTAINER, SectionSize.HUGE, EOFException.INVALID_SECTION_BODIES_SIZE ), pytest.param( SectionKind.CONTAINER, SectionSize.CONTAINER_BIG, EOFException.INVALID_SECTION_BODIES_SIZE, ), pytest.param( SectionKind.CONTAINER, SectionSize.CONTAINER_MAX, EOFException.INVALID_SECTION_BODIES_SIZE, ), ], ) def test_section_size( eof_test: EOFTestFiller, section_size: SectionSize, section_kind: SectionKind, exception: EOFExceptionInstanceOrList, ) -> None: """ Test custom_size is auto, more or less than the actual size of the section. """ eof_code = Container() if section_size != SectionSize.NORMAL and section_kind == SectionKind.TYPE: eof_code.sections.append( Section( kind=SectionKind.TYPE, data="0x00800001", custom_size=section_size, ), ) if section_size != SectionSize.NORMAL and section_kind == SectionKind.CODE: eof_code.sections.append( Section.Code( code=Op.ADDRESS + Op.POP + Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP, custom_size=section_size, ) ) else: eof_code.sections.append( Section.Code( code=Op.ADDRESS + Op.POP + Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP, ) ) if section_size != SectionSize.NORMAL and section_kind == SectionKind.CONTAINER: eof_code.sections.append( Section.Container( container=Container( sections=[ Section.Code(Op.RETURNCODE[0](0, 0)), Section.Container(container=Container(sections=[Section.Code(Op.STOP)])), ] ), custom_size=section_size, ) ) else: eof_code.sections.append( Section.Container( container=Container( sections=[ Section.Code(Op.RETURNCODE[0](0, 0)), Section.Container(container=Container(sections=[Section.Code(Op.STOP)])), ] ), ) ) if section_size != SectionSize.NORMAL and section_kind == SectionKind.DATA: eof_code.sections.append(Section.Data("0x00daaa", custom_size=section_size)) else: eof_code.sections.append(Section.Data("0x00aaaa")) eof_test( container=eof_code, expect_exception=exception, ) @pytest.mark.parametrize( "truncation_len, exception", [ # The original container is not valid by itself because its 2-byte code # section starts with the terminating instruction: INVALID. pytest.param(0, EOFException.UNREACHABLE_INSTRUCTIONS), pytest.param(1, EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1_truncated_section_2"), pytest.param(3, EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1_truncated_section_1"), pytest.param(6, EOFException.INVALID_SECTION_BODIES_SIZE, id="EOF1_truncated_section_0"), ], ) def test_truncated_container_without_data( eof_test: EOFTestFiller, truncation_len: int, exception: EOFException, ) -> None: """ Test takes a semi-valid container and removes some bytes from its tail. Migrated from EOFTests/efValidation/EOF1_truncated_section_.json (cases without data section). """ container = Container(sections=[Section.Code(Op.INVALID + Op.INVALID)]) bytecode = bytes(container) eof_test( container=Container(raw_bytes=bytecode[: len(bytecode) - truncation_len]), expect_exception=exception, ) @pytest.mark.parametrize( "truncation_len, exception", [ pytest.param(0, None), pytest.param(1, EOFException.TOPLEVEL_CONTAINER_TRUNCATED, id="EOF1_truncated_section_4"), pytest.param(2, EOFException.TOPLEVEL_CONTAINER_TRUNCATED, id="EOF1_truncated_section_3"), ], ) def test_truncated_container_with_data( eof_test: EOFTestFiller, truncation_len: int, exception: EOFException, ) -> None: """ Test takes a valid container with data and removes some bytes from its tail. Migrated from EOFTests/efValidation/EOF1_truncated_section_.json (cases with data section). """ data = b"\xaa\xbb" container = Container( sections=[ Section.Code(Op.INVALID), Section.Data(data[0 : (len(data) - truncation_len)], custom_size=2), ] ) eof_test( container=container, expect_exception=exception, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_eof_example.py
tests/unscheduled/eip7692_eof_v1/eip3540_eof_v1/test_eof_example.py
"""EOF Classes example use.""" import pytest from ethereum_test_tools import Bytecode, EOFException, EOFTestFiller from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import AutoSection, Container, Section from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "8dcb0a8c1c0102c87224308028632cc986a61183" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def test_eof_example(eof_test: EOFTestFiller) -> None: """Example of python EOF classes.""" # Lets construct an EOF container code eof_code = Container( name="valid_container_example", sections=[ # TYPES section is constructed automatically based on CODE # CODE section Section.Code( code=Op.CALLF[1](Op.PUSH0) + Op.STOP, # bytecode to be # deployed in the body # Code: call section 1 with a single zero as input, then stop. max_stack_increase=1, # define code header (in body) stack # size ), # There can be multiple code sections Section.Code( # Remove input and call section 2 with no inputs, then remove # output and return code=Op.POP + Op.CALLF[2]() + Op.POP + Op.RETF, code_inputs=1, code_outputs=0, max_stack_increase=0, ), Section.Code( # Call section 3 with two inputs (address twice), return code=Op.CALLF[3](Op.DUP1, Op.ADDRESS) + Op.POP + Op.POP + Op.RETF, code_outputs=1, max_stack_increase=3, ), Section.Code( # Duplicate one input and return code=Op.DUP1 + Op.RETF, code_inputs=2, code_outputs=3, max_stack_increase=1, ), # DATA section Section.Data("0xef"), ], expected_bytecode="ef00010100100200040005000600080002ff000100" "00800001 01000000 00010003 02030001" "5fe300010050e3000250e43080e300035050e480e4ef", ) eof_test( container=eof_code, expect_exception=eof_code.validity_error, ) def test_eof_example_custom_fields(eof_test: EOFTestFiller) -> None: """Example of python EOF container class tuning.""" # if you need to overwrite certain structure bytes, you can use # customization. this is useful for unit testing the eof structure format, # you can reorganize sections and overwrite the header bytes for testing # purposes. most of the combinations are covered by the unit tests # This features are subject for development and will change in the future eof_code = Container( name="valid_container_example_2", magic=b"\xef\x00", # magic can be overwritten for test purposes, # (default is 0xEF00) version=b"\x01", # version can be overwritten for testing purposes # (default is 0x01) header_terminator=b"\x00", # terminator byte can be overwritten # (default is 0x00) extra=b"", # extra bytes to be trailed after the container body bytes # (default is None) sections=[ # TYPES section is constructed automatically based on CODE # CODE section Section.Code( code=Op.PUSH1(2) + Op.STOP, # this is the actual bytecode to be deployed in the # body max_stack_height=1, # define code header (in body) stack size ), # DATA section Section.Data( data="0xef", # custom_size overrides the size bytes, so you can put only 1 # byte into data but still make the header size of 2 to produce # invalid section # # if custom_size != len(data), the section will be invalid custom_size=1, ), ], # auto generate types section based on provided code sections # AutoSection.ONLY_BODY - means the section will be generated only for # the body bytes # # AutoSection.ONLY_BODY - means the section will be generated only for # the header bytes auto_type_section=AutoSection.AUTO, # auto generate default data section (0x empty), by default is True auto_data_section=True, # auto sort section by order 01 02 03 04 # AutoSection.ONLY_BODY - means the sorting will be done only for the # body bytes # AutoSection.ONLY_BODY - means the section will be done only for the # header bytes auto_sort_sections=AutoSection.AUTO, ) eof_test( container=eof_code, expect_exception=eof_code.validity_error, ) @pytest.mark.parametrize( "data_section_bytes", (b"\x01", b"\xef"), ) @pytest.mark.parametrize( "code_section_code, exception", [(Op.PUSH1(10) + Op.STOP, None), (Op.PUSH1(14), EOFException.MISSING_STOP_OPCODE)], ) def test_eof_example_parameters( eof_test: EOFTestFiller, data_section_bytes: bytes, code_section_code: Bytecode, exception: EOFException, ) -> None: """Example of EOF example parameters.""" eof_code = Container( name="parametrized_eof_example", sections=[ Section.Code( code=code_section_code, max_stack_height=1, ), Section.Data(data_section_bytes), ], validity_error=exception, ) eof_test( container=eof_code, expect_exception=eof_code.validity_error, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/test_rjumpi.py
tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/test_rjumpi.py
"""EOF JUMPF tests covering stack and code validation rules.""" import pytest from ethereum_test_tools import ( Account, Alloc, Environment, EOFException, EOFStateTestFiller, EOFTestFiller, StateTestFiller, Transaction, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_BYTECODE_SIZE from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import ( JumpDirection, slot_code_worked, slot_conditional_result, value_calldata_false, value_calldata_true, value_code_worked, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-4200.md" REFERENCE_SPEC_VERSION = "17d4a8d12d2b5e0f2985c866376c16c8c6df7cba" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) RJUMP_LEN = len(Op.RJUMP[0]) RJUMPI_LEN = len(Op.RJUMPI[0]) @pytest.mark.parametrize( "calldata", [pytest.param(b"\x00", id="False"), pytest.param(b"\x01", id="True")], ) def test_rjumpi_condition_forwards( state_test: StateTestFiller, pre: Alloc, calldata: bytes, ) -> None: """Test RJUMPI contract switching based on external input (forwards).""" env = Environment() sender = pre.fund_eoa(10**18) contract_address = pre.deploy_contract( code=Container.Code( Op.PUSH1(0) + Op.CALLDATALOAD + Op.RJUMPI[6] + Op.SSTORE(slot_conditional_result, value_calldata_false) + Op.STOP + Op.SSTORE(slot_conditional_result, value_calldata_true) + Op.STOP, ) ) tx = Transaction( to=contract_address, gas_limit=10_000_000, data=calldata, sender=sender, ) post = { contract_address: Account( storage={ slot_conditional_result: value_calldata_false if calldata == b"\0" else value_calldata_true } ) } state_test(env=env, tx=tx, pre=pre, post=post) @pytest.mark.parametrize( "calldata", [pytest.param(b"\x00", id="False"), pytest.param(b"\x01", id="True")], ) def test_rjumpi_condition_backwards( state_test: StateTestFiller, pre: Alloc, calldata: bytes, ) -> None: """Test RJUMPI contract switching based on external input.""" env = Environment() sender = pre.fund_eoa(10**18) contract_address = pre.deploy_contract( code=Container.Code( Op.PUSH1(1) + Op.RJUMPI[6] + Op.SSTORE(slot_conditional_result, value_calldata_true) + Op.STOP + Op.PUSH0 + Op.CALLDATALOAD + Op.RJUMPI[-11] + Op.SSTORE(slot_conditional_result, value_calldata_false) + Op.STOP, ) ) tx = Transaction( to=contract_address, gas_limit=10_000_000, data=calldata, sender=sender, ) post = { contract_address: Account( storage={ slot_conditional_result: value_calldata_false if calldata == b"\0" else value_calldata_true } ) } state_test(env=env, tx=tx, pre=pre, post=post) @pytest.mark.parametrize( "calldata", [pytest.param(b"\x00", id="False"), pytest.param(b"\x01", id="True")], ) def test_rjumpi_condition_zero( state_test: StateTestFiller, pre: Alloc, calldata: bytes, ) -> None: """ Test RJUMPI contract switching based on external input (condition zero). """ env = Environment() sender = pre.fund_eoa(10**18) contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.CALLDATALOAD + Op.RJUMPI[0] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ] ), ) tx = Transaction( to=contract_address, gas_limit=10_000_000, data=calldata, sender=sender, ) post = {contract_address: Account(storage={slot_code_worked: value_code_worked})} state_test(env=env, tx=tx, pre=pre, post=post) def test_rjumpi_forwards( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0004 (Valid) EOF code containing RJUMPI (Positive).""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[3] + Op.NOOP + Op.NOOP + Op.STOP + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpi_backwards( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0005 (Valid) EOF code containing RJUMPI (Negative).""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[7] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP + Op.PUSH1(1) + Op.RJUMPI[-12] + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpi_zero( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0006 (Valid) EOF code containing RJUMPI (Zero).""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[0] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpi_max_forward( eof_state_test: EOFStateTestFiller, ) -> None: """ EOF1V4200_0007 (Valid) EOF with RJUMPI containing the maximum offset (32767). """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[32767] + Op.NOOP * 32768 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpi_max_backward( eof_state_test: EOFStateTestFiller, ) -> None: """EOF with RJUMPI containing the maximum negative offset (-32768).""" ( eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[0x7FFF] + Op.NOOP * (0x7FFF - 7) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP + Op.PUSH0 + Op.RJUMPI[0x8000] + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ), ) @pytest.mark.parametrize( "container", [ Container( name="forwards_rjumpi_0", sections=[ Section.Code( code=Op.PUSH1[1] + Op.RJUMPI[0] + Op.STOP, max_stack_increase=1, ), ], expected_bytecode="ef00010100040200010006ff000000008000016001e1000000", ), Container( name="forwards_rjumpi_1", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.NOT + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef00010100040200010008ff000000008000025f6000e100011900", ), Container( name="forwards_rjumpi_10", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.POP + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000cff000000008000025f6000e1000450e000011900", ), Container( name="forwards_rjumpi_11", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[3] + Op.RJUMP[0] + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000aff000000008000025f6000e10003e0000000", ), Container( name="forwards_rjumpi_12", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.PUSH0 + Op.RJUMP[0] + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000bff000000008000025f6000e100045fe0000000", ), Container( name="forwards_rjumpi_2", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[6] + Op.PUSH1[0] + Op.RJUMPI[1] + Op.NOT + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000dff000000008000025f6000e100066000e100011900", ), Container( name="forwards_rjumpi_3", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.PUSH0 + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef00010100040200010008ff000000008000025f6000e100015f00", ), Container( name="forwards_rjumpi_4", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[7] + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.NOT + Op.STOP, max_stack_increase=3, ), ], expected_bytecode="ef0001010004020001000eff000000008000035f6000e100075f6000e100011900", ), Container( name="forwards_rjumpi_5", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[1] + Op.ADD + Op.DUP1 + Op.PUSH1[10] + Op.GT + Op.RJUMPI[4] + Op.DUP1 + Op.RJUMPI[-14] + Op.STOP, max_stack_increase=3, ), ], expected_bytecode="ef00010100040200010010ff000000008000035f60010180600a11e1000480e1fff200", ), Container( name="forwards_rjumpi_6", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[1] + Op.ADD + Op.DUP1 + Op.PUSH1[10] + Op.GT + Op.RJUMPI[5] + Op.PUSH0 + Op.DUP1 + Op.RJUMPI[-13] + Op.STOP, max_stack_increase=3, ), ], expected_bytecode="ef00010100040200010011ff000000008000035f60010180600a11e100055f80e1fff300", ), Container( name="forwards_rjumpi_7", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.PUSH0 + Op.RJUMP[1] + Op.PUSH0 + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000cff000000008000025f6000e100045fe000015f00", ), Container( name="forwards_rjumpi_8", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.PUSH0 + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000cff000000008000025f6000e100045fe000011900", ), Container( name="forwards_rjumpi_9", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.POP + Op.RJUMP[1] + Op.POP + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000cff000000008000025f6000e1000450e000015000", ), Container( name="forwards_rjumpi_variable_stack_0", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[1] + Op.RJUMPI[0] + Op.STOP, max_stack_increase=4, ), ], expected_bytecode="ef0001010004020001000eff000000008000045f6000e100025f5f6001e1000000", ), Container( name="forwards_rjumpi_variable_stack_1", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.NOT + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010010ff000000008000055f6000e100025f5f5f6000e100011900", ), Container( name="forwards_rjumpi_variable_stack_10", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.POP + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010014ff000000008000055f6000e100025f5f5f6000e1000450e000011900", ), Container( name="forwards_rjumpi_variable_stack_11", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[3] + Op.RJUMP[0] + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010012ff000000008000055f6000e100025f5f5f6000e10003e0000000", ), Container( name="forwards_rjumpi_variable_stack_12", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.PUSH0 + Op.RJUMP[0] + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010013ff000000008000055f6000e100025f5f5f6000e100045fe0000000", ), Container( name="forwards_rjumpi_variable_stack_2", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[6] + Op.PUSH1[0] + Op.RJUMPI[1] + Op.NOT + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010015ff000000008000055f6000e100025f5f5f6000e100066000e100011900", ), Container( name="forwards_rjumpi_variable_stack_3", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.PUSH0 + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010010ff000000008000055f6000e100025f5f5f6000e100015f00", ), Container( name="forwards_rjumpi_variable_stack_4", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[7] + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.NOT + Op.STOP, max_stack_increase=6, ), ], expected_bytecode="ef00010100040200010016ff000000008000065f6000e100025f5f5f6000e100075f6000e100011900", ), Container( name="forwards_rjumpi_variable_stack_5", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[1] + Op.ADD + Op.DUP1 + Op.PUSH1[10] + Op.GT + Op.RJUMPI[4] + Op.DUP1 + Op.RJUMPI[-14] + Op.STOP, max_stack_increase=6, ), ], expected_bytecode="ef00010100040200010018ff000000008000065f6000e100025f5f5f60010180600a11e1000480e1fff200", ), Container( name="forwards_rjumpi_variable_stack_6", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[1] + Op.ADD + Op.DUP1 + Op.PUSH1[10] + Op.GT + Op.RJUMPI[5] + Op.PUSH0 + Op.DUP1 + Op.RJUMPI[-13] + Op.STOP, max_stack_increase=6, ), ], expected_bytecode="ef00010100040200010019ff000000008000065f6000e100025f5f5f60010180600a11e100055f80e1fff300", ), Container( name="forwards_rjumpi_variable_stack_7", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.PUSH0 + Op.RJUMP[1] + Op.PUSH0 + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010014ff000000008000055f6000e100025f5f5f6000e100045fe000015f00", ), Container( name="forwards_rjumpi_variable_stack_8", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.PUSH0 + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010014ff000000008000055f6000e100025f5f5f6000e100045fe000011900", ), Container( name="forwards_rjumpi_variable_stack_9", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[4] + Op.POP + Op.RJUMP[1] + Op.POP + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010014ff000000008000055f6000e100025f5f5f6000e1000450e000015000", ), ], ids=lambda x: x.name, ) def test_rjumpi_valid_forward( eof_test: EOFTestFiller, container: Container, ) -> None: """ Validate a valid code section containing at least one forward RJUMPI. These tests exercise the stack height validation. """ eof_test(container=container) @pytest.mark.parametrize( "container", [ Container( name="backwards_rjumpi_0", sections=[ Section.Code( code=Op.PUSH1[0] + Op.RJUMPI[-5] + Op.STOP, max_stack_increase=1, ), ], expected_bytecode="ef00010100040200010006ff000000008000016000e1fffb00", ), Container( name="backwards_rjumpi_1", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.STOP, max_stack_increase=1, ), ], expected_bytecode="ef00010100040200010008ff000000008000015f506000e1fff900", ), Container( name="backwards_rjumpi_2", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.PUSH1[0] + Op.RJUMPI[-12] + Op.STOP, max_stack_increase=1, ), ], expected_bytecode="ef0001010004020001000dff000000008000015f506000e1fff96000e1fff400", ), Container( name="backwards_rjumpi_4", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[1] + Op.ADD + Op.DUP1 + Op.RJUMPI[-7] + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef00010100040200010009ff00000000800002 5f60010180e1fff900", ), Container( name="backwards_rjumpi_7", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.RJUMP[-10], max_stack_increase=1, ), ], expected_bytecode="ef0001010004020001000aff000000008000015f506000e1fff9e0fff6", ), Container( name="backwards_rjumpi_variable_stack_0", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[-5] + Op.STOP, max_stack_increase=4, ), ], expected_bytecode="ef0001010004020001000eff000000008000045f6000e100025f5f6000e1fffb00", ), Container( name="backwards_rjumpi_variable_stack_1", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.STOP, max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010010ff000000008000045f6000e100025f5f5f506000e1fff900", ), Container( name="backwards_rjumpi_variable_stack_2", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.PUSH1[0] + Op.RJUMPI[-12] + Op.STOP, max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010015ff000000008000045f6000e100025f5f5f506000e1fff96000e1fff400", ), Container( name="backwards_rjumpi_variable_stack_4", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[1] + Op.ADD + Op.DUP1 + Op.RJUMPI[-7] + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010011ff000000008000055f6000e100025f5f5f60010180e1fff900", ), Container( name="backwards_rjumpi_variable_stack_7", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.RJUMP[-10], max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010012ff000000008000045f6000e100025f5f5f506000e1fff9e0fff6", ), ], ids=lambda x: x.name, ) def test_rjumpi_valid_backward( eof_test: EOFTestFiller, container: Container, ) -> None: """ Validate a valid code section containing at least one backward RJUMPI. These tests exercise the stack height validation. """ eof_test(container=container) def test_rjumpi_max_bytecode_size( eof_test: EOFTestFiller, ) -> None: """ EOF1V4200_0003 EOF with RJUMPI containing the maximum offset that does not exceed the maximum bytecode size. """ noop_count = MAX_BYTECODE_SIZE - 24 code = Op.RJUMPI[len(Op.NOOP) * noop_count](Op.ORIGIN) + (Op.NOOP * noop_count) + Op.STOP container = Container.Code(code=code) assert len(container) == MAX_BYTECODE_SIZE eof_test(container=container) def test_rjumpi_truncated( eof_test: EOFTestFiller, ) -> None: """EOF1I4200_0014 (Invalid) EOF code containing truncated RJUMPI.""" eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.RJUMPI, ) ], ), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) def test_rjumpi_truncated_2( eof_test: EOFTestFiller, ) -> None: """EOF1I4200_0015 (Invalid) EOF code containing truncated RJUMPI.""" eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.RJUMPI + b"\x00", ) ], ), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) @pytest.mark.parametrize("offset", [-7, -15]) def test_rjumpi_into_header( eof_test: EOFTestFiller, offset: int, ) -> None: """ EOF1I4200_0016 (Invalid) EOF code containing RJUMPI with target outside code bounds (Jumping into header). """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[offset] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjumpi_jump_before_header( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0017 (Invalid) EOF code containing RJUMPI with target outside code bounds (Jumping to before code begin). """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[-25] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjumpi_into_data( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0018 (Invalid) EOF code containing RJUMPI with target outside code bounds (Jumping into data section). """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[2] + Op.STOP, ), Section.Data(data=b"\xaa\xbb\xcc"), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjumpi_after_container( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0019 (Invalid) EOF code containing RJUMPI with target outside code bounds (Jumping to after code end). """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[2] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjumpi_to_code_end( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0020 (Invalid) EOF code containing RJUMPI with target outside code bounds (Jumping to code end). """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPI[1] + Op.STOP, ), ],
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
true
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/helpers.py
tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/helpers.py
"""EOF RJump tests helpers.""" import itertools from enum import Enum """Storage addresses for common testing fields""" _slot = itertools.count() next(_slot) # don't use slot 0 slot_code_worked = next(_slot) slot_conditional_result = next(_slot) slot_last_slot = next(_slot) """Storage values for common testing fields""" value_code_worked = 0x2015 value_calldata_true = 10 value_calldata_false = 11 class JumpDirection(Enum): """Enum for the direction of the jump.""" FORWARD = 1 BACKWARD = -1
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/test_rjump.py
tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/test_rjump.py
"""EOF JUMPF tests covering stack and code validation rules.""" import pytest from ethereum_test_tools import Account, EOFException, EOFStateTestFiller, EOFTestFiller from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_BYTECODE_SIZE from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import JumpDirection, slot_code_worked, value_code_worked REFERENCE_SPEC_GIT_PATH = "EIPS/eip-4200.md" REFERENCE_SPEC_VERSION = "17d4a8d12d2b5e0f2985c866376c16c8c6df7cba" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) RJUMP_LEN = len(Op.RJUMP[0]) def test_rjump_negative( eof_state_test: EOFStateTestFiller, ) -> None: """Test for a forward RJUMPI and backward RJUMP.""" eof_state_test( container=Container.Code( Op.PUSH1[1] + Op.RJUMPI[7] # RJUMP cannot be used because of the backward jump restriction + Op.SSTORE(slot_code_worked, Op.MLOAD(0)) + Op.STOP + Op.MSTORE(0, value_code_worked) + Op.RJUMP[-16] ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjump_positive_negative( eof_state_test: EOFStateTestFiller, ) -> None: """ EOF1V4200_0001 (Valid) EOF code containing RJUMP (Positive, Negative). """ eof_state_test( container=Container.Code( Op.PUSH0 + Op.RJUMPI[3] + Op.RJUMP[7] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP + Op.RJUMP[-10], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjump_zero( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0002 (Valid) EOF code containing RJUMP (Zero).""" eof_state_test( container=Container.Code( Op.RJUMP[0] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjump_maxes( eof_state_test: EOFStateTestFiller, ) -> None: """ EOF1V4200_0003 EOF with RJUMP containing the max positive and negative offset (32767). """ eof_state_test( container=Container.Code( Op.PUSH0 + Op.RJUMPI[RJUMP_LEN] # The push/jumpi is to allow the NOOPs to be forward referenced + Op.RJUMP[0x7FFF] + Op.NOOP * (0x7FFF - 7) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP + Op.RJUMP[0x8000], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjump_max_bytecode_size( eof_test: EOFTestFiller, ) -> None: """ EOF1V4200_0003 EOF with RJUMP containing the maximum offset that does not exceed the maximum bytecode size. """ noop_count = MAX_BYTECODE_SIZE - 27 code = ( Op.RJUMPI[RJUMP_LEN](Op.ORIGIN) # The jumpi is to allow the NOOPs to be forward referenced + Op.RJUMP[len(Op.NOOP) * noop_count] + (Op.NOOP * noop_count) + Op.STOP ) container = Container.Code(code) assert len(container) == MAX_BYTECODE_SIZE eof_test(container=container) def test_rjump_truncated_rjump( eof_test: EOFTestFiller, ) -> None: """EOF1I4200_0001 (Invalid) EOF code containing truncated RJUMP.""" eof_test( container=Container.Code(Op.RJUMP), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) def test_rjump_truncated_rjump_2( eof_test: EOFTestFiller, ) -> None: """EOF1I4200_0002 (Invalid) EOF code containing truncated RJUMP.""" eof_test( container=Container.Code(Op.RJUMP + b"\x00"), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) @pytest.mark.parametrize("offset", [-5, -13]) def test_rjump_into_header( eof_test: EOFTestFiller, offset: int, ) -> None: """ EOF1I4200_0003 (Invalid) EOF code containing RJUMP with target outside code bounds (Jumping into header). """ eof_test( container=Container.Code(Op.RJUMP[offset]), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_before_header( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0004 (Invalid) EOF code containing RJUMP with target outside code bounds (Jumping before code begin). """ eof_test( container=Container.Code(Op.RJUMP[-23]), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_data( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0005 (Invalid) EOF code containing RJUMP with target outside code bounds (Jumping into data section). """ eof_test( container=Container( sections=[ Section.Code(Op.RJUMP[2]), Section.Data(data=b"\xaa\xbb\xcc"), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_outside_other_section_before( eof_test: EOFTestFiller, ) -> None: """ EOF code containing RJUMP with target outside code bounds (prior code section). """ eof_test( container=Container( sections=[ Section.Code(code=Op.JUMPF[1]), Section.Code(code=Op.RJUMP[-6]), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_outside_other_section_after( eof_test: EOFTestFiller, ) -> None: """ EOF code containing RJUMP with target outside code bounds (Subsequent code section). """ eof_test( container=Container( sections=[ Section.Code(code=Op.JUMPF[1]), Section.Code(code=Op.RJUMP[3] + Op.JUMPF[2]), Section.Code(code=Op.STOP), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_after_container( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0006 (Invalid) EOF code containing RJUMP with target outside code bounds (Jumping after code end). """ eof_test( container=Container.Code(Op.RJUMP[2]), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_to_code_end( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0007 (Invalid) EOF code containing RJUMP with target outside code bounds (Jumping to code end). """ eof_test( container=Container.Code(Op.RJUMP[1] + Op.STOP), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize("offset", range(1, Op.RJUMP.data_portion_length + 1)) def test_rjump_into_self_data_portion( eof_test: EOFTestFiller, offset: int, ) -> None: """ EOF1I4200_0008 (Invalid) EOF code containing RJUMP with target self RJUMP immediate. """ eof_test( container=Container.Code(Op.RJUMP[-offset] + Op.STOP), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_self_remaining_code( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0008 (Invalid) EOF code containing RJUMP with target self RJUMP but remaining unreachable code. """ eof_test( container=Container.Code(Op.RJUMP[-len(Op.RJUMP[0])] + Op.STOP), expect_exception=EOFException.UNREACHABLE_INSTRUCTIONS, ) @pytest.mark.parametrize("stack_height_spread", [-1, 0, 1, 2]) def test_rjump_into_self( eof_test: EOFTestFiller, stack_height_spread: int, ) -> None: """EOF code containing RJUMP with target self RJUMP.""" # Create variadic stack height by the parametrized spread. stack_spread_code = Bytecode() if stack_height_spread >= 0: stack_spread_code = Op.RJUMPI[stack_height_spread](0) + Op.PUSH0 * stack_height_spread eof_test( container=Container.Code(stack_spread_code + Op.RJUMP[-len(Op.RJUMP[0])]), ) def test_rjump_into_self_pre_code( eof_test: EOFTestFiller, ) -> None: """ EOF code containing RJUMP with target self RJUMP with non-zero stack before RJUMP. """ eof_test( container=Container.Code(Op.PUSH1[0] + Op.RJUMP[-len(Op.RJUMP[0])]), ) @pytest.mark.parametrize( "container", [ Container( name="forwards_rjump_0", sections=[ Section.Code( code=Op.RJUMP[0] + Op.STOP, max_stack_increase=0, ), ], expected_bytecode="ef00010100040200010004ff00000000800000e0000000", ), Container( name="forwards_rjump_1", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[3] + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000bff000000008000025f6000e10003e000011900", ), Container( name="forwards_rjump_2", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[8] + Op.PUSH1[0] + Op.RJUMPI[6] + Op.RJUMP[4] + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef00010100040200010013ff000000008000025f6000e100086000e10006e00004e000011900", ), Container( name="forwards_rjump_3", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[3] + Op.RJUMP[1] + Op.PUSH0 + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef0001010004020001000bff000000008000025f6000e10003e000015f00", ), Container( name="forwards_rjump_4", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[8] + Op.PUSH1[0] + Op.RJUMPI[7] + Op.RJUMP[5] + Op.PUSH0 + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=2, ), ], expected_bytecode="ef00010100040200010014ff000000008000025f6000e100086000e10007e000055fe000011900", ), Container( name="forwards_rjump_variable_stack_0", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.RJUMP[0] + Op.STOP, max_stack_increase=3, ), ], expected_bytecode="ef0001010004020001000cff000000008000035f6000e100025f5fe0000000", ), Container( name="forwards_rjump_variable_stack_1", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[3] + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010013ff000000008000055f6000e100025f5f5f6000e10003e000011900", ), Container( name="forwards_rjump_variable_stack_2", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[8] + Op.PUSH1[0] + Op.RJUMPI[6] + Op.RJUMP[4] + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef0001010004020001001bff000000008000055f6000e100025f5f5f6000e100086000e10006e00004e000011900", ), Container( name="forwards_rjump_variable_stack_3", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[3] + Op.RJUMP[1] + Op.PUSH0 + Op.STOP, max_stack_increase=5, ), ], expected_bytecode="ef00010100040200010013ff000000008000055f6000e100025f5f5f6000e10003e000015f00", ), Container( name="forwards_rjump_variable_stack_4", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[8] + Op.PUSH1[0] + Op.RJUMPI[7] + Op.RJUMP[5] + Op.PUSH0 + Op.RJUMP[1] + Op.NOT + Op.STOP, max_stack_increase=4, ), ], expected_bytecode="ef0001010004020001001bff000000008000045f6000e100025f5f6000e100086000e10007e000055fe000011900", ), ], ids=lambda x: x.name, ) def test_rjump_valid_forward( eof_test: EOFTestFiller, container: Container, ) -> None: """ Validate a valid code section containing at least one forward RJUMP. These tests exercise the stack height validation. """ eof_test(container=container) @pytest.mark.parametrize( "container", [ Container( name="backwards_rjump_1", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.RJUMP[-5], max_stack_increase=1, ), ], expected_bytecode="ef00010100040200010005ff000000008000015f50e0fffb", ), Container( name="backwards_rjump_2", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.PUSH1[1] + Op.RJUMPI[3] + Op.RJUMP[-8] + Op.RJUMP[-11], max_stack_increase=1, ), ], expected_bytecode="ef0001010004020001000dff000000008000015f506001e10003e0fff8e0fff5", ), Container( name="backwards_rjump_variable_stack_0", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.RJUMP[-3], max_stack_increase=3, ), ], expected_bytecode="ef0001010004020001000bff000000008000035f6000e100025f5fe0fffd", ), Container( name="backwards_rjump_variable_stack_1", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.RJUMP[-5], max_stack_increase=4, ), ], expected_bytecode="ef0001010004020001000dff000000008000045f6000e100025f5f5f50e0fffb", ), Container( name="backwards_rjump_variable_stack_2", sections=[ Section.Code( code=( Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.PUSH1[1] + Op.RJUMPI[3] + Op.RJUMP[-8] + Op.RJUMP[-11] ), max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010015ff000000008000045f6000e100025f5f5f506001e10003e0fff8e0fff5", ), ], ids=lambda x: x.name, ) def test_rjump_valid_backward( eof_test: EOFTestFiller, container: Container, ) -> None: """ Validate a valid code section containing at least one backward RJUMP. These tests exercise the stack height validation. """ eof_test(container=container) def test_rjump_into_stack_height_diff( eof_test: EOFTestFiller, ) -> None: """ EOF code containing RJUMP with target instruction that causes stack height difference. """ eof_test( container=Container.Code(Op.PUSH1[0] + Op.RJUMP[-(len(Op.RJUMP[0]) + len(Op.PUSH1[0]))]), expect_exception=EOFException.STACK_HEIGHT_MISMATCH, ) def test_rjump_into_stack_height_diff_2( eof_test: EOFTestFiller, ) -> None: """ EOF code containing RJUMP with target instruction that cause stack height difference. """ eof_test( container=Container.Code( Op.PUSH1[0] + Op.POP + Op.RJUMP[-(len(Op.RJUMP[0]) + len(Op.POP))] ), expect_exception=EOFException.STACK_HEIGHT_MISMATCH, ) @pytest.mark.parametrize( "container", [ Container( name="backwards_rjump_3", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.PUSH1[1] + Op.RJUMPI[3] + Op.RJUMP[-8] + Op.PUSH0 + Op.RJUMP[-12], max_stack_increase=1, ), ], expected_bytecode="ef0001010004020001000eff000000008000015f506001e10003e0fff85fe0fff4", ), Container( name="backwards_rjump_4", sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMP[-4], max_stack_increase=1, ), ], expected_bytecode="ef00010100040200010004ff000000008000015fe0fffc", ), Container( name="backwards_rjump_5", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.RJUMP[-4], max_stack_increase=1, ), ], expected_bytecode="ef00010100040200010005ff000000008000015f50e0fffc", ), Container( name="backwards_rjump_8", sections=[ Section.Code( code=Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.PUSH0 + Op.RJUMP[-11], max_stack_increase=1, ), ], expected_bytecode="ef0001010004020001000bff000000008000015f506000e1fff95fe0fff5", ), Container( name="backwards_rjump_variable_stack_3", sections=[ Section.Code( code=( Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.PUSH1[1] + Op.RJUMPI[3] + Op.RJUMP[-8] + Op.PUSH0 + Op.RJUMP[-12] ), max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010016ff000000008000045f6000e100025f5f5f506001e10003e0fff85fe0fff4", ), Container( name="backwards_rjump_variable_stack_4", sections=[ Section.Code( code=( Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.PUSH0 + Op.RJUMP[-7] ), max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010011ff000000008000045f6000e100025f5f6000e100015fe0fff9", ), Container( name="backwards_rjump_variable_stack_5", sections=[ Section.Code( code=( Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.POP + Op.RJUMP[-7] ), max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010011ff000000008000045f6000e100025f5f6000e1000150e0fff9", ), Container( name="backwards_rjump_variable_stack_6", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.RJUMP[-4], max_stack_increase=4, ), ], expected_bytecode="ef0001010004020001000cff000000008000045f6000e100025f5f5fe0fffc", ), Container( name="backwards_rjump_variable_stack_7", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.RJUMP[-4], max_stack_increase=3, ), ], expected_bytecode="ef0001010004020001000dff000000008000035f6000e100025f5f5f50e0fffc", ), Container( name="backwards_rjump_variable_stack_8", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.POP + Op.PUSH1[0] + Op.RJUMPI[-7] + Op.PUSH0 + Op.RJUMP[-11], max_stack_increase=4, ), ], expected_bytecode="ef00010100040200010013ff000000008000045f6000e100025f5f5f506000e1fff95fe0fff5", ), ], ids=lambda x: x.name, ) def test_rjump_backward_invalid_max_stack_height( eof_test: EOFTestFiller, container: Container, ) -> None: """ Validate a code section containing at least one backward RJUMP invalid because of the incorrect max stack height. """ eof_test(container=container, expect_exception=EOFException.STACK_HEIGHT_MISMATCH) def test_rjump_into_stack_underflow( eof_test: EOFTestFiller, ) -> None: """ EOF code containing RJUMP with target instruction that cause stack underflow. """ eof_test( container=Container.Code( Op.ORIGIN + Op.RJUMPI[len(Op.RJUMP[0])] + Op.RJUMP[len(Op.STOP)] + Op.STOP + Op.POP + Op.STOP ), expect_exception=EOFException.STACK_UNDERFLOW, ) def test_rjump_into_rjump( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0009 (Invalid) EOF code containing RJUMP with target other RJUMP immediate. """ eof_test( container=Container.Code(Op.RJUMP[1] + Op.RJUMP[0]), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_rjumpi( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0010 (Invalid) EOF code containing RJUMP with target RJUMPI immediate. """ eof_test( container=Container.Code(Op.RJUMP[5] + Op.STOP + Op.PUSH1[1] + Op.RJUMPI[-6] + Op.STOP), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize("jump", [JumpDirection.FORWARD, JumpDirection.BACKWARD]) def test_rjump_into_push_1(eof_test: EOFTestFiller, jump: JumpDirection) -> None: """ EOF1I4200_0011 (Invalid) EOF code containing RJUMP with target PUSH1 immediate. """ code = ( Op.PUSH1[1] + Op.RJUMP[-4] if jump == JumpDirection.BACKWARD else Op.RJUMP[1] + Op.PUSH1[1] ) + Op.STOP eof_test( container=Container.Code(code), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "opcode", [ Op.PUSH2, Op.PUSH3, Op.PUSH4, Op.PUSH5, Op.PUSH6, Op.PUSH7, Op.PUSH8, Op.PUSH9, Op.PUSH10, Op.PUSH11, Op.PUSH12, Op.PUSH13, Op.PUSH14, Op.PUSH15, Op.PUSH16, Op.PUSH17, Op.PUSH18, Op.PUSH19, Op.PUSH20, Op.PUSH21, Op.PUSH22, Op.PUSH23, Op.PUSH24, Op.PUSH25, Op.PUSH26, Op.PUSH27, Op.PUSH28, Op.PUSH29, Op.PUSH30, Op.PUSH31, Op.PUSH32, ], ) @pytest.mark.parametrize("jump", [JumpDirection.FORWARD, JumpDirection.BACKWARD]) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjump_into_push_n( eof_test: EOFTestFiller, opcode: Op, jump: JumpDirection, data_portion_end: bool, ) -> None: """ EOF1I4200_0011 (Invalid) EOF code containing RJUMP with target PUSH2+ immediate. """ data_portion_length = int.from_bytes(opcode, byteorder="big") - 0x5F if jump == JumpDirection.FORWARD: offset = data_portion_length if data_portion_end else 1 code = Op.RJUMP[offset] + opcode[0] + Op.STOP else: offset = -4 if data_portion_end else -4 - data_portion_length + 1 code = opcode[0] + Op.RJUMP[offset] eof_test( container=Container.Code(code), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize("target_rjumpv_table_size", [1, 256]) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjump_into_rjumpv( eof_test: EOFTestFiller, target_rjumpv_table_size: int, data_portion_end: bool, ) -> None: """ EOF1I4200_0012 (Invalid) EOF code containing RJUMP with target RJUMPV immediate. """ invalid_destination = 4 + (2 * target_rjumpv_table_size) if data_portion_end else 4 target_jump_table = [0 for _ in range(target_rjumpv_table_size)] eof_test( container=Container.Code( Op.RJUMP[invalid_destination] + Op.STOP + Op.PUSH1[1] + Op.RJUMPV[target_jump_table] + Op.STOP, ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjump_into_callf( eof_test: EOFTestFiller, data_portion_end: bool, ) -> None: """ EOF1I4200_0013 (Invalid) EOF code containing RJUMP with target CALLF immediate. """ invalid_destination = 2 if data_portion_end else 1 eof_test( container=Container( sections=[ Section.Code( code=Op.RJUMP[invalid_destination] + Op.CALLF[1] + Op.STOP, ), Section.Code( code=Op.SSTORE(1, 1) + Op.RETF, code_outputs=0, ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_dupn( eof_test: EOFTestFiller, ) -> None: """EOF code containing RJUMP with target DUPN immediate.""" eof_test( container=Container.Code( Op.PUSH1[1] + Op.PUSH1[1] + Op.RJUMP[1] + Op.DUPN[1] + Op.SSTORE + Op.STOP, ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_swapn( eof_test: EOFTestFiller, ) -> None: """EOF code containing RJUMP with target SWAPN immediate.""" eof_test( container=Container.Code( Op.PUSH1[1] + Op.PUSH1[1] + Op.RJUMP[1] + Op.SWAPN[1] + Op.SSTORE + Op.STOP, ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_exchange( eof_test: EOFTestFiller, ) -> None: """EOF code containing RJUMP with target EXCHANGE immediate.""" eof_test( container=Container.Code( Op.PUSH1[1] + Op.PUSH1[2] + Op.PUSH1[3] + Op.RJUMP[1] + Op.EXCHANGE[0x00] + Op.SSTORE + Op.STOP, ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_eofcreate( eof_test: EOFTestFiller, ) -> None: """EOF code containing RJUMP with target EOFCREATE immediate.""" eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 4 + Op.RJUMP[1] + Op.EOFCREATE[0] + Op.STOP, ), Section.Container( container=Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container( container=Container.Code(code=Op.STOP), ), ] ) ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjump_into_returncode( eof_test: EOFTestFiller, ) -> None: """EOF code containing RJUMP with target RETURNCODE immediate.""" eof_test( container=Container( sections=[ Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP, ), Section.Container( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 2 + Op.RJUMP[1] + Op.RETURNCODE[0], ), Section.Container( container=Container.Code(code=Op.STOP), ), ] ) ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "unreachable_op", [Op.STOP, Op.PUSH1[0], Op.PUSH2[0], Op.RJUMP[-3], Op.RJUMP[0], Op.INVALID], ) @pytest.mark.parametrize( "terminating_op", [Op.STOP, Op.RJUMP[-3], Op.INVALID], ) def test_rjump_unreachable_code( eof_test: EOFTestFiller, unreachable_op: Op, terminating_op: Op, ) -> None:
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
true
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/test_rjumpv.py
tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/test_rjumpv.py
"""EOF JUMPF tests covering stack and code validation rules.""" import pytest from ethereum_test_tools import Account, EOFException, EOFStateTestFiller, EOFTestFiller from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import JumpDirection, slot_code_worked, slot_conditional_result, value_code_worked REFERENCE_SPEC_GIT_PATH = "EIPS/eip-4200.md" REFERENCE_SPEC_VERSION = "17d4a8d12d2b5e0f2985c866376c16c8c6df7cba" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) RJUMP_LEN = len(Op.RJUMP[0]) @pytest.mark.parametrize( "calldata", [ pytest.param(0, id="c0"), pytest.param(1, id="c1"), pytest.param(3, id="c3"), pytest.param(255, id="c255"), pytest.param(256, id="c256"), pytest.param(2**256 - 1, id="c2^256-1"), ], ) @pytest.mark.parametrize( "table_size", [ pytest.param(1, id="t1"), pytest.param(3, id="t3"), pytest.param(256, id="t256"), ], ) def test_rjumpv_condition( eof_state_test: EOFStateTestFiller, calldata: int, table_size: int, ) -> None: """Test RJUMPV contract switching based on external input.""" value_fall_through = 0xFFFF value_base = 0x1000 # Force a `PUSH2` instruction to be used on all targets target_length = 7 jump_table = [(i + 1) * target_length for i in range(table_size)] jump_targets = sum( (Op.SSTORE(slot_conditional_result, i + value_base) + Op.STOP) for i in range(table_size) ) fall_through_case = Op.SSTORE(slot_conditional_result, value_fall_through) + Op.STOP eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.CALLDATALOAD + Op.RJUMPV[jump_table] + fall_through_case + jump_targets, ) ] ), data=calldata.to_bytes(32, "big"), container_post=Account( storage={ slot_conditional_result: calldata + value_base if calldata < table_size else value_fall_through, } ), ) def test_rjumpv_forwards( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0008 (Valid) EOF with RJUMPV table size 1 (Positive).""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.RJUMPV[3] + Op.NOOP + Op.NOOP + Op.STOP + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpv_backwards( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0009 (Valid) EOF with RJUMPV table size 1 (Negative).""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.RJUMPI[7] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP + Op.PUSH1(0) + Op.RJUMPV[-13] + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpv_backwards_onto_dup( eof_test: EOFTestFiller, ) -> None: """Backwards jumpv vector onto a dup.""" container = Container.Code( code=(Op.PUSH0 + Op.DUP1 + Op.RJUMPV[-5] + Op.STOP), max_stack_increase=2, ) eof_test( container=container, ) @pytest.mark.parametrize("length", [8, 9]) def test_rjumpv_backwards_large_table( eof_test: EOFTestFiller, length: int, ) -> None: """Backwards jump vector with a large table.""" jump_table = [0] * length jump_table += [length * -2 - 6] container = Container.Code( code=(Op.RJUMPV[jump_table](length) + Op.STOP), max_stack_increase=1, ) eof_test( container=container, ) def test_rjumpv_zero( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0010 (Valid) EOF with RJUMPV table size 1 (Zero).""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.RJUMPV[0] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpv_size_3( eof_state_test: EOFStateTestFiller, ) -> None: """EOF1V4200_0011 (Valid) EOF with RJUMPV table size 3.""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.RJUMPV[3, 0, -10] + Op.NOOP + Op.NOOP + Op.STOP + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) @pytest.mark.parametrize( "target", [0, 1, 100, 254, 255, 256], ) def test_rjumpv_full_table( eof_state_test: EOFStateTestFiller, target: int, ) -> None: """ EOF1V4200_0012/13/14/15 (Valid) EOF with RJUMPV table size 256 (target parameterized). """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH2[target] + Op.RJUMPV[range(256)] + Op.NOOP * 256 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpv_max_forwards( eof_state_test: EOFStateTestFiller, ) -> None: """ EOF1V4200_0016 (Valid) EOF with RJUMPV containing the maximum offset (32767). """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[32767] + Op.NOOP * 32768 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_rjumpv_truncated_empty( eof_test: EOFTestFiller, ) -> None: """ EOF1I4200_0027 (Invalid) EOF code containing RJUMPV with max_index 0 but no immediates. """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV, ) ], ), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) @pytest.mark.parametrize( "branches", [1, 2, 256], ) @pytest.mark.parametrize( "byte_count_last_branch", [0, 1], ) def test_rjumpv_truncated( eof_test: EOFTestFiller, branches: int, byte_count_last_branch: int, ) -> None: """EOF1I4200_0028/29/30 (Invalid) EOF code containing truncated RJUMPV.""" rjumpv_bytes = int.to_bytes(branches - 1, 1, "big") rjumpv_bytes += b"\0" * ((2 * (branches - 1)) + byte_count_last_branch) eof_test( container=Container.Code(code=Op.PUSH1(1) + Op.RJUMPV[rjumpv_bytes]), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_header( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """ EOF1I4200_0031 (Invalid) EOF code containing RJUMPV with target outside code bounds (Jumping into header). """ invalid_destination = -5 - (2 * table_size) jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize("offset", [-13, -23]) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_before_container( eof_test: EOFTestFiller, table_size: int, invalid_index: int, offset: int, ) -> None: """ EOF1I4200_0032 (Invalid) EOF code containing RJUMPV with target outside code bounds (Jumping to before code begin). """ invalid_destination = offset - (2 * table_size) jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_data( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """ EOF1I4200_0033 (Invalid) EOF code containing RJUMPV with target outside code bounds (Jumping into data section). """ invalid_destination = 2 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP, ), Section.Data(data=b"\xaa\xbb\xcc"), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_after_container( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """ EOF1I4200_0034 (Invalid) EOF code containing RJUMPV with target outside code bounds (Jumping to after code end). """ invalid_destination = 2 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_at_end( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """ EOF1I4200_0035 (Invalid) EOF code containing RJUMPV with target outside code bounds (Jumping to code end). """ invalid_destination = 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjumpv_into_self_data_portion( eof_test: EOFTestFiller, table_size: int, invalid_index: int, data_portion_end: bool, ) -> None: """ EOF1I4200_0036 (Invalid) EOF code containing RJUMPV with target same RJUMPV immediate. """ invalid_destination = -1 if data_portion_end else -(2 * table_size) - 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) @pytest.mark.parametrize("stack_height_spread", [-1, 0, 1, 2]) def test_rjumpv_into_self( eof_test: EOFTestFiller, table_size: int, invalid_index: int, stack_height_spread: int, ) -> None: """ EOF code containing RJUMPV targeting itself. This can never be valid because this is backward jump and RJUMPV consumes one stack item. """ # Create variadic stack height by the parametrized spread. stack_spread_code = Bytecode() if stack_height_spread >= 0: stack_spread_code = Op.RJUMPI[stack_height_spread](0) + Op.PUSH0 * stack_height_spread jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = -len(Op.RJUMPV[jump_table]) eof_test( container=Container( sections=[ Section.Code( code=stack_spread_code + Op.RJUMPV[jump_table](0) + Op.STOP, # max stack increase is computed correctly ) ], ), expect_exception=EOFException.STACK_HEIGHT_MISMATCH, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_stack_height_diff( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """ EOF code containing RJUMPV with target instruction that causes stack height difference. """ jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = -(len(Op.RJUMPV[jump_table]) + len(Op.PUSH1[0]) + len(Op.PUSH1[0])) eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1[0] + Op.PUSH1[0] + Op.RJUMPV[jump_table] + Op.STOP, ), ], ), expect_exception=EOFException.STACK_HEIGHT_MISMATCH, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_stack_underflow( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """ EOF code containing RJUMPV with target instruction that cause stack underflow. """ jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = 1 eof_test( container=Container( sections=[ Section.Code(code=Op.ORIGIN + Op.RJUMPV[jump_table] + Op.STOP + Op.POP + Op.STOP), ], ), expect_exception=EOFException.STACK_UNDERFLOW, ) @pytest.mark.parametrize( "table_size", [ pytest.param(1, id="t1"), pytest.param(256, id="t256"), ], ) def test_rjumpv_skips_stack_underflow( eof_test: EOFTestFiller, table_size: int, ) -> None: """ EOF code containing RJUMPV where the default path produces a stack underflow. """ jump_table = [1 for _ in range(table_size)] eof_test( container=Container( sections=[ Section.Code(code=Op.ORIGIN + Op.RJUMPV[jump_table] + Op.POP + Op.STOP), ], ), expect_exception=EOFException.STACK_UNDERFLOW, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjumpv_into_rjump( eof_test: EOFTestFiller, table_size: int, invalid_index: int, data_portion_end: bool, ) -> None: """ EOF1I4200_0037 (Invalid) EOF code containing RJUMPV with target RJUMP immediate. """ invalid_destination = 3 if data_portion_end else 2 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination if table_size > 1: valid_index = 0 if valid_index == invalid_index: valid_index += 1 jump_table[valid_index] = 1 eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP + Op.RJUMP[0] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjumpv_into_rjumpi( eof_test: EOFTestFiller, table_size: int, invalid_index: int, data_portion_end: bool, ) -> None: """ EOF1I4200_0038 (Invalid) EOF code containing RJUMPV with target RJUMPI immediate. """ invalid_destination = 5 if data_portion_end else 4 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination if table_size > 1: valid_index = 0 if valid_index == invalid_index: valid_index += 1 jump_table[valid_index] = 1 eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP + Op.PUSH1(1) + Op.RJUMPI[0] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) @pytest.mark.parametrize("jump", [JumpDirection.FORWARD, JumpDirection.BACKWARD]) def test_rjumpv_into_push_1( eof_test: EOFTestFiller, jump: JumpDirection, table_size: int, invalid_index: int, ) -> None: """ EOF1I4200_0039 (Invalid) EOF code containing RJUMPV with target PUSH1 immediate. """ if jump == JumpDirection.FORWARD: invalid_destination = 2 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination code = ( Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP + Op.PUSH1(1) + Op.PUSH1(1) + Op.SSTORE + Op.STOP ) else: invalid_destination = -(2 * table_size) - 3 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination code = Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP eof_test( container=Container( sections=[Section.Code(code=code)], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "opcode", [ Op.PUSH2, Op.PUSH3, Op.PUSH4, Op.PUSH5, Op.PUSH6, Op.PUSH7, Op.PUSH8, Op.PUSH9, Op.PUSH10, Op.PUSH11, Op.PUSH12, Op.PUSH13, Op.PUSH14, Op.PUSH15, Op.PUSH16, Op.PUSH17, Op.PUSH18, Op.PUSH19, Op.PUSH20, Op.PUSH21, Op.PUSH22, Op.PUSH23, Op.PUSH24, Op.PUSH25, Op.PUSH26, Op.PUSH27, Op.PUSH28, Op.PUSH29, Op.PUSH30, Op.PUSH31, Op.PUSH32, ], ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) @pytest.mark.parametrize("jump", [JumpDirection.FORWARD, JumpDirection.BACKWARD]) def test_rjumpv_into_push_n( eof_test: EOFTestFiller, opcode: Op, jump: JumpDirection, table_size: int, invalid_index: int, data_portion_end: bool, ) -> None: """ EOF1I4200_0039 (Invalid) EOF code containing RJUMPV with target PUSHN immediate. """ data_portion_length = int.from_bytes(opcode, byteorder="big") - 0x5F if jump == JumpDirection.FORWARD: invalid_destination = data_portion_length + 1 if data_portion_end else 2 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination code = ( Op.PUSH1(1) + Op.RJUMPV[jump_table] + Op.STOP + opcode[1] + Op.PUSH1(1) + Op.SSTORE + Op.STOP ) else: invalid_destination = ( -(2 * table_size) - 3 if data_portion_end else -(2 * table_size) - 2 - data_portion_length ) jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination code = opcode[1] + Op.RJUMPV[jump_table] + Op.STOP eof_test( container=Container( sections=[Section.Code(code=code)], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "source_table_size,invalid_index", [ pytest.param(1, 0, id="s1i0"), pytest.param(256, 0, id="s256i0"), pytest.param(256, 255, id="s256i255"), ], ) @pytest.mark.parametrize("target_table_size", [1, 256], ids=["t1", "t256"]) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjumpv_into_rjumpv( eof_test: EOFTestFiller, source_table_size: int, target_table_size: int, invalid_index: int, data_portion_end: bool, ) -> None: """ EOF1I4200_0040 (Invalid) EOF code containing RJUMPV with target other RJUMPV immediate. """ invalid_destination = 4 + (2 * target_table_size) if data_portion_end else 4 source_jump_table = [0 for _ in range(source_table_size)] source_jump_table[invalid_index] = invalid_destination target_jump_table = [0 for _ in range(target_table_size)] eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.RJUMPV[source_jump_table] + Op.STOP + Op.PUSH1(1) + Op.RJUMPV[target_jump_table] + Op.STOP, ) ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) @pytest.mark.parametrize( "data_portion_end", [True, False], ids=["data_portion_end", "data_portion_start"], ) def test_rjumpv_into_callf( eof_test: EOFTestFiller, table_size: int, invalid_index: int, data_portion_end: bool, ) -> None: """ EOF1I4200_0041 (Invalid) EOF code containing RJUMPV with target CALLF immediate. """ invalid_destination = 2 if data_portion_end else 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.RJUMPV[jump_table] + Op.CALLF[1] + Op.STOP, ), Section.Code( code=Op.SSTORE(1, 1) + Op.RETF, code_outputs=0, ), ] ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_dupn( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """EOF code containing RJUMPV with target DUPN immediate.""" invalid_destination = 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.PUSH1(1) + Op.PUSH1(0) + Op.RJUMPV[jump_table] + Op.DUPN[1] + Op.SSTORE + Op.STOP, ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_swapn( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """EOF code containing RJUMPV with target SWAPN immediate.""" invalid_destination = 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.PUSH1(1) + Op.PUSH1(0) + Op.RJUMPV[jump_table] + Op.SWAPN[1] + Op.SSTORE + Op.STOP, ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_exchange( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """EOF code containing RJUMPV with target EXCHANGE immediate.""" invalid_destination = 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(1) + Op.PUSH1(2) + Op.PUSH1(3) + Op.PUSH1(0) + Op.RJUMPV[jump_table] + Op.EXCHANGE[0x00] + Op.SSTORE + Op.STOP, ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_eofcreate( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """EOF code containing RJUMPV with target EOFCREATE immediate.""" invalid_destination = 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 5 + Op.RJUMPV[jump_table] + Op.EOFCREATE[0] + Op.STOP, ), Section.Container( container=Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container( container=Container.Code(Op.STOP), ), ] ) ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) @pytest.mark.parametrize( "table_size,invalid_index", [ pytest.param(1, 0, id="t1i0"), pytest.param(256, 0, id="t256i0"), pytest.param(256, 255, id="t256i255"), ], ) def test_rjumpv_into_returncode( eof_test: EOFTestFiller, table_size: int, invalid_index: int, ) -> None: """EOF code containing RJUMPV with target RETURNCODE immediate.""" invalid_destination = 1 jump_table = [0 for _ in range(table_size)] jump_table[invalid_index] = invalid_destination eof_test( container=Container( sections=[ Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP, ), Section.Container( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 3 + Op.RJUMPV[jump_table] + Op.RETURNCODE[0], ), Section.Container( container=Container.Code(Op.STOP), ), ] ) ), ], ), expect_exception=EOFException.INVALID_RJUMP_DESTINATION, ) def test_rjumpv_backwards_reference_only( eof_test: EOFTestFiller, ) -> None: """EOF code containing instructions only reachable by backwards RJUMPV.""" rjumpv_len = len(Op.RJUMPV[0]) container = Container.Code( code=( Op.RJUMP[RJUMP_LEN] + Op.RJUMP[rjumpv_len + len(Op.ORIGIN)] + Op.ORIGIN + Op.RJUMPV[-(RJUMP_LEN + rjumpv_len + len(Op.ORIGIN))] + Op.STOP ) ) eof_test( container=container, expect_exception=EOFException.UNREACHABLE_INSTRUCTIONS, ) def test_rjumpv_at_the_end( eof_test: EOFTestFiller, ) -> None: """ https://github.com/ipsilon/eof/blob/main/spec/eof.md#stack-validation 4.i: This implies that the last instruction may be a terminating instruction or RJUMPV. """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH1(0) + Op.PUSH1(0) + Op.RJUMPI[1] + Op.STOP + Op.RJUMPV[-7](1), ) ], ), expect_exception=EOFException.MISSING_STOP_OPCODE, ) def test_rjumpv_backwards_min_stack_wrong( eof_test: EOFTestFiller, ) -> None: """Backwards rjumpv where min_stack does not match.""" container = Container.Code( code=( Op.PUSH0 # (0, 0) + Op.PUSH1(0) # (1, 1) + Op.RJUMPV[1] # (2, 2) To PUSH1 + Op.PUSH0 # (1, 1)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
true
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/__init__.py
tests/unscheduled/eip7692_eof_v1/eip4200_relative_jumps/__init__.py
""" Test cases for [EIP-4200: EOF - Static relative jumps](https://eips.ethereum.org/EIPS/eip-4200). EIP-4200 replaces dynamic jump instructions with relative jump offsets for improved control flow predictability. Opcodes introduced: `RJUMP` (`0xE0`), `RJUMPI` (`0xE1`), `RJUMPV` (`0xE2`). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip5450_stack/test_code_validation.py
tests/unscheduled/eip7692_eof_v1/eip5450_stack/test_code_validation.py
""" Code validation of CALLF, JUMPF, RETF opcodes in conjunction with static relative jumps. """ import itertools from enum import Enum, auto, unique from typing import Generator, Tuple, Union import pytest from ethereum_test_exceptions.exceptions import EOFException from ethereum_test_tools import Account, EOFStateTestFiller, EOFTestFiller from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_STACK_INCREASE_LIMIT, NON_RETURNING_SECTION from ethereum_test_vm import Bytecode, Opcode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from ..eip3540_eof_v1.test_all_opcodes_in_container import valid_eof_opcodes from ..eip7620_eof_create.helpers import ( smallest_initcode_subcontainer, smallest_runtime_subcontainer, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-5450.md" REFERENCE_SPEC_VERSION = "f20b164b00ae5553f7536a6d7a83a0f254455e09" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @unique class RjumpKind(Enum): """Kinds of RJUMP* instruction snippets to generate.""" EMPTY_RJUMP = auto() EMPTY_RJUMPI = auto() RJUMPI_OVER_PUSH = auto() RJUMPI_OVER_NOOP = auto() RJUMPI_OVER_STOP = auto() RJUMPI_OVER_PUSH_POP = auto() RJUMPI_OVER_POP = auto() RJUMPI_OVER_NEXT = auto() RJUMPI_OVER_NEXT_NESTED = auto() RJUMPI_TO_START = auto() RJUMPV_EMPTY_AND_OVER_NEXT = auto() RJUMPV_OVER_PUSH_AND_TO_START = auto() RJUMPI_OVER_RETF = auto() def __str__(self) -> str: """Return string representation of the enum.""" return f"{self.name}" @unique class RjumpSpot(Enum): """ Possible spots in the code section layout where the RJUMP* is injected. """ BEGINNING = auto() BEFORE_TERMINATION = auto() def __str__(self) -> str: """Return string representation of the enum.""" return f"{self.name}" def rjump_code_with( rjump_kind: RjumpKind | None, code_so_far_len: int, next_code: Bytecode ) -> Tuple[Bytecode, bool, bool, bool]: """ Unless `rjump_kind` is None generates a code snippet with an RJUMP* instruction. For some kinds `code_so_far_len` must be code length in bytes preceding the snippet. For some kinds `next_code_len` must be code length in bytes of some code which follows. It is expected that the snippet and the jump target are valid, but the resulting code or its stack balance might not. Also returns some traits of the snippet: `is_backwards`, `pops` and `pushes` """ body = Bytecode() is_backwards = False pops = False pushes = False jumps_over_next = False if rjump_kind == RjumpKind.EMPTY_RJUMP: body = Op.RJUMP[0] elif rjump_kind == RjumpKind.EMPTY_RJUMPI: body = Op.RJUMPI[0](0) elif rjump_kind == RjumpKind.RJUMPI_OVER_PUSH: body = Op.RJUMPI[1](0) + Op.PUSH0 pushes = True elif rjump_kind == RjumpKind.RJUMPI_OVER_NOOP: body = Op.RJUMPI[1](0) + Op.NOOP elif rjump_kind == RjumpKind.RJUMPI_OVER_STOP: body = Op.RJUMPI[1](0) + Op.STOP elif rjump_kind == RjumpKind.RJUMPI_OVER_PUSH_POP: body = Op.RJUMPI[2](0) + Op.PUSH0 + Op.POP elif rjump_kind == RjumpKind.RJUMPI_OVER_POP: body = Op.RJUMPI[1](0) + Op.POP pops = True elif rjump_kind == RjumpKind.RJUMPI_OVER_NEXT: body = Op.RJUMPI[len(next_code)](0) jumps_over_next = True elif rjump_kind == RjumpKind.RJUMPI_OVER_NEXT_NESTED: rjump_inner = Op.RJUMPI[len(next_code)](0) body = Op.RJUMPI[len(rjump_inner)](0) + rjump_inner jumps_over_next = True elif rjump_kind == RjumpKind.RJUMPI_TO_START: rjumpi_len = len(Op.RJUMPI[0](0)) body = Op.RJUMPI[-code_so_far_len - rjumpi_len](0) is_backwards = True elif rjump_kind == RjumpKind.RJUMPV_EMPTY_AND_OVER_NEXT: body = Op.RJUMPV[[0, len(next_code)]](0) jumps_over_next = True elif rjump_kind == RjumpKind.RJUMPV_OVER_PUSH_AND_TO_START: rjumpv_two_destinations_len = len(Op.RJUMPV[[0, 0]](0)) body = Op.RJUMPV[[1, -code_so_far_len - rjumpv_two_destinations_len]](0) + Op.PUSH0 is_backwards = True pushes = True elif rjump_kind == RjumpKind.RJUMPI_OVER_RETF: body = Op.RJUMPI[1](0) + Op.RETF elif not rjump_kind: pass else: raise TypeError("unknown rjumps value" + str(rjump_kind)) if jumps_over_next: # This is against intuition, but if the code we're jumping over pushes, # the path which misses it will be short of stack items, as if the # RJUMP* popped and vice versa. if next_code.pushed_stack_items > next_code.popped_stack_items: pops = True elif next_code.popped_stack_items > next_code.pushed_stack_items: pushes = True return body, is_backwards, pops, pushes def call_code_with(inputs: int, outputs: int, call: Bytecode) -> Bytecode: """ Generate code snippet with the `call` bytecode provided and its respective input/output management. `inputs` and `outputs` are understood as those of the code section we're generating for. """ body = Bytecode() if call.popped_stack_items > inputs: body += Op.PUSH0 * (call.popped_stack_items - inputs) elif call.popped_stack_items < inputs: body += Op.POP * (inputs - call.popped_stack_items) body += call if call.pushed_stack_items < outputs: body += Op.PUSH0 * (outputs - call.pushed_stack_items) elif call.pushed_stack_items > outputs: body += Op.POP * (call.pushed_stack_items - outputs) return body def section_code_with( inputs: int, outputs: int, rjump_kind: RjumpKind | None, rjump_spot: RjumpSpot, call: Bytecode | None, termination: Bytecode, ) -> Tuple[Bytecode, bool, bool, bool, bool]: """ Generate code section with RJUMP* and CALLF/RETF instructions. Also returns some traits of the section: `has_invalid_back_jump`, `rjump_snippet_pops`, `rjump_snippet_pushes`, `rjump_falls_off_code` """ code = Bytecode() code.pushed_stack_items, code.max_stack_height = (inputs, inputs) if call: body = call_code_with(inputs, outputs, call) else: body = Op.POP * inputs + Op.PUSH0 * outputs has_invalid_back_jump = False rjump_snippet_pushes = False rjump_snippet_pops = False rjump_falls_off_code = False if rjump_spot == RjumpSpot.BEGINNING: rjump, is_backwards, rjump_snippet_pops, rjump_snippet_pushes = rjump_code_with( rjump_kind, 0, body ) if rjump_kind == RjumpKind.RJUMPI_OVER_RETF: if inputs > outputs: rjump_snippet_pushes = True elif outputs > inputs: rjump_snippet_pops = True code += rjump code += body if rjump_spot == RjumpSpot.BEFORE_TERMINATION: rjump, is_backwards, rjump_snippet_pops, rjump_snippet_pushes = rjump_code_with( rjump_kind, len(code), next_code=termination ) code += rjump if is_backwards and inputs != outputs: has_invalid_back_jump = True if rjump_spot == RjumpSpot.BEFORE_TERMINATION or ( rjump_spot == RjumpSpot.BEGINNING and len(termination) == 0 ): if rjump_kind in [ RjumpKind.RJUMPI_OVER_NEXT, RjumpKind.RJUMPI_OVER_NEXT_NESTED, RjumpKind.RJUMPV_EMPTY_AND_OVER_NEXT, ]: # Jump over termination or jump over body, but there is nothing # after the body. rjump_falls_off_code = True code += termination return ( code, has_invalid_back_jump, rjump_snippet_pops, rjump_snippet_pushes, rjump_falls_off_code, ) num_sections = 3 possible_inputs_outputs = range(2) @pytest.mark.parametrize( ["inputs", "outputs"], itertools.product( list(itertools.product(*([possible_inputs_outputs] * (num_sections - 1)))), list(itertools.product(*([possible_inputs_outputs] * (num_sections - 1)))), ), ) @pytest.mark.parametrize( "rjump_kind", RjumpKind, ) # Parameter value fixed for first iteration, to cover the most important case. @pytest.mark.parametrize("rjump_section_idx", [0, 1]) @pytest.mark.parametrize( "rjump_spot", RjumpSpot, ) def test_rjumps_callf_retf( eof_test: EOFTestFiller, inputs: Tuple[int, ...], outputs: Tuple[int, ...], rjump_kind: RjumpKind, rjump_section_idx: int, rjump_spot: RjumpSpot, ) -> None: """ Test EOF container validation for EIP-4200 vs EIP-4750 interactions. Each test's code consists of `num_sections` code sections, which call into one another and then return. Code may include RJUMP* snippets of `rjump_kind` in various `rjump_spots`. """ # Zeroth section has always 0 inputs and 0 outputs, so is excluded from # param inputs = (0,) + inputs outputs = (0,) + outputs assert len(inputs) == len(outputs) == num_sections sections = [] container_has_invalid_back_jump = False container_has_rjump_pops = False container_has_rjump_pushes = False container_has_rjump_off_code = False container_has_section_0_retf = ( rjump_section_idx == 0 and rjump_kind == RjumpKind.RJUMPI_OVER_RETF ) for section_idx in range(num_sections): if section_idx == 0: call = Op.CALLF[section_idx + 1] call.popped_stack_items = inputs[section_idx + 1] call.pushed_stack_items = outputs[section_idx + 1] call.min_stack_height = call.popped_stack_items call.max_stack_height = max(call.popped_stack_items, call.pushed_stack_items) termination = Op.STOP elif section_idx < num_sections - 1: call = Op.CALLF[section_idx + 1] call.popped_stack_items = inputs[section_idx + 1] call.pushed_stack_items = outputs[section_idx + 1] call.min_stack_height = call.popped_stack_items call.max_stack_height = max(call.popped_stack_items, call.pushed_stack_items) termination = Op.RETF else: call = None termination = Op.RETF ( code, section_has_invalid_back_jump, rjump_snippet_pops, rjump_snippet_pushes, rjump_falls_off_code, ) = section_code_with( inputs[section_idx], outputs[section_idx], rjump_kind if rjump_section_idx == section_idx else None, rjump_spot, call, termination, ) if section_has_invalid_back_jump: container_has_invalid_back_jump = True if rjump_snippet_pops: container_has_rjump_pops = True # Pushes to the stack never affect the zeroth section, because it # `STOP`s and not `RETF`s. if rjump_snippet_pushes and section_idx != 0: container_has_rjump_pushes = True if rjump_falls_off_code: container_has_rjump_off_code = True if section_idx > 0: sections.append( Section.Code( code, code_inputs=inputs[section_idx], code_outputs=outputs[section_idx], ) ) else: sections.append(Section.Code(code)) possible_exceptions = [] if container_has_invalid_back_jump: possible_exceptions.append(EOFException.STACK_HEIGHT_MISMATCH) if container_has_rjump_pops: possible_exceptions.append(EOFException.STACK_UNDERFLOW) if container_has_rjump_pushes: possible_exceptions.append(EOFException.STACK_HIGHER_THAN_OUTPUTS) if container_has_rjump_off_code: possible_exceptions.append(EOFException.INVALID_RJUMP_DESTINATION) if container_has_section_0_retf: possible_exceptions.append(EOFException.INVALID_NON_RETURNING_FLAG) eof_test(container=Container(sections=sections), expect_exception=possible_exceptions or None) @pytest.mark.parametrize( "inputs", itertools.product(*([possible_inputs_outputs] * (num_sections - 1))) ) @pytest.mark.parametrize( "rjump_kind", RjumpKind, ) # Parameter value fixed for first iteration, to cover the most important case. @pytest.mark.parametrize("rjump_section_idx", [0, 1]) @pytest.mark.parametrize( "rjump_spot", # `termination` is empty for JUMPF codes, because JUMPF serves as one. Spot # `BEFORE_TERMINATION` is unreachable code. [k for k in RjumpSpot if k not in [RjumpSpot.BEFORE_TERMINATION]], ) def test_rjumps_jumpf_nonreturning( eof_test: EOFTestFiller, inputs: Tuple[int, ...], rjump_kind: RjumpKind, rjump_section_idx: int, rjump_spot: RjumpSpot, ) -> None: """ Test EOF container validation for EIP-4200 vs EIP-6206 interactions on non-returning functions. """ # Zeroth section has always 0 inputs and 0 outputs, so is excluded from # param inputs = (0,) + inputs sections = [] container_has_rjump_pops = False container_has_rjump_off_code = False container_has_non_returning_retf = False for section_idx in range(num_sections): if section_idx < num_sections - 1: call = Op.JUMPF[section_idx + 1] call.popped_stack_items = inputs[section_idx + 1] call.pushed_stack_items = 0 call.min_stack_height = call.popped_stack_items call.max_stack_height = max(call.popped_stack_items, call.pushed_stack_items) termination = Bytecode() else: call = None termination = Op.STOP # `section_has_invalid_back_jump` - never happens: we excluded RJUMP # from the end `rjump_snippet_pushes` - never happens: we never RETF # where too large stack would fail ( code, _section_has_invalid_back_jump, rjump_snippet_pops, _rjump_snippet_pushes, rjump_falls_off_code, ) = section_code_with( inputs[section_idx], 0, rjump_kind if rjump_section_idx == section_idx else None, rjump_spot, call, termination, ) if rjump_snippet_pops: container_has_rjump_pops = True if rjump_falls_off_code: container_has_rjump_off_code = True if rjump_kind == RjumpKind.RJUMPI_OVER_RETF: container_has_non_returning_retf = True if section_idx > 0: sections.append( Section.Code( code, code_inputs=inputs[section_idx], code_outputs=NON_RETURNING_SECTION, ) ) else: sections.append(Section.Code(code)) possible_exceptions = [] if container_has_rjump_pops: possible_exceptions.append(EOFException.STACK_UNDERFLOW) if container_has_rjump_off_code: possible_exceptions.append(EOFException.INVALID_RJUMP_DESTINATION) if container_has_non_returning_retf: possible_exceptions.append(EOFException.INVALID_NON_RETURNING_FLAG) eof_test(container=Container(sections=sections), expect_exception=possible_exceptions or None) def gen_stack_underflow_params() -> Generator[tuple[Union[Op, Opcode], int], None, None]: """Generate parameters for stack underflow tests.""" opcodes = sorted(op for op in valid_eof_opcodes if op.min_stack_height > 0) + [ # Opcodes that have variable min_stack_height Op.SWAPN[0x00], Op.SWAPN[0xFF], Op.DUPN[0x00], Op.DUPN[0xFF], Op.EXCHANGE[0x00], Op.EXCHANGE[0xFF], ] for op in opcodes: yield op, 0 if op.min_stack_height > 1: yield op, op.min_stack_height - 1 @pytest.mark.parametrize("spread", [-1, 0, 1, MAX_STACK_INCREASE_LIMIT]) @pytest.mark.parametrize("op,stack_height", gen_stack_underflow_params()) def test_all_opcodes_stack_underflow( eof_test: EOFTestFiller, op: Op, stack_height: int, spread: int ) -> None: """ Test EOF validation failing due to stack overflow caused by the specific instruction `op`. """ code = Bytecode() if spread >= 0: # Check if the op increases the stack height (e.g. DUP instructions). # We need to leave space for this increase not to cause stack overflow. max_stack_increase = max(op.pushed_stack_items - op.popped_stack_items, 0) # Cap the spread if it would exceed the maximum stack height. spread = min(spread, MAX_STACK_INCREASE_LIMIT - (stack_height + max_stack_increase)) # Create a range stack height of 0-spread. code += Op.RJUMPI[spread](Op.CALLVALUE) + Op.PUSH0 * spread # Create the desired stack height. code += Op.PUSH0 * stack_height if op.has_data_portion(): code += op[0] # produce required imm bytes else: code += op if not op.terminating: code += Op.STOP sections = [ Section.Code( code, # Set reasonable stack height. Don't rely on automatic calculation, # because we are in the invalid stack height scenario. max_stack_height=max(spread, stack_height, int(spread >= 0)), ) ] if op == Op.EOFCREATE: # Make EOFCREATE valid by adding the target subcontainer. sections.append(Section.Container(smallest_initcode_subcontainer)) elif op == Op.RETURNCODE: # Make RETURNCODE valid by wrapping it with a container with EOFCREATE. sections = [ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container( container=Container( sections=[ sections[0], Section.Container(smallest_runtime_subcontainer), ] ) ), ] eof_test( container=Container( sections=sections, validity_error=EOFException.STACK_UNDERFLOW, ) ) @pytest.mark.parametrize( "container", [ Container( name="underflow_0", sections=[ Section.Code( code=Op.ADD + Op.STOP, max_stack_height=1, ), ], ), Container( name="underflow_variable_stack_0", sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 + Op.PUSH0 + Op.LOG2 + Op.STOP, max_stack_height=3, ), ], ), Container( name="underflow_variable_stack_1", sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 + Op.PUSH0 + Op.ADD + Op.STOP, max_stack_height=3, ), ], ), Container( name="underflow_variable_stack_2", sections=[ Section.Code( code=Op.PUSH0 * 2 + Op.RJUMPI[1](0) + Op.POP + Op.ADD + Op.STOP, max_stack_height=3, ), ], ), Container( name="underflow_variable_stack_3", sections=[ Section.Code( Op.RJUMPI[8](0) + Op.PUSH0 * 2 + Op.RJUMPI[1](0) + Op.POP * 2 + Op.PUSH0 * 2 + Op.REVERT, max_stack_height=3, ), ], ), ], ids=lambda x: x.name, ) def test_stack_underflow_examples(eof_test: EOFTestFiller, container: Container) -> None: """ Test EOF validation failing due to stack underflow at basic instructions. """ eof_test(container=container, expect_exception=EOFException.STACK_UNDERFLOW) @pytest.mark.parametrize("initial_stack", [0, 1, 2]) @pytest.mark.parametrize("calldata_1", [0, 1]) @pytest.mark.parametrize("calldata_2", [0, 1]) def test_valid_non_constant_stack_examples( eof_state_test: EOFStateTestFiller, initial_stack: int, calldata_1: int, calldata_2: int ) -> None: """Test valid containers with non constant stack items.""" # Stores the number of added items to the stack in storage slot 0 # calldata_1 == 1: number of items = 2 # calldata_1 == 0: # calldata_2 == 0: number of items: 3 # calldata_2 == 1: number of items: 4 expected_storage = {0: 2} if calldata_1 == 1 else ({0: 3} if calldata_2 == 0 else {0: 4}) data = calldata_1.to_bytes(32, "big") + calldata_2.to_bytes(32, "big") container = Container( sections=[ Section.Code( code=Op.PUSH0 * initial_stack + Op.CALLDATALOAD(0) + Op.RJUMPI[19] + Op.PUSH0 * 2 + Op.SSTORE(0, 2) # Stores added items (2) + Op.CALLDATALOAD(32) + Op.RJUMPI[6] + Op.POP + Op.SSTORE(0, 1) # Updates number of added items to 1 + Op.PUSH0 * 2 # <-- RJUMPI[19]/RJUMPI[6] target + Op.SLOAD(0) + Op.PUSH1(2) + Op.ADD # Add latest added items (+2) + Op.PUSH1(0) + Op.SSTORE + Op.STOP, max_stack_height=6 + initial_stack, ), ], ) eof_state_test( container=container, expect_exception=None, data=data, container_post=Account(storage=expected_storage), ) @pytest.mark.parametrize("num_rjumpi", [MAX_STACK_INCREASE_LIMIT, MAX_STACK_INCREASE_LIMIT + 1]) def test_stack_range_maximally_broad(eof_test: EOFTestFiller, num_rjumpi: int) -> None: """Test stack range 0-1023 at final instruction.""" code = Op.STOP() for i in range(0, num_rjumpi): offset = i * 5 + 1 code = Op.PUSH0 + Op.RJUMPI[offset] + Op.PUSH0 + code container = Container.Code(code=code, max_stack_increase=MAX_STACK_INCREASE_LIMIT) eof_test( container=container, expect_exception=None if num_rjumpi <= MAX_STACK_INCREASE_LIMIT else EOFException.INVALID_MAX_STACK_INCREASE, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip5450_stack/__init__.py
tests/unscheduled/eip7692_eof_v1/eip5450_stack/__init__.py
""" Tests for [EIP-5450: EOF - Stack Validation](https://eips.ethereum.org/EIPS/eip-5450). EIP-5450 defines stack validation requirements to ensure consistent behavior during execution. Opcodes introduced: None (specifies validation rules for stack usage). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip5450_stack/test_execution.py
tests/unscheduled/eip7692_eof_v1/eip5450_stack/test_execution.py
"""Test execution of EOF code in the context of the operand stack height.""" import pytest from ethereum_test_exceptions import EOFException from ethereum_test_tools import Account, EOFStateTestFiller from ethereum_test_types.eof.constants import MAX_RUNTIME_STACK_HEIGHT from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import ( MAX_CODE_INPUTS, MAX_STACK_INCREASE_LIMIT, NON_RETURNING_SECTION, ) from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-5450.md" REFERENCE_SPEC_VERSION = "f20b164b00ae5553f7536a6d7a83a0f254455e09" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize("code_inputs", [0, 1, 16, 127, 128]) @pytest.mark.parametrize("call_op", [Op.CALLF, Op.JUMPF]) def test_execution_at_max_stack_height( eof_state_test: EOFStateTestFiller, code_inputs: int, call_op: Op, ) -> None: """ Test execution at the maximum runtime operand stack height (1024). EOF doesn't allow to increase the stack height of a single code section more than 1023. The effect of the maximum runtime stack height is achieved by using non-zero number of the code section inputs and increasing the runtime stack to the limit accordingly. The test pushes consecutive numbers starting from 0 (including inputs). At the maximum stack height SSTORE is used so it should store 1022 at key 1023. """ max_stack_increase = MAX_RUNTIME_STACK_HEIGHT - code_inputs container = Container( sections=[ Section.Code( ( sum(Op.PUSH1(x) for x in range(code_inputs)) + call_op[1] + (Op.STOP if call_op == Op.CALLF else b"") ), ), Section.Code( sum(Op.PUSH2(x) for x in range(code_inputs, MAX_RUNTIME_STACK_HEIGHT)) + Op.SSTORE + Op.POP * (MAX_RUNTIME_STACK_HEIGHT - Op.SSTORE.popped_stack_items) + (Op.RETF if call_op == Op.CALLF else Op.STOP), code_inputs=code_inputs, code_outputs=0 if call_op == Op.CALLF else NON_RETURNING_SECTION, max_stack_increase=max_stack_increase, ), ], ) exception = None if max_stack_increase > MAX_STACK_INCREASE_LIMIT: exception = EOFException.MAX_STACK_INCREASE_ABOVE_LIMIT elif code_inputs > MAX_CODE_INPUTS: exception = EOFException.INPUTS_OUTPUTS_NUM_ABOVE_LIMIT eof_state_test( container=container, expect_exception=exception, container_post=Account( storage={MAX_RUNTIME_STACK_HEIGHT - 1: MAX_RUNTIME_STACK_HEIGHT - 2} ), )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/spec.py
tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/spec.py
"""EOF V1 Constants used throughout all tests.""" TXCREATE_FAILURE = 0
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_creation_tx.py
tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_creation_tx.py
"""Test bad TXCREATE cases.""" import pytest from ethereum_test_base_types.base_types import Address, Bytes from ethereum_test_tools import ( Account, Alloc, Environment, StateTestFiller, Transaction, ) from ethereum_test_tools import Initcode as LegacyInitcode from ethereum_test_types import TransactionReceipt from ethereum_test_types.eof.v1 import Container from ....prague.eip7702_set_code_tx.spec import Spec from .. import EOF_FORK_NAME from ..eip7620_eof_create.helpers import ( smallest_initcode_subcontainer, smallest_runtime_subcontainer, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7873.md" REFERENCE_SPEC_VERSION = "23d96ceff8f0690432ab91089ae257f08f32340f" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.with_all_contract_creating_tx_types(selector=lambda tx_type: tx_type != 6) @pytest.mark.parametrize( "deploy_code", [ Bytes("0xEF"), Bytes("0xEF00"), Bytes("0xEF0001"), Bytes("0xEF01"), smallest_runtime_subcontainer, smallest_initcode_subcontainer, ], ) def test_legacy_create_tx_legacy_initcode_eof_bytecode( state_test: StateTestFiller, pre: Alloc, tx_type: int, deploy_code: Bytes | Container, ) -> None: """ Test that a legacy contract creation tx cannot create EOF code. This tests only ensures EIP-3541 behavior is kept, not altered by EIP-7873 """ env = Environment() sender = pre.fund_eoa() initcode = LegacyInitcode(deploy_code=deploy_code) tx = Transaction( ty=tx_type, sender=sender, to=None, gas_limit=100000, data=initcode, ) destination_contract_address = tx.created_contract post = { destination_contract_address: Account.NONEXISTENT, } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.with_all_contract_creating_tx_types(selector=lambda tx_type: tx_type != 6) @pytest.mark.parametrize( "initcode", [ Bytes("0xEF"), Bytes("0xEF01"), Bytes("0xEF0101"), Spec.delegation_designation(Address(0xAA)), Bytes("0xEF02"), Bytes("0xEF00"), Bytes("0xEF0001"), smallest_runtime_subcontainer, smallest_initcode_subcontainer, ], ) def test_legacy_create_tx_prefix_initcode( state_test: StateTestFiller, pre: Alloc, tx_type: int, initcode: Bytes, ) -> None: """ Test that a legacy contract creation tx behaves as it did before EIP-7873 for initcode stating with `EF`. The transaction should be valid but fail on executing of the first byte `EF`. """ env = Environment() sender = pre.fund_eoa() gas_limit = 100_000 tx = Transaction( ty=tx_type, sender=sender, to=None, gas_limit=gas_limit, data=initcode, expected_receipt=TransactionReceipt(gas_used=gas_limit), ) destination_contract_address = tx.created_contract post = {destination_contract_address: Account.NONEXISTENT, sender: Account(nonce=1)} state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/__init__.py
tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/__init__.py
""" Test cases for [EIP-7873: TXCREATE and InitcodeTransaction](https://eips.ethereum.org/EIPS/eip-7873). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_txcreate_validates.py
tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_txcreate_validates.py
"""Test bad TXCREATE cases.""" from enum import Enum, auto, unique from typing import Tuple import pytest from ethereum_test_base_types import Bytes from ethereum_test_base_types.base_types import Address, Hash from ethereum_test_base_types.composite_types import AccessList from ethereum_test_tools import ( Account, Alloc, Environment, EVMCodeType, StateTestFiller, Transaction, compute_eofcreate_address, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from ....prague.eip7702_set_code_tx.spec import Spec from .. import EOF_FORK_NAME from ..eip7620_eof_create.helpers import ( slot_a, slot_b, slot_code_worked, smallest_initcode_subcontainer, smallest_runtime_subcontainer, value_code_worked, ) from .spec import TXCREATE_FAILURE REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7873.md" REFERENCE_SPEC_VERSION = "1115fe6110fcc0efc823fb7f8f5cd86c42173efe" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @unique class ValidatedCode(Enum): """Kinds of valid/invalid EOF.""" LEGACY = auto() EF = auto() EOFV1_RUNTIME = auto() EOFV1_RUNTIME_INVALID = auto() EOFV1_INITCODE = auto() EOFV2 = auto() DELEGATION = auto() SUBCONTAINER_INVALID = auto() def bytecode(self) -> Bytecode | Container | Bytes: """Bytecode for the code to validate.""" match self: case ValidatedCode.LEGACY: return Op.STOP case ValidatedCode.EF: return Bytes("0xEF") case ValidatedCode.EOFV1_RUNTIME: return smallest_runtime_subcontainer case ValidatedCode.EOFV1_RUNTIME_INVALID: return Container.Code(Op.ADD) case ValidatedCode.EOFV1_INITCODE: return smallest_initcode_subcontainer case ValidatedCode.EOFV2: return Bytes("0xEF0002") case ValidatedCode.DELEGATION: return Bytes(Spec.DELEGATION_DESIGNATION + Bytes("".join(20 * ["ab"]))) case ValidatedCode.SUBCONTAINER_INVALID: return Container( sections=[ Section.Code(Op.RETURNCODE[0](0, 0)), Section.Container(Container.Code(Op.ADD)), ] ) def valid(self) -> bool: """Whether the code is valid in EOF v1.""" return self in [ValidatedCode.EOFV1_INITCODE] def __str__(self) -> str: """Return string representation of the enum.""" return f"{self.name}" class Factory(Enum): """ Kinds of systems leading up to a call to TXCREATE. DIRECT just puts the TXCREATE in the code it generates, while *CALL ones call into another account which does the TXCREATE. """ DIRECT = auto() WITH_CALL = auto() WITH_DELEGATECALL = auto() WITH_STATICCALL = auto() def creation_snippet( self, initcode_hash: Hash, pre: Alloc, salt: int, evm_code_type: EVMCodeType, value: int, input_size: int, ) -> Tuple[Bytecode, Address | None]: """ Return snippet to cause TXCREATE to be called along with an address. This will end up in the `compute_eofcreate_address` or None if that would be the snippet itself. """ if evm_code_type not in [EVMCodeType.LEGACY, EVMCodeType.EOF_V1]: raise Exception(f"Test needs to be updated for {evm_code_type}") # Snippet which invokes the TXCREATE itself txcreate_code = Op.TXCREATE( tx_initcode_hash=initcode_hash, salt=salt, value=value, input_size=input_size ) # Snippet which returns the TXCREATE result to caller callee_txcreate_code = Op.MSTORE(0, txcreate_code) + Op.RETURN(0, 32) # Snippet which recovers the TXCREATE result from returndata (wipes # memory afterwards) returndataload_code = ( Op.RETURNDATALOAD if evm_code_type == EVMCodeType.EOF_V1 else Op.RETURNDATACOPY(0, 0, Op.RETURNDATASIZE) + Op.MLOAD(0) + Op.MSTORE(0, 0) ) match self: case Factory.DIRECT: return txcreate_code, None case Factory.WITH_CALL: callee_address = pre.deploy_contract(callee_txcreate_code) if evm_code_type == EVMCodeType.EOF_V1: return Op.EXTCALL(address=callee_address) + returndataload_code, callee_address else: return Op.CALL(address=callee_address) + returndataload_code, callee_address case Factory.WITH_DELEGATECALL: callee_address = pre.deploy_contract(callee_txcreate_code) if evm_code_type == EVMCodeType.EOF_V1: return Op.EXTDELEGATECALL(address=callee_address) + returndataload_code, None else: return Op.DELEGATECALL(address=callee_address) + returndataload_code, None case Factory.WITH_STATICCALL: callee_address = pre.deploy_contract(callee_txcreate_code) if evm_code_type == EVMCodeType.EOF_V1: return Op.EXTSTATICCALL(address=callee_address) + returndataload_code, None else: return Op.STATICCALL(address=callee_address) + returndataload_code, None def __str__(self) -> str: """Return string representation of the enum.""" return f"{self.name}" @pytest.mark.with_all_evm_code_types # Subset chosen to limit number of test cases @pytest.mark.parametrize("code_a", [ValidatedCode.EOFV1_INITCODE, ValidatedCode.LEGACY]) @pytest.mark.parametrize("code_b", ValidatedCode) # Subset chosen to limit number of test cases @pytest.mark.parametrize("factory_a", [Factory.DIRECT, Factory.WITH_CALL]) @pytest.mark.parametrize("factory_b", Factory) @pytest.mark.parametrize("value", [0, 1]) @pytest.mark.parametrize("input_size", [0, 31]) @pytest.mark.parametrize("access_list_a", [True, False]) def test_txcreate_validates( state_test: StateTestFiller, pre: Alloc, code_a: ValidatedCode, code_b: ValidatedCode, factory_a: Factory, factory_b: Factory, evm_code_type: EVMCodeType, value: int, input_size: int, access_list_a: bool, ) -> None: """ Verifies proper validation of initcode on TXCREATE in various scenarios. """ env = Environment() snippet_a, factory_address_a = factory_a.creation_snippet( Bytes(code_a.bytecode()).keccak256(), pre, 0, evm_code_type, value, input_size ) snippet_b, factory_address_b = factory_b.creation_snippet( Bytes(code_b.bytecode()).keccak256(), pre, 1, evm_code_type, value, input_size ) sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=( Op.SSTORE(slot_code_worked, value_code_worked) + Op.SSTORE(slot_a, snippet_a) + Op.SSTORE(slot_b, snippet_b) + Op.STOP ) ) create_address_a = factory_address_a if factory_address_a else contract_address create_address_b = factory_address_b if factory_address_b else contract_address destination_address_a = compute_eofcreate_address(create_address_a, 0) destination_address_b = compute_eofcreate_address(create_address_b, 1) post = { contract_address: Account( storage={ slot_a: destination_address_a if code_a.valid() and value == 0 and factory_a != Factory.WITH_STATICCALL else TXCREATE_FAILURE, slot_b: destination_address_b if code_b.valid() and value == 0 and factory_b != Factory.WITH_STATICCALL else TXCREATE_FAILURE, slot_code_worked: value_code_worked, } ) } if access_list_a: access_list = [AccessList(address=destination_address_a, storage_keys=[Hash(0x0)])] else: access_list = [] tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[code_a.bytecode(), code_b.bytecode()], access_list=access_list, ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_txcreate_failures.py
tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_txcreate_failures.py
"""Test bad TXCREATE cases.""" import pytest from ethereum_test_base_types import Bytes from ethereum_test_base_types.base_types import Address, Hash from ethereum_test_forks import Fork from ethereum_test_tools import ( Account, Alloc, Environment, EVMCodeType, StateTestFiller, Transaction, compute_eofcreate_address, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_BYTECODE_SIZE, MAX_INITCODE_SIZE from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from ..eip7069_extcall.spec import EXTCALL_FAILURE, EXTCALL_REVERT, LEGACY_CALL_FAILURE from ..eip7620_eof_create.helpers import ( aborting_container, slot_call_or_create, slot_call_result, slot_code_should_fail, slot_code_worked, slot_counter, slot_create_address, slot_max_depth, slot_returndata, slot_returndata_size, smallest_initcode_subcontainer, smallest_runtime_subcontainer, value_canary_should_not_change, value_canary_to_be_overwritten, value_code_worked, ) from .spec import TXCREATE_FAILURE REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7873.md" REFERENCE_SPEC_VERSION = "1115fe6110fcc0efc823fb7f8f5cd86c42173efe" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "revert", [ pytest.param(b"", id="empty"), pytest.param(b"\x08\xc3\x79\xa0", id="Error(string)"), ], ) def test_initcode_revert(state_test: StateTestFiller, pre: Alloc, revert: bytes) -> None: """Verifies proper handling of REVERT in initcode.""" env = Environment() revert_size = len(revert) initcode_subcontainer = Container( name="Initcode Subcontainer that reverts", sections=[ Section.Code( code=Op.MSTORE(0, Op.PUSH32(revert)) + Op.REVERT(32 - revert_size, revert_size), ), ], ) initcode_hash = initcode_subcontainer.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_returndata_size, Op.RETURNDATASIZE) + Op.RETURNDATACOPY(Op.SUB(32, Op.RETURNDATASIZE), 0, Op.RETURNDATASIZE) + Op.SSTORE(slot_returndata, Op.MLOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) post = { contract_address: Account( storage={ slot_create_address: TXCREATE_FAILURE, slot_returndata_size: revert_size, slot_returndata: revert, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "initcode_hash", [ Bytes("").keccak256(), Bytes("00" * 32), Bytes("FF" * 32), Bytes("EF01").keccak256(), smallest_runtime_subcontainer.hash, ], ) @pytest.mark.parametrize("tx_initcode_count", [1, 255, 256]) def test_txcreate_invalid_hash( state_test: StateTestFiller, pre: Alloc, tx_initcode_count: int, initcode_hash: Hash ) -> None: """Verifies proper handling of REVERT in initcode.""" env = Environment() sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) post = { contract_address: Account( storage={ slot_create_address: TXCREATE_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[smallest_initcode_subcontainer] * tx_initcode_count, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_initcode_aborts(state_test: StateTestFiller, pre: Alloc) -> None: """Verifies correct handling of a halt in EOF initcode.""" env = Environment() sender = pre.fund_eoa() initcode_hash = aborting_container.hash contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) # Storage in slot_create_address should not have the address, post = { contract_address: Account( storage={ slot_create_address: TXCREATE_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[aborting_container], ) state_test(env=env, pre=pre, post=post, tx=tx) """ Size of the initcode portion of test_txcreate_deploy_sizes, but as the runtime code is dynamic, we have to use a pre-calculated size """ initcode_size = 32 @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "target_deploy_size", [ pytest.param(0x4000, id="large"), pytest.param(MAX_BYTECODE_SIZE, id="max"), pytest.param(MAX_BYTECODE_SIZE + 1, id="overmax"), pytest.param(MAX_INITCODE_SIZE - initcode_size - 1, id="below_initcodemax"), pytest.param(MAX_INITCODE_SIZE - initcode_size, id="initcodemax"), ], ) def test_txcreate_deploy_sizes( state_test: StateTestFiller, pre: Alloc, target_deploy_size: int, ) -> None: """ Verify a mix of runtime contract sizes. This mixes success and multiple size failure modes. """ env = Environment() runtime_container = Container( sections=[ Section.Code( code=Op.JUMPDEST * (target_deploy_size - len(smallest_runtime_subcontainer)) + Op.STOP, ), ] ) initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container(container=runtime_container), ], ) assert initcode_size == len(initcode_subcontainer) - len(runtime_container) assert initcode_size == (len(initcode_subcontainer) - len(runtime_container)), ( "initcode_size is wrong, expected initcode_size is %d, calculated is %d" % ( initcode_size, len(initcode_subcontainer) - len(runtime_container), ) ) initcode_hash = initcode_subcontainer.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) # Storage in 0 should have the address, Storage 1 is a canary of 1 to make # sure it tried to execute, which also covers cases of data+code being # greater than initcode_size_max, which is allowed. success = target_deploy_size <= MAX_BYTECODE_SIZE post = { contract_address: Account( storage={ slot_create_address: compute_eofcreate_address(contract_address, 0) if success else TXCREATE_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account() if success else Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=20_000_000, sender=sender, initcodes=[initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "auxdata_size", [ pytest.param(MAX_BYTECODE_SIZE - len(smallest_runtime_subcontainer), id="maxcode"), pytest.param(MAX_BYTECODE_SIZE - len(smallest_runtime_subcontainer) + 1, id="overmaxcode"), pytest.param(0x10000 - 60, id="almost64k"), pytest.param(0x10000 - 1, id="64k-1"), pytest.param(0x10000, id="64k"), pytest.param(0x10000 + 1, id="over64k"), ], ) def test_auxdata_size_failures(state_test: StateTestFiller, pre: Alloc, auxdata_size: int) -> None: """ Exercises a number of auxdata size violations, and one maxcode success. """ env = Environment() auxdata_bytes = b"a" * auxdata_size initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.RETURNCODE[0](0, Op.CALLDATASIZE), ), Section.Container(container=smallest_runtime_subcontainer), ], ) sender = pre.fund_eoa() initcode_hash = initcode_subcontainer.hash contract_address = pre.deploy_contract( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE( slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash, input_size=Op.CALLDATASIZE), ) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) deployed_container_size = len(smallest_runtime_subcontainer) + auxdata_size # Storage in 0 will have address in first test, 0 in all other cases # indicating failure # # Storage 1 in 1 is a canary to see if TXCREATE opcode halted success = deployed_container_size <= MAX_BYTECODE_SIZE post = { contract_address: Account( storage={ slot_create_address: compute_eofcreate_address(contract_address, 0) if deployed_container_size <= MAX_BYTECODE_SIZE else 0, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account() if success else Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=20_000_000, sender=sender, initcodes=[initcode_subcontainer], data=auxdata_bytes, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "value", [ pytest.param(1, id="1_wei"), pytest.param(10**9, id="1_gwei"), ], ) def test_txcreate_insufficient_stipend( state_test: StateTestFiller, pre: Alloc, value: int, ) -> None: """ Exercises an TXCREATE that fails because the calling account does not have enough ether to pay the stipend. """ env = Environment() sender = pre.fund_eoa(10**11) initcode_hash = smallest_initcode_subcontainer.hash contract_address = pre.deploy_contract( code=Op.SSTORE( slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash, value=value) ) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, balance=value - 1, ) # create will fail but not trigger a halt, so canary at storage 1 # should be set # # also validate target created contract fails post = { contract_address: Account( storage={ slot_create_address: TXCREATE_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=20_000_000, sender=sender, initcodes=[smallest_initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_insufficient_initcode_gas(state_test: StateTestFiller, pre: Alloc, fork: Fork) -> None: """ Exercises an TXCREATE when there is not enough gas for the constant charge. """ env = Environment() initcode_container = Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container(container=smallest_runtime_subcontainer), ], ) initcode_hash = initcode_container.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_code_should_fail, value_code_worked) + Op.STOP, storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ) # enough gas for everything but EVM opcodes and EIP-150 reserves # FIXME: should not use that calculator!!! # FIXME: the -1000 is a wild guess - revisit this gas_limit = ( 32_000 - 1_000 + fork.transaction_intrinsic_cost_calculator()(calldata=initcode_container) ) # out_of_gas is triggered, so canary won't set value # also validate target created contract fails post = { contract_address: Account( storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=gas_limit, sender=sender, initcodes=[initcode_container], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_insufficient_gas_memory_expansion( state_test: StateTestFiller, pre: Alloc, fork: Fork, ) -> None: """ Exercises TXCREATE when the memory for auxdata has not been expanded but is requested. """ env = Environment() auxdata_size = 0x5000 initcode_hash = smallest_initcode_subcontainer.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.SSTORE( slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash, input_size=auxdata_size), ) + Op.SSTORE(slot_code_should_fail, slot_code_worked) + Op.STOP, storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ) # enough gas for everything but EVM opcodes and EIP-150 reserves auxdata_size_words = (auxdata_size + 31) // 32 gas_limit = ( 32_000 + 3 * auxdata_size_words + auxdata_size_words * auxdata_size_words // 512 + fork.transaction_intrinsic_cost_calculator()(calldata=smallest_initcode_subcontainer) ) # out_of_gas is triggered, so canary won't set value # also validate target created contract fails post = { contract_address: Account( storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=gas_limit, sender=sender, initcodes=[smallest_initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_insufficient_returncode_auxdata_gas( state_test: StateTestFiller, pre: Alloc, fork: Fork, ) -> None: """ Exercises a RETURNCODE when there is not enough gas for the initcode charge. """ env = Environment() auxdata_size = 0x5000 initcode_container = Container( name="Large Initcode Subcontainer", sections=[ Section.Code( code=Op.RETURNCODE[0](0, auxdata_size), ), Section.Container(container=smallest_runtime_subcontainer), ], ) initcode_hash = initcode_container.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.SSTORE(slot_code_worked, value_code_worked) + Op.TXCREATE(tx_initcode_hash=initcode_hash) + Op.STOP, storage={ slot_code_worked: value_canary_to_be_overwritten, }, ) # 63/64ths is not enough to cover RETURNCODE memory expansion. # Unfortunately the 1/64th left won't realistically accommodate a SSTORE auxdata_size_words = (auxdata_size + 31) // 32 gas_limit = ( 32_000 + 2600 # SSTORE + 3 * auxdata_size_words + auxdata_size_words * auxdata_size_words // 512 + fork.transaction_intrinsic_cost_calculator()(calldata=initcode_container) ) # out_of_gas is triggered in the initcode context, so canary will set value # also validate target created contract fails post = { contract_address: Account( storage={ slot_code_worked: value_code_worked, }, ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=gas_limit, sender=sender, initcodes=[initcode_container], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "opcode", [ Op.STATICCALL, Op.EXTSTATICCALL, ], ) @pytest.mark.parametrize("endowment", [0, 1]) # included to verify static flag # check comes first @pytest.mark.parametrize( "initcode", [smallest_initcode_subcontainer, aborting_container], ids=["working_initcode", "aborting_code"], ) def test_static_flag_txcreate( state_test: StateTestFiller, pre: Alloc, opcode: Op, endowment: int, initcode: Container, ) -> None: """Verifies correct handling of the static call flag with TXCREATE.""" env = Environment() initcode_hash = initcode.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.TXCREATE(tx_initcode_hash=initcode_hash, value=endowment) + Op.STOP, ) calling_code = ( Op.SSTORE(slot_call_result, opcode(address=contract_address)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) calling_address = pre.deploy_contract( calling_code, # Need to override the global value from the `with_all_evm_code_types` # marker. evm_code_type=EVMCodeType.EOF_V1 if opcode == Op.EXTSTATICCALL else EVMCodeType.LEGACY, ) post = { calling_address: Account( storage={ slot_call_result: EXTCALL_FAILURE if opcode == Op.EXTSTATICCALL else LEGACY_CALL_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=calling_address, gas_limit=10_000_000, sender=sender, initcodes=[initcode], ) state_test(env=env, pre=pre, post=post, tx=tx) magic_value_call = 0xCA11 magic_value_create = 0xCC12EA7E @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "who_fails", [magic_value_call, magic_value_create], ids=["call_fails", "create_fails"], ) @pytest.mark.pre_alloc_modify def test_eof_txcreate_msg_depth( state_test: StateTestFiller, pre: Alloc, who_fails: int, evm_code_type: EVMCodeType, ) -> None: """ Test TXCREATE handles msg depth limit correctly (1024). NOTE: due to block gas limit and the 63/64th rule this limit is unlikely to be hit on mainnet. NOTE: See `tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_calls.py:: test_eof_calls_msg_depth` for more explanations and comments. Most notable deviation from that test is that here calls and `TXCREATE`s alternate in order to reach the max depth. `who_fails` decides whether the failing depth 1024 will be on a call or on an `TXCREATE` to happen. """ # Not a precise gas_limit formula, but enough to exclude risk of gas # causing the failure. gas_limit = int(20000000 * (64 / 63) ** 1024) env = Environment(gas_limit=gas_limit) callee_address = Address(0x5000) # Memory offsets layout: # - 0 - input - msg depth # - 32 - output - msg depth # - 64 - output - call result # - 96 - output - magic value: create or call returndatacopy_block = Op.RETURNDATACOPY(32, 0, 96) + Op.REVERT(32, 96) deep_most_result_block = ( Op.MSTORE(32, Op.ADD(Op.CALLDATALOAD(0), 1)) + Op.MSTORE(64, Op.NOOP) + Op.REVERT(32, 96) ) rjump_offset = len(returndatacopy_block) initcode = Container.Code( Op.MSTORE(0, Op.ADD(Op.CALLDATALOAD(0), 1)) + Op.MSTORE(96, magic_value_call) + Op.EXTCALL(address=callee_address, args_size=32) + Op.RETURNDATASIZE + Op.ISZERO + Op.RJUMPI[rjump_offset] + returndatacopy_block + deep_most_result_block ) initcode_hash = initcode.hash sender = pre.fund_eoa() jump_code = ( Op.RJUMPI[rjump_offset] if evm_code_type == EVMCodeType.EOF_V1 else Op.ADD(Op.PC, rjump_offset + 3) + Op.JUMPI ) callee_code = ( Op.MSTORE(0, Op.ADD(Op.CALLDATALOAD(0), 1)) + Op.MSTORE(96, magic_value_create) + Op.TXCREATE(tx_initcode_hash=initcode_hash, salt=Op.CALLDATALOAD(0), input_size=32) + Op.RETURNDATASIZE + Op.ISZERO + jump_code + returndatacopy_block + Op.JUMPDEST + deep_most_result_block ) pre.deploy_contract(callee_code, address=callee_address) calling_contract_address = pre.deploy_contract( Container.Code( Op.MSTORE(0, Op.CALLDATALOAD(0)) + Op.EXTCALL(address=callee_address, args_size=32) + Op.SSTORE(slot_max_depth, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_call_result, Op.RETURNDATALOAD(32)) + Op.SSTORE(slot_call_or_create, Op.RETURNDATALOAD(64)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) ) # Only bumps the msg call depth "register" and forwards to the # `calling_contract_address`. If it is used it makes the "failing" depth of # 1024 to happen on TXCREATE, instead of CALL. passthrough_address = pre.deploy_contract( Container.Code( Op.MSTORE(0, 1) + Op.EXTCALL(address=calling_contract_address, args_size=32) + Op.STOP ) ) tx = Transaction( sender=sender, initcodes=[initcode], to=calling_contract_address if who_fails == magic_value_call else passthrough_address, gas_limit=gas_limit, data="", ) calling_storage = { slot_max_depth: 1024, slot_code_worked: value_code_worked, slot_call_result: EXTCALL_REVERT if who_fails == magic_value_call else TXCREATE_FAILURE, slot_call_or_create: who_fails, } post = { calling_contract_address: Account(storage=calling_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.with_all_evm_code_types def test_reentrant_txcreate( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies a reentrant TXCREATE case, where EIP-161 prevents conflict via nonce bump. """ env = Environment() # Calls into the factory contract with 1 as input. reenter_code = Op.MSTORE(0, 1) + Op.EXTCALL(address=Op.CALLDATALOAD(32), args_size=32) # Initcode: if given 0 as 1st word of input will call into the factory # again. 2nd word of input is the address of the factory. initcontainer = Container( sections=[ Section.Code( Op.SSTORE(slot_counter, Op.ADD(Op.SLOAD(slot_counter), 1)) + Op.CALLDATALOAD(0) + Op.RJUMPI[len(reenter_code)] + reenter_code + Op.RETURNCODE[0](0, 0) ), Section.Container(smallest_runtime_subcontainer), ] ) initcode_hash = initcontainer.hash # Factory: # Passes on its input into the initcode. # It's 0 first time, 1 the second time. # Saves the result of deployment in slot 0 first time, 1 the second time. contract_address = pre.deploy_contract( code=Op.CALLDATACOPY(0, 0, 32) + Op.MSTORE(32, Op.ADDRESS) # 1st word - copied from input (reenter flag) # 2nd word - `this.address` + Op.SSTORE( Op.CALLDATALOAD(0), Op.TXCREATE(tx_initcode_hash=initcode_hash, input_size=64), ) + Op.STOP, storage={0: 0xB17D, 1: 0xB17D}, # a canary to be overwritten ) # Flow is: reenter flag 0 -> factory -> reenter flag 0 -> initcode # -> reenter -> reenter flag 1 -> factory -> reenter flag 1 # -> (!) initcode -> stop, # if the EIP-161 nonce bump is not implemented. If it is, it fails before # second initcode marked (!). # Storage in 0 should have the address from the outer TXCREATE. # Storage in 1 should have 0 from the inner TXCREATE. # For the created contract storage in `slot_counter` should be 1 as # initcode executes only once post = { contract_address: Account( storage={ 0: compute_eofcreate_address(contract_address, 0), 1: 0, } ), compute_eofcreate_address(contract_address, 0): Account( nonce=1, code=smallest_runtime_subcontainer, storage={slot_counter: 1} ), } tx = Transaction( to=contract_address, gas_limit=500_000, initcodes=[initcontainer], sender=pre.fund_eoa(), ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "reason", [ "valid", "invalid_deploy_container", "invalid_initcode", "invalid_opcode_during_initcode", "invalid_opcode_with_sstore_during_initcode", "revert_opcode_during_initcode", "out_of_gas_during_initcode", "out_of_gas_when_returning_contract", "out_of_gas_when_returning_contract_due_to_memory_expansion", ], ) def test_invalid_container_deployment( state_test: StateTestFiller, fork: Fork, pre: Alloc, reason: str, ) -> None: """ Verify contract is not deployed when an invalid container deployment is attempted. """ env = Environment() sender = pre.fund_eoa() # Valid defaults deployed_container = Container( sections=[ Section.Code(code=Op.CALLF[1](Op.PUSH0, Op.PUSH0) + Op.STOP), Section.Code(code=Op.ADD + Op.RETF, code_inputs=2, code_outputs=1), ] ) initcontainer: Container = Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0, 0)), Section.Container(deployed_container), ], ) tx_gas_limit = 100_000 fork_intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() fork_gas_costs = fork.gas_costs() # Modify defaults based on invalidity reason if reason == "invalid_deploy_container": deployed_container = Container( sections=[ Section.Code(code=Op.CALLF[1](Op.PUSH0, Op.PUSH0) + Op.STOP), Section.Code(code=Op.ADD + Op.RETF, code_outputs=0), ] ) initcontainer = Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0, 0)), Section.Container(deployed_container), ], ) elif reason == "invalid_initcode": initcontainer = Container( sections=[ Section.Code(code=Op.RETURNCODE[1](0, 0)), Section.Container(deployed_container), ], ) elif ( reason == "invalid_opcode_during_initcode" or reason == "invalid_opcode_with_sstore_during_initcode" or reason == "revert_opcode_during_initcode" or reason == "out_of_gas_during_initcode" ): invalid_code_path: Bytecode if reason == "invalid_opcode_with_sstore_during_initcode": invalid_code_path = Op.SSTORE(0, 1) + Op.INVALID elif reason == "revert_opcode_during_initcode": invalid_code_path = Op.REVERT(0, 0) elif reason == "out_of_gas_during_initcode": invalid_code_path = Op.MSTORE(0xFFFFFFFFFFFFFFFFFFFFFFFFFFF, 1) elif reason == "invalid_opcode_during_initcode": invalid_code_path = Op.INVALID else: raise Exception(f"invalid case: {reason}") initcontainer = Container( sections=[ Section.Code( code=Op.RJUMPI[len(invalid_code_path)](Op.PUSH0) + invalid_code_path + Op.RETURNCODE[0](0, 0) ), Section.Container(deployed_container), ], ) elif reason == "out_of_gas_when_returning_contract": factory_gas_cost = ( 7 * fork_gas_costs.G_VERY_LOW + fork_gas_costs.G_STORAGE_SET + fork_gas_costs.G_COLD_SLOAD + fork_gas_costs.G_CREATE ) initcode_gas_cost = 2 * fork_gas_costs.G_VERY_LOW tx_gas_limit = ( fork_intrinsic_gas_calculator(calldata=initcontainer) + factory_gas_cost + (initcode_gas_cost - 1) * 64 // 63 ) elif reason == "out_of_gas_when_returning_contract_due_to_memory_expansion": factory_gas_cost = ( 7 * fork_gas_costs.G_VERY_LOW + fork_gas_costs.G_STORAGE_SET + fork_gas_costs.G_COLD_SLOAD + fork_gas_costs.G_CREATE ) initcode_gas_cost = ( # Code deposit gas cost len(deployed_container) * fork_gas_costs.G_CODE_DEPOSIT_BYTE # Two push opcodes + 2 * fork_gas_costs.G_VERY_LOW ) tx_gas_limit = ( fork_intrinsic_gas_calculator(calldata=initcontainer) + factory_gas_cost + initcode_gas_cost * 64 // 63 ) initcontainer = Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0xFFFFFFFFFFFFFFFFFFFFFFFFFFF, 0x1)), Section.Container(deployed_container), ], ) elif reason == "valid": pass else: raise TypeError("Unexpected reason", reason) initcode_hash = initcontainer.hash contract_address = pre.deploy_contract( code=Op.SSTORE(slot_code_worked, value_code_worked) + Op.TXCREATE(tx_initcode_hash=initcode_hash) + Op.STOP ) tx = Transaction( to=contract_address, sender=sender, gas_limit=tx_gas_limit, initcodes=[initcontainer], ) destination_contract_address = compute_eofcreate_address(contract_address, 0) post = ( { destination_contract_address: Account.NONEXISTENT, contract_address: Account( nonce=1 if reason in ["invalid_initcode", "invalid_deploy_container"] else 2, storage={ slot_code_worked: value_code_worked, }, ), } if reason != "valid" else { destination_contract_address: Account(nonce=1, code=deployed_container), contract_address: Account( nonce=2, storage={ slot_code_worked: value_code_worked, }, ), } ) state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_txcreate.py
tests/unscheduled/eip7692_eof_v1/eip7873_tx_create/test_txcreate.py
"""Test good TXCREATE cases.""" import pytest from ethereum_test_base_types import Storage from ethereum_test_base_types.base_types import Address from ethereum_test_tools import ( Account, Alloc, Environment, EVMCodeType, StateTestFiller, Transaction, compute_eofcreate_address, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from ..eip7069_extcall.spec import EXTCALL_SUCCESS, LEGACY_CALL_SUCCESS from ..eip7620_eof_create.helpers import ( slot_call_result, slot_calldata, slot_code_worked, slot_create_address, slot_data_load, slot_last_slot, slot_returndata_size, smallest_initcode_subcontainer, smallest_runtime_subcontainer, value_canary_to_be_overwritten, value_code_worked, value_long_value, ) from .spec import TXCREATE_FAILURE REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7873.md" REFERENCE_SPEC_VERSION = "1115fe6110fcc0efc823fb7f8f5cd86c42173efe" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize("tx_initcode_count", [1, 255, 256]) def test_simple_txcreate(state_test: StateTestFiller, pre: Alloc, tx_initcode_count: int) -> None: """Verifies a simple TXCREATE case.""" env = Environment() sender = pre.fund_eoa() initcode_hash = smallest_initcode_subcontainer.hash contract_address = pre.deploy_contract( code=Op.SSTORE(0, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.STOP, storage={0: 0xB17D}, # a canary to be overwritten ) # Storage in 0 should have the address, post = {contract_address: Account(storage={0: compute_eofcreate_address(contract_address, 0)})} tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[smallest_initcode_subcontainer] * tx_initcode_count, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_txcreate_then_dataload( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies that a contract returned with auxdata does not overwrite the parent data. """ env = Environment() sender = pre.fund_eoa() small_auxdata_container = Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0, 32)), Section.Container(container=smallest_runtime_subcontainer), ], ) initcode_hash = small_auxdata_container.hash contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(0, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_data_load, Op.DATALOAD(0)) + Op.STOP, ), Section.Data(data=value_long_value), ], ), storage={slot_data_load: value_canary_to_be_overwritten}, ) post = { contract_address: Account( storage={ 0: compute_eofcreate_address(contract_address, 0), slot_data_load: value_long_value, } ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[small_auxdata_container], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_txcreate_then_call( state_test: StateTestFiller, pre: Alloc, evm_code_type: EVMCodeType, ) -> None: """ Verifies a simple TXCREATE case, and then calls the deployed contract. """ env = Environment() callable_contract = Container( sections=[ Section.Code( code=Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), ] ) callable_contract_initcode = Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container(container=callable_contract), ] ) initcode_hash = callable_contract_initcode.hash sender = pre.fund_eoa() opcode = Op.EXTCALL if evm_code_type == EVMCodeType.EOF_V1 else Op.CALL contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + opcode(address=Op.SLOAD(slot_create_address)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) callable_address = compute_eofcreate_address(contract_address, 0) # Storage in 0 should have the address, # post = { contract_address: Account( storage={slot_create_address: callable_address, slot_code_worked: value_code_worked} ), callable_address: Account(storage={slot_code_worked: value_code_worked}), } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[callable_contract_initcode], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( "auxdata_bytes", [ pytest.param(b"", id="zero"), pytest.param(b"aabbcc", id="short"), pytest.param(b"aabbccddeef", id="one_byte_short"), pytest.param(b"aabbccddeeff", id="exact"), pytest.param(b"aabbccddeeffg", id="one_byte_long"), pytest.param(b"aabbccddeeffgghhii", id="extra"), ], ) def test_auxdata_variations( state_test: StateTestFiller, pre: Alloc, auxdata_bytes: bytes, ) -> None: """Verifies that auxdata bytes are correctly handled in RETURNCODE.""" env = Environment() auxdata_size = len(auxdata_bytes) pre_deploy_header_data_size = 18 pre_deploy_data = b"AABBCC" deploy_success = len(auxdata_bytes) + len(pre_deploy_data) >= pre_deploy_header_data_size runtime_subcontainer = Container( name="Runtime Subcontainer with truncated data", sections=[ Section.Code(code=Op.STOP), Section.Data(data=pre_deploy_data, custom_size=pre_deploy_header_data_size), ], ) initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.MSTORE(0, Op.PUSH32(auxdata_bytes.ljust(32, b"\0"))) + Op.RETURNCODE[0](0, auxdata_size), ), Section.Container(container=runtime_subcontainer), ], ) initcode_hash = initcode_subcontainer.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.STOP, storage={slot_create_address: value_canary_to_be_overwritten}, ) # Storage in 0 should have the address, post = { contract_address: Account( storage={ slot_create_address: compute_eofcreate_address(contract_address, 0) if deploy_success else b"\0" } ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_calldata(state_test: StateTestFiller, pre: Alloc) -> None: """Verifies CALLDATA passing through TXCREATE.""" env = Environment() initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_calldata, Op.MLOAD(0)) + Op.RETURNCODE[0](0, Op.CALLDATASIZE), ), Section.Container(container=smallest_runtime_subcontainer), ], ) initcode_hash = initcode_subcontainer.hash calldata_size = 32 calldata = b"\x45" * calldata_size sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.MSTORE(0, Op.PUSH32(calldata)) + Op.SSTORE( slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash, input_size=calldata_size), ) + Op.STOP, ) # deployed contract is smallest plus data deployed_contract = Container( name="deployed contract", sections=[ *smallest_runtime_subcontainer.sections, Section.Data(data=calldata), ], ) # factory contract Storage in 0 should have the created address, # created contract storage in 0 should have the calldata created_address = compute_eofcreate_address(contract_address, 0) post = { contract_address: Account(storage={slot_create_address: created_address}), created_address: Account(code=deployed_contract, storage={slot_calldata: calldata}), } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize("outer_create_opcode", [Op.TXCREATE, Op.EOFCREATE]) @pytest.mark.parametrize("inner_create_opcode", [Op.TXCREATE, Op.EOFCREATE]) @pytest.mark.parametrize("outer_create_reverts", [True, False]) def test_txcreate_in_initcode( state_test: StateTestFiller, pre: Alloc, outer_create_opcode: Op, inner_create_opcode: Op, outer_create_reverts: bool, ) -> None: """ Verifies an TXCREATE occurring within initcode creates that contract. Via the `outer_create_reverts` also verifies a TXCREATE occurring in an initcode is rolled back when the initcode reverts. """ smallest_initcode_subcontainer_hash = smallest_initcode_subcontainer.hash inner_create_bytecode = ( Op.TXCREATE(tx_initcode_hash=smallest_initcode_subcontainer_hash) if inner_create_opcode == Op.TXCREATE else Op.EOFCREATE[1](0, 0, 0, 0) ) # The terminating code of the inner initcontainer, the RJUMPI is a trick to # not need to deal with the subcontainer indices revert_code = Op.REVERT(0, 0) terminating_code = ( Op.RJUMPI[len(revert_code)](0) + revert_code + Op.RETURNCODE[0](0, 0) if outer_create_reverts else Op.RETURNCODE[0](0, 0) ) nested_initcode_subcontainer = Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, inner_create_bytecode) + Op.SSTORE(slot_code_worked, value_code_worked) + terminating_code, ), Section.Container(container=smallest_runtime_subcontainer), ] + ( [Section.Container(container=smallest_initcode_subcontainer)] if inner_create_opcode == Op.EOFCREATE else [] ) ) nested_initcode_subcontainer_hash = nested_initcode_subcontainer.hash outer_create_bytecode = ( Op.TXCREATE(tx_initcode_hash=nested_initcode_subcontainer_hash) if outer_create_opcode == Op.TXCREATE else Op.EOFCREATE[0](0, 0, 0, 0) ) env = Environment() sender = pre.fund_eoa() contract_code = Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, outer_create_bytecode) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), ] + ( [Section.Container(container=nested_initcode_subcontainer)] if outer_create_opcode == Op.EOFCREATE else [] ) ) contract_address = pre.deploy_contract(code=contract_code) outer_address = compute_eofcreate_address(contract_address, 0) inner_address = compute_eofcreate_address(outer_address, 0) post = { contract_address: Account( storage={ slot_create_address: outer_address if not outer_create_reverts else 0, slot_code_worked: value_code_worked, } ), outer_address: Account( storage={slot_create_address: inner_address, slot_code_worked: value_code_worked} ) if not outer_create_reverts else Account.NONEXISTENT, inner_address: Account() if not outer_create_reverts else Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[nested_initcode_subcontainer, smallest_initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_return_data_cleared( state_test: StateTestFiller, pre: Alloc, evm_code_type: EVMCodeType, ) -> None: """ Verifies the return data is not reused from a extcall but is cleared upon TXCREATE. """ env = Environment() value_return_canary = 0x4158675309 value_return_canary_size = 5 callable_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.MSTORE(0, value_return_canary) + Op.RETURN(0, value_return_canary_size), ) ] ) ) initcode_hash = smallest_initcode_subcontainer.hash slot_returndata_size_2 = slot_last_slot * 2 + slot_returndata_size sender = pre.fund_eoa() opcode = Op.EXTCALL if evm_code_type == EVMCodeType.EOF_V1 else Op.CALL contract_address = pre.deploy_contract( code=Op.SSTORE(slot_call_result, opcode(address=callable_address)) + Op.SSTORE(slot_returndata_size, Op.RETURNDATASIZE) + Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_returndata_size_2, Op.RETURNDATASIZE) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) new_contract_address = compute_eofcreate_address(contract_address, 0) post = { contract_address: Account( storage={ slot_call_result: EXTCALL_SUCCESS if evm_code_type == EVMCodeType.EOF_V1 else LEGACY_CALL_SUCCESS, slot_returndata_size: value_return_canary_size, slot_create_address: new_contract_address, slot_returndata_size_2: 0, slot_code_worked: value_code_worked, }, nonce=2, ), callable_address: Account(nonce=1), new_contract_address: Account(nonce=1), } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, initcodes=[smallest_initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_address_collision( state_test: StateTestFiller, pre: Alloc, ) -> None: """Tests address collision.""" env = Environment( gas_limit=300_000_000_000, ) slot_create_address_2 = slot_last_slot * 2 + slot_create_address slot_create_address_3 = slot_last_slot * 3 + slot_create_address sender = pre.fund_eoa() initcode_hash = smallest_initcode_subcontainer.hash contract_address = pre.deploy_contract( code=Op.SSTORE(slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_create_address_2, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.SSTORE(slot_create_address_3, Op.TXCREATE(tx_initcode_hash=initcode_hash, salt=1)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) salt_zero_address = compute_eofcreate_address(contract_address, 0) salt_one_address = compute_eofcreate_address(contract_address, 1) # Hard-code address for collision, no other way to do this. # We should mark tests that do this, and fail on unmarked tests. pre[salt_one_address] = Account(balance=1, nonce=1) post = { contract_address: Account( storage={ slot_create_address: salt_zero_address, # had an in-transaction collision slot_create_address_2: TXCREATE_FAILURE, # had a pre-existing collision slot_create_address_3: TXCREATE_FAILURE, slot_code_worked: value_code_worked, } ) } # Multiple create fails is expensive, use an absurd amount of gas tx = Transaction( to=contract_address, gas_limit=300_000_000_000, sender=sender, initcodes=[smallest_initcode_subcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_txcreate_revert_eof_returndata( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies the return data is not being deployed, even if happens to be valid EOF. """ env = Environment() code_reverts_with_calldata = Container( name="Initcode Subcontainer reverting with its calldata", sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.REVERT(0, Op.CALLDATASIZE), ), ], ) initcode_hash = code_reverts_with_calldata.hash sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE( slot_create_address, Op.TXCREATE(tx_initcode_hash=initcode_hash, input_size=Op.CALLDATASIZE), ) + Op.SSTORE(slot_returndata_size, Op.RETURNDATASIZE) + Op.STOP, storage={slot_create_address: value_canary_to_be_overwritten}, ) new_address = compute_eofcreate_address(contract_address, 0) post = { contract_address: Account( storage={ slot_create_address: 0, slot_returndata_size: len(smallest_runtime_subcontainer), }, ), new_address: Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=1_000_000, sender=sender, initcodes=[code_reverts_with_calldata], # Simplest possible valid EOF container, which is going to be # revert-returned from initcode and must not end up being deployed. data=smallest_runtime_subcontainer, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types @pytest.mark.parametrize( ["destination_code", "expected_result"], [ pytest.param(Op.ADDRESS, "destination"), pytest.param(Op.CALLER, "caller"), pytest.param(Op.CALLVALUE, "eofcreate_value"), pytest.param(Op.ORIGIN, "sender"), pytest.param(Op.SELFBALANCE, "selfbalance"), pytest.param(Op.BALANCE(Op.CALLER), "factorybalance"), ], ) def test_txcreate_context( state_test: StateTestFiller, pre: Alloc, destination_code: Bytecode, expected_result: str, ) -> None: """Test TXCREATE's initcode context instructions.""" env = Environment() sender = pre.fund_eoa() value = 0x1123 txcreate_value = 0x13 initcode = Container( sections=[ Section.Code(Op.SSTORE(slot_call_result, destination_code) + Op.RETURNCODE[0](0, 0)), Section.Container(smallest_runtime_subcontainer), ] ) initcode_hash = initcode.hash factory_address = pre.deploy_contract( code=Op.SSTORE(slot_code_worked, value_code_worked) + Op.TXCREATE(tx_initcode_hash=initcode_hash, value=txcreate_value) + Op.STOP ) destination_contract_address = compute_eofcreate_address(factory_address, 0) tx = Transaction( sender=sender, to=factory_address, gas_limit=200_000, value=value, initcodes=[initcode], ) expected_bytes: Address | int if expected_result == "destination": expected_bytes = destination_contract_address elif expected_result == "caller": expected_bytes = factory_address elif expected_result == "sender": expected_bytes = sender elif expected_result == "eofcreate_value": expected_bytes = txcreate_value elif expected_result == "selfbalance": expected_bytes = txcreate_value elif expected_result == "factorybalance": # Factory receives value from sender and passes on eofcreate_value as # endowment. expected_bytes = value - txcreate_value else: raise TypeError("Unexpected expected_result", expected_result) calling_storage = { slot_code_worked: value_code_worked, } destination_contract_storage = { slot_call_result: expected_bytes, } post = { factory_address: Account(storage=calling_storage, balance=value - txcreate_value), destination_contract_address: Account( storage=destination_contract_storage, balance=txcreate_value ), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.with_all_evm_code_types def test_txcreate_memory_context( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies an TXCREATE frame enjoys a separate EVM memory from its caller frame. """ env = Environment() destination_storage = Storage() contract_storage = Storage() initcontainer = Container( sections=[ Section.Code( Op.SSTORE(destination_storage.store_next(value_code_worked), value_code_worked) + Op.SSTORE(destination_storage.store_next(0), Op.MSIZE()) + Op.SSTORE(destination_storage.store_next(0), Op.MLOAD(0)) + Op.MSTORE(0, 2) + Op.MSTORE(32, 2) + Op.RETURNCODE[0](0, 0) ), Section.Container(smallest_runtime_subcontainer), ] ) initcode_hash = initcontainer.hash contract_address = pre.deploy_contract( code=Op.SSTORE(contract_storage.store_next(value_code_worked), value_code_worked) + Op.MSTORE(0, 1) + Op.TXCREATE(tx_initcode_hash=initcode_hash) + Op.SSTORE(contract_storage.store_next(32), Op.MSIZE()) + Op.SSTORE(contract_storage.store_next(1), Op.MLOAD(0)) + Op.SSTORE(contract_storage.store_next(0), Op.MLOAD(32)) + Op.STOP, ) destination_contract_address = compute_eofcreate_address(contract_address, 0) post = { contract_address: Account(storage=contract_storage), destination_contract_address: Account(storage=destination_storage), } tx = Transaction( to=contract_address, gas_limit=200_000, sender=pre.fund_eoa(), initcodes=[initcontainer], ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.with_all_evm_code_types def test_short_data_subcontainer( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Deploy a subcontainer where the data is "short" and filled by deployment code. """ env = Environment() sender = pre.fund_eoa() deploy_container = Container( sections=[ Section.Code(Op.STOP), Section.Data(data="001122", custom_size=4), ] ) initcontainer = Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0, 5)), Section.Container(deploy_container), ], ) initcode_hash = initcontainer.hash contract_address = pre.deploy_contract( code=Op.SSTORE(0, Op.TXCREATE(tx_initcode_hash=initcode_hash)) + Op.STOP, storage={0: 0xB17D}, # a canary to be overwritten ) # Storage in 0 should have the address, destination_address = compute_eofcreate_address(contract_address, 0) destination_code = deploy_container.copy() destination_code.sections[1] = Section.Data(data="0011220000000000") post = { contract_address: Account(storage={0: compute_eofcreate_address(contract_address, 0)}), destination_address: Account(code=destination_code), } tx = Transaction( to=contract_address, gas_limit=100_000, sender=sender, initcodes=[initcontainer], ) state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4750_functions/helpers.py
tests/unscheduled/eip7692_eof_v1/eip4750_functions/helpers.py
"""EOF Functions tests helpers.""" import itertools """Storage addresses for common testing fields""" _slot = itertools.count() next(_slot) # don't use slot 0 slot_code_worked = next(_slot) slot_last_slot = next(_slot) slot_stack_canary = next(_slot) """Storage values for common testing fields""" value_code_worked = 0x2015 value_canary_written = 0xDEADB12D
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4750_functions/test_code_validation.py
tests/unscheduled/eip7692_eof_v1/eip4750_functions/test_code_validation.py
"""Code validation of CALLF, RETF opcodes tests.""" from typing import List import pytest from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_types.eof.constants import MAX_RUNTIME_STACK_HEIGHT from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import ( MAX_CODE_OUTPUTS, MAX_CODE_SECTIONS, MAX_STACK_INCREASE_LIMIT, ) from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-4750.md" REFERENCE_SPEC_VERSION = "14400434e1199c57d912082127b1d22643788d11" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) VALID: List[Container] = [ Container( name="retf_stack_validation_0", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=2), Section.Code( code=Op.PUSH0 * 2 + Op.RETF, code_outputs=2, max_stack_height=2, ), ], ), Container( name="retf_stack_validation_3", sections=[ Section.Code( code=Op.PUSH0 + Op.CALLF[1] + Op.STOP, max_stack_height=2, ), Section.Code( code=Op.RJUMPI[7] + Op.PUSH1[1] * 2 + Op.RJUMP[2] + Op.PUSH0 * 2 + Op.RETF, code_inputs=1, code_outputs=2, max_stack_height=2, ), ], ), Container( name="retf_code_input_output", sections=[ Section.Code(code=Op.PUSH0 + Op.CALLF[1] + Op.POP + Op.POP + Op.STOP), Section.Code( code=Op.PUSH0 + Op.RETF, code_outputs=1, ), ], ), Container( name="stack_height_equal_code_outputs_retf_zero_stop", sections=[ Section.Code( code=Op.CALLF[1] + Op.POP + Op.STOP, code_inputs=0, max_stack_height=1, ), Section.Code( code=( Op.RJUMPI[len(Op.PUSH0) + len(Op.RETF)](Op.ORIGIN) + Op.PUSH0 + Op.RETF + Op.STOP ), code_inputs=0, code_outputs=1, max_stack_height=1, ), ], ), Container( name="callf_max_code_sections_1", sections=[ Section.Code(code=(sum(Op.CALLF[i] for i in range(1, MAX_CODE_SECTIONS)) + Op.STOP)) ] + ( [ Section.Code( code=Op.RETF, code_outputs=0, ) ] * (MAX_CODE_SECTIONS - 1) ), ), Container( name="callf_max_code_sections_2", sections=[Section.Code(code=(Op.CALLF[1] + Op.STOP))] + [ Section.Code( code=(Op.CALLF[i + 2] + Op.RETF), code_outputs=0, ) for i in range(MAX_CODE_SECTIONS - 2) ] + [ Section.Code( code=Op.RETF, code_outputs=0, ) ], ), ] INVALID: List[Container] = [ Container( name="retf_stack_validation_1", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=2), Section.Code( code=Op.PUSH0 + Op.RETF, code_outputs=2, max_stack_height=1, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( name="retf_variable_stack_0", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=5), Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 * 2 + Op.RETF, code_outputs=5, max_stack_height=3, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( name="retf_variable_stack_1", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=3), Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 * 2 + Op.RETF, code_outputs=3, max_stack_height=3, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( name="retf_variable_stack_4", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=3), Section.Code( code=Op.PUSH0 * 3 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.POP * 2 + Op.RETF, code_outputs=3, max_stack_height=4, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( name="callf_inputs_underflow_0", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=1), Section.Code( code=Op.PUSH0 + Op.CALLF[2] + Op.RETF, code_outputs=1, max_stack_height=1, ), Section.Code( code=Op.POP + Op.RETF, code_inputs=2, code_outputs=1, max_stack_height=2, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( # CALLF to function with incorrectly specified number of inputs name="code_inputs_underflow_1", # EOF1I4750_0020 sections=[ Section.Code(code=(Op.PUSH0 + Op.PUSH0 + Op.CALLF[1] + Op.STOP)), Section.Code( code=(Op.ADD + Op.RETF), code_inputs=0, code_outputs=0, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( name="code_inputs_underflow_2", sections=[ Section.Code(code=(Op.PUSH0 + Op.CALLF[1] + Op.STOP)), Section.Code( code=(Op.POP + Op.POP + Op.RETF), code_inputs=1, code_outputs=0, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( # CALLF without enough inputs name="callf_inputs_underflow", # EOF1I4750_0019 sections=[ Section.Code(code=(Op.CALLF[1] + Op.STOP)), Section.Code( code=(Op.ADD + Op.RETF), code_inputs=2, code_outputs=1, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( name="retf_stack_validation_2", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=2), Section.Code( code=Op.PUSH0 * 3 + Op.RETF, code_outputs=2, max_stack_height=3, ), ], validity_error=EOFException.STACK_HIGHER_THAN_OUTPUTS, ), Container( name="retf_variable_stack_2", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=1), Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 * 2 + Op.RETF, code_outputs=1, max_stack_height=3, ), ], validity_error=EOFException.STACK_HIGHER_THAN_OUTPUTS, ), Container( name="retf_variable_stack_5", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=1), Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.PUSH0 + Op.RETF, code_outputs=1, max_stack_height=3, ), ], validity_error=EOFException.STACK_HIGHER_THAN_OUTPUTS, ), Container( name="retf_variable_stack_6", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=1), Section.Code( code=Op.PUSH0 * 2 + Op.PUSH1[0] + Op.RJUMPI[1] + Op.POP + Op.RETF, code_outputs=1, max_stack_height=3, ), ], validity_error=EOFException.STACK_HIGHER_THAN_OUTPUTS, ), Container( name="retf_variable_stack_3", sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP), Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 * 2 + Op.RETF, code_outputs=0, max_stack_height=3, ), ], validity_error=EOFException.STACK_HIGHER_THAN_OUTPUTS, ), Container( name="stack_higher_than_code_outputs", sections=[ Section.Code( code=(Op.CALLF[1] + Op.STOP), ), Section.Code( code=(Op.PUSH0 + Op.RETF), code_outputs=0, ), ], validity_error=EOFException.STACK_HIGHER_THAN_OUTPUTS, ), Container( name="stack_shorter_than_code_outputs", sections=[ Section.Code( code=(Op.CALLF[1] + Op.STOP), ), Section.Code( code=(Op.PUSH0 + Op.RETF), code_outputs=2, max_stack_height=1, ), ], validity_error=EOFException.INVALID_MAX_STACK_INCREASE, ), Container( name="stack_shorter_than_code_outputs_1", sections=[ Section.Code( code=(Op.CALLF[1] + Op.STOP), # max_stack_heights of sections aligned with actual stack max_stack_height=1, ), Section.Code( code=(Op.PUSH0 + Op.RETF), code_outputs=2, max_stack_height=1, ), ], validity_error=EOFException.INVALID_MAX_STACK_INCREASE, ), Container( name="stack_shorter_than_code_outputs_2", sections=[ Section.Code( code=(Op.CALLF[1] + Op.STOP), # max_stack_heights of sections aligned with declared outputs max_stack_height=2, ), Section.Code( code=(Op.PUSH0 + Op.RETF), code_outputs=2, max_stack_height=2, ), ], validity_error=EOFException.STACK_UNDERFLOW, ), Container( name="overflow_code_sections_1", sections=[ Section.Code( code=(Op.CALLF[1] + Op.STOP), ) ] + [ Section.Code( code=(Op.CALLF[i + 2] + Op.RETF), code_outputs=0, ) for i in range(MAX_CODE_SECTIONS) ] + [ Section.Code( code=Op.RETF, code_outputs=0, ) ], validity_error=EOFException.TOO_MANY_CODE_SECTIONS, ), ] def container_name(c: Container) -> str: """Return the name of the container for use in pytest ids.""" if hasattr(c, "name") and c.name is not None: return c.name else: return c.__class__.__name__ @pytest.mark.parametrize( "container", [*VALID, *INVALID], ids=container_name, ) def test_eof_validity( eof_test: EOFTestFiller, container: Container, ) -> None: """ Test EOF container validation for features around EIP-4750 / Functions / Code Sections. """ eof_test(container=container) @pytest.mark.parametrize( "container", [ Container( name="imm0", sections=[ Section.Code( code=Op.CALLF, ) ], ), Container( name="imm1", sections=[ Section.Code( code=Op.CALLF + b"\x00", ) ], ), Container( name="imm_from_next_section", sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.CALLF[1] + Op.STOP, ), Section.Code( code=Op.CALLF + b"\x00", # would be valid with "02" + Op.RETF. code_inputs=2, code_outputs=1, max_stack_height=2, ), Section.Code( code=Op.SUB + Op.RETF, # SUB (0x02) can be confused with CALLF[2]. code_inputs=2, code_outputs=1, max_stack_height=2, ), ], ), ], ids=container_name, ) def test_callf_truncated_immediate( eof_test: EOFTestFiller, container: Container, ) -> None: """Test cases for CALLF instructions with truncated immediate bytes.""" eof_test(container=container, expect_exception=EOFException.TRUNCATED_INSTRUCTION) @pytest.mark.parametrize( "container", [ Container( name="callf1", # EOF1I4750_0010 sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ) ], ), Container( name="callf2", # EOF1I0011 sections=[ Section.Code( Op.CALLF[2] + Op.STOP, ), Section.Code( Op.RETF, code_outputs=0, ), ], ), Container( name="callf1_callf2", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( Op.CALLF[2] + Op.RETF, code_outputs=0, ), ], ), ], ids=container_name, ) def test_invalid_code_section_index( eof_test: EOFTestFiller, container: Container, ) -> None: """ Test cases for CALLF instructions with invalid target code section index. """ eof_test(container=container, expect_exception=EOFException.INVALID_CODE_SECTION_INDEX) @pytest.mark.parametrize( "container", [ Container( name="unreachable1", sections=[ Section.Code(Op.INVALID), Section.Code(Op.INVALID), # unreachable ], ), Container( name="unreachable1_selfjumpf", sections=[ Section.Code(Op.INVALID), Section.Code(Op.JUMPF[1]), # unreachable ], ), Container( name="unreachable1_selfcallf", sections=[ Section.Code(Op.INVALID), Section.Code(Op.CALLF[1] + Op.STOP), # unreachable ], ), Container( name="unreachable1_jumpf0", sections=[ Section.Code(Op.INVALID), Section.Code(Op.JUMPF[0]), # unreachable ], ), Container( name="unreachable1_callf0", sections=[ Section.Code(Op.INVALID), Section.Code(Op.CALLF[0] + Op.STOP), # unreachable ], ), Container( name="unreachable1_selfcall_jumpf0", sections=[ Section.Code(Op.INVALID), Section.Code(Op.CALLF[1] + Op.JUMPF[0]), # unreachable ], ), Container( name="unreachable12_of3_2jumpf1", sections=[ Section.Code(Op.INVALID), Section.Code(Op.STOP), # unreachable Section.Code(Op.JUMPF[1]), # unreachable ], ), Container( name="unreachable12_of3_2callf1", sections=[ Section.Code(Op.INVALID), Section.Code(Op.STOP), # unreachable Section.Code(Op.CALLF[1] + Op.STOP), # unreachable ], ), Container( name="unreachable12_of3_jumpf_loop", sections=[ Section.Code(Op.INVALID), Section.Code(Op.JUMPF[2]), # unreachable Section.Code(Op.JUMPF[1]), # unreachable ], ), Container( name="unreachable12_of3_callf_loop_stop", sections=[ Section.Code(Op.INVALID), Section.Code(Op.CALLF[2] + Op.STOP), # unreachable Section.Code(Op.CALLF[1] + Op.STOP), # unreachable ], ), Container( name="unreachable12_of3_callf_loop_retf", sections=[ Section.Code(Op.INVALID), Section.Code(Op.CALLF[2] + Op.RETF, code_outputs=0), # unreachable Section.Code(Op.CALLF[1] + Op.RETF, code_outputs=0), # unreachable ], ), Container( name="unreachable12_of3_callf_loop_mixed", sections=[ Section.Code(Op.INVALID), Section.Code(Op.CALLF[2] + Op.STOP), # unreachable Section.Code(Op.CALLF[1] + Op.RETF, code_outputs=0), # unreachable ], ), Container( name="selfjumpf0_unreachable1", sections=[ Section.Code(Op.JUMPF[0]), # self-reference Section.Code(Op.JUMPF[1]), # unreachable ], ), Container( name="unreachable2_of3", sections=[ Section.Code(Op.CALLF[1] + Op.STOP), Section.Code(Op.RETF, code_outputs=0), Section.Code(Op.INVALID), # unreachable ], ), Container( name="unreachable1_of3", sections=[ Section.Code(Op.CALLF[2] + Op.STOP), Section.Code(Op.INVALID), # unreachable Section.Code(Op.RETF, code_outputs=0), ], ), Container( name="unreachable1_of4", sections=[ Section.Code(Op.CALLF[3] + Op.STOP), Section.Code(Op.INVALID), # unreachable Section.Code(Op.RETF, code_outputs=0), Section.Code(Op.CALLF[2] + Op.RETF, code_outputs=0), ], ), Container( name="unreachable2_of3_retf", sections=[ Section.Code(Op.JUMPF[1]), Section.Code(Op.STOP), Section.Code(Op.RETF, code_outputs=0), ], ), Container( name="unreachable2-255", sections=[ Section.Code(Op.JUMPF[1]), Section.Code(Op.JUMPF[1]), # self-reference ] + [Section.Code(Op.JUMPF[i]) for i in range(3, 255)] # unreachable + [Section.Code(Op.STOP)], # unreachable ), Container( name="unreachable255", sections=[Section.Code(Op.JUMPF[i]) for i in range(1, 255)] + [ Section.Code(Op.JUMPF[254]), # self-reference Section.Code(Op.STOP), # unreachable ], ), ], ids=container_name, ) def test_unreachable_code_sections( eof_test: EOFTestFiller, container: Container, ) -> None: """ Test cases for EOF unreachable code sections (i.e. code sections not reachable from the code section 0). """ eof_test(container=container, expect_exception=EOFException.UNREACHABLE_CODE_SECTIONS) @pytest.mark.parametrize("callee_outputs", [1, 2, MAX_CODE_OUTPUTS]) def test_callf_stack_height_limit_exceeded(eof_test: EOFTestFiller, callee_outputs: int) -> None: """ Test for invalid EOF code containing CALLF instruction exceeding the stack height limit. The code reaches the maximum runtime stack height (1024) which is above the EOF limit for the stack height in the type section (1023). """ callf_stack_height = MAX_RUNTIME_STACK_HEIGHT - callee_outputs container = Container( sections=[ Section.Code( Op.PUSH0 * callf_stack_height + Op.CALLF[1] + Op.STOP, max_stack_height=MAX_RUNTIME_STACK_HEIGHT, ), Section.Code( Op.PUSH0 * callee_outputs + Op.RETF, code_outputs=callee_outputs, max_stack_height=callee_outputs, ), ], ) eof_test(container=container, expect_exception=EOFException.MAX_STACK_INCREASE_ABOVE_LIMIT) @pytest.mark.parametrize("stack_height", [512, 513, 1023]) def test_callf_stack_overflow(eof_test: EOFTestFiller, stack_height: int) -> None: """ Test CALLF instruction recursively calling itself causing stack overflow. """ container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP), Section.Code( code=Op.PUSH1[1] * stack_height + Op.CALLF[1] + Op.POP * stack_height + Op.RETF, code_outputs=0, max_stack_height=stack_height, ), ], ) stack_overflow = stack_height > MAX_RUNTIME_STACK_HEIGHT // 2 eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW if stack_overflow else None, ) @pytest.mark.parametrize("stack_height", [1, 2]) def test_callf_stack_overflow_after_callf(eof_test: EOFTestFiller, stack_height: int) -> None: """ Test CALLF instruction calling next function causing stack overflow at validation time. """ container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP), Section.Code( code=Op.PUSH1[1] * 1023 + Op.CALLF[2] + Op.POP * 1023 + Op.RETF, code_outputs=0, max_stack_height=1023, ), Section.Code( code=Op.PUSH0 * stack_height + Op.POP * stack_height + Op.RETF, code_outputs=0, max_stack_height=stack_height, ), ], ) stack_overflow = 1023 + stack_height > MAX_RUNTIME_STACK_HEIGHT eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW if stack_overflow else None, ) @pytest.mark.parametrize("stack_height", [512, 514, 515]) def test_callf_stack_overflow_variable_stack(eof_test: EOFTestFiller, stack_height: int) -> None: """Test CALLF instruction causing stack overflow.""" container = Container( sections=[ Section.Code( code=Op.RJUMPI[2](0) + Op.PUSH0 * (MAX_RUNTIME_STACK_HEIGHT // 2) + Op.CALLF[1] + Op.STOP, max_stack_height=512, ), Section.Code( code=Op.PUSH1[1] * stack_height + Op.POP * stack_height + Op.RETF, code_outputs=0, max_stack_height=stack_height, ), ], ) stack_overflow = stack_height > MAX_RUNTIME_STACK_HEIGHT // 2 eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW if stack_overflow else None, ) @pytest.mark.parametrize("stack_height", [509, 510, 512]) def test_callf_stack_overflow_variable_stack_2(eof_test: EOFTestFiller, stack_height: int) -> None: """Test CALLF instruction causing stack overflow.""" container = Container( sections=[ Section.Code( code=Op.PUSH0 * 2 + Op.RJUMPI[2](0) + Op.POP * 2 + Op.PUSH0 * (MAX_RUNTIME_STACK_HEIGHT // 2) + Op.CALLF[1] + Op.STOP, max_stack_height=514, ), Section.Code( code=Op.PUSH1[1] * stack_height + Op.POP * stack_height + Op.RETF, code_outputs=0, max_stack_height=stack_height, ), ], ) stack_overflow = stack_height > (MAX_RUNTIME_STACK_HEIGHT // 2) - 2 eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW if stack_overflow else None, ) @pytest.mark.parametrize("stack_height", [1, 2, 5]) def test_callf_stack_overflow_variable_stack_3(eof_test: EOFTestFiller, stack_height: int) -> None: """Test CALLF instruction causing stack overflow.""" container = Container( sections=[ Section.Code( code=Op.RJUMPI[2](0) + Op.PUSH0 * (MAX_RUNTIME_STACK_HEIGHT - 1) + Op.CALLF[1] + Op.STOP, max_stack_height=1023, ), Section.Code( code=Op.PUSH0 * stack_height + Op.POP * stack_height + Op.RETF, code_outputs=0, max_stack_height=stack_height, ), ], ) assert container.sections[0].max_stack_height is not None stack_overflow = ( container.sections[0].max_stack_height + stack_height > MAX_RUNTIME_STACK_HEIGHT ) eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW if stack_overflow else None, ) def test_callf_stack_overflow_variable_stack_4(eof_test: EOFTestFiller) -> None: """Test reaching stack overflow before CALLF instruction.""" container = Container( sections=[ Section.Code( code=Op.PUSH0 * 2 + Op.RJUMPI[2](0) + Op.POP * 2 + Op.PUSH0 * (MAX_RUNTIME_STACK_HEIGHT - 1) + Op.CALLF[1] + Op.STOP, max_stack_height=1023, ), Section.Code( code=Op.RETF, code_outputs=0, max_stack_height=0, ), ], ) eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW, ) @pytest.mark.parametrize("stack_height", [2, 3]) def test_callf_validate_outputs(eof_test: EOFTestFiller, stack_height: int) -> None: """ Test CALLF instruction when calling a function returning more outputs than expected. """ container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=1), Section.Code( code=Op.PUSH0 * stack_height + Op.CALLF[2] + Op.RETF, code_outputs=1, max_stack_height=stack_height, ), Section.Code( code=Op.POP + Op.RETF, code_inputs=2, code_outputs=1, max_stack_height=2, ), ], ) # Only 1 item consumed by function 2, if stack height > 2 # there will be more than 1 item as outputs in function 1 outputs_error = stack_height > 2 eof_test( container=container, expect_exception=EOFException.STACK_HIGHER_THAN_OUTPUTS if outputs_error else None, ) @pytest.mark.parametrize("push_stack", [1023, 1024]) @pytest.mark.parametrize("pop_stack", [1019, 1020, 1021]) @pytest.mark.parametrize( "code_section", [ pytest.param( Section.Code( code=Op.POP * 2 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=2, ), id="pop2", ), pytest.param( Section.Code( code=Op.PUSH1[1] + Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_height=4, ), id="push_pop", ), pytest.param( Section.Code( code=Op.PUSH0 * 2 + Op.RETF, code_inputs=3, code_outputs=5, max_stack_height=5, ), id="push2", ), pytest.param( Section.Code( code=Op.PUSH0 * 2 + Op.POP * 2 + Op.RETF, code_inputs=3, code_outputs=3, max_stack_height=5, ), id="push2_pop2", ), pytest.param( Section.Code( code=Op.PUSH0 + Op.POP * 3 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=3, ), id="push_pop3", ), pytest.param( Section.Code( code=Op.PUSH0 * 2 + Op.POP * 4 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=4, ), id="push2_pop4", ), ], ) def test_callf_with_inputs_stack_overflow( eof_test: EOFTestFiller, code_section: Section, push_stack: int, pop_stack: int ) -> None: """Test CALLF to code section with inputs.""" container = Container( name="callf_with_inputs_stack_overflow_0", sections=[ Section.Code( code=Op.PUSH1[1] * push_stack + Op.CALLF[1] + Op.POP * pop_stack + Op.RETURN, max_stack_height=1023, ), code_section, ], ) assert code_section.max_stack_height is not None exception = None if ( push_stack + code_section.max_stack_height - code_section.code_inputs > MAX_RUNTIME_STACK_HEIGHT ): exception = EOFException.STACK_OVERFLOW elif push_stack - code_section.code_inputs + code_section.code_outputs - pop_stack < 2: exception = EOFException.STACK_UNDERFLOW elif push_stack != container.sections[0].max_stack_height: exception = EOFException.INVALID_MAX_STACK_INCREASE eof_test(container=container, expect_exception=exception) @pytest.mark.parametrize( "code_section", [ pytest.param( Section.Code( code=Op.POP * 2 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=2, ), id="pop2", ), pytest.param( Section.Code( code=Op.PUSH1[1] + Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_height=4, ), id="push_pop", ), pytest.param( Section.Code( code=Op.PUSH0 * 4 + Op.RETF, code_inputs=3, code_outputs=7, max_stack_height=7, ), id="push4", ), pytest.param( Section.Code( code=Op.PUSH0 * 2 + Op.RETF, code_inputs=3, code_outputs=5, max_stack_height=5, ), id="push2", ), pytest.param( Section.Code( code=Op.PUSH0 * 4 + Op.POP * 2 + Op.RETF, code_inputs=3, code_outputs=3, max_stack_height=7, ), id="push4_pop2", ), pytest.param( Section.Code( code=Op.PUSH0 * 2 + Op.POP * 2 + Op.RETF, code_inputs=3, code_outputs=3, max_stack_height=5, ), id="push2_pop2", ), pytest.param( Section.Code( code=Op.PUSH0 * 3 + Op.POP * 5 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=5, ), id="push3_pop5", ), pytest.param( Section.Code( code=Op.PUSH0 + Op.POP * 3 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=3, ), id="push_pop3", ), pytest.param( Section.Code( code=Op.PUSH0 * 4 + Op.POP * 6 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=6, ), id="push4_pop6", ), pytest.param( Section.Code( code=Op.PUSH0 * 2 + Op.POP * 4 + Op.RETF, code_inputs=2, code_outputs=0, max_stack_height=4, ), id="push2_pop4", ), ], ) @pytest.mark.parametrize("push_stack", [1020, 1021]) def test_callf_with_inputs_stack_overflow_variable_stack( eof_test: EOFTestFiller, code_section: Section, push_stack: int ) -> None: """Test CALLF to code section with inputs (variable stack).""" container = Container(
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
true
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4750_functions/__init__.py
tests/unscheduled/eip7692_eof_v1/eip4750_functions/__init__.py
""" Test cases for [EIP-4750: EOF - Functions](https://eips.ethereum.org/EIPS/eip-4750). EIP-4750 formalizes functions in the EVM object format, introducing callable units of code. Opcodes introduced: `CALLF` (`0xE3`), `RETF` (`0xE4`). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip4750_functions/test_callf_execution.py
tests/unscheduled/eip7692_eof_v1/eip4750_functions/test_callf_execution.py
"""EOF CALLF execution tests.""" import math import pytest from ethereum_test_base_types import Hash, Storage from ethereum_test_specs import StateTestFiller from ethereum_test_tools import Account, EOFStateTestFiller from ethereum_test_tools import Opcodes as Op from ethereum_test_types import Alloc, Environment, Transaction from ethereum_test_types.eof.v1 import Container, Section from .. import EOF_FORK_NAME from ..eip7620_eof_create.helpers import ( value_canary_should_not_change, value_canary_to_be_overwritten, ) from .helpers import ( slot_code_worked, slot_stack_canary, value_canary_written, value_code_worked, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-4750.md" REFERENCE_SPEC_VERSION = "14400434e1199c57d912082127b1d22643788d11" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "n,result", ((0, 1), (1, 1), (5, 120), (57, math.factorial(57)), (58, math.factorial(58) % 2**256)), ) def test_callf_factorial(eof_state_test: EOFStateTestFiller, n: int, result: int) -> None: """Test factorial implementation with recursive CALLF instructions.""" eof_state_test( container=Container( sections=[ Section.Code( Op.SSTORE(0, Op.CALLF[1](Op.CALLDATALOAD(0))) + Op.STOP, ), Section.Code( Op.PUSH1[1] + Op.DUP2 + Op.GT + Op.RJUMPI[4] + Op.POP + Op.PUSH1[1] + Op.RETF + Op.PUSH1[1] + Op.DUP2 + Op.SUB + Op.CALLF[1] + Op.DUP2 + Op.MUL + Op.SWAP1 + Op.POP + Op.RETF, code_inputs=1, code_outputs=1, ), ] ), data=Hash(n), container_post=Account(storage={0: result}), ) @pytest.mark.parametrize( "n,result", ((0, 1), (1, 1), (13, 233), (27, 196418)), ) def test_callf_fibonacci(eof_state_test: EOFStateTestFiller, n: int, result: int) -> None: """ Test fibonacci sequence implementation with recursive CALLF instructions. """ eof_state_test( container=Container( sections=[ Section.Code( Op.SSTORE(0, Op.CALLF[1](Op.CALLDATALOAD(0))) + Op.STOP, ), Section.Code( Op.PUSH1[2] + Op.DUP2 + Op.GT + Op.RJUMPI[4] + Op.POP + Op.PUSH1[1] + Op.RETF + Op.PUSH1[2] + Op.DUP2 + Op.SUB + Op.CALLF[1] + Op.PUSH1[1] + Op.DUP3 + Op.SUB + Op.CALLF[1] + Op.ADD + Op.SWAP1 + Op.POP + Op.RETF, code_inputs=1, code_outputs=1, ), ] ), gas_limit=15_000_000, data=Hash(n), container_post=Account(storage={0: result}), ) @pytest.mark.parametrize( "container", ( Container( name="callf_sub_retf", sections=[ Section.Code( Op.SSTORE( slot_code_worked, Op.CALLF[1](value_code_worked + 1, 1), ) + Op.STOP, max_stack_increase=2, ), Section.Code( Op.SUB + Op.RETF, code_inputs=2, code_outputs=1, ), ], ), Container( name="max_code_sections_retf2", sections=[ Section.Code( Op.CALLF[1] + Op.SSTORE + Op.STOP, ) ] + [ Section.Code( Op.CALLF[i] + Op.RETF, code_outputs=2, max_stack_increase=2, ) for i in range(2, 1024) ] + [ Section.Code( Op.PUSH2[value_code_worked] + Op.PUSH1[slot_code_worked] + Op.RETF, code_outputs=2, ), ], ), Container( name="multiple_sections_of_different_types", # EOF1V4750_0005 sections=[ Section.Code( Op.PUSH0 + Op.CALLF[1] + Op.CALLF[2] + Op.PUSH0 + Op.CALLF[3] + Op.SSTORE + Op.STOP, max_stack_increase=4, ), Section.Code( Op.POP + Op.RETF, code_inputs=1, code_outputs=0, ), Section.Code( Op.PUSH2[value_code_worked] + Op.RETF, code_outputs=1, ), Section.Code( Op.DUP2 + Op.PUSH2[slot_code_worked] + Op.RETF, code_inputs=2, code_outputs=4, ), ], ), ), ids=lambda x: x.name, ) def test_callf(eof_state_test: EOFStateTestFiller, container: Container) -> None: """Test basic usage of CALLF and RETF instructions.""" eof_state_test( container=container, container_post=Account(storage={slot_code_worked: value_code_worked}), ) @pytest.mark.parametrize( "container", ( Container( name="no_inputs", sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.PUSH0 + Op.POP + Op.RETF, code_outputs=0, ), ], ), Container( name="with_inputs", sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.PUSH0 + Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_increase=1, ), ], ), Container( name="at_callf", sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.CALLF[2] + # stack has 1024 items Op.POP + Op.RETF, code_outputs=0, ), Section.Code( Op.PUSH0 + Op.RETF, # stack has 1024 items code_outputs=1, ), ], ), Container( name="at_push0", sections=[ Section.Code( code=Op.PUSH0 * 1022 + Op.CALLF[1] + Op.POP * 1022 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.PUSH0 + # stack has 1023 items Op.CALLF[2] + Op.POP + Op.RETF, code_outputs=0, ), Section.Code( Op.PUSH0 + # stack has 1024 items Op.POP + Op.RETF, code_outputs=0, ), ], ), Container( name="nested_with_inputs_at_push0", sections=[ Section.Code( code=Op.PUSH0 * 1022 + Op.CALLF[1] + Op.POP * 1022 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.PUSH0 + # Stack has 1023 items Op.CALLF[2] + Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_increase=1, ), Section.Code( Op.PUSH0 + # Stack has 1024 items Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_increase=1, ), ], ), Container( name="store_value_unmodified_by_callf", sections=[ Section.Code( Op.PUSH2[value_code_worked] # to be stored after CALLF + Op.PUSH0 # input to CALLF + Op.CALLF[1] + Op.PUSH1[slot_code_worked] + Op.SSTORE + Op.STOP, max_stack_increase=2, ), Section.Code( Op.POP # clear input + Op.PUSH0 * 1023 # reach max stack height + Op.POP * 1023 + Op.RETF, # return nothing code_inputs=1, code_outputs=0, ), ], ), Container( name="with_rjumpi", sections=[ Section.Code( Op.PUSH1[1] # input[1] to CALLF + Op.PUSH0 # input[0] to CALLF + Op.CALLF[1] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, max_stack_increase=2, ), Section.Code( Op.POP # clear input[0] + Op.RJUMPI[2 * 1023] # jump to RETF based on input[1] + Op.PUSH0 * 1023 # reach max stack height + Op.POP * 1023 + Op.RETF, # return nothing code_inputs=2, code_outputs=0, ), ], ), ), ids=lambda x: x.name, ) def test_callf_operand_stack_size_max( eof_state_test: EOFStateTestFiller, container: Container ) -> None: """Test operand stack reaching 1024 items.""" eof_state_test( container=container, container_post=Account(storage={slot_code_worked: value_code_worked}), ) @pytest.mark.parametrize( "container", ( Container( name="no_inputs", sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.PUSH0 # Stack has 1024 items + Op.CALLF[2] + Op.POP + Op.RETF, code_outputs=0, ), Section.Code( Op.PUSH0 # Runtime stack overflow + Op.POP + Op.RETF, code_outputs=0, ), ], ), Container( name="with_inputs", sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.PUSH0 # Stack has 1024 items + Op.CALLF[2] + Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_increase=1, ), Section.Code( Op.PUSH0 # Runtime stackoverflow + Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_increase=1, ), ], ), ), ids=lambda x: x.name, ) def test_callf_operand_stack_overflow( eof_state_test: EOFStateTestFiller, container: Container ) -> None: """Test stack overflowing 1024 items in called function.""" eof_state_test( container=container, container_post=Account(storage={slot_code_worked: 0}), ) @pytest.mark.parametrize( ("stack_height", "failure"), ( pytest.param(1020, False, id="no_overflow"), pytest.param(1021, True, id="with_overflow"), ), ) def test_callf_sneaky_stack_overflow( stack_height: int, failure: bool, state_test: StateTestFiller, pre: Alloc, ) -> None: """ CALLF where a normal execution would not overflow, but EIP-4750 CALLF rule #3 triggers. Code Section 0 - Mostly fills the stack Code Section 1 - jumper to 2, so container verification passes (we want a runtime failure) Code Section 2 - Could require too much stack, but doesn't as it JUMPFs to 3 Code Section 3 - Writes canary values The intent is to catch implementations of CALLF that don't enforce rule #3 """ env = Environment() sender = pre.fund_eoa() inputs = 1 outputs = 3 contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.PUSH0 * stack_height + Op.CALLF[1] + Op.POP * stack_height + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), max_stack_increase=stack_height + outputs - inputs, ), Section.Code( Op.CALLF[2] + Op.POP + Op.RETF, code_inputs=inputs, code_outputs=outputs, max_stack_increase=outputs - inputs + 1, ), Section.Code( Op.RJUMPI[4] + Op.PUSH0 + Op.JUMPF[3] + Op.PUSH0 * (outputs - inputs + 3) + Op.POP + Op.RETF, code_inputs=inputs, code_outputs=outputs + 1, max_stack_increase=outputs - inputs + 2, ), Section.Code( Op.POP * inputs + Op.SSTORE(slot_stack_canary, value_canary_written) + Op.PUSH0 * (outputs + 1) + Op.RETF, code_inputs=inputs, code_outputs=outputs + 1, max_stack_increase=outputs - inputs + 1, ), ], ), storage={ slot_code_worked: ( value_canary_should_not_change if failure else value_canary_to_be_overwritten ), slot_stack_canary: ( value_canary_should_not_change if failure else value_canary_to_be_overwritten ), }, ) post = { contract_address: Account( storage={ slot_code_worked: ( value_canary_should_not_change if failure else value_code_worked ), slot_stack_canary: ( value_canary_should_not_change if failure else value_canary_written ), } ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize( ("stack_height", "failure"), ( pytest.param(1018, False, id="no_max_stack"), pytest.param(1019, False, id="with_max_stack"), pytest.param(1020, True, id="over_max_stack"), ), ) def test_callf_max_stack( stack_height: int, failure: bool, state_test: StateTestFiller, pre: Alloc, ) -> None: """ CALLF where a normal execution would not overflow, but EIP-4750 CALLF rule #4 triggers. Code Section 0 - calls #1 with the configured height, but we load some operands so the return stack does not overflow Code Section 1 - expands stack, calls #2, THEN recursively calls itself until input is zero, and returns. Code Section 2 - Just returns, zero inputs, zero outputs This will catch CALLF execution rule #3: always fail if the operand stack is full. Not checking rule 3 results in a call to section 2 and not overfilling the stack (as it is just RETF). """ env = Environment() sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.PUSH0 * 4 # fill the stack up a little bit + Op.PUSH2(stack_height) + Op.CALLF[1] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), ), Section.Code( Op.PUSH1(1) # arg, 1 + Op.SWAP1 # 1, arg + Op.SUB # arg-1, + Op.DUP1 # arg-1, arg-1 + Op.CALLF[2] # arg-1, arg-1 + Op.ISZERO # jump?, arg-1, + Op.RJUMPI[5] # arg-1 + Op.DUP1 # arg-1, arg-1 + Op.CALLF[1] # ret, arg-1 + Op.POP # arg-1 + Op.RETF, code_inputs=1, code_outputs=1, ), Section.Code( Op.RETF, code_outputs=0, ), ], ), storage={ slot_code_worked: ( value_canary_should_not_change if failure else value_canary_to_be_overwritten ), }, ) post = { contract_address: Account( storage={ slot_code_worked: ( value_canary_should_not_change if failure else value_code_worked ), } ) } tx = Transaction( to=contract_address, gas_limit=100_000, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_callf_retf_memory_context( state_test: StateTestFiller, pre: Alloc, ) -> None: """Verifies CALLF and RETF don't corrupt memory.""" env = Environment() storage = Storage() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( Op.SSTORE(storage.store_next(value_code_worked), value_code_worked) + Op.MSTORE(0, 1) + Op.CALLF[1] + Op.SSTORE(storage.store_next(64), Op.MSIZE()) + Op.SSTORE(storage.store_next(2), Op.MLOAD(0)) + Op.SSTORE(storage.store_next(3), Op.MLOAD(32)) + Op.STOP, ), Section.Code( Op.SSTORE(storage.store_next(32), Op.MSIZE()) + Op.SSTORE(storage.store_next(1), Op.MLOAD(0)) + Op.MSTORE(0, 2) + Op.MSTORE(32, 3) + Op.RETF, code_outputs=0, ), ], ), ) post = { contract_address: Account(storage=storage), } tx = Transaction( to=contract_address, gas_limit=500_000, sender=pre.fund_eoa(), ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_subcontainer_validation.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_subcontainer_validation.py
"""EOF Subcontainer tests covering simple cases.""" import pytest from ethereum_test_tools import Account, EOFException, EOFStateTestFiller, EOFTestFiller from ethereum_test_types.eof.v1 import Container, ContainerKind, Section from ethereum_test_types.eof.v1.constants import MAX_BYTECODE_SIZE, MAX_INITCODE_SIZE from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import slot_code_worked, value_code_worked REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7620.md" REFERENCE_SPEC_VERSION = "52ddbcdddcf72dd72427c319f2beddeb468e1737" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) eofcreate_code_section = Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, max_stack_height=4, ) eofcreate_revert_code_section = Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.REVERT(0, 0), ) returncode_code_section = Section.Code( code=Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURNCODE[0](0, 0), max_stack_height=2, ) stop_container = Container.Code(Op.STOP) stop_sub_container = Section.Container(stop_container) return_sub_container = Section.Container(Container.Code(Op.RETURN(0, 0))) revert_sub_container = Section.Container(Container.Code(Op.REVERT(0, 0))) abort_sub_container = Section.Container(Container.Code(Op.INVALID)) returncode_sub_container = Section.Container( Container( sections=[ Section.Code(Op.RETURNCODE[0](0, 0)), stop_sub_container, ], ) ) def test_simple_create_from_deployed( eof_state_test: EOFStateTestFiller, ) -> None: """Simple EOF creation from a deployed EOF container.""" eof_state_test( container=Container( sections=[ eofcreate_code_section, returncode_sub_container, ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_simple_create_from_creation( eof_state_test: EOFStateTestFiller, ) -> None: """Simple EOF creation from a create transaction container.""" eof_state_test( container=Container( sections=[ returncode_code_section, stop_sub_container, ], kind=ContainerKind.INITCODE, ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) @pytest.mark.parametrize( "zero_section", [eofcreate_code_section, returncode_code_section], ids=["eofcreate", "returncode"], ) def test_reverting_container( eof_state_test: EOFStateTestFiller, zero_section: Container, ) -> None: """Test revert containers.""" eof_state_test( container=Container( sections=[ zero_section, revert_sub_container, ], kind=( ContainerKind.INITCODE if zero_section == returncode_code_section else ContainerKind.RUNTIME ), ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) @pytest.mark.parametrize( "code_section,first_sub_container,container_kind", [ (eofcreate_code_section, returncode_sub_container, ContainerKind.RUNTIME), (returncode_code_section, stop_sub_container, ContainerKind.INITCODE), ], ids=["eofcreate", "returncode"], ) @pytest.mark.parametrize( "extra_sub_container", [stop_sub_container, revert_sub_container, returncode_sub_container], ids=["stop", "revert", "returncode"], ) def test_orphan_container( eof_test: EOFTestFiller, code_section: Section, first_sub_container: Container, extra_sub_container: Container, container_kind: ContainerKind, ) -> None: """Test orphaned containers.""" eof_test( container=Container( sections=[ code_section, first_sub_container, extra_sub_container, ], kind=container_kind, ), expect_exception=EOFException.ORPHAN_SUBCONTAINER, ) @pytest.mark.parametrize( "code_section,sub_container,container_kind", [ pytest.param( eofcreate_code_section, returncode_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_RETURNCODE", ), pytest.param( returncode_code_section, stop_sub_container, ContainerKind.INITCODE, id="RETURNCODE_STOP", ), pytest.param( returncode_code_section, return_sub_container, ContainerKind.INITCODE, id="RETURNCODE_RETURN", ), pytest.param( eofcreate_code_section, revert_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_REVERT", ), pytest.param( returncode_code_section, revert_sub_container, ContainerKind.INITCODE, id="RETURNCODE_REVERT", ), ], ) def test_container_combos_valid( eof_state_test: EOFStateTestFiller, code_section: Section, sub_container: Container, container_kind: ContainerKind, ) -> None: """Test valid subcontainer reference / opcode combos.""" eof_state_test( container=Container( sections=[ code_section, sub_container, ], kind=container_kind, ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) @pytest.mark.parametrize( "code_section,first_sub_container,container_kind", [ pytest.param( eofcreate_code_section, stop_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_STOP", ), pytest.param( eofcreate_code_section, return_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_RETURN", ), pytest.param( returncode_code_section, returncode_sub_container, ContainerKind.INITCODE, id="RETURNCODE_RETURNCODE", ), ], ) def test_container_combos_invalid( eof_test: EOFTestFiller, code_section: Section, first_sub_container: Container, container_kind: ContainerKind, ) -> None: """Test invalid subcontainer reference / opcode combos.""" eof_test( container=Container( sections=[ code_section, first_sub_container, ], kind=container_kind, ), expect_exception=EOFException.INCOMPATIBLE_CONTAINER_KIND, ) @pytest.mark.parametrize( "code_section,first_sub_container", [ pytest.param( eofcreate_revert_code_section, returncode_sub_container, id="EOFCREATE_RETURNCODE", ), pytest.param( returncode_code_section, stop_sub_container, id="RETURNCODE_STOP", ), pytest.param( returncode_code_section, return_sub_container, id="RETURNCODE_RETURN", ), pytest.param( eofcreate_revert_code_section, revert_sub_container, id="EOFCREATE_REVERT", ), pytest.param( returncode_code_section, revert_sub_container, id="RETURNCODE_REVERT", ), ], ) def test_container_combos_deeply_nested_valid( eof_test: EOFTestFiller, code_section: Section, first_sub_container: Container, ) -> None: """ Test valid subcontainer reference / opcode combos on a deep container nesting level. """ valid_container = Container( sections=[ code_section, first_sub_container, ], kind=ContainerKind.INITCODE, ) container = valid_container while len(container) < MAX_BYTECODE_SIZE: container = Container( sections=[ eofcreate_revert_code_section, Section.Container(container=container.copy()), ], kind=ContainerKind.INITCODE, ) eof_test( container=container, deployed_container=None, # Execution reverts before deployment ) @pytest.mark.parametrize( "code_section,first_sub_container", [ pytest.param( eofcreate_revert_code_section, stop_sub_container, id="EOFCREATE_STOP", ), pytest.param( eofcreate_revert_code_section, return_sub_container, id="EOFCREATE_RETURN", ), pytest.param( returncode_code_section, returncode_sub_container, id="RETURNCODE_RETURNCODE", ), ], ) def test_container_combos_deeply_nested_invalid( eof_test: EOFTestFiller, code_section: Section, first_sub_container: Container, ) -> None: """ Test invalid subcontainer reference / opcode combos on a deep container nesting level. """ invalid_container = Container( sections=[ code_section, first_sub_container, ], kind=ContainerKind.INITCODE, ) container = invalid_container while len(container) < MAX_BYTECODE_SIZE: container = Container( sections=[ eofcreate_revert_code_section, Section.Container(container=container.copy()), ], kind=ContainerKind.INITCODE, ) eof_test( container=container, expect_exception=EOFException.INCOMPATIBLE_CONTAINER_KIND, ) @pytest.mark.parametrize( "code_section,first_sub_container,container_kind", [ pytest.param( eofcreate_code_section, returncode_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_RETURNCODE", ), pytest.param( returncode_code_section, stop_sub_container, ContainerKind.INITCODE, id="RETURNCODE_STOP", ), pytest.param( returncode_code_section, return_sub_container, ContainerKind.INITCODE, id="RETURNCODE_RETURN", ), pytest.param( eofcreate_code_section, revert_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_REVERT", ), pytest.param( returncode_code_section, revert_sub_container, ContainerKind.INITCODE, id="RETURNCODE_REVERT", ), ], ) def test_container_combos_non_first_code_sections_valid( eof_test: EOFTestFiller, code_section: Section, first_sub_container: Container, container_kind: ContainerKind, ) -> None: """ Test valid subcontainer reference / opcode combos in a non-first code section. """ eof_test( container=Container( sections=[Section.Code(Op.JUMPF[i]) for i in range(1, 1024)] + [code_section, first_sub_container], kind=container_kind, ), ) @pytest.mark.parametrize( "code_section,first_sub_container,container_kind", [ pytest.param( eofcreate_code_section, stop_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_STOP", ), pytest.param( eofcreate_code_section, return_sub_container, ContainerKind.RUNTIME, id="EOFCREATE_RETURN", ), pytest.param( returncode_code_section, returncode_sub_container, ContainerKind.INITCODE, id="RETURNCODE_RETURNCODE", ), ], ) def test_container_combos_non_first_code_sections_invalid( eof_test: EOFTestFiller, code_section: Section, first_sub_container: Container, container_kind: ContainerKind, ) -> None: """ Test invalid subcontainer reference / opcode combos in a non-first code section. """ eof_test( container=Container( sections=[Section.Code(Op.JUMPF[i]) for i in range(1, 1024)] + [code_section, first_sub_container], kind=container_kind, ), expect_exception=EOFException.INCOMPATIBLE_CONTAINER_KIND, ) def test_container_both_kinds_same_sub(eof_test: EOFTestFiller) -> None: """ Test subcontainer conflicts (both EOFCREATE and RETURNCODE Reference). """ eof_test( container=Container( sections=[ Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.JUMPF[1], ), Section.Code( code=Op.RETURNCODE[0](0, 0), ), revert_sub_container, ], ), expect_exception=EOFException.INCOMPATIBLE_CONTAINER_KIND, ) @pytest.mark.parametrize("container_idx", [0, 1, 255]) @pytest.mark.parametrize( "sub_container", [ pytest.param(abort_sub_container, id="abort"), pytest.param(revert_sub_container, id="revert"), ], ) def test_container_ambiguous_kind( eof_test: EOFTestFiller, container_idx: int, sub_container: Section ) -> None: """ Test ambiguous container kind: a single subcontainer reference by both EOFCREATE and RETURNCODE. """ sections = [ Section.Code( code=( sum(Op.EOFCREATE[i](0, 0, 0, 0) for i in range(container_idx)) + Op.EOFCREATE[container_idx](0, 0, 0, 0) + Op.RETURNCODE[container_idx](0, 0) ), ), ] sections += (container_idx + 1) * [sub_container] eof_test( container=Container( sections=sections, kind=ContainerKind.INITCODE, ), expect_exception=EOFException.AMBIGUOUS_CONTAINER_KIND, ) def test_container_both_kinds_different_sub(eof_test: EOFTestFiller) -> None: """Test multiple kinds of subcontainer at the same level.""" eof_test( container=Container( sections=[ Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.JUMPF[1], ), Section.Code( code=Op.RETURNCODE[1](0, 0), ), returncode_sub_container, stop_sub_container, ], kind=ContainerKind.INITCODE, ), deployed_container=stop_container, ) def test_container_multiple_eofcreate_references(eof_test: EOFTestFiller) -> None: """ Test multiple references to the same subcontainer from an EOFCREATE operation. """ eof_test( container=Container( sections=[ Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP, ), returncode_sub_container, ], ), ) def test_container_multiple_returncode_references(eof_test: EOFTestFiller) -> None: """ Test multiple references to the same subcontainer from a RETURNCONTACT operation. """ eof_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.CALLDATALOAD + Op.RJUMPI[6] + Op.RETURNCODE[0](0, 0) + Op.RETURNCODE[0](0, 0) ), stop_sub_container, ], kind=ContainerKind.INITCODE, ), ) @pytest.mark.parametrize("version", [0, 255], ids=lambda x: x) def test_subcontainer_wrong_eof_version( eof_test: EOFTestFiller, version: int, ) -> None: """Test a subcontainer with the incorrect EOF version.""" eof_test( container=Container( sections=[ Section.Code( code=Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP, ), Section.Container( container=Container(version=[version], sections=[Section.Code(code=Op.STOP)]) ), ], kind=ContainerKind.RUNTIME, ), expect_exception=EOFException.INVALID_VERSION, ) @pytest.mark.parametrize("delta", [-1, 1], ids=["smaller", "larger"]) @pytest.mark.parametrize("kind", [ContainerKind.RUNTIME, ContainerKind.INITCODE]) def test_subcontainer_wrong_size( eof_test: EOFTestFiller, delta: int, kind: ContainerKind, ) -> None: """Test a subcontainer with the incorrect size in the parent's header.""" eof_test( container=Container( sections=[ Section.Code( code=(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP) if kind == ContainerKind.RUNTIME else (Op.RETURNCODE[0](0, 0)), ), Section.Container( container=Container(sections=[Section.Code(code=Op.STOP)]), custom_size=len(stop_sub_container.data) + delta, ), ], kind=kind, ), expect_exception=EOFException.INVALID_SECTION_BODIES_SIZE, ) deep_container_parametrize = pytest.mark.parametrize( ["deepest_container", "exception"], [ pytest.param(Container.Code(Op.STOP), None, id="valid"), pytest.param( Container.Code(code=Op.PUSH0), EOFException.MISSING_STOP_OPCODE, id="code-error", ), pytest.param( Container(raw_bytes="EF0100A94F5374FCE5EDBC8E2A8697C15331677E6EBF0B"), EOFException.INVALID_MAGIC, id="structure-error", ), ], ) @deep_container_parametrize @pytest.mark.eof_test_only(reason="Initcontainer exceeds maximum") def test_deep_container( eof_test: EOFTestFiller, deepest_container: Container, exception: EOFException | None ) -> None: """ Test a very deeply nested container. This test skips generating a state test because the initcode size is too large. """ container = deepest_container last_container = deepest_container while len(container) < MAX_INITCODE_SIZE: last_container = container container = Container( sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.EOFCREATE[0] + Op.STOP, ), Section.Container( container=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.RETURNCODE[0], ), Section.Container(container=last_container), ] ) ), ], ) eof_test(container=last_container, expect_exception=exception) @deep_container_parametrize def test_deep_container_initcode( eof_test: EOFTestFiller, deepest_container: Container, exception: EOFException | None ) -> None: """Test a very deeply nested initcontainer.""" container = Container( sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.RETURNCODE[0], ), Section.Container(container=deepest_container), ], kind=ContainerKind.INITCODE, ) last_container = container while len(container) < MAX_INITCODE_SIZE: last_container = container container = Container( sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.RETURNCODE[0], ), Section.Container( container=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.PUSH0 + Op.EOFCREATE[0] + Op.STOP ), Section.Container(container=last_container), ] ) ), ], kind=ContainerKind.INITCODE, ) eof_test( container=last_container, expect_exception=exception, deployed_container=None, ) @pytest.mark.parametrize( ["width", "exception"], [ pytest.param(256, None, id="256"), pytest.param(257, EOFException.TOO_MANY_CONTAINERS, id="257"), pytest.param( 0x8000, EOFException.CONTAINER_SIZE_ABOVE_LIMIT, marks=pytest.mark.eof_test_only(reason="int too big to convert"), id="negative_i16", ), pytest.param( 0xFFFF, EOFException.CONTAINER_SIZE_ABOVE_LIMIT, marks=pytest.mark.eof_test_only(reason="int too big to convert"), id="max_u16", ), ], ) def test_wide_container(eof_test: EOFTestFiller, width: int, exception: EOFException) -> None: """Test a container with the maximum number of sub-containers.""" create_code: Bytecode = Op.STOP for x in range(0, 256): create_code = Op.EOFCREATE[x](0, 0, 0, 0) + create_code eof_test( container=Container( sections=[ Section.Code( code=create_code, ), *( [ Section.Container( container=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.RETURNCODE[0], ), stop_sub_container, ] ) ) ] * width ), ] ), expect_exception=exception, ) @pytest.mark.parametrize( "container", [ pytest.param( Container( sections=[ Section.Code( Op.CALLDATASIZE + Op.PUSH1[0] + Op.PUSH1[255] + Op.PUSH1[0] + Op.EOFCREATE[0] + Op.POP + Op.STOP ), abort_sub_container, ], expected_bytecode=""" ef0001010004020001000b03000100000014ff0000000080000436600060ff6000ec005000ef000101000402 00010001ff00000000800000fe""", ), id="eofcreate_0", ), pytest.param( Container( sections=[ Section.Code(Op.PUSH1[0] + Op.RJUMP[0] + Op.STOP), abort_sub_container, ], expected_bytecode=""" ef0001010004020001000603000100000014ff000000008000016000e0000000ef000101000402000100 01ff00000000800000fe""", # Originally this test was "valid" because it was created # before "orphan subcontainer" rule was introduced. validity_error=EOFException.ORPHAN_SUBCONTAINER, ), id="orphan_subcontainer_0", ), pytest.param( Container( sections=[ Section.Code(Op.PUSH1[0] + Op.RJUMP[0] + Op.STOP), abort_sub_container, Section.Data(custom_size=2), ], expected_bytecode=""" ef0001010004020001000603000100000014ff000200008000016000e0000000ef000101000402000100 01ff00000000800000fe""", # Originally this test was "valid" but against the current spec # it contains two errors: data section truncated and orphan # subcontainer. validity_error=EOFException.TOPLEVEL_CONTAINER_TRUNCATED, ), id="orphan_subcontainer_0_and_truncated_data", ), pytest.param( Container( sections=[ Section.Code(Op.PUSH1[0] + Op.RJUMP[0] + Op.STOP), abort_sub_container, Section.Data("aabb"), ], expected_bytecode=""" ef0001010004020001000603000100000014ff000200008000016000e0000000ef000101000402000100 01ff00000000800000feaabb""", # Originally this test was "valid" because it was created # before "orphan subcontainer" rule was introduced. validity_error=EOFException.ORPHAN_SUBCONTAINER, ), id="orphan_subcontainer_0_and_data", ), pytest.param( Container( sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container("aabbccddeeff"), ], # The original test has been modified to reference the # subcontainer by EOFCREATE. validity_error=EOFException.INVALID_MAGIC, ), id="subcontainer_0_with_invalid_prefix", ), pytest.param( Container( sections=[ Section.Code( Op.CALLDATASIZE + Op.PUSH1[0] + Op.PUSH1[255] + Op.PUSH1[0] + Op.EOFCREATE[1] + Op.POP + Op.STOP ) ] + 2 * [abort_sub_container], expected_bytecode=""" ef0001010004020001000b0300020000001400000014ff0000000080000436600060ff6000ec015000ef00010100 040200010001ff00000000800000feef00010100040200010001ff00000000800000fe""", # Originally this test was "valid" because it was created # before "orphan subcontainer" rule was introduced. validity_error=EOFException.ORPHAN_SUBCONTAINER, ), id="eofcreate_1_orphan_subcontainer_0", ), pytest.param( Container( sections=[ Section.Code(Op.PUSH1[0] + Op.RJUMP[0] + Op.STOP), abort_sub_container, Section.Container(Container.Code(Op.PUSH0 + Op.PUSH0 + Op.RETURN)), ], expected_bytecode=""" ef000101000402000100060300020000001400000016ff000000008000016000e0000000ef000101000402000100 01ff00000000800000feef00010100040200010003ff000000008000025f5ff3""", # Originally this test was "valid" because it was created # before "orphan subcontainer" rule was introduced. validity_error=EOFException.ORPHAN_SUBCONTAINER, ), id="two_orphan_subcontainers", ), pytest.param( Container( sections=[ Section.Code( Op.CALLDATASIZE + Op.PUSH1[0] + Op.PUSH1[255] + Op.PUSH1[0] + Op.EOFCREATE[255] + Op.POP + Op.STOP ) ] + 256 * [abort_sub_container], # Originally this test was "valid" because it was created # before "orphan subcontainer" rule was introduced. validity_error=EOFException.ORPHAN_SUBCONTAINER, ), id="eofcreate_255_max_orphan_subcontainers", ), pytest.param( Container( sections=[Section.Code(Op.PUSH1[0] + Op.RJUMP[0] + Op.STOP)] + 256 * [abort_sub_container], # Originally this test was "valid" because it was created # before "orphan subcontainer" rule was introduced. validity_error=EOFException.ORPHAN_SUBCONTAINER, ), id="max_orphan_subcontainers", ), ], ) def test_migrated_eofcreate(eof_test: EOFTestFiller, container: Container) -> None: """Tests migrated from EOFTests/efValidation/EOF1_eofcreate_valid_.json.""" eof_test(container=container, expect_exception=container.validity_error) def test_dangling_initcode_subcontainer_bytes( eof_test: EOFTestFiller, ) -> None: """ Initcode mode EOF Subcontainer test with subcontainer containing dangling bytes. """ eof_test( container=Container( sections=[ returncode_code_section, Section.Container( container=Container( raw_bytes=stop_sub_container.data + b"\x99", ), ), ], kind=ContainerKind.INITCODE, ), expect_exception=EOFException.INVALID_SECTION_BODIES_SIZE, ) def test_dangling_runtime_subcontainer_bytes( eof_test: EOFTestFiller, ) -> None: """ Runtime mode EOF Subcontainer test with subcontainer containing dangling bytes. """ eof_test( container=Container( sections=[ eofcreate_code_section, Section.Container( container=Container( raw_bytes=returncode_sub_container.data + b"\x99", ), ), ], ), expect_exception=EOFException.INVALID_SECTION_BODIES_SIZE, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_returncode.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_returncode.py
"""Tests for RETURNCODE instruction validation.""" import pytest from ethereum_test_base_types import Account from ethereum_test_specs import StateTestFiller from ethereum_test_tools import Alloc, EOFException, EOFTestFiller from ethereum_test_types import Environment, Transaction, compute_eofcreate_address from ethereum_test_types.eof.v1 import Container, ContainerKind, Section from ethereum_test_types.eof.v1.constants import MAX_BYTECODE_SIZE from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import ( slot_create_address, smallest_runtime_subcontainer, value_canary_to_be_overwritten, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7620.md" REFERENCE_SPEC_VERSION = "f20b164b00ae5553f7536a6d7a83a0f254455e09" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def test_returncode_valid_index_0( eof_test: EOFTestFiller, ) -> None: """Deploy container index 0.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container(container=Container(sections=[Section.Code(code=Op.INVALID)])), ], ), ) def test_returncode_valid_index_1( eof_test: EOFTestFiller, ) -> None: """Deploy container index 1.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( code=Op.RJUMPI[6](0) + Op.RETURNCODE[0](0, 0) + Op.RETURNCODE[1](0, 0), max_stack_height=2, ), Section.Container(container=Container(sections=[Section.Code(code=Op.INVALID)])), Section.Container(container=Container(sections=[Section.Code(code=Op.INVALID)])), ], ), ) def test_returncode_valid_index_255( eof_test: EOFTestFiller, ) -> None: """Deploy container index 255.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( sum((Op.RJUMPI[6](0) + Op.RETURNCODE[i](0, 0)) for i in range(256)) + Op.REVERT(0, 0), max_stack_height=2, ) ] + [Section.Container(container=Container(sections=[Section.Code(code=Op.INVALID)]))] * 256 ), ) def test_returncode_invalid_truncated_immediate( eof_test: EOFTestFiller, ) -> None: """Truncated immediate.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( code=Op.PUSH0 + Op.PUSH0 + Op.RETURNCODE, ), ], ), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) def test_returncode_invalid_index_0( eof_test: EOFTestFiller, ) -> None: """Referring to non-existent container section index 0.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), ], ), expect_exception=EOFException.INVALID_CONTAINER_SECTION_INDEX, ) def test_returncode_invalid_index_1( eof_test: EOFTestFiller, ) -> None: """Referring to non-existent container section index 1.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( code=Op.RETURNCODE[1](0, 0), ), Section.Container(container=Container(sections=[Section.Code(code=Op.INVALID)])), ], ), expect_exception=EOFException.INVALID_CONTAINER_SECTION_INDEX, ) def test_returncode_invalid_index_255( eof_test: EOFTestFiller, ) -> None: """Referring to non-existent container section index 255.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( code=Op.RETURNCODE[255](0, 0), ), Section.Container(container=Container(sections=[Section.Code(code=Op.INVALID)])), ], ), expect_exception=EOFException.INVALID_CONTAINER_SECTION_INDEX, ) def test_returncode_terminating( eof_test: EOFTestFiller, ) -> None: """Unreachable code after RETURNCODE.""" eof_test( container_kind=ContainerKind.INITCODE, container=Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0) + Op.REVERT(0, 0), ), Section.Container(container=Container(sections=[Section.Code(code=Op.INVALID)])), ], ), expect_exception=EOFException.UNREACHABLE_INSTRUCTIONS, ) @pytest.mark.parametrize( "offset_field", [ pytest.param(True, id="offset"), pytest.param(False, id="size"), ], ) @pytest.mark.parametrize( ("test_arg", "success"), [ pytest.param(0, True, id="zero"), pytest.param(0xFF, True, id="8-bit"), pytest.param(0x100, True, id="9-bit"), pytest.param(0xFFFF, True, id="16-bit"), pytest.param(0x10000, True, id="17-bit"), pytest.param(0x1FFFF20, False, id="32-bit-mem-cost"), pytest.param(0x2D412E0, False, id="33-bit-mem-cost"), pytest.param(0xFFFFFFFF, False, id="32-bit"), pytest.param(0x100000000, False, id="33-bit"), pytest.param(0x1FFFFFFFF20, False, id="64-bit-mem-cost"), pytest.param(0x2D413CCCF00, False, id="65-bit-mem-cost"), pytest.param(0xFFFFFFFFFFFFFFFF, False, id="64-bit"), pytest.param(0x10000000000000000, False, id="65-bit"), pytest.param(0xFFFFFFFFFFFFFFFF, False, id="128-bit"), pytest.param(0x10000000000000000, False, id="129-bit"), pytest.param(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, False, id="256-bit"), ], ) def test_returncode_memory_expansion( state_test: StateTestFiller, pre: Alloc, offset_field: str, test_arg: int, success: bool, ) -> None: """ Attempts an EOFCREATE with a possibly too-large auxdata. Create either fails due to gas or contract too large, resulting in address or zero on failure in the create address slot. The name id of `*-mem-cost` refers to the bit-length of the result of the calculated memory expansion cost. Their length choice is designed to cause problems on shorter bit-length representations with native integers. The `offset_field` param indicates what part of the input data arguments are being tested, either the offset of the data in memory or the size of the data in memory. The `test_arg` param is the value passed into the field being tested (offset or size), intending to trigger integer size bugs for that particular field. """ env = Environment(gas_limit=2_000_000_000) sender = pre.fund_eoa(10**27) eof_size_acceptable = offset_field or test_arg < MAX_BYTECODE_SIZE mem_size_initcode_container = Container( sections=[ Section.Code( code=Op.RETURNCODE[0]( auxdata_offset=test_arg if offset_field else 32, auxdata_size=32 if offset_field else test_arg, ) ), Section.Container(container=smallest_runtime_subcontainer), ], ) contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.STOP, ), Section.Container(container=mem_size_initcode_container), ], ), storage={ slot_create_address: value_canary_to_be_overwritten, }, ) # Storage in 0 should have the address, post = { contract_address: Account( storage={ slot_create_address: compute_eofcreate_address(contract_address, 0) if success and eof_size_acceptable else 0, } ) } tx = Transaction( to=contract_address, gas_limit=2_000_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_legacy_eof_creates.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_legacy_eof_creates.py
"""Test interactions between CREATE, CREATE2, and EOFCREATE.""" import pytest from ethereum_test_base_types.base_types import Address, Bytes from ethereum_test_tools import ( Account, Alloc, Environment, StateTestFiller, Transaction, ) from ethereum_test_tools import Initcode as LegacyInitcode from ethereum_test_types.eof.v1 import Container from ethereum_test_types.helpers import compute_create_address from ethereum_test_vm import Opcodes from ethereum_test_vm import Opcodes as Op from ....prague.eip7702_set_code_tx.spec import Spec from .. import EOF_FORK_NAME from .helpers import ( slot_all_subcall_gas_gone, slot_code_worked, slot_create_address, smallest_initcode_subcontainer, smallest_runtime_subcontainer, value_code_worked, ) from .spec import EOFCREATE_FAILURE REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7620.md" REFERENCE_SPEC_VERSION = "52ddbcdddcf72dd72427c319f2beddeb468e1737" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "legacy_create_opcode", [ pytest.param(Op.CREATE, id="CREATE"), pytest.param(Op.CREATE2, id="CREATE2"), ], ) @pytest.mark.parametrize( "initcode", [ Bytes("0xEF00"), Bytes("0xEF0001"), pytest.param(smallest_initcode_subcontainer, id="deploy_eof_initcontainer"), pytest.param(smallest_runtime_subcontainer, id="deploy_eof_container"), ], ) def test_cross_version_creates_fail_light( state_test: StateTestFiller, pre: Alloc, legacy_create_opcode: Opcodes, initcode: Bytes | Container, ) -> None: """ Verifies that CREATE and CREATE2 cannot run EOF initcodes and fail early on attempt. """ env = Environment() sender = pre.fund_eoa() tx_gas_limit = 10_000_000 contract_address = pre.deploy_contract( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_create_address, legacy_create_opcode(size=Op.CALLDATASIZE)) # Approximates whether code until here consumed the 63/64th gas given # to subcall + Op.SSTORE(slot_all_subcall_gas_gone, Op.LT(Op.GAS, tx_gas_limit // 64)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) post = { contract_address: Account( storage={ slot_create_address: EOFCREATE_FAILURE, slot_code_worked: value_code_worked, slot_all_subcall_gas_gone: 0, }, nonce=1, ), # Double check no accounts were created compute_create_address(address=contract_address, nonce=1): Account.NONEXISTENT, compute_create_address( address=contract_address, initcode=initcode, salt=0, opcode=Op.CREATE2 ): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=tx_gas_limit, sender=sender, data=initcode, ) state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "legacy_create_opcode", [ pytest.param(Op.CREATE, id="CREATE"), pytest.param(Op.CREATE2, id="CREATE2"), ], ) @pytest.mark.parametrize( "initcode", [ Bytes("0xEF"), Bytes("0xEF01"), Bytes("0xEF0101"), Spec.delegation_designation(Address(0xAA)), Bytes("0xEF02"), ], ) def test_cross_version_creates_fail_hard( state_test: StateTestFiller, pre: Alloc, legacy_create_opcode: Opcodes, initcode: Bytes, ) -> None: """ Verifies that CREATE and CREATE2 fail hard on attempt to run initcode starting with `EF` but not `EF00`. """ env = Environment() sender = pre.fund_eoa() tx_gas_limit = 10_000_000 contract_address = pre.deploy_contract( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_create_address, legacy_create_opcode(size=Op.CALLDATASIZE)) # Approximates whether code until here consumed the 63/64th gas given # to subcall + Op.SSTORE(slot_all_subcall_gas_gone, Op.LT(Op.GAS, tx_gas_limit // 64)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) post = { contract_address: Account( storage={ slot_create_address: EOFCREATE_FAILURE, slot_code_worked: value_code_worked, slot_all_subcall_gas_gone: 1, }, nonce=2, ), # Double check no accounts were created compute_create_address(address=contract_address, nonce=1): Account.NONEXISTENT, compute_create_address( address=contract_address, initcode=initcode, salt=0, opcode=Op.CREATE2 ): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=tx_gas_limit, sender=sender, data=initcode, ) state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "legacy_create_opcode", [ pytest.param(Op.CREATE, id="CREATE"), pytest.param(Op.CREATE2, id="CREATE2"), ], ) @pytest.mark.parametrize( "deploy_code", [ Bytes("0xEF"), Bytes("0xEF00"), Bytes("0xEF0001"), Bytes("0xEF01"), pytest.param(smallest_initcode_subcontainer, id="deploy_eof_initcontainer"), pytest.param(smallest_runtime_subcontainer, id="deploy_eof_container"), ], ) def test_legacy_initcode_eof_contract_fails( state_test: StateTestFiller, pre: Alloc, legacy_create_opcode: Opcodes, deploy_code: Bytes | Container, ) -> None: """ Verifies that legacy initcode cannot create EOF. This tests only ensures EIP-3541 behavior is kept, not altered by EIP-7620. """ env = Environment() init_code = LegacyInitcode(deploy_code=deploy_code) salt_param = [0] if legacy_create_opcode == Op.CREATE2 else [] factory_code = ( Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_create_address, legacy_create_opcode(0, 0, Op.CALLDATASIZE, *salt_param)) + Op.SSTORE(slot_code_worked, value_code_worked) ) sender = pre.fund_eoa() contract_address = pre.deploy_contract(code=factory_code) # Storage in 0 should be empty as the final CREATE filed # and 1 in 1 to show execution continued and did not halt post = { contract_address: Account( storage={slot_create_address: EOFCREATE_FAILURE, slot_code_worked: value_code_worked} ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, data=init_code, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/spec.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/spec.py
"""EOF V1 Constants used throughout all tests.""" EOFCREATE_FAILURE = 0
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_eofcreate_failures.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_eofcreate_failures.py
"""Test good and bad EOFCREATE cases.""" import pytest from ethereum_test_base_types.base_types import Address from ethereum_test_tools import ( Account, Alloc, Environment, StateTestFiller, Transaction, compute_eofcreate_address, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_BYTECODE_SIZE, MAX_INITCODE_SIZE from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from ..eip7069_extcall.spec import EXTCALL_FAILURE, EXTCALL_REVERT, LEGACY_CALL_FAILURE from .helpers import ( aborting_container, slot_call_or_create, slot_call_result, slot_code_should_fail, slot_code_worked, slot_counter, slot_create_address, slot_max_depth, slot_returndata, slot_returndata_size, smallest_initcode_subcontainer, smallest_runtime_subcontainer, value_canary_should_not_change, value_code_worked, ) from .spec import EOFCREATE_FAILURE REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7620.md" REFERENCE_SPEC_VERSION = "52ddbcdddcf72dd72427c319f2beddeb468e1737" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "revert", [ pytest.param(b"", id="empty"), pytest.param(b"\x08\xc3\x79\xa0", id="Error(string)"), ], ) def test_initcode_revert(state_test: StateTestFiller, pre: Alloc, revert: bytes) -> None: """Verifies proper handling of REVERT in initcode.""" env = Environment() revert_size = len(revert) initcode_subcontainer = Container( name="Initcode Subcontainer that reverts", sections=[ Section.Code( code=Op.MSTORE(0, Op.PUSH32(revert)) + Op.REVERT(32 - revert_size, revert_size), ), ], ) factory_contract = Container( name="factory contract", sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_returndata_size, Op.RETURNDATASIZE) + Op.RETURNDATACOPY(Op.SUB(32, Op.RETURNDATASIZE), 0, Op.RETURNDATASIZE) + Op.SSTORE(slot_returndata, Op.MLOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=initcode_subcontainer), ], ) sender = pre.fund_eoa() contract_address = pre.deploy_contract(code=factory_contract) post = { contract_address: Account( storage={ slot_create_address: EOFCREATE_FAILURE, slot_returndata_size: revert_size, slot_returndata: revert, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_initcode_aborts( state_test: StateTestFiller, pre: Alloc, ) -> None: """Verifies correct handling of a halt in EOF initcode.""" env = Environment() sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=aborting_container), ] ) ) # Storage in slot_create_address should not have the address, post = { contract_address: Account( storage={ slot_create_address: EOFCREATE_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) """ Size of the factory portion of test_eofcreate_deploy_sizes, but as the runtime code is dynamic, we have to use a pre-calculated size """ factory_size = 78 @pytest.mark.parametrize( "target_deploy_size", [ pytest.param(0x4000, id="large"), pytest.param(MAX_BYTECODE_SIZE, id="max"), pytest.param(MAX_BYTECODE_SIZE + 1, id="overmax"), pytest.param(MAX_INITCODE_SIZE - factory_size, id="initcodemax"), pytest.param( MAX_INITCODE_SIZE - factory_size + 1, id="initcodeovermax", marks=pytest.mark.skip("Oversized container in pre-alloc"), ), pytest.param( 0xFFFF - factory_size, id="64k-1", marks=pytest.mark.skip("Oversized container in pre-alloc"), ), ], ) def test_eofcreate_deploy_sizes( state_test: StateTestFiller, pre: Alloc, target_deploy_size: int, ) -> None: """ Verifies a mix of runtime contract sizes mixing success and multiple size failure modes. """ env = Environment() runtime_container = Container( sections=[ Section.Code( code=Op.JUMPDEST * (target_deploy_size - len(smallest_runtime_subcontainer)) + Op.STOP, ), ] ) initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container(container=runtime_container), ], ) factory_container = Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=initcode_subcontainer), ] ) assert factory_size == (len(factory_container) - len(runtime_container)), ( "factory_size is wrong, expected factory_size is %d, calculated is %d" % ( factory_size, len(factory_container) - len(runtime_container), ) ) sender = pre.fund_eoa() contract_address = pre.deploy_contract(code=factory_container) # Storage in 0 should have the address, Storage 1 is a canary of 1 to make # sure it tried to execute, which also covers cases of data+code being # greater than initcode_size_max, which is allowed. success = target_deploy_size <= MAX_BYTECODE_SIZE post = { contract_address: Account( storage={ slot_create_address: compute_eofcreate_address(contract_address, 0) if success else EOFCREATE_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account() if success else Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize( "target_deploy_size", [ pytest.param(0x4000, id="large"), pytest.param(MAX_BYTECODE_SIZE, id="max"), pytest.param(MAX_BYTECODE_SIZE + 1, id="overmax"), pytest.param(MAX_INITCODE_SIZE - factory_size, id="initcodemax"), pytest.param(MAX_INITCODE_SIZE - factory_size + 1, id="initcodeovermax"), pytest.param(0xFFFF - factory_size, id="64k-1"), ], ) @pytest.mark.skip("Not implemented") def test_eofcreate_deploy_sizes_tx( state_test: StateTestFiller, target_deploy_size: int, ) -> None: """ Verifies a mix of runtime contract sizes mixing success and multiple size failure modes where the initcontainer is included in a transaction. """ raise NotImplementedError("Not implemented") @pytest.mark.parametrize( "auxdata_size", [ pytest.param(MAX_BYTECODE_SIZE - len(smallest_runtime_subcontainer), id="maxcode"), pytest.param(MAX_BYTECODE_SIZE - len(smallest_runtime_subcontainer) + 1, id="overmaxcode"), pytest.param(0x10000 - 60, id="almost64k"), pytest.param(0x10000 - 1, id="64k-1"), pytest.param(0x10000, id="64k"), pytest.param(0x10000 + 1, id="over64k"), ], ) def test_auxdata_size_failures(state_test: StateTestFiller, pre: Alloc, auxdata_size: int) -> None: """ Exercises a number of auxdata size violations, and one maxcode success. """ env = Environment() auxdata_bytes = b"a" * auxdata_size initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.RETURNCODE[0](0, Op.CALLDATASIZE), ), Section.Container(container=smallest_runtime_subcontainer), ], ) sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_create_address, Op.EOFCREATE[0](input_size=Op.CALLDATASIZE)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=initcode_subcontainer), ] ) ) deployed_container_size = len(smallest_runtime_subcontainer) + auxdata_size # Storage in 0 will have address in first test, 0 in all other cases # indicating failure # # Storage 1 in 1 is a canary to see if EOFCREATE opcode # halted success = deployed_container_size <= MAX_BYTECODE_SIZE post = { contract_address: Account( storage={ slot_create_address: compute_eofcreate_address(contract_address, 0) if success else 0, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account() if success else Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, data=auxdata_bytes, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize( "value", [ pytest.param(1, id="1_wei"), pytest.param(10**9, id="1_gwei"), ], ) def test_eofcreate_insufficient_stipend( state_test: StateTestFiller, pre: Alloc, value: int, ) -> None: """ Exercises an EOFCREATE that fails because the calling account does not have enough ether to pay the stipend. """ env = Environment() initcode_container = Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](value=value)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=smallest_initcode_subcontainer), ] ) sender = pre.fund_eoa(10**11) contract_address = pre.deploy_contract( code=initcode_container, balance=value - 1, ) # create will fail but not trigger a halt, so canary at storage 1 should be # set # # also validate target created contract fails post = { contract_address: Account( storage={ slot_create_address: EOFCREATE_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_insufficient_initcode_gas( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Exercises an EOFCREATE when there is not enough gas for the initcode charge. """ env = Environment() initcode_data = b"a" * 0x5000 initcode_container = Container( name="Large Initcode Subcontainer", sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container(container=smallest_runtime_subcontainer), Section.Data(data=initcode_data), ], ) sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_should_fail, value_code_worked) + Op.STOP, ), Section.Container(container=initcode_container), ], ), storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ) # enough gas for everything but EVM opcodes and EIP-150 reserves gas_limit = 21_000 + 32_000 + (len(initcode_data) + 31) // 32 * 6 # out_of_gas is triggered, so canary won't set value # also validate target created contract fails post = { contract_address: Account( storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=gas_limit, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_insufficient_gas_memory_expansion( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Exercises EOFCREATE when the memory for auxdata has not been expanded but is requested. """ env = Environment() auxdata_size = 0x5000 initcode_container = Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](input_size=auxdata_size)) + Op.SSTORE(slot_code_should_fail, slot_code_worked) + Op.STOP, ), Section.Container(container=smallest_initcode_subcontainer), ], ) sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=initcode_container, storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ) # enough gas for everything but EVM opcodes and EIP-150 reserves initcode_container_words = (len(initcode_container) + 31) // 32 auxdata_size_words = (auxdata_size + 31) // 32 gas_limit = ( 21_000 + 32_000 + initcode_container_words * 6 + 3 * auxdata_size_words + auxdata_size_words * auxdata_size_words // 512 ) # out_of_gas is triggered, so canary won't set value # also validate target created contract fails post = { contract_address: Account( storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=gas_limit, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_insufficient_returncode_auxdata_gas( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Exercises a RETURNCODE when there is not enough gas for the initcode charge. """ env = Environment() auxdata_size = 0x5000 initcode_container = Container( name="Large Initcode Subcontainer", sections=[ Section.Code( code=Op.RETURNCODE[0](0, auxdata_size), ), Section.Container(container=smallest_runtime_subcontainer), ], ) sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_should_fail, value_code_worked) + Op.STOP, ), Section.Container(container=initcode_container), ], ), storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ) # enough gas for everything but EVM opcodes and EIP-150 reserves initcode_container_words = (len(initcode_container) + 31) // 32 auxdata_size_words = (auxdata_size + 31) // 32 gas_limit = ( 21_000 + 32_000 + initcode_container_words * 6 + 3 * auxdata_size_words + auxdata_size_words * auxdata_size_words // 512 ) # out_of_gas is triggered, so canary won't set value # also validate target created contract fails post = { contract_address: Account( storage={ slot_create_address: value_canary_should_not_change, slot_code_should_fail: value_canary_should_not_change, }, ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=gas_limit, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize( "opcode", [ Op.STATICCALL, Op.EXTSTATICCALL, ], ) @pytest.mark.parametrize("endowment", [0, 1]) # included to verify static flag # check comes first @pytest.mark.parametrize( "initcode", [smallest_initcode_subcontainer, aborting_container], ids=["working_initcode", "aborting_code"], ) def test_static_flag_eofcreate( state_test: StateTestFiller, pre: Alloc, opcode: Op, endowment: int, initcode: Container, ) -> None: """Verifies correct handling of the static call flag with EOFCREATE.""" env = Environment() sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.EOFCREATE[0](value=endowment) + Op.STOP, ), Section.Container(container=initcode), ] ) ) calling_code = ( Op.SSTORE(slot_call_result, opcode(address=contract_address)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) calling_address = pre.deploy_contract( Container.Code(calling_code) if opcode == Op.EXTSTATICCALL else calling_code ) post = { calling_address: Account( storage={ slot_call_result: EXTCALL_FAILURE if opcode == Op.EXTSTATICCALL else LEGACY_CALL_FAILURE, slot_code_worked: value_code_worked, } ), compute_eofcreate_address(contract_address, 0): Account.NONEXISTENT, } tx = Transaction( to=calling_address, gas_limit=10_000_000, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) magic_value_call = 0xCA11 magic_value_create = 0xCC12EA7E @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, ], ) @pytest.mark.parametrize( "who_fails", [magic_value_call, magic_value_create], ids=["call_fails", "create_fails"], ) @pytest.mark.pre_alloc_modify def test_eof_eofcreate_msg_depth( state_test: StateTestFiller, pre: Alloc, opcode: Op, who_fails: int, ) -> None: """ Test EOFCREATE handles msg depth limit correctly (1024). NOTE: due to block gas limit and the 63/64th rule this limit is unlikely to be hit on mainnet. NOTE: See `tests/unscheduled/eip7692_eof_v1/eip7069_extcall/ test_calls.py::test_eof_calls_msg_depth` for more explanations and comments. Most notable deviation from that test is that here calls and `EOFCREATE`s alternate in order to reach the max depth. `who_fails` decides whether the failing depth 1024 will be on a call or on an `EOFCREATE` to happen. """ # Not a precise gas_limit formula, but enough to exclude risk of gas # causing the failure. gas_limit = int(20000000 * (64 / 63) ** 1024) env = Environment(gas_limit=gas_limit) sender = pre.fund_eoa() callee_address = Address(0x5000) # Memory offsets layout: # - 0 - input - msg depth # - 32 - output - msg depth # - 64 - output - call result # - 96 - output - magic value: create or call returndatacopy_block = Op.RETURNDATACOPY(32, 0, 96) + Op.REVERT(32, 96) deep_most_result_block = ( Op.MSTORE(32, Op.ADD(Op.CALLDATALOAD(0), 1)) + Op.MSTORE(64, Op.NOOP) + Op.REVERT(32, 96) ) rjump_offset = len(returndatacopy_block) callee_code = Container( sections=[ Section.Code( Op.MSTORE(0, Op.ADD(Op.CALLDATALOAD(0), 1)) + Op.MSTORE(96, magic_value_create) + Op.EOFCREATE[0](salt=Op.CALLDATALOAD(0), input_size=32) + Op.RETURNDATASIZE + Op.ISZERO + Op.RJUMPI[rjump_offset] + returndatacopy_block + deep_most_result_block ), Section.Container( Container.Code( Op.MSTORE(0, Op.ADD(Op.CALLDATALOAD(0), 1)) + Op.MSTORE(96, magic_value_call) + opcode(address=callee_address, args_size=32) + Op.RETURNDATASIZE + Op.ISZERO + Op.RJUMPI[rjump_offset] + returndatacopy_block + deep_most_result_block ) ), ] ) pre.deploy_contract(callee_code, address=callee_address) calling_contract_address = pre.deploy_contract( Container.Code( Op.MSTORE(0, Op.CALLDATALOAD(0)) + opcode(address=callee_address, args_size=32) + Op.SSTORE(slot_max_depth, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_call_result, Op.RETURNDATALOAD(32)) + Op.SSTORE(slot_call_or_create, Op.RETURNDATALOAD(64)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) ) # Only bumps the msg call depth "register" and forwards to the # `calling_contract_address`. If it is used it makes the "failing" depth of # 1024 to happen on EOFCREATE, instead of CALL. passthrough_address = pre.deploy_contract( Container.Code( Op.MSTORE(0, 1) + Op.EXTCALL(address=calling_contract_address, args_size=32) + Op.STOP ) ) tx = Transaction( sender=sender, to=calling_contract_address if who_fails == magic_value_call else passthrough_address, gas_limit=gas_limit, data="", ) calling_storage = { slot_max_depth: 1024, slot_code_worked: value_code_worked, slot_call_result: EXTCALL_REVERT if who_fails == magic_value_call else EOFCREATE_FAILURE, slot_call_or_create: who_fails, } post = { calling_contract_address: Account(storage=calling_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) def test_reentrant_eofcreate( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies a reentrant EOFCREATE case, where EIP-161 prevents conflict via nonce bump. """ env = Environment() # Calls into the factory contract with 1 as input. reenter_code = Op.MSTORE(0, 1) + Op.EXTCALL(address=Op.CALLDATALOAD(32), args_size=32) # Initcode: if given 0 as 1st word of input will call into the factory # again. 2nd word of input is the address of the factory. initcontainer = Container( sections=[ Section.Code( Op.SSTORE(slot_counter, Op.ADD(Op.SLOAD(slot_counter), 1)) + Op.CALLDATALOAD(0) + Op.RJUMPI[len(reenter_code)] + reenter_code + Op.RETURNCODE[0](0, 0) ), Section.Container(smallest_runtime_subcontainer), ] ) # Factory: # Passes on its input into the initcode. # It's 0 first time, 1 the second time. # Saves the result of deployment in slot 0 first time, 1 the # second time. contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( Op.CALLDATACOPY(0, 0, 32) + Op.MSTORE(32, Op.ADDRESS) # 1st word - copied from input (reenter flag) # 2nd word - `this.address` + Op.SSTORE(Op.CALLDATALOAD(0), Op.EOFCREATE[0](input_size=64)) + Op.STOP, ), Section.Container(initcontainer), ], ), storage={0: 0xB17D, 1: 0xB17D}, # a canary to be overwritten ) # Flow is: # reenter flag 0 -> factory -> reenter flag 0 -> initcode -> # reenter -> reenter flag 1 -> factory -> reenter flag 1 -> (!) initcode # -> stop # if the EIP-161 nonce bump is not implemented. # # If it is, it fails before second inicode marked (!). # # Storage in 0 should have the address from the outer EOFCREATE. # Storage in 1 should have 0 from the inner EOFCREATE. For the created # contract storage in `slot_counter` should be 1 as initcode # executes only once. post = { contract_address: Account( storage={ 0: compute_eofcreate_address(contract_address, 0), 1: 0, } ), compute_eofcreate_address(contract_address, 0): Account( nonce=1, code=smallest_runtime_subcontainer, storage={slot_counter: 1} ), } tx = Transaction( to=contract_address, gas_limit=500_000, sender=pre.fund_eoa(), ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/helpers.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/helpers.py
"""A collection of contracts used in 7620 EOF tests.""" import itertools from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import Container, Section """Storage addresses for common testing fields""" _slot = itertools.count() next(_slot) # don't use slot 0 slot_code_worked = next(_slot) slot_code_should_fail = next(_slot) slot_create_address = next(_slot) slot_calldata = next(_slot) slot_call_result = next(_slot) slot_returndata = next(_slot) slot_returndata_size = next(_slot) slot_max_depth = next(_slot) slot_call_or_create = next(_slot) slot_counter = next(_slot) slot_data_load = next(_slot) slot_all_subcall_gas_gone = next(_slot) slot_a = next(_slot) slot_b = next(_slot) slot_last_slot = next(_slot) value_code_worked = 0x2015 value_canary_should_not_change = 0x2019 value_canary_to_be_overwritten = 0x2009 value_long_value = b"abcdefghijklmnopqrstuvwxyz123456" smallest_runtime_subcontainer = Container.Code(code=Op.STOP, name="Runtime Subcontainer") smallest_initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code(code=Op.RETURNCODE[0](0, 0)), Section.Container(container=smallest_runtime_subcontainer), ], ) smallest_initcode_subcontainer_gas = 2 * 3 aborting_container = Container.Code(Op.INVALID, name="Aborting Container") reverting_container = Container.Code(Op.REVERT(0, 0), name="Reverting Container") expensively_reverting_container = Container.Code( Op.SHA3(0, 32) + Op.REVERT(0, 0), name="Expensively Reverting Container" ) expensively_reverting_container_gas = 2 * 3 + 30 + 3 + 6 + 2 * 3 big_runtime_subcontainer = Container.Code(Op.NOOP * 10000 + Op.STOP, name="Big Subcontainer") bigger_initcode_subcontainer_gas = 3 + 4 + 2 * 3 bigger_initcode_subcontainer = Container( name="Bigger Initcode Subcontainer", sections=[ Section.Code( code=Op.RJUMPI[len(Op.RETURNCODE[0](0, 0))](1) + Op.RETURNCODE[0](0, 0) + Op.RETURNCODE[1](0, 0) ), Section.Container(container=smallest_runtime_subcontainer), Section.Container(container=smallest_runtime_subcontainer), ], ) data_runtime_container = smallest_runtime_subcontainer.copy() data_runtime_container.sections.append(Section.Data("0x00")) data_initcode_subcontainer = Container( name="Data Initcode Subcontainer", sections=[ Section.Code(code=Op.RETURNCODE[0](0, 0)), Section.Container(container=data_runtime_container), ], ) data_appending_initcode_subcontainer = Container( name="Data Appending Initcode Subcontainer", sections=[ Section.Code(code=Op.RETURNCODE[0](0, 1)), Section.Container(container=smallest_runtime_subcontainer), ], ) data_appending_initcode_subcontainer_gas = 2 * 3 + 3
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_memory.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_memory.py
"""Test good and bad EOFCREATE cases.""" import pytest from ethereum_test_base_types import Account, Storage from ethereum_test_tools import Alloc, Environment, StateTestFiller, compute_eofcreate_address from ethereum_test_types import Transaction from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import ( slot_code_worked, slot_create_address, smallest_initcode_subcontainer, smallest_runtime_subcontainer, value_canary_to_be_overwritten, value_code_worked, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7620.md" REFERENCE_SPEC_VERSION = "52ddbcdddcf72dd72427c319f2beddeb468e1737" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "offset_field", [ pytest.param(True, id="offset"), pytest.param(False, id="size"), ], ) @pytest.mark.parametrize( ("test_arg", "success"), [ pytest.param(0, True, id="zero"), pytest.param(0xFF, True, id="8-bit"), pytest.param(0x100, True, id="9-bit"), pytest.param(0xFFFF, True, id="16-bit"), pytest.param(0x10000, True, id="17-bit"), pytest.param(0x1FFFF20, False, id="32-bit-mem-cost"), pytest.param(0x2D412E0, False, id="33-bit-mem-cost"), pytest.param(0xFFFFFFFF, False, id="32-bit"), pytest.param(0x100000000, False, id="33-bit"), pytest.param(0x1FFFFFFFF20, False, id="64-bit-mem-cost"), pytest.param(0x2D413CCCF00, False, id="65-bit-mem-cost"), pytest.param(0xFFFFFFFFFFFFFFFF, False, id="64-bit"), pytest.param(0x10000000000000000, False, id="65-bit"), pytest.param(0xFFFFFFFFFFFFFFFF, False, id="128-bit"), pytest.param(0x10000000000000000, False, id="129-bit"), pytest.param(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, False, id="256-bit"), ], ) def test_eofcreate_memory( state_test: StateTestFiller, pre: Alloc, offset_field: str, test_arg: int, success: bool, ) -> None: """ Tests auxdata sizes in EOFCREATE including multiple offset conditions. EOFCREATE either succeeds or fails based on memory access cost, resulting in new address or zero in the create address slot. The name id of `*-mem-cost` refers to the bit-length of the result of the calculated memory expansion cost. Their length choice is designed to cause problems on shorter bit-length representations with native integers. The `offset_field` param indicates what part of the input data arguments are being tested, either the offset of the data in memory or the size of the data in memory. The `test_arg` param is the value passed into the field being tested (offset or size), intending to trigger integer size bugs for that particular field. """ env = Environment(gas_limit=2_000_000_000) sender = pre.fund_eoa(10**27) initial_storage = Storage( { slot_create_address: value_canary_to_be_overwritten, # type: ignore slot_code_worked: value_canary_to_be_overwritten, # type: ignore } ) calling_contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE( slot_create_address, Op.EOFCREATE[0]( value=0, salt=0, input_offset=test_arg if offset_field else 32, input_size=32 if offset_field else test_arg, ), ) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=smallest_initcode_subcontainer), ] ), storage=initial_storage, ) destination_contract_address = compute_eofcreate_address(calling_contract_address, 0) post = { calling_contract_address: Account( storage={ slot_create_address: destination_contract_address, slot_code_worked: value_code_worked, } if success else initial_storage, ), destination_contract_address: Account(code=smallest_runtime_subcontainer) if success else Account.NONEXISTENT, } tx = Transaction(sender=sender, to=calling_contract_address, gas_limit=2_000_000_000) state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/__init__.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/__init__.py
""" Test cases for EOF Contract Creation for EIP-7620. EIP-7620 replaces `CREATE` and `CREATE2` with `EOFCREATE` for deploying contracts in the EOF format. Full specification: [EIP-7620: EOF Contract Creation](https://eips.ethereum.org/EIPS/eip-7620). Opcodes introduced: `EOFCREATE` (`0xEC`), `RETURNCODE` (`0xEE`). EOFCREATE, RETURNCODE, and container tests. evmone tests not ported: - create_tx_with_eof_initcode: This calls it invalid, it is now the way to add EOF contacts to state - eofcreate_extcall_returncode: Per the new initcode mode tests you cannot have RETURNCODE in a deployed contract - eofcreate_dataloadn_referring_to_auxdata: covered by tests.unscheduled.eip7480_data_section. test_data_opcodes.test_data_section_succeed - eofcreate_initcontainer_return: RETURN is banned in initcode containers - eofcreate_initcontainer_stop: STOP is banned in initcode containers - All TXCREATE tests. """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_gas.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_gas.py
"""Test good and bad EOFCREATE cases.""" import pytest from ethereum_test_forks import Fork from ethereum_test_tools import Alloc, Environment, StateTestFiller, compute_eofcreate_address from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from ..gas_test import gas_test from .helpers import ( aborting_container, big_runtime_subcontainer, bigger_initcode_subcontainer, bigger_initcode_subcontainer_gas, data_appending_initcode_subcontainer, data_appending_initcode_subcontainer_gas, data_initcode_subcontainer, data_runtime_container, expensively_reverting_container, expensively_reverting_container_gas, reverting_container, slot_counter, smallest_initcode_subcontainer, smallest_initcode_subcontainer_gas, smallest_runtime_subcontainer, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7620.md" REFERENCE_SPEC_VERSION = "52ddbcdddcf72dd72427c319f2beddeb468e1737" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) EOFCREATE_GAS = 32000 def make_factory(initcode: Container) -> Container: """Wrap initcontainer into a minimal runtime container.""" return Container( name="Factory Subcontainer", sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container(initcode), ], ) @pytest.mark.parametrize("value", [0, 1]) @pytest.mark.parametrize("new_account", [True, False]) @pytest.mark.parametrize( "mem_expansion_bytes", [0, 1, 32, 33], ) @pytest.mark.parametrize( ["initcode", "initcode_execution_cost", "runtime"], [ pytest.param( smallest_initcode_subcontainer, smallest_initcode_subcontainer_gas, smallest_runtime_subcontainer, id="smallest_code", ), pytest.param( Container.Init(aborting_container), smallest_initcode_subcontainer_gas, aborting_container, id="aborting_runtime", ), pytest.param( reverting_container, smallest_initcode_subcontainer_gas, None, id="reverting_initcode" ), pytest.param( expensively_reverting_container, expensively_reverting_container_gas, None, id="expensively_reverting_initcode", ), pytest.param( Container.Init(big_runtime_subcontainer), smallest_initcode_subcontainer_gas, big_runtime_subcontainer, id="big_runtime", ), pytest.param( Container.Init(make_factory(smallest_initcode_subcontainer)), smallest_initcode_subcontainer_gas, make_factory(smallest_initcode_subcontainer), id="nested_initcode", ), pytest.param( bigger_initcode_subcontainer, bigger_initcode_subcontainer_gas, smallest_runtime_subcontainer, id="bigger_initcode", ), pytest.param( data_initcode_subcontainer, smallest_initcode_subcontainer_gas, data_runtime_container, id="data_initcode", ), pytest.param( data_appending_initcode_subcontainer, data_appending_initcode_subcontainer_gas, data_runtime_container, id="data_appending_initcode", ), ], ) def test_eofcreate_gas( state_test: StateTestFiller, pre: Alloc, fork: Fork, value: int, new_account: bool, mem_expansion_bytes: int, initcode: Container, initcode_execution_cost: int, runtime: Container, ) -> None: """Tests variations of EOFCREATE gas.""" deployed_code_cost = 200 * len(runtime) if runtime else 0 subject_address = pre.fund_eoa(0) salt_addresses = [compute_eofcreate_address(subject_address, i) for i in range(4)] if not new_account: for a in salt_addresses: pre.fund_address(a, 1) # Using `TLOAD` / `TSTORE` to work around warm/cold gas differences. We # need a counter to pick a distinct salt on each `EOFCREATE` and avoid # running into address conflicts. code_increment_counter = ( Op.TLOAD(slot_counter) + Op.DUP1 + Op.TSTORE(slot_counter, Op.PUSH1(1) + Op.ADD) ) cost_memory_bytes = fork.memory_expansion_gas_calculator() gas_test( state_test, Environment(), pre, setup_code=Op.PUSH32(value) + Op.PUSH1(mem_expansion_bytes) + Op.PUSH0 + code_increment_counter, subject_code=Op.EOFCREATE[0], tear_down_code=Op.STOP, cold_gas=EOFCREATE_GAS + cost_memory_bytes(new_bytes=mem_expansion_bytes) + initcode_execution_cost + deployed_code_cost, subject_subcontainer=initcode, subject_balance=value * 4, subject_address=subject_address, oog_difference=initcode_execution_cost + deployed_code_cost + 1, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_eofcreate.py
tests/unscheduled/eip7692_eof_v1/eip7620_eof_create/test_eofcreate.py
"""Test good and bad EOFCREATE cases.""" import pytest from ethereum_test_base_types import Storage from ethereum_test_base_types.base_types import Address from ethereum_test_exceptions import EOFException from ethereum_test_specs import EOFTestFiller from ethereum_test_tools import ( Account, Alloc, Environment, StateTestFiller, Transaction, compute_eofcreate_address, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from ..eip7069_extcall.spec import EXTCALL_SUCCESS from .helpers import ( slot_call_result, slot_calldata, slot_code_worked, slot_create_address, slot_data_load, slot_last_slot, slot_returndata_size, smallest_initcode_subcontainer, smallest_runtime_subcontainer, value_canary_to_be_overwritten, value_code_worked, value_long_value, ) from .spec import EOFCREATE_FAILURE REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7620.md" REFERENCE_SPEC_VERSION = "52ddbcdddcf72dd72427c319f2beddeb468e1737" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def test_simple_eofcreate( state_test: StateTestFiller, pre: Alloc, ) -> None: """Verifies a simple EOFCREATE case.""" env = Environment() sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(0, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.STOP, ), Section.Container(container=smallest_initcode_subcontainer), ], ), storage={0: 0xB17D}, # a canary to be overwritten ) # Storage in 0 should have the address, post = {contract_address: Account(storage={0: compute_eofcreate_address(contract_address, 0)})} tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_eofcreate_then_dataload( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies that a contract returned with auxdata does not overwrite the parent data. """ env = Environment() sender = pre.fund_eoa() small_auxdata_container = Container( sections=[ Section.Code(code=Op.RETURNCODE[0](0, 32)), Section.Container(container=smallest_runtime_subcontainer), ], ) contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(0, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_data_load, Op.DATALOAD(0)) + Op.STOP, ), Section.Container( container=small_auxdata_container, ), Section.Data(data=value_long_value), ], ), storage={slot_data_load: value_canary_to_be_overwritten}, ) post = { contract_address: Account( storage={ 0: compute_eofcreate_address(contract_address, 0), slot_data_load: value_long_value, } ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_eofcreate_then_call( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies a simple EOFCREATE case, and then calls the deployed contract. """ env = Environment() callable_contract = Container( sections=[ Section.Code( code=Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), ] ) callable_contract_initcode = Container( sections=[ Section.Code( code=Op.RETURNCODE[0](0, 0), ), Section.Container(container=callable_contract), ] ) sender = pre.fund_eoa() contract_address = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.EXTCALL(Op.SLOAD(slot_create_address), 0, 0, 0) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=callable_contract_initcode), ], ) ) callable_address = compute_eofcreate_address(contract_address, 0) # Storage in 0 should have the address, # post = { contract_address: Account( storage={slot_create_address: callable_address, slot_code_worked: value_code_worked} ), callable_address: Account(storage={slot_code_worked: value_code_worked}), } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize( "auxdata_bytes", [ pytest.param(b"", id="zero"), pytest.param(b"aabbcc", id="short"), pytest.param(b"aabbccddeef", id="one_byte_short"), pytest.param(b"aabbccddeeff", id="exact"), pytest.param(b"aabbccddeeffg", id="one_byte_long"), pytest.param(b"aabbccddeeffgghhii", id="extra"), ], ) def test_auxdata_variations(state_test: StateTestFiller, pre: Alloc, auxdata_bytes: bytes) -> None: """Verifies that auxdata bytes are correctly handled in RETURNCODE.""" env = Environment() auxdata_size = len(auxdata_bytes) pre_deploy_header_data_size = 18 pre_deploy_data = b"AABBCC" deploy_success = len(auxdata_bytes) + len(pre_deploy_data) >= pre_deploy_header_data_size runtime_subcontainer = Container( name="Runtime Subcontainer with truncated data", sections=[ Section.Code(code=Op.STOP), Section.Data(data=pre_deploy_data, custom_size=pre_deploy_header_data_size), ], ) initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.MSTORE(0, Op.PUSH32(auxdata_bytes.ljust(32, b"\0"))) + Op.RETURNCODE[0](0, auxdata_size), ), Section.Container(container=runtime_subcontainer), ], ) sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.STOP, ), Section.Container(container=initcode_subcontainer), ] ), storage={slot_create_address: value_canary_to_be_overwritten}, ) # Storage in 0 should have the address, post = { contract_address: Account( storage={ slot_create_address: compute_eofcreate_address(contract_address, 0) if deploy_success else b"\0" } ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_calldata(state_test: StateTestFiller, pre: Alloc) -> None: """Verifies CALLDATA passing through EOFCREATE.""" env = Environment() initcode_subcontainer = Container( name="Initcode Subcontainer", sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_calldata, Op.MLOAD(0)) + Op.RETURNCODE[0](0, Op.CALLDATASIZE), ), Section.Container(container=smallest_runtime_subcontainer), ], ) calldata_size = 32 calldata = b"\x45" * calldata_size sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.MSTORE(0, Op.PUSH32(calldata)) + Op.SSTORE(slot_create_address, Op.EOFCREATE[0](input_size=calldata_size)) + Op.STOP, ), Section.Container(container=initcode_subcontainer), ] ) ) # deployed contract is smallest plus data deployed_contract = Container( name="deployed contract", sections=[ *smallest_runtime_subcontainer.sections, Section.Data(data=calldata), ], ) # factory contract Storage in 0 should have the created address, # created contract storage in 0 should have the calldata created_address = compute_eofcreate_address(contract_address, 0) post = { contract_address: Account(storage={slot_create_address: created_address}), created_address: Account(code=deployed_contract, storage={slot_calldata: calldata}), } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_eofcreate_in_initcode( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies an EOFCREATE occurring within initcode creates that contract. """ nested_initcode_subcontainer = Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURNCODE[1](0, 0), ), Section.Container(container=smallest_initcode_subcontainer), Section.Container(container=smallest_runtime_subcontainer), ] ) env = Environment() sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=nested_initcode_subcontainer), ] ) ) outer_address = compute_eofcreate_address(contract_address, 0) inner_address = compute_eofcreate_address(outer_address, 0) post = { contract_address: Account( storage={slot_create_address: outer_address, slot_code_worked: value_code_worked} ), outer_address: Account( storage={slot_create_address: inner_address, slot_code_worked: value_code_worked} ), } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_eofcreate_in_initcode_reverts( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies an EOFCREATE occurring in an initcode is rolled back when the initcode reverts. """ nested_initcode_subcontainer = Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.REVERT(0, 0), ), Section.Container(container=smallest_initcode_subcontainer), ] ) env = Environment() sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=nested_initcode_subcontainer), ] ), storage={slot_create_address: value_canary_to_be_overwritten}, ) outer_address = compute_eofcreate_address(contract_address, 0) inner_address = compute_eofcreate_address(outer_address, 0) post = { contract_address: Account( storage={ slot_create_address: 0, slot_code_worked: value_code_worked, } ), outer_address: Account.NONEXISTENT, inner_address: Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_return_data_cleared( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies the return data is not reused from a extcall but is cleared upon eofcreate. """ env = Environment() value_return_canary = 0x4158675309 value_return_canary_size = 5 callable_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.MSTORE(0, value_return_canary) + Op.RETURN(0, value_return_canary_size), ) ] ) ) slot_returndata_size_2 = slot_last_slot * 2 + slot_returndata_size sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_call_result, Op.EXTCALL(callable_address, 0, 0, 0)) + Op.SSTORE(slot_returndata_size, Op.RETURNDATASIZE) + Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_returndata_size_2, Op.RETURNDATASIZE) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=smallest_initcode_subcontainer), ], ) ) new_contract_address = compute_eofcreate_address(contract_address, 0) post = { contract_address: Account( storage={ slot_call_result: EXTCALL_SUCCESS, slot_returndata_size: value_return_canary_size, slot_create_address: new_contract_address, slot_returndata_size_2: 0, slot_code_worked: value_code_worked, }, nonce=2, ), callable_address: Account(nonce=1), new_contract_address: Account(nonce=1), } tx = Transaction( to=contract_address, gas_limit=10_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_address_collision( state_test: StateTestFiller, pre: Alloc, ) -> None: """Tests address collision.""" env = Environment( gas_limit=300_000_000_000, ) slot_create_address_2 = slot_last_slot * 2 + slot_create_address slot_create_address_3 = slot_last_slot * 3 + slot_create_address sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.SSTORE(slot_create_address, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_create_address_2, Op.EOFCREATE[0](0, 0, 0, 0)) + Op.SSTORE(slot_create_address_3, Op.EOFCREATE[0](salt=1)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Container(container=smallest_initcode_subcontainer), ], ) ) salt_zero_address = compute_eofcreate_address(contract_address, 0) salt_one_address = compute_eofcreate_address(contract_address, 1) # Hard-code address for collision, no other way to do this. # We should mark tests that do this, and fail on unmarked tests. pre[salt_one_address] = Account(balance=1, nonce=1) post = { contract_address: Account( storage={ slot_create_address: salt_zero_address, # had an in-transaction collision slot_create_address_2: EOFCREATE_FAILURE, # had a pre-existing collision slot_create_address_3: EOFCREATE_FAILURE, slot_code_worked: value_code_worked, } ) } # Multiple create fails is expensive, use an absurd amount of gas tx = Transaction( to=contract_address, gas_limit=300_000_000_000, gas_price=10, protected=False, sender=sender, ) state_test(env=env, pre=pre, post=post, tx=tx) def test_eofcreate_revert_eof_returndata( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies the return data is not being deployed, even if happens to be valid EOF. """ env = Environment() code_reverts_with_calldata = Container( name="Initcode Subcontainer reverting with its calldata", sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.REVERT(0, Op.CALLDATASIZE), ), ], ) sender = pre.fund_eoa() salt = 0 contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE( slot_create_address, Op.EOFCREATE[0](salt=salt, input_size=Op.CALLDATASIZE) ) + Op.SSTORE(slot_returndata_size, Op.RETURNDATASIZE) + Op.STOP, ), Section.Container(container=code_reverts_with_calldata), ], ), storage={slot_create_address: value_canary_to_be_overwritten}, ) eof_create_address = compute_eofcreate_address(contract_address, salt) post = { contract_address: Account( storage={ slot_create_address: 0, slot_returndata_size: len(smallest_runtime_subcontainer), }, ), eof_create_address: Account.NONEXISTENT, } tx = Transaction( to=contract_address, gas_limit=1_000_000, sender=sender, # Simplest possible valid EOF container, which is going to be # revert-returned from initcode and must not end up being deployed. data=smallest_runtime_subcontainer, ) state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.parametrize("index", [0, 1, 255], ids=lambda x: x) def test_eofcreate_invalid_index( eof_test: EOFTestFiller, index: int, ) -> None: """EOFCREATE referring non-existent container section index.""" container = Container.Code(code=Op.EOFCREATE[index](0, 0, 0, 0) + Op.STOP) if index != 0: container.sections.append(Section.Container(container=Container.Code(Op.INVALID))) eof_test( container=container, expect_exception=EOFException.INVALID_CONTAINER_SECTION_INDEX, ) def test_eofcreate_invalid_truncated_immediate( eof_test: EOFTestFiller, ) -> None: """EOFCREATE instruction with missing immediate byte.""" eof_test( container=Container( sections=[ Section.Code(Op.PUSH0 * 4 + Op.EOFCREATE), Section.Container(Container.Code(Op.INVALID)), ], ), expect_exception=EOFException.TRUNCATED_INSTRUCTION, ) @pytest.mark.parametrize( ["data_len", "data_section_size"], [ (0, 1), (0, 0xFFFF), (2, 3), (2, 0xFFFF), ], ) def test_eofcreate_truncated_container( eof_test: EOFTestFiller, data_len: int, data_section_size: int, ) -> None: """ EOFCREATE instruction targeting a container with truncated data section. """ assert data_len < data_section_size eof_test( container=Container( sections=[ Section.Code(Op.EOFCREATE[0](0, 0, 0, 0) + Op.STOP), Section.Container( Container( sections=[ Section.Code(Op.INVALID), Section.Data(b"\xda" * data_len, custom_size=data_section_size), ], ) ), ], ), expect_exception=EOFException.EOFCREATE_WITH_TRUNCATED_CONTAINER, ) @pytest.mark.parametrize( ["destination_code", "expected_result"], [ pytest.param(Op.ADDRESS, "destination"), pytest.param(Op.CALLER, "caller"), pytest.param(Op.CALLVALUE, "eofcreate_value"), pytest.param(Op.ORIGIN, "sender"), pytest.param(Op.SELFBALANCE, "selfbalance"), pytest.param(Op.BALANCE(Op.CALLER), "factorybalance"), ], ) def test_eofcreate_context( state_test: StateTestFiller, pre: Alloc, destination_code: Bytecode, expected_result: str, ) -> None: """Test EOFCREATE's initcode context instructions.""" env = Environment() sender = pre.fund_eoa() value = 0x1123 eofcreate_value = 0x13 initcode = Container( sections=[ Section.Code(Op.SSTORE(slot_call_result, destination_code) + Op.RETURNCODE[0](0, 0)), Section.Container(smallest_runtime_subcontainer), ] ) factory_contract = Container( sections=[ Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.EOFCREATE[0](value=eofcreate_value) + Op.STOP ), Section.Container(initcode), ] ) factory_address = pre.deploy_contract(factory_contract) destination_contract_address = compute_eofcreate_address(factory_address, 0) tx = Transaction(sender=sender, to=factory_address, gas_limit=200_000, value=value) expected_bytes: Address | int if expected_result == "destination": expected_bytes = destination_contract_address elif expected_result == "caller": expected_bytes = factory_address elif expected_result == "sender": expected_bytes = sender elif expected_result == "eofcreate_value": expected_bytes = eofcreate_value elif expected_result == "selfbalance": expected_bytes = eofcreate_value elif expected_result == "factorybalance": # Factory receives value from sender and passes on eofcreate_value as # endowment. expected_bytes = value - eofcreate_value else: raise TypeError("Unexpected expected_result", expected_result) calling_storage = { slot_code_worked: value_code_worked, } destination_contract_storage = { slot_call_result: expected_bytes, } post = { factory_address: Account(storage=calling_storage, balance=value - eofcreate_value), destination_contract_address: Account( storage=destination_contract_storage, balance=eofcreate_value ), } state_test( env=env, pre=pre, post=post, tx=tx, ) def test_eofcreate_memory_context( state_test: StateTestFiller, pre: Alloc, ) -> None: """ Verifies an EOFCREATE frame enjoys a separate EVM memory from its caller frame. """ env = Environment() destination_storage = Storage() contract_storage = Storage() initcontainer = Container( sections=[ Section.Code( Op.SSTORE(destination_storage.store_next(value_code_worked), value_code_worked) + Op.SSTORE(destination_storage.store_next(0), Op.MSIZE()) + Op.SSTORE(destination_storage.store_next(0), Op.MLOAD(0)) + Op.MSTORE(0, 2) + Op.MSTORE(32, 2) + Op.RETURNCODE[0](0, 0) ), Section.Container(smallest_runtime_subcontainer), ] ) contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( Op.SSTORE(contract_storage.store_next(value_code_worked), value_code_worked) + Op.MSTORE(0, 1) + Op.EOFCREATE[0](0, 0, 0, 0) + Op.SSTORE(contract_storage.store_next(32), Op.MSIZE()) + Op.SSTORE(contract_storage.store_next(1), Op.MLOAD(0)) + Op.SSTORE(contract_storage.store_next(0), Op.MLOAD(32)) + Op.STOP, ), Section.Container(initcontainer), ], ), ) destination_contract_address = compute_eofcreate_address(contract_address, 0) post = { contract_address: Account(storage=contract_storage), destination_contract_address: Account(storage=destination_storage), } tx = Transaction( to=contract_address, gas_limit=200_000, sender=pre.fund_eoa(), ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7480_data_section/spec.py
tests/unscheduled/eip7692_eof_v1/eip7480_data_section/spec.py
"""EOF V1 Constants used throughout all tests."""
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7480_data_section/test_code_validation.py
tests/unscheduled/eip7692_eof_v1/eip7480_data_section/test_code_validation.py
"""EOF V1 Code Validation tests.""" import pytest from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_INITCODE_SIZE from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7480.md" REFERENCE_SPEC_VERSION = "3ee1334ef110420685f1c8ed63e80f9e1766c251" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) smallest_runtime_subcontainer = Container( name="Runtime Subcontainer", sections=[ Section.Code(code=Op.STOP), ], ) def container_name(c: Container) -> str: """Return the name of the container for use in pytest ids.""" if hasattr(c, "name") and c.name is not None: return c.name else: return c.__class__.__name__ @pytest.mark.parametrize( "container", [ Container( name="empty_data_section", sections=[ Section.Code( code=Op.ADDRESS + Op.POP + Op.STOP, ), Section.Data(data=""), ], ), Container( name="small_data_section", sections=[ Section.Code( code=Op.ADDRESS + Op.POP + Op.STOP, ), Section.Data(data="1122334455667788" * 4), ], ), pytest.param( Container( name="large_data_section", sections=[ Section.Code( code=Op.ADDRESS + Op.POP + Op.STOP, ), Section.Data(data="1122334455667788" * 3 * 1024), ], ), marks=pytest.mark.eof_test_only(reason="initcode exceeds max size"), ), pytest.param( Container( name="max_data_section", sections=[ Section.Code(code=Op.STOP), # Hits the 49152 bytes limit for the entire container Section.Data( data=b"\x00" * (MAX_INITCODE_SIZE - len(smallest_runtime_subcontainer)) ), ], ), marks=pytest.mark.eof_test_only(reason="initcode exceeds max size"), ), Container( name="DATALOADN_zero", sections=[ Section.Code( code=Op.DATALOADN[0] + Op.POP + Op.STOP, ), Section.Data(data="1122334455667788" * 16), ], ), Container( name="DATALOADN_middle", sections=[ Section.Code( code=Op.DATALOADN[16] + Op.POP + Op.STOP, ), Section.Data(data="1122334455667788" * 16), ], ), Container( name="DATALOADN_edge", sections=[ Section.Code( code=Op.DATALOADN[128 - 32] + Op.POP + Op.STOP, ), Section.Data(data="1122334455667788" * 16), ], ), ], ids=container_name, ) def test_valid_containers_with_data_section( eof_test: EOFTestFiller, container: Container, ) -> None: """Test EOF validation of valid containers with data sections.""" assert container.validity_error is None, ( f"Valid container with validity error: {container.validity_error}" ) eof_test( container=container, ) @pytest.mark.parametrize( "container", [ Container( name="DATALOADN_0_empty_data", sections=[ Section.Code( code=Op.DATALOADN[0] + Op.POP + Op.STOP, ), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_max_empty_data", sections=[ Section.Code( code=Op.DATALOADN[0xFFFF - 32] + Op.POP + Op.STOP, ), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_1_over_data", sections=[ Section.Code( code=Op.DATALOADN[1] + Op.POP + Op.STOP, ), Section.Data(b"\x00"), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_32_over_data", sections=[ Section.Code( code=Op.DATALOADN[32] + Op.POP + Op.STOP, ), Section.Data(b"\xda" * 32), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_0_data_31", sections=[ Section.Code( code=Op.DATALOADN[0] + Op.POP + Op.STOP, ), Section.Data(b"\xda" * 31), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_32_data_63", sections=[ Section.Code( code=Op.DATALOADN[32] + Op.POP + Op.STOP, ), Section.Data(b"\xda" * 63), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_max_imm", sections=[ Section.Code( code=Op.DATALOADN[0xFFFF] + Op.POP + Op.STOP, ), Section.Data(b"\xda" * 32), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_max_small_data", sections=[ Section.Code( code=Op.DATALOADN[0xFFFF - 32] + Op.POP + Op.STOP, ), Section.Data(data="1122334455667788" * 16), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), Container( name="DATALOADN_max_half_data", sections=[ Section.Code( code=Op.DATALOADN[0xFFFF - 32] + Op.POP + Op.STOP, ), Section.Data(data=("1122334455667788" * 4 * 1024)[2:]), ], validity_error=EOFException.INVALID_DATALOADN_INDEX, ), pytest.param( Container( name="data_section_over_container_limit", sections=[ Section.Code(code=Op.STOP), # Over the 49152 bytes limit for the entire container Section.Data( data=(b"12345678" * 6 * 1024)[len(smallest_runtime_subcontainer) - 1 :] ), ], validity_error=EOFException.CONTAINER_SIZE_ABOVE_LIMIT, ), marks=pytest.mark.eof_test_only(reason="initcode exceeds max size"), ), ], ids=container_name, ) def test_invalid_containers_with_data_section( eof_test: EOFTestFiller, container: Container, ) -> None: """Test EOF validation of invalid containers with data sections.""" assert container.validity_error is not None, "Invalid container without validity error" eof_test( container=container, expect_exception=container.validity_error, ) @pytest.mark.parametrize( "container", [ Container( name="imm0", sections=[ Section.Code(Op.DATALOADN), Section.Data(b"\xff" * 32), ], ), Container( name="imm1", sections=[ Section.Code(Op.DATALOADN + b"\x00"), Section.Data(b"\xff" * 32), ], ), Container( name="imm_from_next_section", sections=[ Section.Code( Op.CALLF[1] + Op.JUMPF[2], max_stack_height=1, ), Section.Code( Op.DATALOADN + b"\x00", code_outputs=1, ), Section.Code( Op.STOP, ), Section.Data(b"\xff" * 32), ], ), ], ids=container_name, ) def test_dataloadn_truncated_immediate( eof_test: EOFTestFiller, container: Container, ) -> None: """Test cases for DATALOADN instructions with truncated immediate bytes.""" eof_test(container=container, expect_exception=EOFException.TRUNCATED_INSTRUCTION)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7480_data_section/__init__.py
tests/unscheduled/eip7692_eof_v1/eip7480_data_section/__init__.py
""" Test cases for EOF Data section access instructions for EIP-7480. EIP-7480 specifies instructions for accessing data stored in the dedicated data section of the EOF format. Full specification: [EIP-7480: EOF - Data section access instructions](https://eips.ethereum.org/EIPS/eip-7480). Opcodes introduced: `DATALOAD` (`0xD0`), `DATALOADN` (`0xD1`), `DATASIZE` (`0xD2`), `DATACOPY` (`0xD3`). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7480_data_section/test_datacopy_memory_expansion.py
tests/unscheduled/eip7692_eof_v1/eip7480_data_section/test_datacopy_memory_expansion.py
"""Memory expansion tests for DATACOPY.""" from typing import Mapping, Tuple import pytest from ethereum_test_forks import Fork from ethereum_test_tools import ( Account, Address, Alloc, Bytecode, Environment, StateTestFiller, Storage, Transaction, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7480.md" REFERENCE_SPEC_VERSION = "3ee1334ef110420685f1c8ed63e80f9e1766c251" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.fixture def callee_bytecode(dest: int, src: int, length: int, data_section: bytes) -> Container: """Callee performs a single datacopy operation and then returns.""" bytecode = Bytecode() # Copy the initial memory bytecode += Op.CALLDATACOPY(0x00, 0x00, Op.CALLDATASIZE()) # Pushes for the return operation bytecode += Op.PUSH1(0x00) + Op.PUSH1(0x00) # Perform the datacopy operation bytecode += Op.DATACOPY(dest, src, length) bytecode += Op.RETURN return Container(sections=[Section.Code(code=bytecode), Section.Data(data=data_section)]) @pytest.fixture def subcall_exact_cost( fork: Fork, initial_memory: bytes, dest: int, length: int, ) -> int: """ Return exact cost of the subcall, based on the initial memory and the length of the copy. """ cost_memory_bytes = fork.memory_expansion_gas_calculator() datacopy_cost = 3 datacopy_cost += 3 * ((length + 31) // 32) if length > 0 and dest + length > len(initial_memory): datacopy_cost += cost_memory_bytes( new_bytes=dest + length, previous_bytes=len(initial_memory) ) calldatacopy_cost = 3 calldatacopy_cost += 3 * ((len(initial_memory) + 31) // 32) calldatacopy_cost += cost_memory_bytes(new_bytes=len(initial_memory)) pushes_cost = 3 * 7 calldatasize_cost = 2 return datacopy_cost + calldatacopy_cost + pushes_cost + calldatasize_cost @pytest.fixture def bytecode_storage( subcall_exact_cost: int, successful: bool, memory_expansion_address: Address, ) -> Tuple[Bytecode, Storage.StorageDictType]: """ Prepare bytecode and storage for the test, based on the expected result of the subcall (whether it succeeds or fails depending on the length of the memory expansion). """ bytecode = Bytecode() storage = {} # Pass on the calldata bytecode += Op.CALLDATACOPY(0x00, 0x00, Op.CALLDATASIZE()) subcall_gas = subcall_exact_cost if successful else subcall_exact_cost - 1 # Perform the subcall and store a one in the result location bytecode += Op.SSTORE( Op.CALL(subcall_gas, memory_expansion_address, 0, 0, Op.CALLDATASIZE(), 0, 0), 1 ) storage[int(successful)] = 1 return (bytecode, storage) @pytest.fixture def tx_max_fee_per_gas() -> int: # noqa: D103 return 7 @pytest.fixture def block_gas_limit() -> int: # noqa: D103 return 100_000_000 @pytest.fixture def tx_gas_limit( # noqa: D103 subcall_exact_cost: int, block_gas_limit: int, ) -> int: return min(max(500_000, subcall_exact_cost * 2), block_gas_limit) @pytest.fixture def env( # noqa: D103 block_gas_limit: int, ) -> Environment: return Environment(gas_limit=block_gas_limit) @pytest.fixture def caller_address( # noqa: D103 pre: Alloc, bytecode_storage: Tuple[bytes, Storage.StorageDictType] ) -> Address: return pre.deploy_contract(code=bytecode_storage[0]) @pytest.fixture def memory_expansion_address(pre: Alloc, callee_bytecode: bytes) -> Address: # noqa: D103 return pre.deploy_contract(code=callee_bytecode) @pytest.fixture def sender(pre: Alloc, tx_max_fee_per_gas: int, tx_gas_limit: int) -> Address: # noqa: D103 return pre.fund_eoa(tx_max_fee_per_gas * tx_gas_limit) @pytest.fixture def tx( # noqa: D103 sender: Address, caller_address: Address, initial_memory: bytes, tx_max_fee_per_gas: int, tx_gas_limit: int, ) -> Transaction: return Transaction( sender=sender, to=caller_address, data=initial_memory, gas_limit=tx_gas_limit, max_fee_per_gas=tx_max_fee_per_gas, max_priority_fee_per_gas=0, ) @pytest.fixture def post( # noqa: D103 caller_address: Address, bytecode_storage: Tuple[bytes, Storage.StorageDictType] ) -> Mapping: return { caller_address: Account(storage=bytecode_storage[1]), } @pytest.mark.parametrize( "dest,src,length", [ (0x00, 0x00, 0x01), (0x100, 0x00, 0x01), (0x1F, 0x00, 0x01), (0x20, 0x00, 0x01), (0x1000, 0x00, 0x01), (0x1000, 0x00, 0x40), (0x00, 0x00, 0x00), (2**256 - 1, 0x00, 0x00), (0x00, 2**256 - 1, 0x00), (2**256 - 1, 2**256 - 1, 0x00), ], ids=[ "single_byte_expansion", "single_byte_expansion_2", "single_byte_expansion_word_boundary", "single_byte_expansion_word_boundary_2", "multi_word_expansion", "multi_word_expansion_2", "zero_length_expansion", "huge_dest_zero_length", "huge_src_zero_length", "huge_dest_huge_src_zero_length", ], ) @pytest.mark.parametrize("successful", [True, False]) @pytest.mark.parametrize( "initial_memory", [ bytes(range(0x00, 0x100)), bytes(), ], ids=[ "from_existent_memory", "from_empty_memory", ], ) @pytest.mark.parametrize( "data_section", [ bytes(), b"\xfc", bytes(range(0x00, 0x20)), bytes(range(0x00, 0x100)), ], ids=["empty_data_section", "byte_data_section", "word_data_section", "large_data_section"], ) def test_datacopy_memory_expansion( state_test: StateTestFiller, env: Environment, pre: Alloc, post: Mapping[str, Account], tx: Transaction, ) -> None: """ Perform DATACOPY operations that expand the memory, and verify the gas it costs to do so. """ state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "dest,src,length", [ pytest.param(2**256 - 1, 0x00, 0x01, id="max_dest_single_byte_expansion"), pytest.param(2**256 - 2, 0x00, 0x01, id="max_dest_minus_one_single_byte_expansion"), pytest.param(2**255 - 1, 0x00, 0x01, id="half_max_dest_single_byte_expansion"), pytest.param(0x00, 0x00, 2**256 - 1, id="max_length_expansion"), pytest.param(0x00, 0x00, 2**256 - 2, id="max_length_minus_one_expansion"), pytest.param(0x00, 0x00, 2**255 - 1, id="half_max_length_expansion"), pytest.param(0x1FFFF20, 0x00, 0x01, id="32-bit-mem-cost_offset"), pytest.param(0x2D412E0, 0x00, 0x01, id="33-bit-mem-cost_offset"), pytest.param(0x00, 0x00, 0x1FFFF20, id="32-bit-mem-cost_size"), pytest.param(0x00, 0x00, 0x2D412E0, id="33-bit-mem-cost_size"), pytest.param(0x1FFFFFFFF20, 0x00, 0x01, id="64-bit-mem-cost_offset"), pytest.param(0x2D413CCCF00, 0x00, 0x01, id="65-bit-mem-cost_offset"), pytest.param(0x00, 0x00, 0x1FFFFFFFF20, id="64-bit-mem-cost_size"), pytest.param(0x00, 0x00, 0x2D413CCCF00, id="65-bit-mem-cost_size"), ], ) @pytest.mark.parametrize( "subcall_exact_cost", [2**128 - 1], ids=[""], ) # Limit subcall gas, otherwise it would be impossibly large @pytest.mark.parametrize("successful", [False]) @pytest.mark.parametrize( "initial_memory", [ bytes(range(0x00, 0x100)), bytes(), ], ids=[ "from_existent_memory", "from_empty_memory", ], ) @pytest.mark.parametrize( "data_section", [ bytes(), b"\xfc", bytes(range(0x00, 0x20)), bytes(range(0x00, 0x100)), ], ids=["empty_data_section", "byte_data_section", "word_data_section", "large_data_section"], ) def test_datacopy_huge_memory_expansion( state_test: StateTestFiller, env: Environment, pre: Mapping[str, Account], post: Mapping[str, Account], tx: Transaction, ) -> None: """ Perform DATACOPY operations that expand the memory by huge amounts, and verify that it correctly runs out of gas. """ state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7480_data_section/test_data_opcodes.py
tests/unscheduled/eip7692_eof_v1/eip7480_data_section/test_data_opcodes.py
"""Execution of DATA* opcodes within EOF V1 containers tests.""" import pytest from ethereum_test_specs import EOFStateTestFiller from ethereum_test_tools import Account, Alloc, Environment, StateTestFiller, Transaction from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7480.md" REFERENCE_SPEC_VERSION = "3ee1334ef110420685f1c8ed63e80f9e1766c251" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize("index", [0, 1, 31, 32, 33, 63, 64]) @pytest.mark.parametrize("suffix_len", [0, 1, 31, 32, 24000]) def test_dataloadn(eof_state_test: EOFStateTestFiller, index: int, suffix_len: int) -> None: """Basic tests for DATALOADN execution.""" sentinel = 0x8000000000000000000000000000000000000000000000000000000000000001 eof_state_test( container=Container( sections=[ Section.Code( Op.SSTORE(0, Op.DATALOADN[index]) + Op.STOP, ), Section.Data( index * b"\xbe" + sentinel.to_bytes(32, byteorder="big") + suffix_len * b"\xaf" ), ], ), container_post=Account(storage={0: sentinel}), ) def create_data_test(offset: int, datasize: int) -> tuple[Container, dict[int, int]]: """ Generate data load operators test cases based on load offset and data section size. """ data = b"".join(i.to_bytes(length=2, byteorder="big") for i in range(1, datasize // 2 + 1)) assert len(data) == datasize overhang = min(32, offset + 32 - datasize) answer = data[offset : offset + 32] if overhang <= 0 else data[offset:] + b"\x00" * overhang dataloadn_op = Op.DATALOADN[offset] if overhang <= 0 else Op.PUSH32[answer] return ( Container( sections=[ Section.Code( code=( Op.CALLF[1] + Op.CALLF[2] + Op.CALLF[3] + Op.CALLF[4] + Op.SSTORE(0, 1) + Op.STOP ), ), Section.Code( code=(Op.DATALOAD(offset) + Op.PUSH1(1) + Op.SSTORE + Op.RETF), code_inputs=0, code_outputs=0, ), Section.Code( code=(dataloadn_op + Op.PUSH1(2) + Op.SSTORE + Op.RETF), code_inputs=0, code_outputs=0, ), Section.Code( code=(Op.DATASIZE + Op.PUSH1(3) + Op.SSTORE + Op.RETF), code_inputs=0, code_outputs=0, ), Section.Code( code=(Op.DATACOPY(0, offset, 32) + Op.SSTORE(4, Op.MLOAD(0)) + Op.RETF), code_inputs=0, code_outputs=0, ), Section.Data(data), ], ), { 0: 1, 1: int.from_bytes(answer, byteorder="big"), 2: int.from_bytes(answer, byteorder="big"), 3: datasize, 4: int.from_bytes(answer, byteorder="big"), }, ) @pytest.mark.parametrize( ["offset", "datasize"], [ pytest.param(0, 0, id="empty_zero"), pytest.param(0, 2, id="short_zero"), pytest.param(0, 32, id="exact_zero"), pytest.param(0, 64, id="large_zero"), pytest.param(32, 0, id="empty_32"), pytest.param(32, 34, id="short_32"), pytest.param(32, 64, id="exact_32"), pytest.param(32, 96, id="large_32"), pytest.param(0x5BFE, 0, id="empty_23k"), pytest.param(0x5BFE, 0x5C00, id="short_23k"), pytest.param(0x5BE0, 0x5D00, id="exact_23k"), pytest.param(0x2345, 0x5C00, id="large_23k"), pytest.param(2**16 - 1, 32, id="u16_max"), pytest.param(2**16, 32, id="u16_max_plus_1"), pytest.param(2**32 - 1, 32, id="u32_max"), pytest.param(2**32, 32, id="u32_max_plus_1"), pytest.param(2**64 - 1, 32, id="u64_max"), pytest.param(2**64, 32, id="u64_max_plus_1"), ], ) def test_data_section_succeed( state_test: StateTestFiller, pre: Alloc, offset: int, datasize: int, ) -> None: """Test simple contracts that simply expect data section to succeed.""" env = Environment() (container, expected_storage) = create_data_test(offset, datasize) callee_contract = pre.deploy_contract(code=container) entry_point = pre.deploy_contract( code=Op.SSTORE(0, Op.DELEGATECALL(Op.GAS, callee_contract, 0, 0, 0, 0)) + Op.STOP() ) sender = pre.fund_eoa() tx = Transaction( to=entry_point, gas_limit=50000000, gas_price=10, protected=False, data="", sender=sender, ) post = {entry_point: Account(storage=expected_storage)} state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_returndataload.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_returndataload.py
""" RETURNDATALOAD instruction tests Tests for RETURNDATALOAD instruction in [EIP-7069: Revamped CALL instructions](https://eips.ethereum.org/EIPS/eip-7069). """ from typing import cast import pytest from ethereum_test_tools import Account, Alloc, Environment, StateTestFiller, Storage, Transaction from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from . import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION from .helpers import ( slot_code_worked, slot_eof_target_call_status, slot_eof_target_returndata, slot_eof_target_returndatasize, slot_legacy_target_call_status, slot_legacy_target_returndatasize, value_code_worked, value_exceptional_abort_canary, ) from .spec import EXTCALL_FAILURE, EXTCALL_SUCCESS, LEGACY_CALL_FAILURE, LEGACY_CALL_SUCCESS REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "opcode", [ Op.CALL, Op.CALLCODE, Op.DELEGATECALL, Op.STATICCALL, Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) @pytest.mark.parametrize( "return_data", [ b"", b"\x10" * 0x10, b"\x20" * 0x20, b"\x30" * 0x30, ], ids=lambda x: "len_%x" % len(x), ) @pytest.mark.parametrize( "offset", [ 0, 0x10, 0x20, 0x30, ], ids=lambda x: "offset_%x" % x, ) @pytest.mark.parametrize( "size", [ 0, 0x10, 0x20, 0x30, ], ids=lambda x: "size_%x" % x, ) def test_returndatacopy_handling( state_test: StateTestFiller, pre: Alloc, opcode: Op, return_data: bytes, offset: int, size: int, ) -> None: """ Tests ReturnDataLoad including multiple offset conditions and differing legacy vs. eof boundary conditions. entrypoint creates a "0xff" test area of memory, delegate calls to caller. Caller is either EOF or legacy, as per parameter. Calls returner and copies the return data based on offset and size params. Cases are expected to trigger boundary violations. Entrypoint copies the test area to storage slots, and the expected result is asserted. """ env = Environment() slot_result_start = 0x1000 sender = pre.fund_eoa() address_returner = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.DATACOPY(0, 0, Op.DATASIZE) + Op.RETURN(0, Op.DATASIZE), ), Section.Data(data=return_data), ] ) ) result = [0xFF] * 0x40 result[0:size] = [0] * size extent = size - max(0, size + offset - len(return_data)) if extent > 0 and len(return_data) > 0: result[0:extent] = [return_data[0]] * extent code_under_test = ( opcode(address=address_returner) + Op.RETURNDATACOPY(0, offset, size) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, size) ) match opcode: case Op.EXTCALL | Op.EXTDELEGATECALL | Op.EXTSTATICCALL: address_caller = pre.deploy_contract( Container( sections=[ Section.Code( code=code_under_test, ) ] ) ) case Op.CALL | Op.CALLCODE | Op.DELEGATECALL | Op.STATICCALL: address_caller = pre.deploy_contract(code_under_test) address_entry_point = pre.deploy_contract( Op.NOOP # First, create a "dirty" area, so we can check zero overwrite + Op.MSTORE(0x00, -1) + Op.MSTORE(0x20, -1) # call the contract under test + Op.DELEGATECALL(1_000_000, address_caller, 0, 0, 0, 0) + Op.RETURNDATACOPY(0, 0, Op.RETURNDATASIZE) # store the return data + Op.SSTORE(slot_result_start, Op.MLOAD(0x0)) + Op.SSTORE(slot_result_start + 1, Op.MLOAD(0x20)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) post = { address_entry_point: Account( storage={ slot_code_worked: value_code_worked, slot_result_start: bytes(result[:0x20]), (slot_result_start + 0x1): bytes(result[0x20:]), } ) } if opcode in [Op.CALL, Op.CALLCODE, Op.DELEGATECALL, Op.STATICCALL] and ( (offset + size) > len(return_data) ): post[address_entry_point] = Account( storage={ slot_code_worked: value_code_worked, slot_result_start: b"\xff" * 32, slot_result_start + 1: b"\xff" * 32, } ) tx = Transaction(to=address_entry_point, gas_limit=2_000_000, sender=sender) state_test( env=env, pre=pre, tx=tx, post=post, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) @pytest.mark.parametrize( "return_data", [ b"", b"\x10" * 0x10, b"\x20" * 0x20, b"\x30" * 0x30, ], ids=lambda x: "len_%x" % len(x), ) @pytest.mark.parametrize( "offset", [ 0, 0x10, 0x20, 0x30, ], ids=lambda x: "offset_%x" % x, ) def test_returndataload_handling( state_test: StateTestFiller, pre: Alloc, opcode: Op, return_data: bytes, offset: int, ) -> None: """ Much simpler than returndatacopy, no memory or boosted call. Returner is called and results are stored in storage slot, which is asserted for expected values. The parameters offset and return data are configured to test boundary conditions. """ env = Environment() slot_result_start = 0x1000 sender = pre.fund_eoa() address_returner = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.DATACOPY(0, 0, Op.DATASIZE) + Op.RETURN(0, Op.DATASIZE), ), Section.Data(data=return_data), ] ) ) address_entry_point = pre.deploy_contract( Container( sections=[ Section.Code( code=opcode(address=address_returner) + Op.SSTORE(slot_result_start, Op.RETURNDATALOAD(offset)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ] ) ) result = [0] * 0x20 extent = 0x20 - max(0, 0x20 + offset - len(return_data)) if extent > 0 and len(return_data) > 0: result[0:extent] = [return_data[0]] * extent post = { address_entry_point: Account( storage={ slot_code_worked: value_code_worked, slot_result_start: bytes(result), } ) } tx = Transaction(to=address_entry_point, gas_limit=2_000_000, sender=sender) state_test( env=env, pre=pre, tx=tx, post=post, ) @pytest.mark.parametrize( "opcode", [ Op.CALL, Op.EXTCALL, ], ) def test_returndatacopy_oob( state_test: StateTestFiller, pre: Alloc, opcode: Op, ) -> None: """ Extends the RETURNDATACOPY test for correct out-of-bounds behavior, by checking if the caller frame's context being EOF or legacy doesn't impact the execution logic of the RETURNDATACOPY instance under test. """ env = Environment() sender = pre.fund_eoa() # Both callee codes below make an OOB (out-of-bounds) RETURNDATACOPY of one # byte, which they then attempt to return (Legacy should exceptionally halt # on RETURNDATACOPY). address_callee_eof = pre.deploy_contract( code=Container( sections=[ Section.Code( code=Op.RETURNDATACOPY(0, 0, 1) + Op.RETURN(0, 1), max_stack_height=3, ) ] ) ) address_callee_legacy = pre.deploy_contract(Op.RETURNDATACOPY(0, 0, 1) + Op.RETURN(0, 1)) # Caller code is selected to either be Legacy or EOF using params. code_entry_point = ( Op.SSTORE(slot_eof_target_call_status, opcode(address=address_callee_eof)) + Op.SSTORE(slot_eof_target_returndatasize, Op.RETURNDATASIZE) + Op.SSTORE(slot_eof_target_returndata, Op.RETURNDATACOPY(0, 0, 1) + Op.MLOAD(0)) + Op.SSTORE( slot_legacy_target_call_status, opcode(address=address_callee_legacy), ) + Op.SSTORE(slot_legacy_target_returndatasize, Op.RETURNDATASIZE) + Op.STOP ) storage_entry_point = Storage( cast( Storage.StorageDictType, { slot_eof_target_call_status: value_exceptional_abort_canary, slot_eof_target_returndata: value_exceptional_abort_canary, slot_eof_target_returndatasize: value_exceptional_abort_canary, slot_legacy_target_call_status: value_exceptional_abort_canary, slot_legacy_target_returndatasize: value_exceptional_abort_canary, }, ) ) address_entry_point = ( pre.deploy_contract(code=code_entry_point, storage=storage_entry_point) if opcode == Op.CALL else pre.deploy_contract( Container( sections=[ Section.Code( code=code_entry_point, max_stack_height=4, storage=storage_entry_point, ) ] ) ) ) tx = Transaction(to=address_entry_point, gas_limit=2_000_000, sender=sender) post = { address_entry_point: Account( storage={ slot_eof_target_call_status: LEGACY_CALL_SUCCESS, slot_eof_target_returndata: "0x00", slot_eof_target_returndatasize: "0x01", slot_legacy_target_call_status: LEGACY_CALL_FAILURE, slot_legacy_target_returndatasize: "0x00", } if opcode == Op.CALL else { slot_eof_target_call_status: EXTCALL_SUCCESS, slot_eof_target_returndata: "0x00", slot_eof_target_returndatasize: "0x01", slot_legacy_target_call_status: EXTCALL_FAILURE, slot_legacy_target_returndatasize: "0x00", } ) } state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/spec.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/spec.py
"""EOF V1 Constants used throughout all tests.""" LEGACY_CALL_FAILURE = 0 LEGACY_CALL_SUCCESS = 1 EXTCALL_SUCCESS = 0 EXTCALL_REVERT = 1 EXTCALL_FAILURE = 2
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_calldata.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_calldata.py
""" Call data tests for EXT*CALL instructions Tests for call data handling in [EIP-7069: Revamped CALL instructions](https://eips.ethereum.org/EIPS/eip-7069). """ import pytest from ethereum_test_tools import Account, Alloc, Environment, StateTestFiller, Transaction from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from . import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION from .helpers import ( size_calldata, slot_call_status, slot_calldata_1, slot_calldata_2, slot_code_worked, slot_delegate_code_worked, slot_eof_target_returndata, value_calldata_1, value_calldata_2, value_code_worked, value_exceptional_abort_canary, ) from .spec import EXTCALL_FAILURE, EXTCALL_SUCCESS, LEGACY_CALL_FAILURE, LEGACY_CALL_SUCCESS REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def right_pad_32(v: bytes) -> bytes: """Take bytes and returns a 32 byte version right padded with zeros.""" return v.ljust(32, b"\0") @pytest.mark.parametrize("value", [0, 1]) @pytest.mark.parametrize( "memory", [ b"", b"1234567890abcdef", b"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=-", b"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=-" * 4, ], ids=lambda x: "size_%d" % len(x), ) @pytest.mark.parametrize("offset", [0, 8, 24, 80]) @pytest.mark.parametrize("length", [0, 8, 32, 48]) def test_extcalls_inputdata( state_test: StateTestFiller, pre: Alloc, value: int, memory: bytes, offset: int, length: int, ) -> None: """ Tests call data into EXTCALL including multiple offset conditions. Caller pushes data into memory, then calls the target. Target writes 64 bytes of call data to storage and a success byte. """ env = Environment() sender = pre.fund_eoa() address_returner = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.SSTORE(slot_calldata_1, Op.CALLDATALOAD(0)) + Op.SSTORE(slot_calldata_2, Op.CALLDATALOAD(32)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ), ] ), ) address_caller = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.DATACOPY(0, 0, len(memory)) + Op.SSTORE( slot_call_status, Op.EXTCALL(address_returner, offset, length, value), ) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ), Section.Data(data=memory), ] ), storage={slot_call_status: value_exceptional_abort_canary}, balance=10**9, ) calldata = memory[offset : offset + length] post = { address_returner: Account( storage={ slot_code_worked: value_code_worked, slot_calldata_1: right_pad_32(calldata[0:32]), slot_calldata_2: right_pad_32(calldata[32:64]), } ), address_caller: Account( storage={ slot_code_worked: value_code_worked, slot_call_status: EXTCALL_SUCCESS, } ), } tx = Transaction(to=address_caller, gas_limit=2_000_000, sender=sender) state_test( env=env, pre=pre, tx=tx, post=post, ) @pytest.mark.parametrize( "memory", [ b"", b"1234567890abcdef", b"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=-", b"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=-" * 4, ], ids=lambda x: "size_%d" % len(x), ) @pytest.mark.parametrize("offset", [0, 8, 24, 80]) @pytest.mark.parametrize("length", [0, 8, 32, 48]) def test_extdelegatecall_inputdata( state_test: StateTestFiller, pre: Alloc, memory: bytes, offset: int, length: int, ) -> None: """ Tests call data into EXTDELEGATECALL including multiple offset conditions. Caller pushes data into memory, then calls the target. Target writes 64 bytes of call data to storage and a success byte. """ env = Environment() sender = pre.fund_eoa() address_returner = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.SSTORE(slot_calldata_1, Op.CALLDATALOAD(0)) + Op.SSTORE(slot_calldata_2, Op.CALLDATALOAD(32)) + Op.SSTORE(slot_delegate_code_worked, value_code_worked) + Op.STOP ), ] ), ) address_caller = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.DATACOPY(0, 0, len(memory)) + Op.SSTORE( slot_call_status, Op.EXTDELEGATECALL(address_returner, offset, length), ) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ), Section.Data(data=memory), ] ), storage={slot_call_status: value_exceptional_abort_canary}, balance=10**9, ) calldata = memory[offset : offset + length] post = { address_returner: Account(storage={}), address_caller: Account( storage={ slot_code_worked: value_code_worked, slot_delegate_code_worked: value_code_worked, slot_call_status: EXTCALL_SUCCESS, slot_calldata_1: right_pad_32(calldata[0:32]), slot_calldata_2: right_pad_32(calldata[32:64]), } ), } tx = Transaction(to=address_caller, gas_limit=2_000_000, sender=sender) state_test( env=env, pre=pre, tx=tx, post=post, ) @pytest.mark.parametrize( "memory", [ b"", b"1234567890abcdef", b"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=-", b"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=-" * 4, ], ids=lambda x: "size_%d" % len(x), ) @pytest.mark.parametrize("offset", [0, 8, 24, 80]) @pytest.mark.parametrize("length", [0, 8, 32, 48]) def test_extstaticcall_inputdata( state_test: StateTestFiller, pre: Alloc, memory: bytes, offset: int, length: int, ) -> None: """ Tests call data into EXTSTATICCALL including multiple offset conditions. Caller pushes data into memory, then calls the target. Target writes 64 bytes of call data to storage and a success byte. """ env = Environment() sender = pre.fund_eoa() address_returner = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.RETURN(0, Op.CALLDATASIZE) ), ] ), ) address_caller = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.DATACOPY(0, 0, len(memory)) + Op.SSTORE( slot_call_status, Op.EXTSTATICCALL(address_returner, offset, length), ) + Op.SSTORE(slot_calldata_1, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_calldata_2, Op.RETURNDATALOAD(32)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ), Section.Data(data=memory), ] ), storage={slot_call_status: value_exceptional_abort_canary}, balance=10**9, ) calldata = memory[offset : offset + length] post = { address_returner: Account(storage={}), address_caller: Account( storage={ slot_code_worked: value_code_worked, slot_call_status: EXTCALL_SUCCESS, slot_calldata_1: right_pad_32(calldata[0:32]), slot_calldata_2: right_pad_32(calldata[32:64]), } ), } tx = Transaction(to=address_caller, gas_limit=2_000_000, sender=sender) state_test( env=env, pre=pre, tx=tx, post=post, ) @pytest.mark.parametrize( "opcode", [ Op.CALL, Op.CALLCODE, Op.DELEGATECALL, Op.STATICCALL, Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) def test_calldata_remains_after_subcall( state_test: StateTestFiller, pre: Alloc, opcode: Op, ) -> None: """ Tests call data remains after a call to another contract. Caller pushes data into memory, then calls the target. Target calls 3rd contract. 3rd contract returns. Target writes calldata to storage. """ env = Environment() sender = pre.fund_eoa() address_sub_called = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.SSTORE(slot_delegate_code_worked, value_code_worked) + Op.STOP ) ] ), storage={slot_delegate_code_worked: value_exceptional_abort_canary}, ) called_code = ( Op.MSTORE(0, value_calldata_2) + Op.SSTORE(slot_call_status, value_exceptional_abort_canary) + Op.SSTORE(slot_calldata_1, value_exceptional_abort_canary) + Op.SSTORE(slot_code_worked, value_exceptional_abort_canary) + Op.SSTORE( slot_call_status, opcode( address=address_sub_called, args_offset=0, args_size=size_calldata, ), ) + Op.SSTORE(slot_calldata_1, Op.CALLDATALOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) match opcode: case Op.CALL | Op.CALLCODE | Op.DELEGATECALL | Op.STATICCALL: address_called = pre.deploy_contract(code=called_code) case Op.EXTCALL | Op.EXTDELEGATECALL | Op.EXTSTATICCALL: address_called = pre.deploy_contract( Container( sections=[ Section.Code(code=called_code), ] ), ) address_caller = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.MSTORE(0, value_calldata_1) + Op.SSTORE(slot_calldata_1, value_exceptional_abort_canary) + Op.SSTORE(slot_code_worked, value_exceptional_abort_canary) + Op.SSTORE( slot_call_status, Op.EXTCALL(address_called, 0, size_calldata, 0), ) + Op.SSTORE(slot_calldata_1, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ), ] ), storage={slot_call_status: value_exceptional_abort_canary}, balance=10**9, ) match opcode: case Op.STATICCALL: called_storage = { slot_code_worked: value_code_worked, slot_call_status: LEGACY_CALL_FAILURE, slot_calldata_1: value_calldata_1, } sub_called_storage = { slot_delegate_code_worked: value_exceptional_abort_canary, } case Op.DELEGATECALL | Op.CALLCODE: called_storage = { slot_code_worked: value_code_worked, slot_delegate_code_worked: value_code_worked, slot_call_status: LEGACY_CALL_SUCCESS, slot_calldata_1: value_calldata_1, } sub_called_storage = { slot_delegate_code_worked: value_exceptional_abort_canary, } case Op.CALL: called_storage = { slot_code_worked: value_code_worked, slot_call_status: LEGACY_CALL_SUCCESS, slot_calldata_1: value_calldata_1, } sub_called_storage = { slot_delegate_code_worked: value_code_worked, } case Op.EXTSTATICCALL: called_storage = { slot_code_worked: value_code_worked, slot_call_status: EXTCALL_FAILURE, slot_calldata_1: value_calldata_1, } sub_called_storage = { slot_delegate_code_worked: value_exceptional_abort_canary, } case Op.EXTDELEGATECALL: called_storage = { slot_code_worked: value_code_worked, slot_delegate_code_worked: value_code_worked, slot_call_status: EXTCALL_SUCCESS, slot_calldata_1: value_calldata_1, } sub_called_storage = { slot_delegate_code_worked: value_exceptional_abort_canary, } case Op.EXTCALL: called_storage = { slot_code_worked: value_code_worked, slot_call_status: EXTCALL_SUCCESS, slot_calldata_1: value_calldata_1, } sub_called_storage = { slot_delegate_code_worked: value_code_worked, } case _: raise ValueError(f"Unexpected opcode: {opcode}") post = { address_caller: Account(storage={slot_code_worked: value_code_worked}), address_called: Account(storage=called_storage), address_sub_called: Account(storage=sub_called_storage), } tx = Transaction(to=address_caller, gas_limit=4_000_000, sender=sender) state_test( env=env, pre=pre, tx=tx, post=post, ) @pytest.mark.parametrize("operation", [Op.EXTCALL, Op.EXTSTATICCALL, Op.EXTDELEGATECALL]) @pytest.mark.parametrize( "offset_field", [ pytest.param(True, id="offset"), pytest.param(False, id="size"), ], ) @pytest.mark.parametrize( ("test_arg", "success"), [ pytest.param(0, True, id="zero"), pytest.param(0xFF, True, id="8-bit"), pytest.param(0x100, True, id="9-bit"), pytest.param(0xFFFF, True, id="16-bit"), pytest.param(0x10000, True, id="17-bit"), pytest.param(0x1FFFF20, False, id="32-bit-mem-cost"), pytest.param(0x2D412E0, False, id="33-bit-mem-cost"), pytest.param(0xFFFFFFFF, False, id="32-bit"), pytest.param(0x100000000, False, id="33-bit"), pytest.param(0x1FFFFFFFF20, False, id="64-bit-mem-cost"), pytest.param(0x2D413CCCF00, False, id="65-bit-mem-cost"), pytest.param(0xFFFFFFFFFFFFFFFF, False, id="64-bit"), pytest.param(0x10000000000000000, False, id="65-bit"), pytest.param(0xFFFFFFFFFFFFFFFF, False, id="128-bit"), pytest.param(0x10000000000000000, False, id="129-bit"), pytest.param(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, False, id="256-bit"), ], ) def test_extcalls_input_offset( state_test: StateTestFiller, pre: Alloc, operation: Op, offset_field: str, test_arg: int, success: bool, ) -> None: """ Tests call data into EXT*CALL including multiple offset conditions. Returner returns a success value, which caller stores. If memory expansion cost is less than 2 billion gas call succeeds. Else whole transaction aborts, leaving canaries in memory. The name id of `*-mem-cost` refers to the bit-length of the result of the calculated memory expansion cost. Their length choice is designed to cause problems on shorter bit-length representations with native integers. The `offset_field` param indicates what part of the input data arguments are being tested, either the offset of the data in memory or the size of the data in memory. The `test_arg` param is the value passed into the field being tested (offset or size), intending to trigger integer size bugs for that particular field. """ env = Environment(gas_limit=1_000_000_000) sender = pre.fund_eoa() address_returner = pre.deploy_contract( Container( sections=[ Section.Code(code=Op.MSTORE(0, value_code_worked) + Op.RETURN(0, 32)), ] ), ) address_caller = pre.deploy_contract( Container( sections=[ Section.Code( code=( operation(address=address_returner, args_offset=test_arg, args_size=32) if offset_field else operation( address=address_returner, args_offset=32, args_size=test_arg ) ) + Op.SSTORE(slot_eof_target_returndata, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) ] ), storage={ slot_code_worked: value_exceptional_abort_canary, slot_eof_target_returndata: value_exceptional_abort_canary, }, ) post = { address_caller: Account( storage={ slot_eof_target_returndata: value_code_worked if success else value_exceptional_abort_canary, slot_code_worked: value_code_worked if success else value_exceptional_abort_canary, } ), } tx = Transaction(to=address_caller, gas_limit=1_000_000_000, sender=sender) state_test( env=env, pre=pre, tx=tx, post=post, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_address_space_extension.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_address_space_extension.py
"""Tests the "Address Space Extension" aspect of EXT*CALL.""" import itertools import pytest from ethereum_test_tools import Account, Address, Alloc, Environment, StateTestFiller, Transaction from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import value_exceptional_abort_canary from .spec import EXTCALL_REVERT, EXTCALL_SUCCESS, LEGACY_CALL_SUCCESS REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7069.md" REFERENCE_SPEC_VERSION = "1795943aeacc86131d5ab6bb3d65824b3b1d4cad" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) _slot = itertools.count(1) slot_top_level_call_status = next(_slot) slot_target_call_status = next(_slot) slot_target_returndata = next(_slot) @pytest.mark.parametrize( "target_address", ( pytest.param(b"", id="zero"), pytest.param(b"\xc0\xde", id="short"), pytest.param(b"\x78" * 20, id="mid_20"), pytest.param(b"\xff" * 20, id="max_20"), pytest.param(b"\x01" + (b"\x00" * 20), id="min_ase"), pytest.param(b"\x5a" * 28, id="mid_ase"), pytest.param(b"\x5a" * 32, id="full_ase"), pytest.param(b"\xff" * 32, id="max_ase"), ), ) @pytest.mark.parametrize( "target_account_type", ( "empty", "EOA", "LegacyContract", # Hard-codes an address in pre-alloc "EOFContract", # Hard-codes an address in pre-alloc ), ids=lambda x: x, ) @pytest.mark.parametrize( "target_opcode", ( Op.CALL, Op.CALLCODE, Op.STATICCALL, Op.DELEGATECALL, Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ), ) def test_address_space_extension( state_test: StateTestFiller, pre: Alloc, target_address: bytes, target_opcode: Op, target_account_type: str, ) -> None: """ Test contacts with possibly extended address and fail if address is too large. """ env = Environment() ase_address = len(target_address) > 20 stripped_address = Address(target_address[-20:], left_padding=True) if ase_address and target_address[0] == b"00": raise ValueError("Test instrumentation requires target addresses trim leading zeros") ase_ready_opcode = ( False if target_opcode in [Op.CALL, Op.CALLCODE, Op.DELEGATECALL, Op.STATICCALL] else True ) sender = pre.fund_eoa() address_caller = pre.deploy_contract( Container( sections=[ Section.Code( code=Op.SSTORE( slot_target_call_status, target_opcode(address=Op.CALLDATALOAD(0)), ) + Op.RETURNDATACOPY(0, 0, Op.RETURNDATASIZE) + Op.SSTORE(slot_target_returndata, Op.MLOAD(0)) + Op.STOP, code_inputs=0, ) ], ) if ase_ready_opcode else Op.SSTORE( slot_target_call_status, target_opcode(address=Op.CALLDATALOAD(0)), ) + Op.RETURNDATACOPY(0, 0, Op.RETURNDATASIZE) + Op.SSTORE(slot_target_returndata, Op.MLOAD(0)) + Op.STOP, storage={ slot_target_call_status: value_exceptional_abort_canary, slot_target_returndata: value_exceptional_abort_canary, }, ) address_entry_point = pre.deploy_contract( Op.MSTORE(0, Op.PUSH32(target_address)) + Op.SSTORE( slot_top_level_call_status, Op.CALL(50000, address_caller, 0, 0, 32, 0, 0), ) + Op.STOP(), storage={ slot_top_level_call_status: value_exceptional_abort_canary, }, ) match target_account_type: case "empty": # add no account pass case "EOA": pre.fund_address(stripped_address, 10**18) # TODO: we could use pre.fund_eoa here with nonce!=0. case "LegacyContract": pre[stripped_address] = Account( code=Op.MSTORE(0, Op.ADDRESS) + Op.RETURN(0, 32), balance=0, nonce=0, ) case "EOFContract": pre[stripped_address] = Account( code=Container( sections=[ Section.Code( code=Op.MSTORE(0, Op.ADDRESS) + Op.RETURN(0, 32), ) ], ), balance=0, nonce=0, ) caller_storage: dict[int, int | bytes | Address] = {} match target_account_type: case "empty" | "EOA": if ase_address and ase_ready_opcode: caller_storage[slot_target_call_status] = value_exceptional_abort_canary caller_storage[slot_target_returndata] = value_exceptional_abort_canary elif target_opcode == Op.EXTDELEGATECALL: caller_storage[slot_target_call_status] = EXTCALL_REVERT caller_storage[slot_target_returndata] = 0 else: caller_storage[slot_target_call_status] = ( EXTCALL_SUCCESS if ase_ready_opcode else LEGACY_CALL_SUCCESS ) case "LegacyContract" | "EOFContract": match target_opcode: case Op.CALL | Op.STATICCALL: caller_storage[slot_target_call_status] = LEGACY_CALL_SUCCESS # CALL and STATICCALL call will call the stripped address caller_storage[slot_target_returndata] = stripped_address case Op.CALLCODE | Op.DELEGATECALL: caller_storage[slot_target_call_status] = LEGACY_CALL_SUCCESS # CALLCODE and DELEGATECALL call will call the stripped # address but will change the sender to self caller_storage[slot_target_returndata] = address_caller case Op.EXTCALL | Op.EXTSTATICCALL: # EXTCALL and EXTSTATICCALL will fault if calling an ASE # address if ase_address: caller_storage[slot_target_call_status] = value_exceptional_abort_canary caller_storage[slot_target_returndata] = value_exceptional_abort_canary else: caller_storage[slot_target_call_status] = EXTCALL_SUCCESS caller_storage[slot_target_returndata] = stripped_address case Op.EXTDELEGATECALL: if ase_address: caller_storage[slot_target_call_status] = value_exceptional_abort_canary caller_storage[slot_target_returndata] = value_exceptional_abort_canary elif target_account_type == "LegacyContract": caller_storage[slot_target_call_status] = EXTCALL_REVERT caller_storage[slot_target_returndata] = 0 else: caller_storage[slot_target_call_status] = EXTCALL_SUCCESS # EXTDELEGATECALL call will call the stripped address # but will change the sender to self caller_storage[slot_target_returndata] = address_caller post = { address_entry_point: Account( storage={ slot_top_level_call_status: EXTCALL_SUCCESS if ase_ready_opcode and ase_address else LEGACY_CALL_SUCCESS } ), address_caller: Account(storage=caller_storage), } tx = Transaction( sender=sender, to=address_entry_point, gas_limit=50_000_000, data="", ) state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_calls.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_calls.py
"""test calls across EOF and Legacy.""" import itertools from enum import Enum, auto, unique import pytest from ethereum_test_base_types import Address, HashInt from ethereum_test_tools import ( EOA, Account, Alloc, Environment, StateTestFiller, Storage, Transaction, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.helpers import compute_eofcreate_address from ethereum_test_vm import Bytecode, EVMCodeType from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .spec import ( EXTCALL_FAILURE, EXTCALL_REVERT, EXTCALL_SUCCESS, LEGACY_CALL_FAILURE, LEGACY_CALL_SUCCESS, ) pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-3540.md" REFERENCE_SPEC_VERSION = "2f013de4065babde7c02f84a2ce9864a3c5bfbd3" """Storage addresses for common testing fields""" _slot = itertools.count(1) slot_code_worked = next(_slot) slot_call_result = next(_slot) slot_returndata = next(_slot) slot_returndatasize = next(_slot) slot_caller = next(_slot) slot_returndatasize_before_clear = next(_slot) slot_max_depth = next(_slot) slot_last_slot = next(_slot) """Storage values for common testing fields""" value_code_worked = 0x2015 value_returndata_magic = b"\x42" contract_eof_sstore = Container( sections=[ Section.Code( code=Op.SSTORE(slot_caller, Op.CALLER()) + Op.STOP, ) ] ) @unique class TargetAccountType(Enum): """Kinds of target accounts for calls.""" EMPTY = auto() EOA = auto() LEGACY_CONTRACT = auto() EOF_CONTRACT = auto() LEGACY_CONTRACT_INVALID = auto() EOF_CONTRACT_INVALID = auto() LEGACY_CONTRACT_REVERT = auto() EOF_CONTRACT_REVERT = auto() IDENTITY_PRECOMPILE = auto() def __str__(self) -> str: """Return string representation of the enum.""" return f"{self.name}" @pytest.fixture def target_address(pre: Alloc, target_account_type: TargetAccountType) -> Address: """Target address of the call depending on required type of account.""" match target_account_type: case TargetAccountType.EMPTY: return pre.fund_eoa(amount=0) case TargetAccountType.EOA: return pre.fund_eoa() case TargetAccountType.LEGACY_CONTRACT: return pre.deploy_contract( code=Op.STOP, ) case TargetAccountType.EOF_CONTRACT: return pre.deploy_contract( code=Container.Code(Op.STOP), ) case TargetAccountType.LEGACY_CONTRACT_INVALID: return pre.deploy_contract( code=Op.INVALID, ) case TargetAccountType.EOF_CONTRACT_INVALID: return pre.deploy_contract( code=Container.Code(Op.INVALID), ) case TargetAccountType.LEGACY_CONTRACT_REVERT: return pre.deploy_contract( code=Op.REVERT(0, 0), ) case TargetAccountType.EOF_CONTRACT_REVERT: return pre.deploy_contract( code=Container.Code(Op.REVERT(0, 0)), ) case TargetAccountType.IDENTITY_PRECOMPILE: return identity @pytest.mark.parametrize( "opcode", [ Op.CALL, Op.DELEGATECALL, Op.CALLCODE, Op.STATICCALL, ], ) def test_legacy_calls_eof_sstore( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """Test legacy contracts calling EOF contracts that use SSTORE.""" env = Environment() destination_contract_address = pre.deploy_contract(contract_eof_sstore) caller_contract = Op.SSTORE( slot_call_result, opcode(address=destination_contract_address) ) + Op.SSTORE(slot_code_worked, value_code_worked) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = Storage( { slot_code_worked: value_code_worked, # type: ignore slot_call_result: LEGACY_CALL_SUCCESS, # type: ignore } ) destination_storage = Storage() if opcode == Op.CALL: destination_storage[slot_caller] = calling_contract_address elif opcode == Op.DELEGATECALL: calling_storage[slot_caller] = sender elif opcode == Op.CALLCODE: calling_storage[slot_caller] = calling_contract_address elif opcode == Op.STATICCALL: calling_storage[slot_call_result] = LEGACY_CALL_FAILURE post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage=destination_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.CALL, Op.DELEGATECALL, Op.CALLCODE, Op.STATICCALL, ], ) def test_legacy_calls_eof_mstore( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """Test legacy contracts calling EOF contracts that only return data.""" env = Environment() destination_contract_code = Container( sections=[ Section.Code( code=Op.MSTORE8(0, int.from_bytes(value_returndata_magic, "big")) + Op.RETURN(0, len(value_returndata_magic)), ) ] ) destination_contract_address = pre.deploy_contract(destination_contract_code) caller_contract = ( Op.SSTORE(slot_call_result, opcode(address=destination_contract_address)) + Op.SSTORE(slot_returndatasize, Op.RETURNDATASIZE) + Op.RETURNDATACOPY(31, 0, 1) + Op.SSTORE(slot_returndata, Op.MLOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = { slot_code_worked: value_code_worked, slot_call_result: LEGACY_CALL_SUCCESS, slot_returndatasize: len(value_returndata_magic), slot_returndata: value_returndata_magic, } post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage={}), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) def test_eof_calls_eof_sstore( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """Test EOF contracts calling EOF contracts that use SSTORE.""" env = Environment() destination_contract_address = pre.deploy_contract(contract_eof_sstore) caller_contract = Container( sections=[ Section.Code( code=Op.SSTORE(slot_call_result, opcode(address=destination_contract_address)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ] ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = Storage( { HashInt(slot_code_worked): HashInt(value_code_worked), HashInt(slot_call_result): HashInt(EXTCALL_SUCCESS), } ) destination_storage = Storage() if opcode == Op.EXTCALL: destination_storage[slot_caller] = calling_contract_address elif opcode == Op.EXTDELEGATECALL: calling_storage[slot_caller] = sender elif opcode == Op.EXTSTATICCALL: calling_storage[slot_call_result] = EXTCALL_FAILURE post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage=destination_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) def test_eof_calls_eof_mstore( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """Test EOF contracts calling EOF contracts that return data.""" env = Environment() destination_contract_code = Container( sections=[ Section.Code( code=Op.MSTORE8(0, int.from_bytes(value_returndata_magic, "big")) + Op.RETURN(0, 32), ) ] ) destination_contract_address = pre.deploy_contract(destination_contract_code) caller_contract = Container( sections=[ Section.Code( code=Op.SSTORE(slot_call_result, opcode(address=destination_contract_address)) + Op.SSTORE(slot_returndatasize, Op.RETURNDATASIZE) + Op.SSTORE(slot_returndata, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ] ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = { slot_code_worked: value_code_worked, slot_call_result: EXTCALL_SUCCESS, slot_returndatasize: 0x20, slot_returndata: value_returndata_magic + b"\0" * (0x20 - len(value_returndata_magic)), } post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage={}), } state_test( env=env, pre=pre, post=post, tx=tx, ) identity = Address(0x04) # `blake2f`` is chosen for the test because it fails unless args_size == 213, # which is what we are interested in. blake2f = Address(0x09) # `p256verify` / RIP-7212 has been in and out of prague and osaka. # Hence we need to test explicitly p256verify = Address(0x100) @pytest.mark.parametrize( ["opcode", "precompile", "expected_result"], [ pytest.param(Op.EXTCALL, identity, EXTCALL_SUCCESS, id="extcall_success"), pytest.param(Op.EXTDELEGATECALL, identity, EXTCALL_REVERT, id="extdelegatecall_blocked1"), pytest.param(Op.EXTSTATICCALL, identity, EXTCALL_SUCCESS, id="extstaticcall_success"), pytest.param(Op.EXTCALL, blake2f, EXTCALL_FAILURE, id="extcall_failure"), pytest.param(Op.EXTDELEGATECALL, blake2f, EXTCALL_REVERT, id="extdelegatecall_blocked2"), pytest.param(Op.EXTSTATICCALL, blake2f, EXTCALL_FAILURE, id="extstaticcall_failure"), pytest.param(Op.EXTCALL, p256verify, EXTCALL_SUCCESS, id="extcall_p256verify"), pytest.param( Op.EXTDELEGATECALL, p256verify, EXTCALL_REVERT, id="extdelegatecall_p256verify" ), pytest.param(Op.EXTSTATICCALL, p256verify, EXTCALL_SUCCESS, id="extstaticcall_p256verify"), ], ) def test_eof_calls_precompile( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, precompile: Address, expected_result: int, ) -> None: """Test EOF contracts calling precompiles.""" env = Environment() caller_contract = Container.Code( Op.MSTORE(0, value_returndata_magic) + Op.SSTORE(slot_call_result, opcode(address=precompile, args_offset=0, args_size=32)) + Op.SSTORE(slot_returndatasize, Op.RETURNDATASIZE) + Op.SSTORE(slot_returndata, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=5000000, ) success_identity = expected_result == EXTCALL_SUCCESS and precompile == identity calling_storage = { slot_code_worked: value_code_worked, slot_call_result: expected_result, slot_returndatasize: 32 if success_identity else 0, slot_returndata: value_returndata_magic if success_identity else 0, } post = { calling_contract_address: Account(storage=calling_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) def test_eof_calls_legacy_sstore( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """Test EOF contracts calling Legacy contracts that use SSTORE.""" env = Environment() destination_contract_code = Op.SSTORE(slot_caller, Op.CALLER()) + Op.STOP destination_contract_address = pre.deploy_contract(destination_contract_code) caller_contract = Container( sections=[ Section.Code( code=Op.SSTORE(slot_call_result, opcode(address=destination_contract_address)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ] ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = { slot_code_worked: value_code_worked, slot_call_result: EXTCALL_SUCCESS, } destination_storage = {} if opcode == Op.EXTCALL: destination_storage[slot_caller] = calling_contract_address elif opcode == Op.EXTDELEGATECALL: # EOF delegate call to legacy is a light failure by rule calling_storage[slot_call_result] = EXTCALL_REVERT elif opcode == Op.EXTSTATICCALL: calling_storage[slot_call_result] = EXTCALL_FAILURE post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage=destination_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) def test_eof_calls_legacy_mstore( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """Test EOF contracts calling Legacy contracts that return data.""" env = Environment() destination_contract_code = Op.MSTORE8( 0, int.from_bytes(value_returndata_magic, "big") ) + Op.RETURN(0, 32) destination_contract_address = pre.deploy_contract(destination_contract_code) caller_contract = Container( sections=[ Section.Code( code=Op.SSTORE(slot_call_result, opcode(address=destination_contract_address)) + Op.SSTORE(slot_returndatasize, Op.RETURNDATASIZE) + Op.SSTORE(slot_returndata, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) ] ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = { slot_code_worked: value_code_worked, slot_call_result: EXTCALL_SUCCESS, slot_returndatasize: 0x20, slot_returndata: value_returndata_magic + b"\0" * (0x20 - len(value_returndata_magic)), } if opcode == Op.EXTDELEGATECALL: # EOF delegate call to legacy is a light failure by rule calling_storage[slot_call_result] = EXTCALL_REVERT calling_storage[slot_returndatasize] = 0 calling_storage[slot_returndata] = 0 post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage={}), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) @pytest.mark.parametrize( ["destination_code", "expected_result"], [ pytest.param(Op.REVERT(0, 0), EXTCALL_REVERT, id="legacy_revert"), pytest.param(Op.INVALID, EXTCALL_FAILURE, id="legacy_invalid"), pytest.param(Op.SHA3(0, 2**255), EXTCALL_FAILURE, id="legacy_oog"), pytest.param(Op.RETURNDATACOPY(0, 1, 2), EXTCALL_FAILURE, id="legacy_oob_returndata"), pytest.param(Container.Code(Op.REVERT(0, 0)), EXTCALL_REVERT, id="eof_revert"), pytest.param(Container.Code(Op.INVALID), EXTCALL_FAILURE, id="eof_invalid"), pytest.param(Container.Code(Op.SHA3(0, 2**255) + Op.STOP), EXTCALL_FAILURE, id="eof_oog"), ], ) def test_callee_fails( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, destination_code: Bytecode | Container, expected_result: int, ) -> None: """Test EOF contracts calling contracts that fail for various reasons.""" env = Environment() destination_contract_address = pre.deploy_contract(destination_code) caller_contract = Container.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.SSTORE(slot_call_result, opcode(address=destination_contract_address)) + Op.STOP, ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=4000000, ) calling_storage = { slot_code_worked: value_code_worked, slot_call_result: EXTCALL_REVERT if opcode == Op.EXTDELEGATECALL and not isinstance(destination_code, Container) else expected_result, } post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage={}), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( ["opcode", "destination_code", "expected_result"], [ pytest.param(Op.EXTCALL, Op.ADDRESS, "destination", id="extcall_address"), pytest.param(Op.EXTDELEGATECALL, Op.ADDRESS, "caller", id="extdelegatecall_address"), pytest.param(Op.EXTSTATICCALL, Op.ADDRESS, "destination", id="extstaticcall_address"), pytest.param(Op.EXTCALL, Op.CALLER, "caller", id="extcall_caller"), pytest.param(Op.EXTDELEGATECALL, Op.CALLER, "sender", id="extdelegatecall_caller"), pytest.param(Op.EXTSTATICCALL, Op.CALLER, "caller", id="extstaticcall_caller"), pytest.param(Op.EXTCALL, Op.CALLVALUE, 0, id="extcall_call_value"), pytest.param( Op.EXTDELEGATECALL, Op.CALLVALUE, "tx_value", id="extdelegatecall_call_value" ), pytest.param(Op.EXTSTATICCALL, Op.CALLVALUE, 0, id="extstaticcall_call_value"), pytest.param(Op.EXTCALL, Op.ORIGIN, "sender", id="extcall_origin"), pytest.param(Op.EXTDELEGATECALL, Op.ORIGIN, "sender", id="extdelegatecall_origin"), pytest.param(Op.EXTSTATICCALL, Op.ORIGIN, "sender", id="extstaticcall_origin"), ], ) @pytest.mark.with_all_evm_code_types def test_callee_context( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, destination_code: Bytecode, expected_result: str | int, evm_code_type: EVMCodeType, ) -> None: """Test EOF calls' callee context instructions.""" env = Environment() tx_value = 0x1123 destination_contract_address = pre.deploy_contract( Op.MSTORE(0, destination_code) + Op.RETURN(0, 32) ) caller_contract = Container.Code( Op.SSTORE(slot_code_worked, value_code_worked) + opcode(address=destination_contract_address) + Op.SSTORE(slot_returndata, Op.RETURNDATALOAD(0)) + Op.STOP, ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=100000, value=tx_value, ) expected_bytes: Address | int if expected_result == "destination": expected_bytes = destination_contract_address elif expected_result == "caller": expected_bytes = calling_contract_address elif expected_result == "sender": expected_bytes = sender elif expected_result == "tx_value": expected_bytes = tx_value elif isinstance(expected_result, int): expected_bytes = expected_result else: raise TypeError("Unexpected expected_result", expected_result) calling_storage = { slot_code_worked: value_code_worked, slot_returndata: 0 if (opcode == Op.EXTDELEGATECALL and evm_code_type == EVMCodeType.LEGACY) else expected_bytes, } post = { calling_contract_address: Account(storage=calling_storage), destination_contract_address: Account(storage={}), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, ], ) @pytest.mark.parametrize("fail_opcode", [Op.REVERT, Op.INVALID]) def test_eof_calls_eof_then_fails( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, fail_opcode: Op, ) -> None: """Test EOF contracts calling EOF contracts and failing after the call.""" env = Environment() destination_contract_address = pre.deploy_contract(contract_eof_sstore) caller_contract = Container.Code( Op.SSTORE(slot_call_result, opcode(address=destination_contract_address)) + Op.SSTORE(slot_code_worked, value_code_worked) + fail_opcode(offset=0, size=0), ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) post = { calling_contract_address: Account(storage=Storage()), destination_contract_address: Account(storage=Storage()), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) @pytest.mark.parametrize( "target_account_type", TargetAccountType, ) @pytest.mark.parametrize("value", [0, 1]) def test_eof_calls_clear_return_buffer( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, target_address: Address, value: int, ) -> None: """Test EOF contracts calling clears returndata buffer.""" env = Environment() filling_contract_code = Container.Code( Op.MSTORE8(0, int.from_bytes(value_returndata_magic, "big")) + Op.RETURN(0, 32), ) filling_callee_address = pre.deploy_contract(filling_contract_code) caller_contract = Container.Code( # First fill the return buffer and sanity check Op.EXTCALL(filling_callee_address, 0, 0, 0) + Op.SSTORE(slot_returndatasize_before_clear, Op.RETURNDATASIZE) # Then call something that doesn't return and check returndata cleared + opcode(address=target_address, value=value) + Op.SSTORE(slot_returndatasize, Op.RETURNDATASIZE) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ) calling_contract_address = pre.deploy_contract(caller_contract) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = { slot_code_worked: value_code_worked, # Sanity check slot_returndatasize_before_clear: 0x20, slot_returndatasize: 0, } post = { calling_contract_address: Account(storage=calling_storage), filling_callee_address: Account(storage={}), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.CALL, Op.EXTCALL, ], ) def test_eof_calls_static_flag_with_value( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """ Test EOF contracts calls handle static flag and sending value correctly. """ env = Environment() noop_callee_address = pre.deploy_contract(Container.Code(Op.STOP)) failing_contract_code = opcode(address=noop_callee_address, value=1) + Op.STOP failing_contract_address = pre.deploy_contract( Container.Code( failing_contract_code, ) if opcode == Op.EXTCALL else failing_contract_code ) calling_contract_address = pre.deploy_contract( Container.Code( Op.SSTORE(slot_call_result, Op.EXTSTATICCALL(address=failing_contract_address)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ) ) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=5_000_000, ) calling_storage = { slot_code_worked: value_code_worked, slot_call_result: EXTCALL_FAILURE, } post = { calling_contract_address: Account(storage=calling_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) min_retained_gas = 2300 min_callee_gas = 5000 @pytest.mark.parametrize( ["opcode", "extra_gas_value_transfer", "value"], [ [Op.EXTCALL, 0, 0], [Op.EXTCALL, 9_000, 1], [Op.EXTSTATICCALL, 0, 0], [Op.EXTDELEGATECALL, 0, 0], ], ids=["extcall_without_value", "extcall_with_value", "extstaticcall", "extdelegatecall"], ) @pytest.mark.parametrize( ["extra_gas_limit", "reverts"], [ [0, False], [min_retained_gas, False], [min_callee_gas, False], [min_retained_gas + min_callee_gas, True], ], ids=["no_allowances", "only_retained", "only_callee", "both_allowances"], ) def test_eof_calls_min_callee_gas( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, extra_gas_value_transfer: int, value: int, extra_gas_limit: int, reverts: bool, ) -> None: """ Test EOF contracts calls do light failure when retained/callee gas is not enough. Premise of the test is that there exists a range of `gas_limit` values, which are enough for all instructions to execute, but call's returned value is 1, meaning not enough for gas allowances (MIN_RETAINED_GAS and MIN_CALLEE_GAS) - ones marked with `reverts==False`. Once we provide both allowances, the RJUMPI condition is no longer met and `reverts==True`. """ env = Environment() noop_callee_address = pre.deploy_contract(Container.Code(Op.STOP)) revert_block = Op.REVERT(0, 0) calling_contract_address = pre.deploy_contract( Container.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.EQ(opcode(address=noop_callee_address, value=value), EXTCALL_REVERT) # If the return code isn't 1, it means gas was enough to cover the # allowances. + Op.RJUMPI[len(revert_block)] + revert_block + Op.STOP ), balance=value, ) # `no_oog_gas` is minimum amount of gas_limit which makes the transaction # not go oog. push_operations = 3 + len(opcode.kwargs) no_oog_gas = ( 21_000 + 20_000 # SSTORE + 2_100 # SSTORE COLD_SLOAD_COST + push_operations * 3 # PUSH operations + 100 # WARM_STORAGE_READ_COST + 2500 # COLD_ACCOUNT_ACCESS - WARM_STORAGE_READ_COST + extra_gas_value_transfer + 4 # RJUMPI + 3 # EQ ) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=no_oog_gas + extra_gas_limit, ) calling_storage = { slot_code_worked: 0 if reverts else value_code_worked, } post = { calling_contract_address: Account(storage=calling_storage), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "balance", [0, 1, 2, pytest.param(2**256 - 1, marks=pytest.mark.pre_alloc_modify)] ) @pytest.mark.parametrize("value", [0, 1, 2, 2**256 - 1]) def test_eof_calls_with_value( state_test: StateTestFiller, pre: Alloc, sender: EOA, balance: int, value: int, ) -> None: """ Test EOF contracts calls handle value calls with and without enough balance. """ env = Environment() noop_callee_address = pre.deploy_contract(Container.Code(Op.STOP)) calling_contract_address = pre.deploy_contract( Container.Code( Op.SSTORE(slot_call_result, Op.EXTCALL(address=noop_callee_address, value=value)) + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP ), balance=balance, ) tx = Transaction( sender=sender, to=calling_contract_address, gas_limit=50000000, ) calling_storage = { slot_code_worked: value_code_worked, slot_call_result: EXTCALL_REVERT if balance < value else EXTCALL_SUCCESS, } post = { calling_contract_address: Account(storage=calling_storage), noop_callee_address: Account(balance=0 if balance < value else value), } state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "opcode", [ Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL, ], ) def test_eof_calls_msg_depth( state_test: StateTestFiller, pre: Alloc, sender: EOA, opcode: Op, ) -> None: """ Test EOF contracts calls handle msg depth limit correctly (1024). Note: due to block gas limit and the 63/64th rule this limit is unlikely to be hit on mainnet. """ # Not a precise gas_limit formula, but enough to exclude risk of gas # causing the failure. gas_limit = int(200000 * (64 / 63) ** 1024) env = Environment(gas_limit=gas_limit) # Flow of the test: # `callee_code` is recursively calling itself, passing msg depth as # calldata (kept with the `MSTORE(0, ADD(...))`). When maximum msg depth is # reached the call fails and starts returning. The deep-most frame returns: # - current reached msg depth (expected to be the maximum 1024), with the # `MSTORE(32, ADD(...))` # - the respective return code of the EXT*CALL (expected to be 1 - light # failure), with the `MSTORE(64, NOOP)`. Note the `NOOP` is just to # appease the `Op.MSTORE` call, the return code value is actually # coming from the `Op.DUP1` # When unwinding the msg call stack, the intermediate frames return # whatever the deeper callee returned with the `RETURNDATACOPY` # instruction. # Memory offsets layout: # - 0 - input - msg depth # - 32 - output - msg depth # - 64 - output - call result returndatacopy_block = Op.RETURNDATACOPY(32, 0, 64) + Op.RETURN(32, 64) deep_most_result_block = ( Op.MSTORE(32, Op.ADD(Op.CALLDATALOAD(0), 1)) + Op.MSTORE(64, Op.NOOP) + Op.RETURN(32, 64) ) rjump_offset = len(returndatacopy_block) callee_code = Container.Code( # current stack depth in memory bytes 0-31 Op.MSTORE(0, Op.ADD(Op.CALLDATALOAD(0), 1)) # pass it along deeper as calldata + opcode(address=Op.ADDRESS, args_size=32) # duplicate return code for the `returndatacopy_block` below + Op.DUP1 # if return code was: # - 1, we're in the deep-most frame, `deep_most_result_block` returns # the actual result # - 0, we're in an intermediate frame, `returndatacopy_block` only # passes on the result + Op.RJUMPI[rjump_offset] + returndatacopy_block + deep_most_result_block ) callee_address = pre.deploy_contract(callee_code) calling_contract_address = pre.deploy_contract( Container.Code( Op.MSTORE(0, Op.CALLDATALOAD(0)) + Op.EXTCALL(address=callee_address, args_size=32) + Op.SSTORE(slot_max_depth, Op.RETURNDATALOAD(0)) + Op.SSTORE(slot_call_result, Op.RETURNDATALOAD(32))
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
true
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/helpers.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/helpers.py
"""EOF extcall tests helpers.""" import itertools """Storage addresses for common testing fields""" _slot = itertools.count() next(_slot) # don't use slot 0 slot_code_worked = next(_slot) slot_eof_target_call_status = next(_slot) slot_legacy_target_call_status = next(_slot) slot_eof_target_returndata = next(_slot) slot_eof_target_returndatasize = next(_slot) slot_legacy_target_returndatasize = next(_slot) slot_delegate_code_worked = next(_slot) slot_call_status = next(_slot) slot_calldata_1 = next(_slot) slot_calldata_2 = next(_slot) slot_last_slot = next(_slot) """Storage value indicating an abort""" value_exceptional_abort_canary = 0x1984 """Storage values for common testing fields""" value_code_worked = 0x2015 """Memory and storage value for calldata""" value_calldata_1 = 0xC1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1 value_calldata_2 = 0xC2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2C2 size_calldata = 32
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_returndatacopy_memory_expansion.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_returndatacopy_memory_expansion.py
"""Memory expansion tests for RETURNDATACOPY executing in EOF code.""" from typing import Mapping, Tuple import pytest from ethereum_test_forks import Fork from ethereum_test_tools import ( Account, Address, Alloc, Bytecode, Environment, StateTestFiller, Storage, Transaction, ) from ethereum_test_tools import Opcodes as Op from ethereum_test_types.eof.v1 import Container from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7069.md" REFERENCE_SPEC_VERSION = "e469fd6c8d736b2a3e1ce632263e3ad36fc8624d" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.fixture def callee_bytecode(dest: int, src: int, length: int) -> Container: """Callee performs a single returndatacopy operation and then returns.""" bytecode = Bytecode() # Copy the initial memory bytecode += Op.CALLDATACOPY(0x00, 0x00, Op.CALLDATASIZE()) # Pushes for the return operation bytecode += Op.PUSH1(0x00) + Op.PUSH1(0x00) # Perform the returndatacopy operation bytecode += Op.RETURNDATACOPY(dest, src, length) bytecode += Op.RETURN return Container.Code(code=bytecode) @pytest.fixture def subcall_exact_cost( fork: Fork, initial_memory: bytes, dest: int, length: int, ) -> int: """ Return exact cost of the subcall, based on the initial memory and the length of the copy. """ cost_memory_bytes = fork.memory_expansion_gas_calculator() returndatacopy_cost = 3 returndatacopy_cost += 3 * ((length + 31) // 32) if length > 0 and dest + length > len(initial_memory): returndatacopy_cost += cost_memory_bytes( new_bytes=dest + length, previous_bytes=len(initial_memory) ) calldatacopy_cost = 3 calldatacopy_cost += 3 * ((len(initial_memory) + 31) // 32) calldatacopy_cost += cost_memory_bytes(new_bytes=len(initial_memory)) pushes_cost = 3 * 7 calldatasize_cost = 2 return returndatacopy_cost + calldatacopy_cost + pushes_cost + calldatasize_cost @pytest.fixture def bytecode_storage( subcall_exact_cost: int, successful: bool, memory_expansion_address: Address, ) -> Tuple[Bytecode, Storage.StorageDictType]: """ Prepare bytecode and storage for the test, based on the expected result of the subcall (whether it succeeds or fails depending on the length of the memory expansion). """ bytecode = Bytecode() storage = {} # Pass on the calldata bytecode += Op.CALLDATACOPY(0x00, 0x00, Op.CALLDATASIZE()) subcall_gas = subcall_exact_cost if successful else subcall_exact_cost - 1 # Perform the subcall and store a one in the result location bytecode += Op.SSTORE( Op.CALL(subcall_gas, memory_expansion_address, 0, 0, Op.CALLDATASIZE(), 0, 0), 1 ) storage[int(successful)] = 1 return (bytecode, storage) @pytest.fixture def tx_max_fee_per_gas() -> int: # noqa: D103 return 7 @pytest.fixture def block_gas_limit() -> int: # noqa: D103 return 100_000_000 @pytest.fixture def tx_gas_limit( # noqa: D103 subcall_exact_cost: int, block_gas_limit: int, ) -> int: return min(max(500_000, subcall_exact_cost * 2), block_gas_limit) @pytest.fixture def env( # noqa: D103 block_gas_limit: int, ) -> Environment: return Environment(gas_limit=block_gas_limit) @pytest.fixture def caller_address( # noqa: D103 pre: Alloc, bytecode_storage: Tuple[bytes, Storage.StorageDictType] ) -> Address: return pre.deploy_contract(code=bytecode_storage[0]) @pytest.fixture def memory_expansion_address(pre: Alloc, callee_bytecode: bytes) -> Address: # noqa: D103 return pre.deploy_contract(code=callee_bytecode) @pytest.fixture def sender(pre: Alloc, tx_max_fee_per_gas: int, tx_gas_limit: int) -> Address: # noqa: D103 return pre.fund_eoa(tx_max_fee_per_gas * tx_gas_limit) @pytest.fixture def tx( # noqa: D103 sender: Address, caller_address: Address, initial_memory: bytes, tx_max_fee_per_gas: int, tx_gas_limit: int, ) -> Transaction: return Transaction( sender=sender, to=caller_address, data=initial_memory, gas_limit=tx_gas_limit, max_fee_per_gas=tx_max_fee_per_gas, max_priority_fee_per_gas=0, ) @pytest.fixture def post( # noqa: D103 caller_address: Address, bytecode_storage: Tuple[bytes, Storage.StorageDictType] ) -> Mapping: return { caller_address: Account(storage=bytecode_storage[1]), } @pytest.mark.parametrize( "dest,src,length", [ (0x00, 0x00, 0x01), (0x100, 0x00, 0x01), (0x1F, 0x00, 0x01), (0x20, 0x00, 0x01), (0x1000, 0x00, 0x01), (0x1000, 0x00, 0x40), (0x00, 0x00, 0x00), (2**256 - 1, 0x00, 0x00), (0x00, 2**256 - 1, 0x00), (2**256 - 1, 2**256 - 1, 0x00), ], ids=[ "single_byte_expansion", "single_byte_expansion_2", "single_byte_expansion_word_boundary", "single_byte_expansion_word_boundary_2", "multi_word_expansion", "multi_word_expansion_2", "zero_length_expansion", "huge_dest_zero_length", "huge_src_zero_length", "huge_dest_huge_src_zero_length", ], ) @pytest.mark.parametrize("successful", [True, False]) @pytest.mark.parametrize( "initial_memory", [ bytes(range(0x00, 0x100)), bytes(), ], ids=[ "from_existent_memory", "from_empty_memory", ], ) def test_returndatacopy_memory_expansion( state_test: StateTestFiller, env: Environment, pre: Alloc, post: Mapping[str, Account], tx: Transaction, ) -> None: """ Perform RETURNDATACOPY operations that expand the memory, and verify the gas it costs. """ state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "dest,src,length", [ pytest.param(2**256 - 1, 0x00, 0x01, id="max_dest_single_byte_expansion"), pytest.param(2**256 - 2, 0x00, 0x01, id="max_dest_minus_one_single_byte_expansion"), pytest.param(2**255 - 1, 0x00, 0x01, id="half_max_dest_single_byte_expansion"), pytest.param(0x00, 0x00, 2**256 - 1, id="max_length_expansion"), pytest.param(0x00, 0x00, 2**256 - 2, id="max_length_minus_one_expansion"), pytest.param(0x00, 0x00, 2**255 - 1, id="half_max_length_expansion"), pytest.param(0x1FFFF20, 0x00, 0x01, id="32-bit-mem-cost_offset"), pytest.param(0x2D412E0, 0x00, 0x01, id="33-bit-mem-cost_offset"), pytest.param(0x00, 0x00, 0x1FFFF20, id="32-bit-mem-cost_size"), pytest.param(0x00, 0x00, 0x2D412E0, id="33-bit-mem-cost_size"), pytest.param(0x1FFFFFFFF20, 0x00, 0x01, id="64-bit-mem-cost_offset"), pytest.param(0x2D413CCCF00, 0x00, 0x01, id="65-bit-mem-cost_offset"), pytest.param(0x00, 0x00, 0x1FFFFFFFF20, id="64-bit-mem-cost_size"), pytest.param(0x00, 0x00, 0x2D413CCCF00, id="65-bit-mem-cost_size"), ], ) @pytest.mark.parametrize( "subcall_exact_cost", [2**128 - 1], ids=[""], ) # Limit subcall gas, otherwise it would be impossibly large @pytest.mark.parametrize("successful", [False]) @pytest.mark.parametrize( "initial_memory", [ bytes(range(0x00, 0x100)), bytes(), ], ids=[ "from_existent_memory", "from_empty_memory", ], ) def test_returndatacopy_huge_memory_expansion( state_test: StateTestFiller, env: Environment, pre: Mapping[str, Account], post: Mapping[str, Account], tx: Transaction, ) -> None: """ Perform RETURNDATACOPY operations that expand the memory by huge amounts, and verify that it correctly runs out of gas. """ state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/__init__.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/__init__.py
""" Test cases for EIP-7069 Revamped CALL instructions [EIP-7069: Revamped CALL instructions](https://eips.ethereum.org/EIPS/eip-7069) proposes modifications to `CALL` instructions to align with the structured EOF format. Opcodes introduced: `EXTCALL` (`0xF8`), `EXTDELEGATECALL` (`0xF9`), `EXTSTATICCALL` (`0xFB`), `RETURNDATALOAD` (`0xF7`). """ REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7069.md" REFERENCE_SPEC_VERSION = "1795943aeacc86131d5ab6bb3d65824b3b1d4cad"
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_gas.py
tests/unscheduled/eip7692_eof_v1/eip7069_extcall/test_gas.py
""" Gas consumption tests for EXT*CALL instructions Tests for gas consumption in [EIP-7069: Revamped CALL instructions](https://eips.ethereum.org/EIPS/eip-7069). """ import pytest from ethereum_test_base_types import Address from ethereum_test_forks import Fork from ethereum_test_tools import Alloc, Environment, StateTestFiller from ethereum_test_types.eof.v1 import Container from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from ..gas_test import gas_test from . import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) COLD_ACCOUNT_ACCESS_GAS = 2600 WARM_ACCOUNT_ACCESS_GAS = 100 CALL_WITH_VALUE_GAS = 9000 ACCOUNT_CREATION_GAS = 25000 @pytest.fixture def state_env() -> Environment: """ Prepare the environment for all state test cases. Main difference is that the excess blob gas is not increased by the target, as there is no genesis block -> block 1 transition, and therefore the excess blob gas is not decreased by the target. """ return Environment() @pytest.mark.parametrize( ["opcode", "pre_setup", "cold_gas", "warm_gas", "new_account"], [ pytest.param( Op.EXTCALL, Op.PUSH0, COLD_ACCOUNT_ACCESS_GAS, WARM_ACCOUNT_ACCESS_GAS, False, id="EXTCALL", ), pytest.param( Op.EXTCALL, Op.PUSH1(1), COLD_ACCOUNT_ACCESS_GAS + CALL_WITH_VALUE_GAS, WARM_ACCOUNT_ACCESS_GAS + CALL_WITH_VALUE_GAS, False, id="EXTCALL_with_value", ), pytest.param( Op.EXTDELEGATECALL, Op.NOOP, COLD_ACCOUNT_ACCESS_GAS, WARM_ACCOUNT_ACCESS_GAS, False, id="EXTDELEGATECALL", ), pytest.param( Op.EXTSTATICCALL, Op.NOOP, COLD_ACCOUNT_ACCESS_GAS, WARM_ACCOUNT_ACCESS_GAS, False, id="EXTSTATICCALL", ), pytest.param( Op.EXTCALL, Op.PUSH0, COLD_ACCOUNT_ACCESS_GAS, WARM_ACCOUNT_ACCESS_GAS, True, id="EXTCALL_new_acc", ), pytest.param( Op.EXTCALL, Op.PUSH1(1), COLD_ACCOUNT_ACCESS_GAS + ACCOUNT_CREATION_GAS + CALL_WITH_VALUE_GAS, WARM_ACCOUNT_ACCESS_GAS + ACCOUNT_CREATION_GAS + CALL_WITH_VALUE_GAS, True, id="EXTCALL_with_value_new_acc", ), pytest.param( Op.EXTDELEGATECALL, Op.NOOP, COLD_ACCOUNT_ACCESS_GAS, WARM_ACCOUNT_ACCESS_GAS, True, id="EXTDELEGATECALL_new_acc", ), pytest.param( Op.EXTSTATICCALL, Op.NOOP, COLD_ACCOUNT_ACCESS_GAS, WARM_ACCOUNT_ACCESS_GAS, True, id="EXTSTATICCALL_new_acc", ), ], ) @pytest.mark.parametrize( "mem_expansion_bytes", [0, 1, 32, 33], ) def test_ext_calls_gas( state_test: StateTestFiller, pre: Alloc, fork: Fork, state_env: Environment, opcode: Op, pre_setup: Op, cold_gas: int, warm_gas: int, new_account: bool, mem_expansion_bytes: int, ) -> None: """ Tests variations of EXT*CALL gas, both warm and cold, without and with mem expansions. """ address_target = ( pre.fund_eoa(0) if new_account else pre.deploy_contract(Container.Code(Op.STOP)) ) cost_memory_bytes = fork.memory_expansion_gas_calculator() gas_test( state_test, state_env, pre, setup_code=pre_setup + Op.PUSH1(mem_expansion_bytes) + Op.PUSH0 + Op.PUSH20(address_target), subject_code=opcode, tear_down_code=Op.STOP, cold_gas=cold_gas + cost_memory_bytes(new_bytes=mem_expansion_bytes), warm_gas=warm_gas + cost_memory_bytes(new_bytes=mem_expansion_bytes), ) @pytest.mark.parametrize("opcode", [Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL]) @pytest.mark.parametrize("value", [0, 1]) def test_transfer_gas_is_cleared( state_test: StateTestFiller, pre: Alloc, state_env: Environment, opcode: Op, value: int, ) -> None: """ Test that EXT*CALL call doesn't charge for value transfer, even if the outer call transferred value. NOTE: This is particularly possible for EXTDELEGATECALL, which carries over the value sent in the outer call, however, we extend the test to all 3 EXT*CALL opcodes for good measure. """ noop_callee_address = pre.deploy_contract(Container.Code(Op.STOP)) extdelegatecall_contract_address = pre.deploy_contract( Container.Code(opcode(address=noop_callee_address) + Op.STOP) ) push_gas = (4 if opcode == Op.EXTCALL else 3) * 3 gas_test( state_test, state_env, pre, setup_code=Op.PUSH1(value) + Op.PUSH0 * 2 + Op.PUSH20(extdelegatecall_contract_address), subject_code=Op.EXTCALL, subject_balance=5 * value, tear_down_code=Op.STOP, # NOTE: CALL_WITH_VALUE_GAS is charged only once on the outer EXTCALL, # while the base call gas - twice. cold_gas=2 * COLD_ACCOUNT_ACCESS_GAS + (CALL_WITH_VALUE_GAS if value > 0 else 0) + push_gas, warm_gas=2 * WARM_ACCOUNT_ACCESS_GAS + (CALL_WITH_VALUE_GAS if value > 0 else 0) + push_gas, out_of_gas_testing=False, ) @pytest.mark.parametrize("opcode", [Op.EXTCALL, Op.EXTDELEGATECALL, Op.EXTSTATICCALL]) def test_late_account_create( state_test: StateTestFiller, pre: Alloc, state_env: Environment, opcode: Op, ) -> None: """ Test EXTCALL to a non-existent account after another EXT*CALL has called it and not created it. """ empty_address = Address(0xDECAFC0DE) gas_test( state_test, state_env, pre, prelude_code=Op.BALANCE(address=empty_address), setup_code=opcode(address=empty_address) + Op.PUSH1(1) + Op.PUSH0 + Op.PUSH0 + Op.PUSH20(empty_address), subject_code=Op.EXTCALL, subject_balance=5, tear_down_code=Op.STOP, cold_gas=WARM_ACCOUNT_ACCESS_GAS + CALL_WITH_VALUE_GAS + ACCOUNT_CREATION_GAS, warm_gas=WARM_ACCOUNT_ACCESS_GAS + CALL_WITH_VALUE_GAS, out_of_gas_testing=False, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/test_dupn.py
tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/test_dupn.py
""" DUPN instruction tests Tests for DUPN instruction in [EIP-663: SWAPN, DUPN and EXCHANGE instructions](https://eips.ethereum.org/EIPS/eip-663). """ import pytest from ethereum_test_tools import ( Account, Alloc, Environment, EOFException, EOFStateTestFiller, EOFTestFiller, StateTestFiller, Transaction, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_STACK_INCREASE_LIMIT from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from . import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def test_dupn_all_valid_immediates(eof_state_test: EOFStateTestFiller) -> None: """Test case for all valid DUPN immediates.""" n = 2**8 values = range(0xD00, 0xD00 + n) eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in values) + sum(Op.SSTORE(x, Op.DUPN[x]) for x in range(0, n)) + Op.STOP, ) ], ) post = Account(storage=dict(zip(range(0, n), reversed(values), strict=False))) eof_state_test( tx_sender_funding_amount=1_000_000_000, container=eof_code, container_post=post, ) @pytest.mark.parametrize( "stack_height,max_stack_height", [ # [0, 0] is tested in test_all_opcodes_stack_underflow() [0, 1], [1, 1], [1, 2], [2**8 - 1, 2**8 - 1], [2**8 - 1, 2**8], ], ) def test_dupn_stack_underflow( stack_height: int, max_stack_height: int, eof_test: EOFTestFiller, ) -> None: """Test case out of bounds DUPN immediate.""" eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(0, stack_height)) + Op.DUPN[stack_height] + Op.STOP, max_stack_height=max_stack_height, ) ], ) eof_test( container=eof_code, expect_exception=EOFException.STACK_UNDERFLOW, ) @pytest.mark.parametrize( "dupn_operand,max_stack_height,expect_exception", [ [0, MAX_STACK_INCREASE_LIMIT, EOFException.INVALID_MAX_STACK_INCREASE], [0, MAX_STACK_INCREASE_LIMIT + 1, EOFException.MAX_STACK_INCREASE_ABOVE_LIMIT], [2**8 - 1, MAX_STACK_INCREASE_LIMIT, EOFException.INVALID_MAX_STACK_INCREASE], [2**8 - 1, MAX_STACK_INCREASE_LIMIT + 1, EOFException.MAX_STACK_INCREASE_ABOVE_LIMIT], ], ) def test_dupn_stack_overflow( dupn_operand: int, max_stack_height: int, expect_exception: EOFException, eof_test: EOFTestFiller, ) -> None: """Test case where DUPN produces an stack overflow.""" eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(0, MAX_STACK_INCREASE_LIMIT)) + Op.DUPN[dupn_operand] + Op.STOP, max_stack_height=max_stack_height, ) ], ) eof_test( container=eof_code, expect_exception=expect_exception, ) @pytest.mark.parametrize( "dupn_arg,stack_height", [pytest.param(5, 9, id="5_of_9"), pytest.param(12, 30, id="12_of_30")] ) def test_dupn_simple( stack_height: int, dupn_arg: int, pre: Alloc, state_test: StateTestFiller, ) -> None: """Test case for simple DUPN operations.""" sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(stack_height, 0, -1)) + Op.DUPN[dupn_arg] + sum((Op.PUSH1(v) + Op.SSTORE) for v in range(0, stack_height + 1)) + Op.STOP, max_stack_height=stack_height + 2, ) ], ) ) storage = {v: v for v in range(1, stack_height + 1)} storage[0] = dupn_arg + 1 print(storage) post = {contract_address: Account(storage=storage)} tx = Transaction(to=contract_address, sender=sender, gas_limit=10_000_000) state_test(env=Environment(), pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/test_exchange.py
tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/test_exchange.py
""" Tests [EIP-663: SWAPN, DUPN and EXCHANGE instructions](https://eips.ethereum.org/EIPS/eip-663). """ import pytest from ethereum_test_tools import ( Account, Alloc, Environment, EOFException, EOFStateTestFiller, EOFTestFiller, StateTestFiller, Transaction, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from . import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def test_exchange_all_valid_immediates(eof_state_test: EOFStateTestFiller) -> None: """Test case for all valid EXCHANGE immediates.""" n = 256 s = 34 values = range(0x3E8, 0x3E8 + s) eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in values) + sum(Op.EXCHANGE[x] for x in range(0, n)) + sum((Op.PUSH1[x] + Op.SSTORE) for x in range(0, s)) + Op.STOP, ) ], ) # this does the same full-loop exchange values_rotated = list(range(0x3E8, 0x3E8 + s)) for e in range(0, n): a = (e >> 4) + 1 b = (e & 0x0F) + 1 + a temp = values_rotated[a] values_rotated[a] = values_rotated[b] values_rotated[b] = temp post = Account(storage=dict(zip(range(0, s), reversed(values_rotated), strict=False))) eof_state_test( tx_sender_funding_amount=1_000_000_000, container=eof_code, container_post=post, ) @pytest.mark.parametrize( "stack_height,x,y", [ # 2 and 3 are the lowest valid values for x and y, # which translates to the zero immediate value. # (0, 2, 3) is tested in test_all_opcodes_stack_underflow() pytest.param(1, 2, 3, id="stack_height=1_n=1_m=1"), pytest.param(2, 2, 3, id="stack_height=2_n=1_m=1"), pytest.param(17, 2, 18, id="stack_height=17_n=1_m=16"), pytest.param(17, 17, 18, id="stack_height=17_n=16_m=1"), pytest.param(32, 17, 33, id="stack_height=32_n=16_m=16"), ], ) def test_exchange_stack_underflow( eof_test: EOFTestFiller, stack_height: int, x: int, y: int, ) -> None: """Test case the EXCHANGE causing stack underflow.""" eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(stack_height)) + Op.EXCHANGE[x, y] + Op.POP * stack_height + Op.STOP, max_stack_height=stack_height, ) ], ) eof_test( container=eof_code, expect_exception=EOFException.STACK_UNDERFLOW, ) @pytest.mark.parametrize( "m_arg,n_arg,extra_stack", [pytest.param(0, 0, 3, id="m0_n0_extra3"), pytest.param(2, 3, 7, id="m2_n3_extra7")], ) def test_exchange_simple( m_arg: int, n_arg: int, extra_stack: int, pre: Alloc, state_test: StateTestFiller, ) -> None: """Test case for simple EXCHANGE operations.""" sender = pre.fund_eoa() stack_height = m_arg + n_arg + 2 + extra_stack contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(stack_height, 0, -1)) + Op.EXCHANGE[m_arg << 4 | n_arg] + sum((Op.PUSH1(v) + Op.SSTORE) for v in range(1, stack_height + 1)) + Op.STOP, max_stack_height=stack_height + 1, ) ], ) ) storage = {v: v for v in range(1, stack_height + 1)} first = m_arg + 2 # one based index, plus m=0 means first non-top item second = first + n_arg + 1 # n+1 past m storage[first], storage[second] = storage[second], storage[first] print(storage) post = {contract_address: Account(storage=storage)} tx = Transaction(to=contract_address, sender=sender, gas_limit=10_000_000) state_test(env=Environment(), pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/__init__.py
tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/__init__.py
""" Test cases for EIP-663 SWAPN, DUPN and EXCHANGE instructions [EIP-663](https://eips.ethereum.org/EIPS/eip-663) defines new stack manipulation instructions that allow accessing the stack at higher depths. Opcodes introduced: `DUPN` (`0xE6`), `SWAPN` (`0xE7`), `EXCHANGEN` (`0xE8`). """ REFERENCE_SPEC_GIT_PATH = "EIPS/eip-663.md" REFERENCE_SPEC_VERSION = "b658bb87fe039d29e9475d5cfaebca9b92e0fca2"
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/test_swapn.py
tests/unscheduled/eip7692_eof_v1/eip663_dupn_swapn_exchange/test_swapn.py
"""Tests [EIP-663: SWAPN, DUPN and EXCHANGE instructions](https://eips.ethereum.org/EIPS/eip-663).""" import pytest from ethereum_test_tools import ( Account, Alloc, Environment, EOFException, EOFStateTestFiller, EOFTestFiller, StateTestFiller, Transaction, ) from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import MAX_STACK_INCREASE_LIMIT from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from . import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def test_swapn_all_valid_immediates(eof_state_test: EOFStateTestFiller) -> None: """Test case for all valid SWAPN immediates.""" n = 256 values = range(0x500, 0x500 + 257) eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in values) + sum(Op.SSTORE(x, Op.SWAPN[0xFF - x]) for x in range(0, n)) + Op.STOP, ) ], ) values_rotated = list(values[1:]) + [values[0]] post = Account(storage=dict(zip(range(0, n), reversed(values_rotated), strict=False))) eof_state_test( tx_sender_funding_amount=1_000_000_000, container=eof_code, container_post=post, ) @pytest.mark.parametrize( "swapn_operand", [ 0, 2**8 - 1, ], ) def test_swapn_on_max_stack( swapn_operand: int, eof_test: EOFTestFiller, ) -> None: """Test case out of bounds SWAPN (max stack).""" eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(0, MAX_STACK_INCREASE_LIMIT)) + Op.SWAPN[swapn_operand] + Op.STOP, ) ], ) eof_test( container=eof_code, ) @pytest.mark.parametrize( "stack_height", [ 0, 1, 21, 2**8 - 1, ], ) def test_swapn_stack_underflow( stack_height: int, eof_test: EOFTestFiller, ) -> None: """Test case out of bounds SWAPN (underflow).""" eof_code = Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(0, stack_height)) + Op.SWAPN[stack_height] + Op.STOP, # This is also tested in test_all_opcodes_stack_underflow() # so make it differ by the declared stack height. max_stack_height=stack_height + 1, ) ], ) eof_test( container=eof_code, expect_exception=EOFException.STACK_UNDERFLOW, ) @pytest.mark.parametrize( "swapn_arg,stack_height", [pytest.param(5, 9, id="5_of_9"), pytest.param(12, 30, id="12_of_30")], ) def test_swapn_simple( stack_height: int, swapn_arg: int, pre: Alloc, state_test: StateTestFiller, ) -> None: """Test case for simple SWAPN operations.""" sender = pre.fund_eoa() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( code=sum(Op.PUSH2[v] for v in range(stack_height, 0, -1)) + Op.SWAPN[swapn_arg] + sum((Op.PUSH1(v) + Op.SSTORE) for v in range(1, stack_height + 1)) + Op.STOP, max_stack_height=stack_height + 1, ) ], ) ) storage = {v: v for v in range(1, stack_height + 1)} storage[1], storage[swapn_arg + 2] = storage[swapn_arg + 2], storage[1] print(storage) post = {contract_address: Account(storage=storage)} tx = Transaction(to=contract_address, sender=sender, gas_limit=10_000_000) state_test(env=Environment(), pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_validation.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_validation.py
"""EOF validation tests for JUMPF instruction.""" import pytest from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_types.eof.constants import MAX_RUNTIME_STACK_HEIGHT from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-6206.md" REFERENCE_SPEC_VERSION = "2f365ea0cd58faa6e26013ea77ce6d538175f7d0" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "container", [ Container( name="to_0", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( Op.JUMPF[0], code_outputs=0, ), ], ), Container( name="to_2", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( Op.JUMPF[2], code_outputs=0, ), Section.Code( Op.INVALID, ), ], ), Container( name="to_retf", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( Op.JUMPF[2], code_outputs=0, ), Section.Code( Op.RETF, ), ], ), ], ids=lambda container: container.name, ) def test_returning_jumpf( eof_test: EOFTestFiller, container: Container, ) -> None: """Test cases for JUMPF instruction validation in a returning sections.""" eof_test(container=container, expect_exception=EOFException.INVALID_NON_RETURNING_FLAG) @pytest.mark.parametrize( "container", [ Container( name="jumpf1", sections=[ Section.Code( Op.JUMPF[1], ) ], ), Container( name="jumpf2", sections=[ Section.Code( Op.JUMPF[2], ), Section.Code( Op.STOP, ), ], ), Container( name="jumpf1_jumpf2", sections=[ Section.Code( Op.JUMPF[1], ), Section.Code( Op.JUMPF[2], ), ], ), ], ids=lambda container: container.name, ) def test_invalid_code_section_index( eof_test: EOFTestFiller, container: Container, ) -> None: """ Test cases for JUMPF instructions with invalid target code section index. """ eof_test(container=container, expect_exception=EOFException.INVALID_CODE_SECTION_INDEX) def test_returning_section_aborts_jumpf( eof_test: EOFTestFiller, ) -> None: """ Test EOF container validation where in the same code section we have returning and nonreturning terminating instructions. """ container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=1), Section.Code( code=Op.PUSH0 * 2 + Op.RJUMPI[4] + Op.POP + Op.JUMPF[2] + Op.RETF, code_outputs=1, ), Section.Code( code=Op.PUSH0 * 2 + Op.RJUMPI[1] + Op.RETF + Op.INVALID, code_inputs=0, code_outputs=1, ), ], ) eof_test(container=container) @pytest.mark.parametrize("stack_height", [512, 513, 1023]) def test_jumpf_self_stack_overflow(eof_test: EOFTestFiller, stack_height: int) -> None: """ Test JUMPF instruction jumping to itself causing validation time stack overflow. """ container = Container( sections=[ Section.Code( code=(Op.PUSH0 * stack_height) + Op.JUMPF[0], max_stack_height=stack_height, ), ], ) stack_overflow = stack_height > MAX_RUNTIME_STACK_HEIGHT // 2 eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW if stack_overflow else None, ) @pytest.mark.parametrize("stack_height_other", [1, 2, 512, 513, 1023]) @pytest.mark.parametrize("stack_height", [1, 2, 512, 513, 1023]) def test_jumpf_other_stack_overflow( eof_test: EOFTestFiller, stack_height: int, stack_height_other: int ) -> None: """ Test JUMPF instruction jumping to other section causing validation time stack overflow. """ container = Container( sections=[ Section.Code( code=(Op.PUSH0 * stack_height) + Op.JUMPF[1], max_stack_height=stack_height, ), Section.Code( code=(Op.PUSH0 * stack_height_other) + Op.STOP, max_stack_height=stack_height_other, ), ], ) stack_overflow = stack_height + stack_height_other > MAX_RUNTIME_STACK_HEIGHT eof_test( container=container, expect_exception=EOFException.STACK_OVERFLOW if stack_overflow else None, ) @pytest.mark.parametrize("code_inputs", [0, 3]) @pytest.mark.parametrize("stack_height", [0, 2, 3, 4]) def test_jumpf_to_non_returning( eof_test: EOFTestFiller, stack_height: int, code_inputs: int ) -> None: """Test JUMPF jumping to a non-returning function.""" container = Container( sections=[ Section.Code( code=Op.PUSH0 * stack_height + Op.JUMPF[1], max_stack_height=stack_height ), Section.Code(code=Op.STOP, code_inputs=code_inputs, max_stack_height=code_inputs), ], ) eof_test( container=container, expect_exception=EOFException.STACK_UNDERFLOW if stack_height < code_inputs else None, ) @pytest.mark.parametrize("code_inputs", [0, 1, 3, 5]) def test_jumpf_to_non_returning_variable_stack(eof_test: EOFTestFiller, code_inputs: int) -> None: """ Test JUMPF jumping to a non-returning function with stack depending on RJUMPI. """ container = Container( sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 * 2 + Op.JUMPF[1], max_stack_height=3, ), Section.Code(code=Op.INVALID, code_inputs=code_inputs, max_stack_height=code_inputs), ], ) eof_test( container=container, expect_exception=EOFException.STACK_UNDERFLOW if code_inputs >= 3 else None, ) @pytest.mark.parametrize("code_inputs", [0, 3]) @pytest.mark.parametrize("code_outputs", [1, 2]) @pytest.mark.parametrize("stack_height", [0, 1, 2, 3, 4, 5]) def test_jumpf_to_returning( eof_test: EOFTestFiller, code_inputs: int, code_outputs: int, stack_height: int ) -> None: """Test JUMPF jumping to a returning function.""" exceptions = [] if code_inputs > stack_height or (stack_height - code_inputs + code_outputs) < 2: exceptions.append(EOFException.STACK_UNDERFLOW) if stack_height - code_inputs + code_outputs > 2: exceptions.append(EOFException.STACK_HIGHER_THAN_OUTPUTS) third_cs_stack_height = code_inputs if code_inputs > code_outputs else code_outputs third_cs = None if code_outputs < code_inputs: third_cs = Op.POP * (code_inputs - code_outputs) + Op.RETF else: third_cs = Op.PUSH0 * (code_outputs - code_inputs) + Op.RETF container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=2), Section.Code(code=Op.PUSH0 * stack_height + Op.JUMPF[2], code_outputs=2), Section.Code( code=third_cs, code_inputs=code_inputs, code_outputs=code_outputs, max_stack_height=third_cs_stack_height, ), ], ) eof_test( container=container, expect_exception=exceptions if exceptions else None, ) @pytest.mark.parametrize("code_inputs", [0, 1, 3, 5]) @pytest.mark.parametrize("code_outputs", [1, 3]) @pytest.mark.parametrize("stack_increase", [0, 1, 2, 3, 4]) def test_jumpf_to_returning_variable_stack_1( eof_test: EOFTestFiller, code_inputs: int, code_outputs: int, stack_increase: int, ) -> None: """ Test JUMPF with variable stack jumping to a returning function increasing the stack. """ exception = None if code_inputs >= 3 or code_outputs + 1 < 3: # 3 = Section 1's max stack exception = EOFException.STACK_UNDERFLOW if 3 - code_inputs + code_outputs > 3: exception = EOFException.STACK_HIGHER_THAN_OUTPUTS container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=3), Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 * 2 + Op.JUMPF[2], code_outputs=3, max_stack_height=3, ), Section.Code( code=Op.PUSH0 * stack_increase + Op.RETF, code_inputs=code_inputs, code_outputs=code_outputs, max_stack_height=code_inputs if code_inputs > code_outputs else code_outputs, ), ], ) eof_test( container=container, expect_exception=exception, ) @pytest.mark.parametrize("code_inputs", [1, 3, 5]) @pytest.mark.parametrize("code_outputs", [1]) @pytest.mark.parametrize("stack_decrease", [0, 2, 4]) def test_jumpf_to_returning_variable_stack_2( eof_test: EOFTestFiller, code_inputs: int, code_outputs: int, stack_decrease: int, ) -> None: """ Test JUMPF with variable stack jumping to a returning function decreasing the stack. """ exceptions = [] if code_inputs >= 3 or code_outputs + 1 < 3: # 3 = Section 1's max stack exceptions.append(EOFException.STACK_UNDERFLOW) if 3 - code_inputs + code_outputs > 2: exceptions.append(EOFException.STACK_HIGHER_THAN_OUTPUTS) container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=2), Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 * 2 + Op.JUMPF[2], code_outputs=2, max_stack_height=3, ), Section.Code( code=Op.POP * stack_decrease + Op.RETF, code_inputs=code_inputs, code_outputs=code_outputs, max_stack_height=code_inputs if code_inputs > code_outputs else code_outputs, ), ], ) eof_test( container=container, expect_exception=exceptions, ) def test_jumpf_to_returning_variable_stack_3(eof_test: EOFTestFiller) -> None: """ Test JUMPF with variable stack jumping to a returning function increasing the stack. """ container = Container( sections=[ Section.Code(code=Op.CALLF[1] + Op.STOP, max_stack_height=2), Section.Code( code=Op.PUSH0 + Op.PUSH1[0] + Op.RJUMPI[2] + Op.PUSH0 * 2 + Op.JUMPF[2], code_outputs=2, max_stack_height=3, ), Section.Code( code=Op.PUSH0 + Op.RETF, code_outputs=1, max_stack_height=1, ), ], ) eof_test( container=container, expect_exception=EOFException.STACK_HIGHER_THAN_OUTPUTS, ) @pytest.mark.parametrize( "container", [ Container( name="underflow_2", sections=[ Section.Code( code=Op.CALLF[1] + Op.STOP, max_stack_height=2, ), Section.Code( code=Op.JUMPF[2], code_outputs=2, max_stack_height=0, ), Section.Code( code=Op.PUSH0 + Op.RETF, code_inputs=1, code_outputs=2, max_stack_height=2, ), ], ), Container( name="underflow_3", sections=[ Section.Code( code=Op.JUMPF[1], ), Section.Code( code=Op.REVERT(0, 0), code_inputs=1, max_stack_height=3, ), ], ), Container( name="underflow_variable_stack_4", sections=[ Section.Code( code=Op.CALLF[1] + Op.STOP, max_stack_height=3, ), Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 + Op.PUSH0 + Op.JUMPF[2], code_outputs=3, max_stack_height=3, ), Section.Code( code=Op.POP + Op.POP + Op.RETF, code_inputs=5, code_outputs=3, max_stack_height=5, ), ], ), Container( name="underflow_variable_stack_6", sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 + Op.PUSH0 + Op.JUMPF[1], max_stack_height=3, ), Section.Code( code=Op.REVERT(0, 0), code_inputs=4, max_stack_height=6, ), ], ), Container( name="underflow_variable_stack_7", sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 + Op.PUSH0 + Op.JUMPF[1], max_stack_height=3, ), Section.Code( code=Op.REVERT(0, 0), code_inputs=3, max_stack_height=5, ), ], ), Container( name="underflow_variable_stack_8", sections=[ Section.Code( code=Op.PUSH0 * 3 + Op.RJUMPI[1](0) + Op.POP + Op.JUMPF[1], max_stack_height=3, ), Section.Code( code=Op.REVERT(0, 0), code_inputs=3, max_stack_height=5, ), ], ), ], ids=lambda x: x.name, ) def test_jumpf_stack_underflow_examples(eof_test: EOFTestFiller, container: Container) -> None: """Test JUMPF instruction causing validation time stack underflow.""" eof_test(container=container, expect_exception=EOFException.STACK_UNDERFLOW)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/spec.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/spec.py
"""EOF V1 Constants used throughout all tests."""
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_target.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_target.py
"""EOF JUMPF tests covering JUMPF target rules.""" import pytest from ethereum_test_tools import Account, EOFException, EOFStateTestFiller from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import NON_RETURNING_SECTION from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import slot_code_worked, value_code_worked REFERENCE_SPEC_GIT_PATH = "EIPS/eip-6206.md" REFERENCE_SPEC_VERSION = "2f365ea0cd58faa6e26013ea77ce6d538175f7d0" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "target_outputs", [NON_RETURNING_SECTION, 0, 2, 4, 127], ids=lambda x: "to-%s" % ("N" if x == NON_RETURNING_SECTION else x), ) @pytest.mark.parametrize( "source_outputs", [NON_RETURNING_SECTION, 0, 2, 4, 127], ids=lambda x: "so-%s" % ("N" if x == NON_RETURNING_SECTION else x), ) def test_jumpf_target_rules( eof_state_test: EOFStateTestFiller, source_outputs: int, target_outputs: int, ) -> None: """ Validate the target section rules of JUMPF, and execute valid cases. We are not testing stack so a lot of the logic is to get correct stack values. """ source_non_returning = source_outputs == NON_RETURNING_SECTION source_height = 0 if source_non_returning else source_outputs source_section_index = 1 target_non_returning = target_outputs == NON_RETURNING_SECTION target_height = 0 if target_non_returning else target_outputs target_section_index = 2 # Because we are testing the target and not the stack height validation we # need to do some work to make sure the stack passes validation. # `source_extra_push` is how many more pushes we need to match our stack # commitments source_extra_push = max(0, source_height - target_height) source_section = Section.Code( code=Op.PUSH0 * (source_height) + Op.CALLDATALOAD(0) + Op.RJUMPI[1] + (Op.STOP if source_non_returning else Op.RETF) + Op.PUSH0 * source_extra_push + Op.JUMPF[target_section_index], code_inputs=0, code_outputs=source_outputs, max_stack_height=source_height + max(1, source_extra_push), ) # `delta` is how many stack items the target output is from the input # height, and tracks the number of pushes or (if negative) pops the target # needs to do to match output commitments delta = 0 if target_non_returning or source_non_returning else target_outputs - source_height target_section = Section.Code( code=((Op.PUSH0 * delta) if delta >= 0 else (Op.POP * -delta)) + Op.CALLF[3] + (Op.STOP if target_non_returning else Op.RETF), code_inputs=source_height, code_outputs=target_outputs, max_stack_height=max(source_height, source_height + delta), ) base_code = ( Op.JUMPF[source_section_index] if source_non_returning else (Op.CALLF[source_section_index](0, 0) + Op.STOP) ) base_height = 0 if source_non_returning else 2 + source_outputs container = Container( name="so-%s_to-%s" % ( "N" if source_non_returning else source_outputs, "N" if target_non_returning else target_outputs, ), sections=[ Section.Code( code=base_code, max_stack_height=base_height, ), source_section, target_section, Section.Code( code=Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETF, code_outputs=0, ), ], ) if target_non_returning or source_non_returning: if not target_non_returning and source_non_returning: # both as non-returning handled above container.validity_error = EOFException.INVALID_NON_RETURNING_FLAG elif source_outputs < target_outputs: container.validity_error = EOFException.JUMPF_DESTINATION_INCOMPATIBLE_OUTPUTS eof_state_test( container=container, container_post=Account(storage={slot_code_worked: value_code_worked}), data=b"\1", ) @pytest.mark.skip("Not implemented") def test_jumpf_multi_target_rules( eof_state_test: EOFStateTestFiller, ) -> None: """ NOT IMPLEMENTED: Test a section that contains multiple JUMPF to different targets with different outputs. """ pass
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_stack.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_stack.py
"""EOF JUMPF tests covering stack validation rules.""" import pytest from ethereum_test_specs import EOFTestFiller from ethereum_test_tools import Account, EOFException, EOFStateTestFiller from ethereum_test_types.eof.constants import MAX_RUNTIME_STACK_HEIGHT from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import slot_code_worked, value_code_worked REFERENCE_SPEC_GIT_PATH = "EIPS/eip-6206.md" REFERENCE_SPEC_VERSION = "2f365ea0cd58faa6e26013ea77ce6d538175f7d0" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "target_inputs", [0, 2, 4], ids=lambda x: "ti-%d" % x, ) @pytest.mark.parametrize( "stack_height", [0, 2, 4], ids=lambda x: "h-%d" % x, ) def test_jumpf_stack_non_returning_rules( eof_state_test: EOFStateTestFiller, target_inputs: int, stack_height: int, ) -> None: """ Tests for JUMPF validation stack rules. Non-returning section cases. Valid cases are executed. """ container = Container( name="stack-non-retuning_h-%d_ti-%d" % (stack_height, target_inputs), sections=[ Section.Code( code=Op.JUMPF[1], ), Section.Code( code=Op.PUSH0 * stack_height + Op.JUMPF[2], max_stack_height=stack_height, ), Section.Code( code=Op.POP * target_inputs + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, code_inputs=target_inputs, max_stack_height=max(2, target_inputs), ), ], ) if stack_height < target_inputs: container.validity_error = EOFException.STACK_UNDERFLOW eof_state_test( container=container, container_post=Account(storage={slot_code_worked: value_code_worked}), data=b"\1", ) @pytest.mark.parametrize( "source_outputs", [0, 2, 4], ids=lambda x: "so-%d" % x, ) @pytest.mark.parametrize( "target_outputs", [0, 2, 4], ids=lambda x: "to-%d" % x, ) @pytest.mark.parametrize( "target_inputs", [0, 2, 4], ids=lambda x: "ti-%d" % x, ) @pytest.mark.parametrize("stack_diff", [-1, 0, 1], ids=["less-stack", "same-stack", "more-stack"]) def test_jumpf_stack_returning_rules( eof_state_test: EOFStateTestFiller, source_outputs: int, target_outputs: int, target_inputs: int, stack_diff: int, ) -> None: """ Tests for JUMPF validation stack rules. Returning section cases. Valid cases are executed. """ if target_outputs > source_outputs: # These create invalid containers without JUMPF validation, Don't test. return if target_inputs == 0 and stack_diff < 0: # Code generation is impossible for this configuration. Don't test. return target_delta = target_outputs - target_inputs container = Container( name="stack-retuning_co-%d_to-%d_ti-%d_diff-%d" % (source_outputs, target_outputs, target_inputs, stack_diff), sections=[ Section.Code( code=Op.CALLF[1] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, max_stack_height=2 + source_outputs, ), Section.Code( code=Op.PUSH0 * max(0, target_inputs + stack_diff) + Op.JUMPF[2], code_outputs=source_outputs, max_stack_height=target_inputs, ), Section.Code( code=(Op.POP * -target_delta if target_delta < 0 else Op.PUSH0 * target_delta) + Op.RETF, code_inputs=target_inputs, code_outputs=target_outputs, max_stack_height=max(target_inputs, target_outputs), ), ], ) if stack_diff < source_outputs - target_outputs: container.validity_error = EOFException.STACK_UNDERFLOW elif stack_diff > source_outputs - target_outputs: container.validity_error = EOFException.STACK_HIGHER_THAN_OUTPUTS eof_state_test( container=container, container_post=Account(storage={slot_code_worked: value_code_worked}), data=b"\1", ) @pytest.mark.parametrize( ["target_inputs", "target_outputs", "stack_height", "expected_exception"], [ pytest.param(1, 0, 1, EOFException.STACK_UNDERFLOW, id="less_stack"), pytest.param(2, 1, 2, None, id="same_stack"), pytest.param( 3, 2, 3, EOFException.JUMPF_DESTINATION_INCOMPATIBLE_OUTPUTS, id="more_stack" ), pytest.param( 2, 2, 1, EOFException.JUMPF_DESTINATION_INCOMPATIBLE_OUTPUTS, id="less_output" ), pytest.param(1, 1, 1, None, id="same_output"), pytest.param(0, 0, 1, None, id="more_output"), ], ) def test_jumpf_incompatible_outputs( eof_test: EOFTestFiller, target_inputs: int, target_outputs: int, stack_height: int, expected_exception: EOFException, ) -> None: """Tests JUMPF into a section with incorrect number of outputs.""" current_section_outputs = 1 if (current_section_outputs + target_inputs - target_outputs) != stack_height: assert expected_exception is not None eof_test( container=Container( sections=[ Section.Code(Op.CALLF(1) + Op.STOP, max_stack_height=1), Section.Code( Op.PUSH0 * stack_height + Op.JUMPF(2), code_outputs=current_section_outputs, ), Section.Code( Op.POP * (target_inputs - target_outputs) + Op.RETF, code_inputs=target_inputs, code_outputs=target_outputs, max_stack_height=target_inputs, ), ] ), expect_exception=expected_exception, ) @pytest.mark.parametrize( ["target_inputs", "target_outputs", "stack_height", "expected_exception"], [ pytest.param(1, 0, 1, EOFException.STACK_UNDERFLOW, id="less_stack"), pytest.param(2, 1, 2, EOFException.STACK_HIGHER_THAN_OUTPUTS, id="same_stack"), pytest.param( 3, 2, 3, EOFException.JUMPF_DESTINATION_INCOMPATIBLE_OUTPUTS, id="more_stack" ), pytest.param( 2, 2, 1, EOFException.JUMPF_DESTINATION_INCOMPATIBLE_OUTPUTS, id="less_output" ), pytest.param(1, 1, 1, EOFException.STACK_HIGHER_THAN_OUTPUTS, id="same_output"), pytest.param(0, 0, 1, EOFException.STACK_HIGHER_THAN_OUTPUTS, id="more_output"), ], ) def test_jumpf_diff_max_stack_height( eof_test: EOFTestFiller, target_inputs: int, target_outputs: int, stack_height: int, expected_exception: EOFException, ) -> None: """Tests jumpf with a different max stack height.""" current_section_outputs = 1 eof_test( container=Container( sections=[ Section.Code(Op.CALLF(1) + Op.STOP, max_stack_height=1), Section.Code( (Op.PUSH0 * stack_height) # (0, 0) + Op.PUSH0 # (stack_height, stack_height) + Op.RJUMPI[1] # (stack_height + 1, stack_height + 1) + Op.PUSH0 # (stack_height, stack_height) + Op.JUMPF(2), # (stack_height, stack_height + 1) code_outputs=current_section_outputs, ), Section.Code( Op.POP * (target_inputs - target_outputs) + Op.RETF, code_inputs=target_inputs, code_outputs=target_outputs, max_stack_height=target_inputs, ), ] ), expect_exception=expected_exception, ) @pytest.mark.parametrize( ["target_inputs", "target_outputs", "stack_height", "expected_exception"], [ pytest.param(1, 0, 1, EOFException.STACK_UNDERFLOW, id="less_stack"), pytest.param(2, 1, 2, EOFException.STACK_UNDERFLOW, id="same_stack"), pytest.param( 3, 2, 3, EOFException.JUMPF_DESTINATION_INCOMPATIBLE_OUTPUTS, id="more_stack" ), pytest.param( 2, 2, 1, EOFException.JUMPF_DESTINATION_INCOMPATIBLE_OUTPUTS, id="less_output" ), pytest.param(1, 1, 1, EOFException.STACK_UNDERFLOW, id="same_output"), pytest.param(0, 0, 1, EOFException.STACK_UNDERFLOW, id="more_output"), ], ) def test_jumpf_diff_min_stack_height( eof_test: EOFTestFiller, target_inputs: int, target_outputs: int, stack_height: int, expected_exception: EOFException, ) -> None: """Tests jumpf with a different min stack height.""" current_section_outputs = 1 eof_test( container=Container( sections=[ Section.Code(Op.CALLF(1) + Op.STOP, max_stack_height=1), Section.Code( (Op.PUSH0 * (stack_height - 1)) # (0, 0) + Op.PUSH0 # (stack_height - 1, stack_height - 1) + Op.RJUMPI[1] # (stack_height, stack_height) + Op.PUSH0 # (stack_height - 1, stack_height - 1) + Op.JUMPF(2), # (stack_height - 1, stack_height) code_outputs=current_section_outputs, ), Section.Code( Op.POP * (target_inputs - target_outputs) + Op.RETF, code_inputs=target_inputs, code_outputs=target_outputs, max_stack_height=target_inputs, ), ] ), expect_exception=expected_exception, ) def test_jumpf_self_variadic_stack_overflow(eof_test: EOFTestFiller) -> None: """Test JUMPF calling self causing EOF validation stack overflow.""" container = Container( name="jumpf_stack_overflow_variable_stack_0", sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 * 511 + Op.JUMPF[0], max_stack_height=512, ), ], ) eof_test(container=container) @pytest.mark.parametrize("stack_height", [512, 1022, 1023]) @pytest.mark.parametrize("callee_stack_height", [0, 1, 2, 5, 511, 512, 513]) def test_jumpf_variadic_stack_overflow( eof_test: EOFTestFiller, stack_height: int, callee_stack_height: int ) -> None: """ Test JUMPF stack validation causing stack overflow with variable stack height. """ container = Container( sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 * (stack_height - 1) + Op.JUMPF[1], max_stack_height=stack_height, ), Section.Code( code=Op.PUSH0 * callee_stack_height + Op.STOP, max_stack_height=callee_stack_height, ), ], validity_error=EOFException.STACK_OVERFLOW if stack_height + callee_stack_height > MAX_RUNTIME_STACK_HEIGHT else None, ) eof_test(container=container) @pytest.mark.parametrize("stack_height", [1022, 1023]) @pytest.mark.parametrize("callee_stack_increase", [0, 1, 2]) def test_jumpf_with_inputs_stack_overflow( eof_test: EOFTestFiller, stack_height: int, callee_stack_increase: int ) -> None: """Test validation of JUMPF with inputs causing stack overflow.""" container = Container( sections=[ Section.Code( code=Op.PUSH0 * stack_height + Op.JUMPF[1], max_stack_height=stack_height, ), Section.Code( code=Op.PUSH0 * callee_stack_increase + Op.STOP, code_inputs=2, max_stack_height=2 + callee_stack_increase, ), ], validity_error=EOFException.STACK_OVERFLOW if stack_height + callee_stack_increase > MAX_RUNTIME_STACK_HEIGHT else None, ) eof_test(container=container) @pytest.mark.parametrize("stack_height", [1022, 1023]) @pytest.mark.parametrize("callee_stack_increase", [0, 1, 2]) def test_jumpf_with_inputs_stack_overflow_variable_stack( eof_test: EOFTestFiller, stack_height: int, callee_stack_increase: int ) -> None: """ Test JUMPF with variable stack depending on RJUMPI calling function with inputs. """ container = Container( sections=[ Section.Code( code=Op.PUSH0 + Op.RJUMPI[2](0) + Op.PUSH0 * (stack_height - 1) + Op.JUMPF[1], max_stack_height=stack_height, ), Section.Code( code=Op.PUSH0 * callee_stack_increase + Op.STOP, code_inputs=2, max_stack_height=2 + callee_stack_increase, ), ], validity_error=EOFException.STACK_OVERFLOW if stack_height + callee_stack_increase > MAX_RUNTIME_STACK_HEIGHT else None, ) eof_test(container=container)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/helpers.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/helpers.py
"""EOF JumpF tests helpers.""" import itertools """Storage addresses for common testing fields""" _slot = itertools.count() next(_slot) # don't use slot 0 slot_code_worked = next(_slot) slot_last_slot = next(_slot) slot_stack_canary = next(_slot) """Storage values for common testing fields""" value_code_worked = 0x2015 value_canary_written = 0xDEADB12D
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_nonreturning_validation.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_nonreturning_validation.py
"""EOF validation tests for non-returning code sections.""" import pytest from ethereum_test_tools import EOFException, EOFTestFiller from ethereum_test_types.eof.v1 import NON_RETURNING_SECTION, Container, ContainerKind, Section from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME REFERENCE_SPEC_GIT_PATH = "EIPS/eip-6206.md" REFERENCE_SPEC_VERSION = "2f365ea0cd58faa6e26013ea77ce6d538175f7d0" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) @pytest.mark.parametrize( "code", [ pytest.param(Op.STOP, id="STOP"), pytest.param(Op.INVALID, id="INVALID"), pytest.param(Op.ADDRESS + Op.POP + Op.INVALID, id="ADDRESS_POP_INVALID"), pytest.param(Op.RETURN(0, 0), id="RETURN"), pytest.param(Op.RETF, id="RETF"), pytest.param(Op.PUSH0 + Op.RETF, id="PUSH0_RETF"), ], ) @pytest.mark.parametrize( "outputs", [0, 1, 0x7F, 0x81, 0xFF], ) def test_first_section_returning(eof_test: EOFTestFiller, code: Bytecode, outputs: int) -> None: """ Test EOF validation failing because the first section is not non-returning. """ eof_test( container=Container( sections=[Section.Code(code, code_outputs=outputs)], validity_error=EOFException.INVALID_FIRST_SECTION_TYPE, ) ) @pytest.mark.parametrize( "code", [ pytest.param(Op.INVALID, id="INVALID"), pytest.param(Op.RETF, id="RETF"), pytest.param(Op.POP + Op.RETF, id="POP_RETF"), ], ) @pytest.mark.parametrize( "inputs", [1, 2, 0x7F, 0x80, 0x81, 0xFF], ) @pytest.mark.parametrize( "outputs", [ 0, NON_RETURNING_SECTION, ], ) def test_first_section_with_inputs( eof_test: EOFTestFiller, code: Bytecode, inputs: int, outputs: int ) -> None: """ Test EOF validation failing because the first section has non-zero number of inputs. """ eof_test( container=Container( sections=[ Section.Code( code, code_inputs=inputs, code_outputs=outputs, max_stack_height=max(inputs, outputs), ) ], validity_error=EOFException.INVALID_FIRST_SECTION_TYPE, ) ) @pytest.mark.parametrize( "code_section", [ pytest.param(Section.Code(Op.STOP, code_outputs=0), id="stop0"), pytest.param(Section.Code(Op.PUSH0 + Op.STOP, code_outputs=1), id="stop1"), pytest.param(Section.Code(Op.INVALID, code_outputs=0), id="invalid0"), pytest.param(Section.Code(Op.PUSH0 + Op.INVALID, code_outputs=1), id="invalid1"), pytest.param(Section.Code(Op.RETURN(0, 0), code_outputs=0), id="return0"), pytest.param(Section.Code(Op.PUSH0 + Op.RETURN(0, 0), code_outputs=1), id="return1"), pytest.param(Section.Code(Op.REVERT(0, 0), code_outputs=0), id="revert0"), pytest.param(Section.Code(Op.PUSH0 + Op.REVERT(0, 0), code_outputs=1), id="revert1"), pytest.param(Section.Code(Op.RJUMP[-3], code_outputs=0), id="rjump0"), pytest.param(Section.Code(Op.PUSH0 + Op.RJUMP[-3], code_outputs=1), id="rjump1"), ], ) def test_returning_section_not_returning(eof_test: EOFTestFiller, code_section: Section) -> None: """ Test EOF validation failing due to returning section with no RETF or JUMPF-to-returning. """ eof_test( container=Container( sections=[ Section.Code(Op.CALLF[1] + Op.STOP, max_stack_height=code_section.code_outputs), code_section, ], validity_error=EOFException.INVALID_NON_RETURNING_FLAG, ), ) @pytest.mark.parametrize( "code_section", [ pytest.param(Section.Code(Op.RETURNCODE[0](0, 0), code_outputs=0), id="returncode0"), pytest.param( Section.Code(Op.PUSH0 + Op.RETURNCODE[0](0, 0), code_outputs=1), id="returncode1", ), ], ) def test_returning_section_returncode(eof_test: EOFTestFiller, code_section: Section) -> None: """ Test EOF validation failing because a returning section has no RETF or JUMPF-to-returning - RETURNCODE version. """ eof_test( container=Container( sections=[ Section.Code(Op.CALLF[1] + Op.INVALID, max_stack_height=code_section.code_outputs), code_section, ] + [Section.Container(Container.Code(Op.INVALID))], validity_error=EOFException.INVALID_NON_RETURNING_FLAG, kind=ContainerKind.INITCODE, ) ) first = pytest.mark.parametrize("first", [True, False]) code_prefix = pytest.mark.parametrize( "code_prefix", [ Bytecode(), Op.PUSH0, pytest.param(Op.PUSH0 * NON_RETURNING_SECTION, id="PUSH0x0x80"), ], ) @first @code_prefix def test_retf_in_nonreturning(eof_test: EOFTestFiller, first: bool, code_prefix: Bytecode) -> None: """ Test EOF validation failing due to non-returning section with the RETF instruction. """ sections = [Section.Code(code_prefix + Op.RETF, code_outputs=NON_RETURNING_SECTION)] if not first: # Prefix sections with additional valid JUMPF to invalid section sections = [Section.Code(Op.JUMPF[1])] + sections eof_test( container=Container( sections=sections, validity_error=EOFException.INVALID_NON_RETURNING_FLAG ) ) @first @code_prefix def test_jumpf_in_nonreturning( eof_test: EOFTestFiller, first: bool, code_prefix: Bytecode ) -> None: """ Test EOF validation failing due to non-returning section with the JUMPF instruction. """ invalid_section = Section.Code( code_prefix + Op.JUMPF[1 if first else 2], code_outputs=NON_RETURNING_SECTION, ) target_section = Section.Code(Op.RETF, code_outputs=0) sections = [invalid_section, target_section] if not first: # Prefix sections with additional valid JUMPF to invalid section sections = [Section.Code(Op.JUMPF[1])] + sections eof_test( container=Container( sections=sections, validity_error=EOFException.INVALID_NON_RETURNING_FLAG, ) ) @pytest.mark.parametrize( "container", [ Container( name="0_to_1", sections=[ Section.Code( Op.CALLF[1], ), Section.Code( Op.STOP, ), ], ), Container( name="self_0", sections=[ Section.Code( Op.CALLF[0] + Op.STOP, ) ], ), Container( name="self_1", sections=[ Section.Code( Op.JUMPF[1], ), Section.Code( Op.CALLF[1] + Op.STOP, ), ], ), Container( name="1_to_0", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( Op.CALLF[0] + Op.RETF, code_outputs=0, ), ], ), Container( name="1_to_2", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( Op.CALLF[2] + Op.RETF, code_outputs=0, ), Section.Code( Op.INVALID, ), ], ), ], ids=lambda x: x.name, ) def test_callf_to_nonreturning(eof_test: EOFTestFiller, container: Container) -> None: """Test EOF validation failing due to CALLF to non-returning section.""" eof_test(container=container, expect_exception=EOFException.CALLF_TO_NON_RETURNING)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_execution.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/test_jumpf_execution.py
"""EOF JUMPF tests covering simple cases.""" import pytest from ethereum_test_base_types import Storage from ethereum_test_specs import StateTestFiller from ethereum_test_tools import Account, Environment, EOFException, EOFStateTestFiller, Transaction from ethereum_test_types import Alloc from ethereum_test_types.eof.v1 import Container, Section from ethereum_test_types.eof.v1.constants import NON_RETURNING_SECTION from ethereum_test_vm import Opcodes as Op from .. import EOF_FORK_NAME from .helpers import ( slot_code_worked, slot_stack_canary, value_canary_written, value_code_worked, ) REFERENCE_SPEC_GIT_PATH = "EIPS/eip-6206.md" REFERENCE_SPEC_VERSION = "2f365ea0cd58faa6e26013ea77ce6d538175f7d0" pytestmark = pytest.mark.valid_from(EOF_FORK_NAME) def test_jumpf_forward( eof_state_test: EOFStateTestFiller, ) -> None: """Test JUMPF jumping forward.""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.JUMPF[1], ), Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), data=b"\1", ) @pytest.mark.parametrize( "container", [ Container( name="forward", sections=[ Section.Code( code=Op.CALLF[1] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Code( code=Op.JUMPF[2], code_outputs=0, ), Section.Code( code=Op.RETF, code_outputs=0, ), ], ), Container( name="backward", sections=[ Section.Code( code=Op.CALLF[2] + Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, ), Section.Code( code=Op.RETF, code_outputs=0, ), Section.Code( code=Op.JUMPF[1], code_outputs=0, ), ], ), Container( name="equal_outputs", sections=[ Section.Code( Op.CALLF[1] + Op.SSTORE + Op.STOP, max_stack_height=2, ), Section.Code( Op.JUMPF[2], code_outputs=2, max_stack_height=0, ), Section.Code( Op.PUSH2[value_code_worked] + Op.PUSH2[slot_code_worked] + Op.RETF, code_outputs=2, max_stack_height=2, ), ], ), Container( name="compatible_outputs", sections=[ Section.Code( code=Op.CALLF[1] + Op.SSTORE + Op.STOP, max_stack_height=2, ), Section.Code( Op.PUSH2[value_code_worked] + Op.JUMPF[2], code_outputs=2, max_stack_height=1, ), Section.Code( Op.PUSH2[slot_code_worked] + Op.RETF, code_outputs=1, max_stack_height=1, ), ], ), ], ids=lambda container: container.name, ) def test_jumpf_to_retf(eof_state_test: EOFStateTestFiller, container: Container) -> None: """Tests JUMPF to a returning section with RETF.""" eof_state_test( container=container, container_post=Account(storage={slot_code_worked: value_code_worked}), data=b"\1", ) def test_jumpf_to_self( eof_state_test: EOFStateTestFiller, ) -> None: """Tests JUMPF jumping to self.""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.SLOAD(slot_code_worked) + Op.ISZERO + Op.RJUMPI[1] + Op.STOP + Op.SSTORE(slot_code_worked, value_code_worked) + Op.JUMPF[0], ) ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), data=b"\1", ) @pytest.mark.parametrize( "container", [ Container( name="1_to_2_arg0", sections=[ Section.Code( Op.CALLF[1] + Op.STOP, ), Section.Code( Op.PUSH0 + Op.RJUMPI[3] + Op.JUMPF[2] + Op.RETF, code_outputs=0, ), Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETF, code_outputs=0, ), ], ), Container( name="1_to_2_arg1", sections=[ Section.Code( Op.PUSH1[1] + Op.CALLF[1] + Op.STOP, ), Section.Code( Op.RJUMPI[1] + Op.RETF + Op.SSTORE(slot_code_worked, value_code_worked) + Op.JUMPF[2], code_inputs=1, code_outputs=0, ), Section.Code( Op.RETF, code_outputs=0, ), ], ), Container( name="1_to_0_to_1", sections=[ Section.Code( Op.ISZERO(Op.SLOAD(slot_code_worked)) + Op.CALLF[1] + Op.STOP, ), Section.Code( Op.RJUMPI[1] + Op.RETF + Op.SSTORE(slot_code_worked, value_code_worked) + Op.JUMPF[0], code_inputs=1, code_outputs=0, ), ], ), Container( name="retf_in_nonreturning", sections=[ Section.Code( Op.PUSH0 + Op.JUMPF[1], ), Section.Code( Op.RJUMPI[1] + Op.RETF + Op.JUMPF[0], code_inputs=1, ), ], validity_error=EOFException.INVALID_NON_RETURNING_FLAG, ), Container( name="jumpf_to_returning", sections=[ Section.Code( Op.PUSH0 + Op.JUMPF[1], ), Section.Code( Op.RJUMPI[1] + Op.RETF + Op.JUMPF[2], code_inputs=1, ), Section.Code( Op.RETF, code_outputs=0, ), ], validity_error=EOFException.INVALID_NON_RETURNING_FLAG, ), Container( name="jumpf_to_returning_2", sections=[ Section.Code( Op.PUSH0 + Op.JUMPF[1], ), Section.Code( Op.RJUMPI[3] + Op.JUMPF[2] + Op.RETF, code_inputs=1, ), Section.Code( Op.RETF, code_outputs=0, ), ], validity_error=EOFException.INVALID_NON_RETURNING_FLAG, ), ], ids=lambda container: container.name, ) def test_jumpf_and_retf(eof_state_test: EOFStateTestFiller, container: Container) -> None: """Tests JUMPF and RETF in the same section.""" eof_state_test( container=container, container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_jumpf_too_large( eof_state_test: EOFStateTestFiller, ) -> None: """Tests JUMPF jumping to a section outside the max section range.""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.JUMPF[1025], ) ], validity_error=EOFException.INVALID_CODE_SECTION_INDEX, ), ) def test_jumpf_way_too_large( eof_state_test: EOFStateTestFiller, ) -> None: """Tests JUMPF jumping to uint64.MAX.""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.JUMPF[0xFFFF], ) ], validity_error=EOFException.INVALID_CODE_SECTION_INDEX, ), ) def test_jumpf_to_nonexistent_section( eof_state_test: EOFStateTestFiller, ) -> None: """ Tests JUMPF jumping to valid section number but where the section does not exist. """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.JUMPF[5], ) ], validity_error=EOFException.INVALID_CODE_SECTION_INDEX, ), ) def test_callf_to_non_returning_section( eof_state_test: EOFStateTestFiller, ) -> None: """Tests CALLF into a non-returning section.""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.CALLF[1], ), Section.Code( code=Op.STOP, code_outputs=0, ), ], validity_error=EOFException.MISSING_STOP_OPCODE, ), ) def test_jumpf_stack_size_1024( eof_state_test: EOFStateTestFiller, ) -> None: """Test stack reaching 1024 items in target function of JUMPF.""" eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 1022 + Op.JUMPF[1], max_stack_height=1022, ), Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, code_inputs=0, code_outputs=NON_RETURNING_SECTION, max_stack_height=2, ), ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_jumpf_with_inputs_stack_size_1024( eof_state_test: EOFStateTestFiller, ) -> None: """ Test stack reaching 1024 items in target function of JUMPF with inputs. """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 1022 + Op.JUMPF[1], max_stack_height=1022, ), Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.STOP, code_inputs=3, code_outputs=NON_RETURNING_SECTION, max_stack_height=5, ), ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_jumpf_stack_size_1024_at_push( eof_state_test: EOFStateTestFiller, ) -> None: """ Test stack reaching 1024 items in JUMPF target function at PUSH0 instruction. """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), max_stack_height=1023, ), Section.Code( # stack has 1023 items Op.JUMPF[2], code_inputs=0, code_outputs=0, max_stack_height=0, ), Section.Code( Op.PUSH0 + # stack has 1024 items Op.POP + Op.RETF, code_inputs=0, code_outputs=0, max_stack_height=1, ), ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) @pytest.mark.parametrize( ("stack_height", "failure"), ( pytest.param(1021, False, id="no_overflow"), pytest.param(1022, True, id="rule_overflow"), pytest.param(1023, True, id="execution_overflow"), ), ) def test_jumpf_stack_overflow( stack_height: int, failure: bool, eof_state_test: EOFStateTestFiller, ) -> None: """ Test rule #2 in execution semantics, where we make sure we have enough stack to guarantee safe execution (the "reserved stack rule") max possible stack will not exceed 1024. But some executions may not overflow the stack, so we need to ensure the rule is checked. `no_overflow` - the stack does not overflow at JUMPF call, executes to end `rule_overflow` - reserved stack rule triggers, but execution would not overflow if allowed `execution_overflow` - execution would overflow (but still blocked by reserved stack rule) """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * stack_height + Op.CALLF[1] + Op.POP * stack_height + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), max_stack_height=stack_height, ), Section.Code( # Stack has stack_height items Op.JUMPF[2], code_inputs=0, code_outputs=0, max_stack_height=0, ), Section.Code( Op.CALLDATALOAD(0) + Op.ISZERO + Op.RJUMPI[6] + Op.PUSH0 * 3 + Op.POP * 3 + Op.SSTORE(slot_stack_canary, value_canary_written) + Op.RETF, code_inputs=0, code_outputs=0, max_stack_height=3, ), ], ), container_post=Account( storage={ slot_code_worked: 0 if failure else value_code_worked, slot_stack_canary: 0 if failure else value_canary_written, } ), ) def test_jumpf_with_inputs_stack_size_1024_at_push( eof_state_test: EOFStateTestFiller, ) -> None: """ Test stack reaching 1024 items in JUMPF target function with inputs at PUSH0 instruction. """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), max_stack_height=1023, ), Section.Code( # Stack has 1023 items Op.JUMPF[2], code_inputs=3, code_outputs=3, max_stack_height=3, ), Section.Code( Op.PUSH0 + # Stack has 1024 items Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_height=4, ), ], ), container_post=Account(storage={slot_code_worked: value_code_worked}), ) def test_jumpf_with_inputs_stack_overflow( eof_state_test: EOFStateTestFiller, ) -> None: """ Test stack overflowing 1024 items in JUMPF target function with inputs. """ eof_state_test( container=Container( sections=[ Section.Code( code=Op.PUSH0 * 1023 + Op.CALLF[1] + Op.POP * 1023 + Op.SSTORE(slot_code_worked, value_code_worked) + Op.RETURN(0, 0), max_stack_height=1023, ), Section.Code( # Stack has 1023 items Op.JUMPF[2], code_inputs=3, code_outputs=3, max_stack_height=3, ), Section.Code( Op.PUSH0 + Op.PUSH0 + # Runtime stackoverflow Op.POP + Op.POP + Op.RETF, code_inputs=3, code_outputs=3, max_stack_height=5, ), ], ), container_post=Account(storage={slot_code_worked: 0}), ) @pytest.mark.parametrize( "container", [ Container( name="self", sections=[ Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.JUMPF[0], ), ], ), Container( name="1_to_0", sections=[ Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.JUMPF[1], ), Section.Code( Op.JUMPF[0], ), ], ), Container( name="2_to_1", sections=[ Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.JUMPF[1], ), Section.Code( Op.JUMPF[2], ), Section.Code( Op.JUMPF[1], ), ], ), Container( name="2_to_1_returning", sections=[ Section.Code( Op.SSTORE(slot_code_worked, value_code_worked) + Op.CALLF[1] + Op.STOP, ), Section.Code( Op.JUMPF[2], code_outputs=0, ), Section.Code( Op.JUMPF[1], code_outputs=0, ), ], ), Container( name="1_to_0_invalid", sections=[ Section.Code( Op.JUMPF[1], ), Section.Code( Op.JUMPF[0], code_outputs=0, ), ], validity_error=EOFException.INVALID_NON_RETURNING_FLAG, ), ], ids=lambda container: container.name, ) def test_jumpf_infinite_loop(eof_state_test: EOFStateTestFiller, container: Container) -> None: """Tests JUMPF causing an infinite loop.""" eof_state_test( container=container, container_post=Account(storage={slot_code_worked: 0}), ) def test_jumpf_memory_context( state_test: StateTestFiller, pre: Alloc, ) -> None: """Verifies JUMPF doesn't corrupt memory.""" env = Environment() storage = Storage() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( Op.SSTORE(storage.store_next(value_code_worked), value_code_worked) + Op.MSTORE(0, 1) + Op.JUMPF[1], ), Section.Code( Op.SSTORE(storage.store_next(32), Op.MSIZE()) + Op.SSTORE(storage.store_next(1), Op.MLOAD(0)) + Op.STOP, ), ], ), ) post = { contract_address: Account( storage=storage, ), } tx = Transaction( to=contract_address, gas_limit=500_000, sender=pre.fund_eoa(), ) state_test(env=env, pre=pre, post=post, tx=tx) def test_callf_jumpf_retf_memory_context( state_test: StateTestFiller, pre: Alloc, ) -> None: """Verifies CALLF, JUMPF and RETF don't corrupt memory.""" env = Environment() storage = Storage() contract_address = pre.deploy_contract( code=Container( sections=[ Section.Code( Op.SSTORE(storage.store_next(value_code_worked), value_code_worked) + Op.MSTORE(0, 1) + Op.CALLF[1] + Op.SSTORE(storage.store_next(96), Op.MSIZE()) + Op.SSTORE(storage.store_next(2), Op.MLOAD(0)) + Op.SSTORE(storage.store_next(21), Op.MLOAD(32)) + Op.SSTORE(storage.store_next(31), Op.MLOAD(64)) + Op.STOP, ), Section.Code( Op.SSTORE(storage.store_next(32), Op.MSIZE()) + Op.SSTORE(storage.store_next(1), Op.MLOAD(0)) + Op.MSTORE(0, 2) + Op.MSTORE(32, 3) + Op.JUMPF[2], code_outputs=0, ), Section.Code( Op.SSTORE(storage.store_next(64), Op.MSIZE()) + Op.SSTORE(storage.store_next(2), Op.MLOAD(0)) + Op.SSTORE(storage.store_next(3), Op.MLOAD(32)) + Op.MSTORE(32, 21) + Op.MSTORE(64, 31) + Op.RETF, code_outputs=0, ), ], ), ) post = { contract_address: Account( storage=storage, ), } tx = Transaction( to=contract_address, gas_limit=500_000, sender=pre.fund_eoa(), ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/__init__.py
tests/unscheduled/eip7692_eof_v1/eip6206_jumpf/__init__.py
""" Test cases for [EIP-6206: EOF - JUMPF and non-returning functions](https:// eips.ethereum.org/EIPS/eip-6206). EIP-6206 adds a conditional forward jump instruction and support for functions without return values. Opcodes introduced: `JUMPF` (`0xE5`). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/byzantium/__init__.py
tests/byzantium/__init__.py
"""Test cases for EVM functionality introduced in Byzantium."""
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/byzantium/eip198_modexp_precompile/test_modexp.py
tests/byzantium/eip198_modexp_precompile/test_modexp.py
""" Test [EIP-198: MODEXP Precompile](https://eips.ethereum.org/EIPS/eip-198). Tests the MODEXP precompile, located at address 0x0000..0005. Test cases from the EIP are labelled with `EIP-198-caseX` in the test id. """ import pytest from ethereum_test_tools import ( Account, Alloc, Bytes, Environment, StateTestFiller, Transaction, compute_create_address, ) from ethereum_test_vm import Opcodes as Op from .helpers import ModExpInput, ModExpOutput REFERENCE_SPEC_GIT_PATH = "EIPS/eip-198.md" REFERENCE_SPEC_VERSION = "5c8f066acb210c704ef80c1033a941aa5374aac5" @pytest.mark.valid_from("Byzantium") @pytest.mark.parametrize( ["mod_exp_input", "output"], [ ( ModExpInput(base="", exponent="", modulus="02"), ModExpOutput(returned_data="0x01"), ), ( ModExpInput(base="", exponent="", modulus="0002"), ModExpOutput(returned_data="0x0001"), ), ( ModExpInput(base="00", exponent="00", modulus="02"), ModExpOutput(returned_data="0x01"), ), ( ModExpInput(base="", exponent="01", modulus="02"), ModExpOutput(returned_data="0x00"), ), ( ModExpInput(base="01", exponent="01", modulus="02"), ModExpOutput(returned_data="0x01"), ), ( ModExpInput(base="02", exponent="01", modulus="03"), ModExpOutput(returned_data="0x02"), ), ( ModExpInput(base="02", exponent="02", modulus="05"), ModExpOutput(returned_data="0x04"), ), ( ModExpInput(base="", exponent="", modulus=""), ModExpOutput(returned_data="0x"), ), ( ModExpInput(base="", exponent="", modulus="00"), ModExpOutput(returned_data="0x00"), ), ( ModExpInput(base="", exponent="", modulus="01"), ModExpOutput(returned_data="0x00"), ), ( ModExpInput(base="", exponent="", modulus="0001"), ModExpOutput(returned_data="0x0000"), ), ( ModExpInput( base="", exponent="", modulus="", declared_exponent_length=2**32, declared_modulus_length=1, ), ModExpOutput(returned_data="0x00", call_success=False), ), # Test cases from EIP 198. pytest.param( ModExpInput( base="03", exponent="fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e", modulus="fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", ), ModExpOutput( returned_data="0000000000000000000000000000000000000000000000000000000000000001", ), id="EIP-198-case1", ), pytest.param( ModExpInput( base="", exponent="fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e", modulus="fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", ), ModExpOutput( returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="EIP-198-case2", ), pytest.param( # Note: This is the only test case which goes out-of- # gas. Bytes( "0000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000020" "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe" "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="EIP-198-case3-raw-input-out-of-gas", ), pytest.param( ModExpInput( base="03", exponent="ffff", modulus="8000000000000000000000000000000000000000000000000000000000000000", extra_data="07", ), ModExpOutput( returned_data="0x3b01b01ac41f2d6e917c6d6a221ce793802469026d9ab7578fa2e79e4da6aaab", ), id="EIP-198-case4-extra-data_07", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000000000002" "0000000000000000000000000000000000000000000000000000000000000020" "03" "ffff" "80" ), ModExpOutput( returned_data="0x3b01b01ac41f2d6e917c6d6a221ce793802469026d9ab7578fa2e79e4da6aaab", ), id="EIP-198-case5-raw-input", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000008000000000000020" "0000000000000000000000000000000000000000000000000000000000000001" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-exponent-length-0x80000000-out-of-gas", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000004000000000000020" "0000000000000000000000000000000000000000000000000000000000000001" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-exponent-length-0x40000000-out-of-gas", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000002000000000000020" "0000000000000000000000000000000000000000000000000000000000000001" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-exponent-length-0x20000000-out-of-gas", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000001000000000000020" "0000000000000000000000000000000000000000000000000000000000000001" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-exponent-length-0x10000000-out-of-gas", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000080000020" "0000000000000000000000000000000000000000000000000000000000000001" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-modulus-length-0x80000020-out-of-gas", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000040000020" "0000000000000000000000000000000000000000000000000000000000000001" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-modulus-length-0x40000020-out-of-gas", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000020000020" "0000000000000000000000000000000000000000000000000000000000000001" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-modulus-length-0x20000020-out-of-gas", ), pytest.param( Bytes( "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000000000040" "00000000000000000000000000000000000000000000000000000000ffffffff" "80" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), id="large-modulus-length-0xffffffff-out-of-gas", ), pytest.param( Bytes( "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9" "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000000000001" ), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), # FIXME marks=pytest.mark.skip( reason=( "EELS bug: U256 overflow in modexp pointer arithmetic " "before Osaka - see github.com/ethereum/execution-specs/issues/1465" ) ), id="max-base-length-overflow-out-of-gas", ), pytest.param( Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa0"), ModExpOutput( call_success=False, returned_data="0000000000000000000000000000000000000000000000000000000000000000", ), # FIXME marks=pytest.mark.skip( reason=( "EELS bug: U256 overflow in modexp pointer arithmetic " "before Osaka - see github.com/ethereum/execution-specs/issues/1465" ) ), id="immunefi-38958-by-omik-overflow", ), ], ids=lambda param: param.__repr__(), # only required to remove parameter # names (input/output) ) def test_modexp( state_test: StateTestFiller, mod_exp_input: ModExpInput | Bytes, output: ModExpOutput, pre: Alloc, ) -> None: """Test the MODEXP precompile.""" env = Environment() sender = pre.fund_eoa() account = pre.deploy_contract( # Store all CALLDATA into memory (offset 0) Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE()) # Store the returned CALL status (success = 1, fail = 0) into slot 0: + Op.SSTORE( 0, # Setup stack to CALL into ModExp with the CALLDATA and CALL into # it (+ pop value) Op.CALL(Op.GAS(), 0x05, 0, 0, Op.CALLDATASIZE(), 0, 0), ) # Store contract deployment code to deploy the returned data from # ModExp as contract code (16 bytes) + Op.MSTORE( 0, ( # Need to `ljust` this PUSH32 in order to ensure the code # starts in memory at offset 0 (memory right-aligns stack items # which are not 32 bytes) Op.PUSH32( bytes( Op.CODECOPY(0, 16, Op.SUB(Op.CODESIZE(), 16)) + Op.RETURN(0, Op.SUB(Op.CODESIZE, 16)) ).ljust(32, bytes(1)) ) ), ) # RETURNDATACOPY the returned data from ModExp into memory (offset 16 # bytes) + Op.RETURNDATACOPY(16, 0, Op.RETURNDATASIZE()) # CREATE contract with the deployment code + the returned data from # ModExp + Op.CREATE(0, 0, Op.ADD(16, Op.RETURNDATASIZE())) # STOP (handy for tracing) + Op.STOP(), ) tx = Transaction( ty=0x0, to=account, data=mod_exp_input, gas_limit=500_000, protected=True, sender=sender, ) post = {} if output.call_success: contract_address = compute_create_address(address=account, nonce=1) post[contract_address] = Account(code=output.returned_data) post[account] = Account(storage={0: output.call_success}) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/byzantium/eip198_modexp_precompile/helpers.py
tests/byzantium/eip198_modexp_precompile/helpers.py
""" Helper functions for the EIP-198 ModExp precompile tests. """ from typing import Tuple from pydantic import Field from ethereum_test_tools import Bytes, TestParameterGroup class ModExpInput(TestParameterGroup): """ Helper class that defines the MODEXP precompile inputs and creates the call data from them. Attributes: base (str): The base value for the MODEXP precompile. exponent (str): The exponent value for the MODEXP precompile. modulus (str): The modulus value for the MODEXP precompile. extra_data (str): Defines extra padded data to be added at the end of the calldata to the precompile. Defaults to an empty string. """ base: Bytes exponent: Bytes modulus: Bytes extra_data: Bytes = Field(default_factory=Bytes) raw_input: Bytes | None = None declared_base_length: int | None = None declared_exponent_length: int | None = None declared_modulus_length: int | None = None @property def length_base(self) -> Bytes: """Return the length of the base.""" length = ( self.declared_base_length if self.declared_base_length is not None else len(self.base) ) return Bytes(length.to_bytes(32, "big")) @property def length_exponent(self) -> Bytes: """Return the length of the exponent.""" length = ( self.declared_exponent_length if self.declared_exponent_length is not None else len(self.exponent) ) return Bytes(length.to_bytes(32, "big")) @property def length_modulus(self) -> Bytes: """Return the length of the modulus.""" length = ( self.declared_modulus_length if self.declared_modulus_length is not None else len(self.modulus) ) return Bytes(length.to_bytes(32, "big")) def __bytes__(self) -> bytes: """Generate input for the MODEXP precompile.""" if self.raw_input is not None: return self.raw_input return ( self.length_base + self.length_exponent + self.length_modulus + self.base + self.exponent + self.modulus + self.extra_data ) @classmethod def from_bytes(cls, input_data: Bytes | str) -> "ModExpInput": """ Create a ModExpInput from a bytes object. Assumes correct formatting of the input data. """ if isinstance(input_data, str): input_data = Bytes(input_data) assert not isinstance(input_data, str) padded_input_data = input_data if len(padded_input_data) < 96: padded_input_data = Bytes(padded_input_data.ljust(96, b"\0")) base_length = int.from_bytes(padded_input_data[0:32], byteorder="big") exponent_length = int.from_bytes(padded_input_data[32:64], byteorder="big") modulus_length = int.from_bytes(padded_input_data[64:96], byteorder="big") total_required_length = 96 + base_length + exponent_length + modulus_length if len(padded_input_data) < total_required_length: padded_input_data = Bytes(padded_input_data.ljust(total_required_length, b"\0")) current_index = 96 base = padded_input_data[current_index : current_index + base_length] current_index += base_length exponent = padded_input_data[current_index : current_index + exponent_length] current_index += exponent_length modulus = padded_input_data[current_index : current_index + modulus_length] return cls(base=base, exponent=exponent, modulus=modulus, raw_input=input_data) def get_declared_lengths(self) -> Tuple[int, int, int]: """Extract declared lengths from the raw input bytes.""" raw = self.raw_input if self.raw_input is not None else bytes(self) if len(raw) < 96: raw = raw.ljust(96, b"\0") base_length = int.from_bytes(raw[0:32], byteorder="big") exponent_length = int.from_bytes(raw[32:64], byteorder="big") modulus_length = int.from_bytes(raw[64:96], byteorder="big") return base_length, exponent_length, modulus_length def get_exponent_head(self) -> int: """Get the first 32 bytes of the exponent as an integer.""" raw = self.raw_input if self.raw_input is not None else bytes(self) base_length, exponent_length, _ = self.get_declared_lengths() exp_start = 96 + base_length # Extract up to 32 bytes of exponent data exp_head_bytes = raw[exp_start : exp_start + min(32, exponent_length)] # Pad with zeros if less than 32 bytes exp_head_bytes = exp_head_bytes.rjust(32, b"\0") return int.from_bytes(exp_head_bytes[:32], byteorder="big") class ModExpOutput(TestParameterGroup): """ Expected test result. Attributes: call_success (bool): The return_code from CALL, 0 indicates unsuccessful call (out-of-gas), 1 indicates call succeeded. returned_data(str): The output returnData is the expected output of the call. """ call_success: bool = True returned_data: Bytes
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/byzantium/eip198_modexp_precompile/__init__.py
tests/byzantium/eip198_modexp_precompile/__init__.py
"""Test for precompiles introduced in Byzantium."""
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/amsterdam/__init__.py
tests/amsterdam/__init__.py
""" Test cases for EVM functionality introduced in Amsterdam, [EIP-7773: Hardfork Meta - Glamsterdam](https://eip.directory/eips/eip-7773). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/amsterdam/eip7928_block_level_access_lists/spec.py
tests/amsterdam/eip7928_block_level_access_lists/spec.py
"""Reference spec for [EIP-7928: Block-level Access Lists.](https://eips.ethereum.org/EIPS/eip-7928).""" from dataclasses import dataclass @dataclass(frozen=True) class ReferenceSpec: """Reference specification.""" git_path: str version: str ref_spec_7928 = ReferenceSpec( git_path="EIPS/eip-7928.md", version="e7f0963a024b3d0dedc4488a7553bf7c70dedb3e", ) @dataclass(frozen=True) class Spec: """Constants and parameters from EIP-7928.""" # RLP encoding is used for block access list data structures BAL_ENCODING_FORMAT: str = "RLP" # Maximum limits for block access list data structures TARGET_MAX_GAS_LIMIT = 600_000_000 MAX_TXS: int = 30_000 MAX_SLOTS: int = 300_000 MAX_ACCOUNTS: int = 300_000 # TODO: Use this as a function of the current fork. MAX_CODE_SIZE: int = 24_576 # 24 KiB # Type size constants ADDRESS_SIZE: int = 20 # Ethereum address size in bytes STORAGE_KEY_SIZE: int = 32 # Storage slot key size in bytes STORAGE_VALUE_SIZE: int = 32 # Storage value size in bytes HASH_SIZE: int = 32 # Hash size in bytes # Numeric type limits MAX_TX_INDEX: int = 2**16 - 1 # uint16 max value MAX_BALANCE: int = 2**128 - 1 # uint128 max value MAX_NONCE: int = 2**64 - 1 # uint64 max value
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists_opcodes.py
tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists_opcodes.py
""" Tests for EIP-7928 Block Access Lists with single-opcode success and OOG scenarios. Block access lists (BAL) are generated via a client's state tracing journal. Residual journal entries may persist when opcodes run out of gas, resulting in a bloated BAL payload. Issues identified in: https://github.com/paradigmxyz/reth/issues/17765 https://github.com/bluealloy/revm/pull/2903 These tests ensure out-of-gas operations are not recorded in BAL, preventing consensus issues. """ from enum import Enum import pytest from ethereum_test_forks import Fork from ethereum_test_tools import ( Account, Alloc, Block, BlockchainTestFiller, Transaction, ) from ethereum_test_tools import ( Opcodes as Op, ) from ethereum_test_types.block_access_list import ( BalAccountExpectation, BalStorageChange, BalStorageSlot, BlockAccessListExpectation, ) from ethereum_test_vm import Bytecode from .spec import ref_spec_7928 REFERENCE_SPEC_GIT_PATH = ref_spec_7928.git_path REFERENCE_SPEC_VERSION = ref_spec_7928.version pytestmark = pytest.mark.valid_from("Amsterdam") class OutOfGasAt(Enum): """ Enumeration of specific gas boundaries where OOG can occur. """ EIP_2200_STIPEND = "oog_at_eip2200_stipend" EIP_2200_STIPEND_PLUS_1 = "oog_at_eip2200_stipend_plus_1" EXACT_GAS_MINUS_1 = "oog_at_exact_gas_minus_1" @pytest.mark.parametrize( "out_of_gas_at", [ OutOfGasAt.EIP_2200_STIPEND, OutOfGasAt.EIP_2200_STIPEND_PLUS_1, OutOfGasAt.EXACT_GAS_MINUS_1, None, # no oog, successful sstore ], ids=lambda x: x.value if x else "successful_sstore", ) def test_bal_sstore_and_oog( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, out_of_gas_at: OutOfGasAt | None, ) -> None: """ Test BAL recording with SSTORE at various OOG boundaries and success. 1. OOG at EIP-2200 stipend check & implicit SLOAD -> no BAL changes 2. OOG post EIP-2200 stipend check & implicit SLOAD -> storage read in BAL 3. OOG at exact gas minus 1 -> storage read in BAL 4. exact gas (success) -> storage write in BAL """ alice = pre.fund_eoa() gas_costs = fork.gas_costs() # Create contract that attempts SSTORE to cold storage slot 0x01 storage_contract_code = Bytecode(Op.SSTORE(0x01, 0x42)) storage_contract = pre.deploy_contract(code=storage_contract_code) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() # Costs: # - PUSH1 (value and slot) = G_VERY_LOW * 2 # - SSTORE cold (to zero slot) = G_STORAGE_SET + G_COLD_SLOAD sload_cost = gas_costs.G_COLD_SLOAD sstore_cost = gas_costs.G_STORAGE_SET sstore_cold_cost = sstore_cost + sload_cost push_cost = gas_costs.G_VERY_LOW * 2 stipend = gas_costs.G_CALL_STIPEND if out_of_gas_at == OutOfGasAt.EIP_2200_STIPEND: # 2300 after PUSHes (fails stipend check: 2300 <= 2300) tx_gas_limit = intrinsic_gas_cost + push_cost + stipend elif out_of_gas_at == OutOfGasAt.EIP_2200_STIPEND_PLUS_1: # 2301 after PUSHes (passes stipend, does SLOAD, fails charge_gas) tx_gas_limit = intrinsic_gas_cost + push_cost + stipend + 1 elif out_of_gas_at == OutOfGasAt.EXACT_GAS_MINUS_1: # fail at charge_gas() at exact gas - 1 (boundary condition) tx_gas_limit = intrinsic_gas_cost + push_cost + sstore_cold_cost - 1 else: # exact gas for successful SSTORE tx_gas_limit = intrinsic_gas_cost + push_cost + sstore_cold_cost tx = Transaction( sender=alice, to=storage_contract, gas_limit=tx_gas_limit, ) # Storage read recorded only if we pass the stipend check and reach # implicit SLOAD (STIPEND_PLUS_1 and EXACT_GAS_MINUS_1) expect_storage_read = out_of_gas_at in ( OutOfGasAt.EIP_2200_STIPEND_PLUS_1, OutOfGasAt.EXACT_GAS_MINUS_1, ) expect_storage_write = out_of_gas_at is None block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ storage_contract: BalAccountExpectation( storage_changes=[ BalStorageSlot( slot=0x01, slot_changes=[BalStorageChange(tx_index=1, post_value=0x42)], ), ] if expect_storage_write else [], storage_reads=[0x01] if expect_storage_read else [], ) } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), storage_contract: Account(storage={0x01: 0x42} if expect_storage_write else {}), }, ) @pytest.mark.parametrize( "fails_at_sload", [True, False], ids=["oog_at_sload", "successful_sload"], ) def test_bal_sload_and_oog( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, fails_at_sload: bool, ) -> None: """ Ensure BAL handles SLOAD and OOG during SLOAD appropriately. """ alice = pre.fund_eoa() gas_costs = fork.gas_costs() # Create contract that attempts SLOAD from cold storage slot 0x01 storage_contract_code = Bytecode( Op.PUSH1(0x01) # Storage slot (cold) + Op.SLOAD # Load value from slot - this will OOG + Op.STOP ) storage_contract = pre.deploy_contract(code=storage_contract_code) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() # Costs: # - PUSH1 (slot) = G_VERY_LOW # - SLOAD cold = G_COLD_SLOAD push_cost = gas_costs.G_VERY_LOW sload_cold_cost = gas_costs.G_COLD_SLOAD tx_gas_limit = intrinsic_gas_cost + push_cost + sload_cold_cost if fails_at_sload: # subtract 1 gas to ensure OOG at SLOAD tx_gas_limit -= 1 tx = Transaction( sender=alice, to=storage_contract, gas_limit=tx_gas_limit, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ storage_contract: BalAccountExpectation( storage_reads=[] if fails_at_sload else [0x01], ) } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), storage_contract: Account(storage={}), }, ) @pytest.mark.parametrize( "fails_at_balance", [True, False], ids=["oog_at_balance", "successful_balance"] ) def test_bal_balance_and_oog( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, fails_at_balance: bool, ) -> None: """Ensure BAL handles BALANCE and OOG during BALANCE appropriately.""" alice = pre.fund_eoa() bob = pre.fund_eoa() gas_costs = fork.gas_costs() # Create contract that attempts to check Bob's balance balance_checker_code = Bytecode( Op.PUSH20(bob) # Bob's address + Op.BALANCE # Check balance (cold access) + Op.STOP ) balance_checker = pre.deploy_contract(code=balance_checker_code) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() # Costs: # - PUSH20 = G_VERY_LOW # - BALANCE cold = G_COLD_ACCOUNT_ACCESS push_cost = gas_costs.G_VERY_LOW balance_cold_cost = gas_costs.G_COLD_ACCOUNT_ACCESS tx_gas_limit = intrinsic_gas_cost + push_cost + balance_cold_cost if fails_at_balance: # subtract 1 gas to ensure OOG at BALANCE tx_gas_limit -= 1 tx = Transaction( sender=alice, to=balance_checker, gas_limit=tx_gas_limit, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ balance_checker: BalAccountExpectation.empty(), # Bob should only appear in BAL if BALANCE succeeded **({bob: None} if fails_at_balance else {bob: BalAccountExpectation.empty()}), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), bob: Account(), balance_checker: Account(), }, ) @pytest.mark.parametrize( "fails_at_extcodesize", [True, False], ids=["oog_at_extcodesize", "successful_extcodesize"] ) def test_bal_extcodesize_and_oog( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, fails_at_extcodesize: bool, ) -> None: """ Ensure BAL handles EXTCODESIZE and OOG during EXTCODESIZE appropriately. """ alice = pre.fund_eoa() gas_costs = fork.gas_costs() # Create target contract with some code target_contract = pre.deploy_contract(code=Bytecode(Op.STOP)) # Create contract that checks target's code size codesize_checker_code = Bytecode( Op.PUSH20(target_contract) # Target contract address + Op.EXTCODESIZE # Check code size (cold access) + Op.STOP ) codesize_checker = pre.deploy_contract(code=codesize_checker_code) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() # Costs: # - PUSH20 = G_VERY_LOW # - EXTCODESIZE cold = G_COLD_ACCOUNT_ACCESS push_cost = gas_costs.G_VERY_LOW extcodesize_cold_cost = gas_costs.G_COLD_ACCOUNT_ACCESS tx_gas_limit = intrinsic_gas_cost + push_cost + extcodesize_cold_cost if fails_at_extcodesize: # subtract 1 gas to ensure OOG at EXTCODESIZE tx_gas_limit -= 1 tx = Transaction( sender=alice, to=codesize_checker, gas_limit=tx_gas_limit, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ codesize_checker: BalAccountExpectation.empty(), # Target should only appear if EXTCODESIZE succeeded **( {target_contract: None} if fails_at_extcodesize else {target_contract: BalAccountExpectation.empty()} ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), codesize_checker: Account(), target_contract: Account(), }, ) @pytest.mark.parametrize("fails_at_call", [True, False], ids=["oog_at_call", "successful_call"]) def test_bal_call_and_oog( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, fails_at_call: bool, ) -> None: """Ensure BAL handles CALL and OOG during CALL appropriately.""" alice = pre.fund_eoa() bob = pre.fund_eoa() gas_costs = fork.gas_costs() # Create contract that attempts to call Bob call_contract_code = Bytecode( Op.PUSH1(0) # retSize + Op.PUSH1(0) # retOffset + Op.PUSH1(0) # argsSize + Op.PUSH1(0) # argsOffset + Op.PUSH1(0) # value + Op.PUSH20(bob) # address + Op.PUSH2(0xFFFF) # gas (provide enough for the call) + Op.CALL # Call (cold account access) + Op.STOP ) call_contract = pre.deploy_contract(code=call_contract_code) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() # Costs: # - 7 PUSH operations = G_VERY_LOW * 7 # - CALL cold = G_COLD_ACCOUNT_ACCESS (minimum for account access) push_cost = gas_costs.G_VERY_LOW * 7 call_cold_cost = gas_costs.G_COLD_ACCOUNT_ACCESS tx_gas_limit = intrinsic_gas_cost + push_cost + call_cold_cost if fails_at_call: # subtract 1 gas to ensure OOG at CALL tx_gas_limit -= 1 tx = Transaction( sender=alice, to=call_contract, gas_limit=tx_gas_limit, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ call_contract: BalAccountExpectation.empty(), # Bob should only appear if CALL succeeded **({bob: None} if fails_at_call else {bob: BalAccountExpectation.empty()}), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), call_contract: Account(), }, ) @pytest.mark.parametrize( "fails_at_delegatecall", [True, False], ids=["oog_at_delegatecall", "successful_delegatecall"] ) def test_bal_delegatecall_and_oog( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, fails_at_delegatecall: bool, ) -> None: """ Ensure BAL handles DELEGATECALL and OOG during DELEGATECALL appropriately. """ alice = pre.fund_eoa() gas_costs = fork.gas_costs() # Create target contract target_contract = pre.deploy_contract(code=Bytecode(Op.STOP)) # Create contract that attempts delegatecall to target delegatecall_contract_code = Bytecode( Op.PUSH1(0) # retSize + Op.PUSH1(0) # retOffset + Op.PUSH1(0) # argsSize + Op.PUSH1(0) # argsOffset + Op.PUSH20(target_contract) # address + Op.PUSH2(0xFFFF) # gas (provide enough for the call) + Op.DELEGATECALL # Delegatecall (cold account access) + Op.STOP ) delegatecall_contract = pre.deploy_contract(code=delegatecall_contract_code) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() # Costs: # - 6 PUSH operations = G_VERY_LOW * 6 # - DELEGATECALL cold = G_COLD_ACCOUNT_ACCESS push_cost = gas_costs.G_VERY_LOW * 6 delegatecall_cold_cost = gas_costs.G_COLD_ACCOUNT_ACCESS tx_gas_limit = intrinsic_gas_cost + push_cost + delegatecall_cold_cost if fails_at_delegatecall: # subtract 1 gas to ensure OOG at DELEGATECALL tx_gas_limit -= 1 tx = Transaction( sender=alice, to=delegatecall_contract, gas_limit=tx_gas_limit, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ delegatecall_contract: BalAccountExpectation.empty(), # Target should only appear if DELEGATECALL succeeded **( {target_contract: None} if fails_at_delegatecall else {target_contract: BalAccountExpectation.empty()} ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), delegatecall_contract: Account(), target_contract: Account(), }, ) @pytest.mark.parametrize( "fails_at_extcodecopy", [True, False], ids=["oog_at_extcodecopy", "successful_extcodecopy"] ) def test_bal_extcodecopy_and_oog( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, fails_at_extcodecopy: bool, ) -> None: """ Ensure BAL handles EXTCODECOPY and OOG during EXTCODECOPY appropriately. """ alice = pre.fund_eoa() gas_costs = fork.gas_costs() # Create target contract with some code target_contract = pre.deploy_contract(code=Bytecode(Op.PUSH1(0x42) + Op.STOP)) # Create contract that attempts to copy code from target extcodecopy_contract_code = Bytecode( Op.PUSH1(0) # size - copy 0 bytes to minimize memory expansion cost + Op.PUSH1(0) # codeOffset + Op.PUSH1(0) # destOffset + Op.PUSH20(target_contract) # address + Op.EXTCODECOPY # Copy code (cold access + base cost) + Op.STOP ) extcodecopy_contract = pre.deploy_contract(code=extcodecopy_contract_code) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() # Costs: # - 4 PUSH operations = G_VERY_LOW * 4 # - EXTCODECOPY cold = G_COLD_ACCOUNT_ACCESS + (G_COPY * words) # where words = ceil32(size) // 32 = ceil32(0) // 32 = 0 push_cost = gas_costs.G_VERY_LOW * 4 extcodecopy_cold_cost = gas_costs.G_COLD_ACCOUNT_ACCESS # + (G_COPY * 0) = 0 tx_gas_limit = intrinsic_gas_cost + push_cost + extcodecopy_cold_cost if fails_at_extcodecopy: # subtract 1 gas to ensure OOG at EXTCODECOPY tx_gas_limit -= 1 tx = Transaction( sender=alice, to=extcodecopy_contract, gas_limit=tx_gas_limit, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ extcodecopy_contract: BalAccountExpectation.empty(), # Target should only appear if EXTCODECOPY succeeded **( {target_contract: None} if fails_at_extcodecopy else {target_contract: BalAccountExpectation.empty()} ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), extcodecopy_contract: Account(), target_contract: Account(), }, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/amsterdam/eip7928_block_level_access_lists/__init__.py
tests/amsterdam/eip7928_block_level_access_lists/__init__.py
"""Tests for [EIP-7928: Block-level Access Lists](https://eips.ethereum.org/EIPS/eip-7928)."""
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists.py
tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists.py
"""Tests for EIP-7928 using the consistent data class pattern.""" from typing import Callable, Dict import pytest from ethereum_test_base_types import AccessList, Address, Hash from ethereum_test_forks import Fork from ethereum_test_specs.blockchain import Header from ethereum_test_tools import ( Account, Alloc, Block, BlockchainTestFiller, Initcode, Transaction, compute_create_address, ) from ethereum_test_types import Environment from ethereum_test_types.block_access_list import ( BalAccountExpectation, BalBalanceChange, BalCodeChange, BalNonceChange, BalStorageChange, BalStorageSlot, BlockAccessListExpectation, ) from ethereum_test_vm import Opcodes as Op from .spec import ref_spec_7928 REFERENCE_SPEC_GIT_PATH = ref_spec_7928.git_path REFERENCE_SPEC_VERSION = ref_spec_7928.version pytestmark = pytest.mark.valid_from("Amsterdam") def test_bal_nonce_changes( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """Ensure BAL captures changes to nonce.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) tx = Transaction( sender=alice, to=bob, value=100, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), bob: Account(balance=100), }, ) def test_bal_balance_changes( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, ) -> None: """Ensure BAL captures changes to balance.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator( calldata=b"", contract_creation=False, access_list=[], ) tx_gas_limit = intrinsic_gas_cost + 1000 # add a small buffer tx = Transaction( sender=alice, to=bob, value=100, gas_limit=tx_gas_limit, gas_price=1_000_000_000, ) alice_account = pre[alice] assert alice_account is not None, "Alice account should exist" alice_initial_balance = alice_account.balance # Account for both the value sent and gas cost (gas_price * gas_used) alice_final_balance = alice_initial_balance - 100 - (intrinsic_gas_cost * 1_000_000_000) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], balance_changes=[ BalBalanceChange(tx_index=1, post_balance=alice_final_balance) ], ), bob: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=100)], ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1, balance=alice_final_balance), bob: Account(balance=100), }, ) def test_bal_code_changes( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """Ensure BAL captures changes to account code.""" runtime_code = Op.STOP runtime_code_bytes = bytes(runtime_code) init_code = ( Op.PUSH1(len(runtime_code_bytes)) # size = 1 + Op.DUP1 # duplicate size for return + Op.PUSH1(0x0C) # offset in init code where runtime code starts + Op.PUSH1(0x00) # dest offset + Op.CODECOPY # copy runtime code to memory + Op.PUSH1(0x00) # memory offset for return + Op.RETURN # return runtime code + runtime_code # the actual runtime code to deploy ) init_code_bytes = bytes(init_code) # Factory contract that uses CREATE to deploy factory_code = ( # Push init code to memory Op.PUSH32(init_code_bytes) + Op.PUSH1(0x00) + Op.MSTORE # Store at memory position 0 # CREATE parameters: value, offset, size + Op.PUSH1(len(init_code_bytes)) # size of init code + Op.PUSH1(32 - len(init_code_bytes)) # offset in memory (account for padding) + Op.PUSH1(0x00) # value = 0 (no ETH sent) + Op.CREATE # Deploy the contract + Op.STOP ) factory_contract = pre.deploy_contract(code=factory_code) alice = pre.fund_eoa() tx = Transaction( sender=alice, to=factory_contract, gas_limit=500000, ) created_contract = compute_create_address(address=factory_contract, nonce=1) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), factory_contract: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=2)], ), created_contract: BalAccountExpectation( code_changes=[BalCodeChange(tx_index=1, new_code=runtime_code_bytes)], ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), factory_contract: Account(nonce=2), # incremented by CREATE to 2 created_contract: Account( code=runtime_code_bytes, storage={}, ), }, ) @pytest.mark.parametrize("self_destruct_in_same_tx", [True, False], ids=["same_tx", "new_tx"]) @pytest.mark.parametrize("pre_funded", [True, False], ids=["pre_funded", "not_pre_funded"]) def test_bal_self_destruct( pre: Alloc, blockchain_test: BlockchainTestFiller, self_destruct_in_same_tx: bool, pre_funded: bool, ) -> None: """Ensure BAL captures balance changes caused by `SELFDESTRUCT`.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) selfdestruct_code = ( Op.SLOAD(0x01) # Read from storage slot 0x01 + Op.SSTORE(0x02, 0x42) # Write to storage slot 0x02 + Op.SELFDESTRUCT(bob) ) # A pre existing self-destruct contract with initial storage kaboom = pre.deploy_contract(code=selfdestruct_code, storage={0x01: 0x123}) # A template for self-destruct contract self_destruct_init_code = Initcode(deploy_code=selfdestruct_code) template = pre.deploy_contract(code=self_destruct_init_code) transfer_amount = expected_recipient_balance = 100 pre_fund_amount = 10 if self_destruct_in_same_tx: # The goal is to create a self-destructing contract in the same # transaction to trigger deletion of code as per EIP-6780. # The factory contract below creates a new self-destructing # contract and calls it in this transaction. bytecode_size = len(self_destruct_init_code) factory_bytecode = ( # Clone template memory Op.EXTCODECOPY(template, 0, 0, bytecode_size) # Fund 100 wei and deploy the clone + Op.CREATE(transfer_amount, 0, bytecode_size) # Call the clone, which self-destructs + Op.CALL(100_000, Op.DUP6, 0, 0, 0, 0, 0) + Op.STOP ) factory = pre.deploy_contract(code=factory_bytecode) kaboom_same_tx = compute_create_address(address=factory, nonce=1) # Determine which account will be self-destructed self_destructed_account = kaboom_same_tx if self_destruct_in_same_tx else kaboom if pre_funded: expected_recipient_balance += pre_fund_amount pre.fund_address(address=self_destructed_account, amount=pre_fund_amount) tx = Transaction( sender=alice, to=factory if self_destruct_in_same_tx else kaboom, value=transfer_amount, gas_limit=1_000_000, gas_price=0xA, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), bob: BalAccountExpectation( balance_changes=[ BalBalanceChange(tx_index=1, post_balance=expected_recipient_balance) ] ), self_destructed_account: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=0)] if pre_funded else [], # Accessed slots for same-tx are recorded as reads (0x02) storage_reads=[0x01, 0x02] if self_destruct_in_same_tx else [0x01], # Storage changes are recorded for non-same-tx # self-destructs storage_changes=[ BalStorageSlot( slot=0x02, slot_changes=[BalStorageChange(tx_index=1, post_value=0x42)] ) ] if not self_destruct_in_same_tx else [], code_changes=[], # should not be present nonce_changes=[], # should not be present ), } ), ) post: Dict[Address, Account] = { alice: Account(nonce=1), bob: Account(balance=expected_recipient_balance), } # If the account was self-destructed in the same transaction, # we expect the account to non-existent and its balance to be 0. if self_destruct_in_same_tx: post.update( { factory: Account( nonce=2, # incremented after CREATE balance=0, # spent on CREATE code=factory_bytecode, ), kaboom_same_tx: Account.NONEXISTENT, # type: ignore # The pre-existing contract remains unaffected kaboom: Account(balance=0, code=selfdestruct_code, storage={0x01: 0x123}), } ) else: post.update( { # This contract was self-destructed in a separate tx. # From EIP 6780: `SELFDESTRUCT` does not delete any data # (including storage keys, code, or the account itself). kaboom: Account( balance=0, code=selfdestruct_code, storage={0x01: 0x123, 0x2: 0x42} ), } ) blockchain_test( pre=pre, blocks=[block], post=post, ) @pytest.mark.parametrize( "account_access_opcode", [ pytest.param(lambda target_addr: Op.BALANCE(target_addr), id="balance"), pytest.param(lambda target_addr: Op.EXTCODESIZE(target_addr), id="extcodesize"), pytest.param(lambda target_addr: Op.EXTCODECOPY(target_addr, 0, 0, 32), id="extcodecopy"), pytest.param(lambda target_addr: Op.EXTCODEHASH(target_addr), id="extcodehash"), pytest.param(lambda target_addr: Op.CALL(0, target_addr, 0, 0, 0, 0, 0), id="call"), pytest.param( lambda target_addr: Op.CALLCODE(0, target_addr, 0, 0, 0, 0, 0), id="callcode" ), pytest.param( lambda target_addr: Op.DELEGATECALL(0, target_addr, 0, 0, 0, 0), id="delegatecall" ), pytest.param( lambda target_addr: Op.STATICCALL(0, target_addr, 0, 0, 0, 0), id="staticcall" ), ], ) def test_bal_account_access_target( pre: Alloc, blockchain_test: BlockchainTestFiller, account_access_opcode: Callable[[Address], Op], ) -> None: """Ensure BAL captures target address of account access opcodes.""" alice = pre.fund_eoa() target_contract = pre.deploy_contract(code=Op.STOP) oracle_contract = pre.deploy_contract( balance=100, code=account_access_opcode(target_contract), ) tx = Transaction(sender=alice, to=oracle_contract, gas_limit=5_000_000, gas_price=0xA) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)] ), target_contract: BalAccountExpectation.empty(), oracle_contract: BalAccountExpectation.empty(), } ), ) blockchain_test(pre=pre, blocks=[block], post={}) def test_bal_call_with_value_transfer( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """ Ensure BAL captures balance changes from CALL opcode with value transfer. """ alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) # Oracle contract that uses CALL to transfer 100 wei to Bob oracle_code = Op.CALL(0, bob, 100, 0, 0, 0, 0) oracle_contract = pre.deploy_contract(code=oracle_code, balance=200) tx = Transaction(sender=alice, to=oracle_contract, gas_limit=1_000_000, gas_price=0xA) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), oracle_contract: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=100)], ), bob: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=100)], ), } ), ) blockchain_test(pre=pre, blocks=[block], post={}) def test_bal_callcode_with_value_transfer( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """ Ensure BAL captures balance changes from CALLCODE opcode with value transfer. """ alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) # TargetContract sends 100 wei to bob target_code = Op.CALL(0, bob, 100, 0, 0, 0, 0) target_contract = pre.deploy_contract(code=target_code) # Oracle contract that uses CALLCODE to execute TargetContract's code oracle_code = Op.CALLCODE(50_000, target_contract, 100, 0, 0, 0, 0) oracle_contract = pre.deploy_contract(code=oracle_code, balance=200) tx = Transaction(sender=alice, to=oracle_contract, gas_limit=1_000_000, gas_price=0xA) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), oracle_contract: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=100)], ), bob: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=100)], ), target_contract: BalAccountExpectation.empty(), } ), ) blockchain_test(pre=pre, blocks=[block], post={}) @pytest.mark.parametrize( "delegated_opcode", [ pytest.param( lambda target_addr: Op.DELEGATECALL(50000, target_addr, 0, 0, 0, 0), id="delegatecall" ), pytest.param( lambda target_addr: Op.CALLCODE(50000, target_addr, 0, 0, 0, 0, 0), id="callcode" ), ], ) def test_bal_delegated_storage_writes( pre: Alloc, blockchain_test: BlockchainTestFiller, delegated_opcode: Callable[[Address], Op], ) -> None: """ Ensure BAL captures delegated storage writes via DELEGATECALL and CALLCODE. """ alice = pre.fund_eoa() # TargetContract that writes 0x42 to slot 0x01 target_code = Op.SSTORE(0x01, 0x42) target_contract = pre.deploy_contract(code=target_code) # Oracle contract that uses delegated opcode to execute # TargetContract's code oracle_code = delegated_opcode(target_contract) oracle_contract = pre.deploy_contract(code=oracle_code) tx = Transaction( sender=alice, to=oracle_contract, gas_limit=1_000_000, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), oracle_contract: BalAccountExpectation( storage_changes=[ BalStorageSlot( slot=0x01, slot_changes=[BalStorageChange(tx_index=1, post_value=0x42)], ) ], ), target_contract: BalAccountExpectation.empty(), } ), ) blockchain_test(pre=pre, blocks=[block], post={}) @pytest.mark.parametrize( "delegated_opcode", [ pytest.param( lambda target_addr: Op.DELEGATECALL(50000, target_addr, 0, 0, 0, 0), id="delegatecall" ), pytest.param( lambda target_addr: Op.CALLCODE(50000, target_addr, 0, 0, 0, 0, 0), id="callcode" ), ], ) def test_bal_delegated_storage_reads( pre: Alloc, blockchain_test: BlockchainTestFiller, delegated_opcode: Callable[[Address], Op], ) -> None: """ Ensure BAL captures delegated storage reads via DELEGATECALL and CALLCODE. """ alice = pre.fund_eoa() # TargetContract that reads from slot 0x01 target_code = Op.SLOAD(0x01) + Op.STOP target_contract = pre.deploy_contract(code=target_code) # Oracle contract with storage slot 0x01 = 0x42, # uses delegated opcode to execute TargetContract's code oracle_code = delegated_opcode(target_contract) oracle_contract = pre.deploy_contract(code=oracle_code, storage={0x01: 0x42}) tx = Transaction( sender=alice, to=oracle_contract, gas_limit=1_000_000, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), oracle_contract: BalAccountExpectation( storage_reads=[0x01], ), target_contract: BalAccountExpectation.empty(), } ), ) blockchain_test(pre=pre, blocks=[block], post={}) def test_bal_block_rewards( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, ) -> None: """Ensure BAL captures fee recipient balance changes from block rewards.""" alice_initial_balance = 1_000_000 alice = pre.fund_eoa(amount=alice_initial_balance) bob = pre.fund_eoa(amount=0) charlie = pre.fund_eoa(amount=0) # fee recipient intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas = intrinsic_gas_calculator( calldata=b"", contract_creation=False, access_list=[], ) tx_gas_limit = intrinsic_gas + 1000 # add a small buffer gas_price = 0xA tx = Transaction( sender=alice, to=bob, value=100, gas_limit=tx_gas_limit, gas_price=gas_price, ) # EIP-1559 fee calculation: # - Total gas cost total_gas_cost = intrinsic_gas * gas_price # - Tip portion genesis_env = Environment(base_fee_per_gas=0x7) base_fee_per_gas = fork.base_fee_per_gas_calculator()( parent_base_fee_per_gas=int(genesis_env.base_fee_per_gas or 0), parent_gas_used=0, parent_gas_limit=genesis_env.gas_limit, ) tip_to_charlie = (gas_price - base_fee_per_gas) * intrinsic_gas alice_final_balance = alice_initial_balance - 100 - total_gas_cost block = Block( txs=[tx], fee_recipient=charlie, # Set Charlie as the fee recipient header_verify=Header(base_fee_per_gas=base_fee_per_gas), expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], balance_changes=[ BalBalanceChange(tx_index=1, post_balance=alice_final_balance) ], ), bob: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=100)], ), charlie: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=tip_to_charlie)], ), } ), ) blockchain_test( pre=pre, blocks=[block], post={}, genesis_environment=genesis_env, ) def test_bal_2930_account_listed_but_untouched( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """Ensure BAL excludes untouched access list accounts.""" alice = pre.fund_eoa() bob = pre.fund_eoa() oracle = pre.deploy_contract(code=Op.STOP) access_list = AccessList( address=oracle, storage_keys=[Hash(0x1)], ) gas_limit = 1_000_000 tx = Transaction(ty=1, sender=alice, to=bob, gas_limit=gas_limit, access_list=[access_list]) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), # The address excluded from BAL since state is not accessed oracle: None, } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), }, ) def test_bal_2930_slot_listed_but_untouched( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, ) -> None: """Ensure BAL excludes untouched access list storage slots.""" alice = pre.fund_eoa() pure_calculator = pre.deploy_contract( # Pure add operation Op.ADD(35, 7) ) access_list = AccessList( address=pure_calculator, storage_keys=[Hash(0x1)], ) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() gas_limit = ( intrinsic_gas_calculator( calldata=b"", contract_creation=False, access_list=[access_list], ) + 1000 ) # intrinsic + buffer tx = Transaction( ty=1, sender=alice, to=pure_calculator, gas_limit=gas_limit, access_list=[access_list] ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), # The account was loaded. pure_calculator: BalAccountExpectation.empty(), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), }, ) def test_bal_2930_slot_listed_and_unlisted_writes( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, ) -> None: """ Ensure BAL includes storage writes regardless of access list presence. """ alice = pre.fund_eoa() storage_writer = pre.deploy_contract(code=Op.SSTORE(0x01, 0x42) + Op.SSTORE(0x02, 0x43)) # Access list only includes slot 0x01, but contract writes to both # 0x01 and 0x02 access_list = AccessList( address=storage_writer, storage_keys=[Hash(0x01)], ) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() gas_limit = ( intrinsic_gas_calculator( calldata=b"", contract_creation=False, access_list=[access_list], ) + 50000 ) # intrinsic + buffer for storage writes tx = Transaction( ty=1, sender=alice, to=storage_writer, gas_limit=gas_limit, access_list=[access_list] ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), storage_writer: BalAccountExpectation( storage_changes=[ BalStorageSlot( slot=0x01, slot_changes=[BalStorageChange(tx_index=1, post_value=0x42)], ), BalStorageSlot( slot=0x02, slot_changes=[BalStorageChange(tx_index=1, post_value=0x43)], ), ], ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), storage_writer: Account(storage={0x01: 0x42, 0x02: 0x43}), }, ) def test_bal_2930_slot_listed_and_unlisted_reads( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, ) -> None: """Ensure BAL includes storage reads regardless of access list presence.""" alice = pre.fund_eoa() storage_reader = pre.deploy_contract( code=Op.SLOAD(0x01) + Op.SLOAD(0x02), storage={0x01: 0x42, 0x02: 0x43}, # Pre-populate storage with values ) # Access list only includes slot 0x01, but contract reads from both # 0x01 and 0x02 access_list = AccessList( address=storage_reader, storage_keys=[Hash(0x01)], ) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() gas_limit = ( intrinsic_gas_calculator( calldata=b"", contract_creation=False, access_list=[access_list], ) + 50000 ) # intrinsic + buffer for storage reads tx = Transaction( ty=1, sender=alice, to=storage_reader, gas_limit=gas_limit, access_list=[access_list] ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), storage_reader: BalAccountExpectation( storage_reads=[0x01, 0x02], ), } ), ) blockchain_test( pre=pre, blocks=[block], post={ alice: Account(nonce=1), storage_reader: Account(storage={0x01: 0x42, 0x02: 0x43}), }, ) def test_bal_self_transfer( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, ) -> None: """Test that BAL correctly handles self-transfers.""" start_balance = 1_000_000 alice = pre.fund_eoa(amount=start_balance) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() tx = Transaction( sender=alice, to=alice, gas_limit=intrinsic_gas_cost, value=100, gas_price=0xA ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], balance_changes=[ BalBalanceChange( tx_index=1, post_balance=start_balance - intrinsic_gas_cost * int(tx.gas_price or 0), ) ], ) } ), ) blockchain_test(pre=pre, blocks=[block], post={}) def test_bal_zero_value_transfer( pre: Alloc, blockchain_test: BlockchainTestFiller, fork: Fork, ) -> None: """Test that BAL correctly handles zero-value transfers.""" start_balance = 1_000_000 alice = pre.fund_eoa(amount=start_balance) bob = pre.fund_eoa(amount=100) intrinsic_gas_calculator = fork.transaction_intrinsic_cost_calculator() intrinsic_gas_cost = intrinsic_gas_calculator() tx = Transaction(sender=alice, to=bob, gas_limit=intrinsic_gas_cost, value=0, gas_price=0xA) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], balance_changes=[ BalBalanceChange( tx_index=1, post_balance=start_balance - intrinsic_gas_cost * int(tx.gas_price or 0), ) ], ), # Include the address; omit from balance_changes. bob: BalAccountExpectation(balance_changes=[]), } ), ) blockchain_test(pre=pre, blocks=[block], post={}) @pytest.mark.parametrize( "initial_balance,transfer_amount,transfer_mechanism", [ pytest.param(0, 0, "call", id="zero_balance_zero_transfer_call"), pytest.param(0, 0, "selfdestruct", id="zero_balance_zero_transfer_selfdestruct"), pytest.param(1, 1, "call", id="nonzero_balance_net_zero"), pytest.param(100, 50, "call", id="larger_balance_net_zero"), ], ) def test_bal_net_zero_balance_transfer( pre: Alloc, blockchain_test: BlockchainTestFiller, initial_balance: int, transfer_amount: int, transfer_mechanism: str, ) -> None: """ Test that BAL does not record balance changes when net change is zero. A contract starts with `initial_balance`, receives `transfer_amount` (increasing its balance), then sends `transfer_amount` to a recipient (decreasing its balance back to `initial_balance`). The net change is zero, so BAL should not record any balance changes for this contract. The contract verifies this by reading its own balance with SELFBALANCE, storing it in slot 0, then sending that amount to the recipient. """ alice = pre.fund_eoa() recipient = pre.fund_eoa(amount=0) net_zero_bal_contract_code = ( Op.SSTORE(0, Op.SELFBALANCE) + Op.SELFDESTRUCT(recipient) if transfer_mechanism == "selfdestruct" # store current balance in slot 0 else ( Op.SSTORE(0, Op.SELFBALANCE) # send only the `transfer_amount` received to recipient (net zero) + Op.CALL(0, recipient, Op.CALLVALUE, 0, 0, 0, 0) + Op.STOP ) ) net_zero_bal_contract = pre.deploy_contract( code=net_zero_bal_contract_code, balance=initial_balance ) tx = Transaction( sender=alice, to=net_zero_bal_contract, value=transfer_amount, gas_limit=1_000_000, gas_price=0xA, ) expected_balance_in_slot = initial_balance + transfer_amount block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), net_zero_bal_contract: BalAccountExpectation( # receives transfer_amount and sends transfer_amount away # (net-zero change) balance_changes=[], storage_reads=[0x00] if expected_balance_in_slot == 0 else [],
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
true
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists_invalid.py
tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists_invalid.py
""" Test cases for invalid Block Access Lists. These tests verify that clients properly reject blocks with corrupted BALs. """ import pytest from ethereum_test_exceptions import BlockException from ethereum_test_tools import ( Account, Alloc, Block, BlockchainTestFiller, Storage, Transaction, ) from ethereum_test_tools import ( Opcodes as Op, ) from ethereum_test_types.block_access_list import ( BalAccountChange, BalAccountExpectation, BalBalanceChange, BalNonceChange, BalStorageChange, BalStorageSlot, BlockAccessListExpectation, ) from ethereum_test_types.block_access_list.modifiers import ( append_account, duplicate_account, modify_balance, modify_nonce, modify_storage, remove_accounts, remove_balances, remove_nonces, reverse_accounts, swap_tx_indices, ) from .spec import ref_spec_7928 REFERENCE_SPEC_GIT_PATH = ref_spec_7928.git_path REFERENCE_SPEC_VERSION = ref_spec_7928.version @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_missing_nonce( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL is missing required nonce changes. """ sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) tx = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), receiver: None, }, blocks=[ Block( txs=[tx], exception=BlockException.INVALID_BLOCK_ACCESS_LIST, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), } ).modify(remove_nonces(sender)), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_nonce_value( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL contains incorrect nonce value. """ sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) tx = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), # Unchanged receiver: None, }, blocks=[ Block( txs=[tx], exception=BlockException.INVALID_BLOCK_ACCESS_LIST, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), } ).modify(modify_nonce(sender, tx_index=1, nonce=42)), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_storage_value( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL contains incorrect storage values. """ sender = pre.fund_eoa(amount=10**18) # Simple storage contract with canary values storage = Storage({1: 0, 2: 0, 3: 0}) # type: ignore contract = pre.deploy_contract( code=Op.SSTORE(1, 1) + Op.SSTORE(2, 2) + Op.SSTORE(3, 3), storage=storage.canary(), ) tx = Transaction( sender=sender, to=contract, gas_limit=100_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), contract: Account(storage=storage.canary()), }, blocks=[ Block( txs=[tx], exception=BlockException.INVALID_BLOCK_ACCESS_LIST, expected_block_access_list=BlockAccessListExpectation( account_expectations={ contract: BalAccountExpectation( storage_changes=[ BalStorageSlot( slot=0x01, slot_changes=[BalStorageChange(tx_index=1, post_value=0x01)], ), BalStorageSlot( slot=0x02, slot_changes=[BalStorageChange(tx_index=1, post_value=0x02)], ), BalStorageSlot( slot=0x03, slot_changes=[BalStorageChange(tx_index=1, post_value=0x03)], ), ], ), } ).modify( # Corrupt storage value for slot 0x02 modify_storage(contract, tx_index=1, slot=0x02, value=0xFF) ), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_tx_order( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL has incorrect transaction ordering. """ sender1 = pre.fund_eoa(amount=10**18) sender2 = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) tx1 = Transaction( sender=sender1, to=receiver, value=10**15, gas_limit=21_000, ) tx2 = Transaction( sender=sender2, to=receiver, value=2 * 10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender1: Account(balance=10**18, nonce=0), sender2: Account(balance=10**18, nonce=0), receiver: None, }, blocks=[ Block( txs=[tx1, tx2], exception=BlockException.INVALID_BLOCK_ACCESS_LIST, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender1: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), sender2: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=2, post_nonce=1)], ), receiver: BalAccountExpectation( balance_changes=[ BalBalanceChange(tx_index=1, post_balance=10**15), BalBalanceChange(tx_index=2, post_balance=3 * 10**15), ], ), } ).modify(swap_tx_indices(1, 2)), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_account( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL contains accounts that don't exist. """ sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) phantom = pre.fund_eoa(amount=0) tx = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), receiver: None, phantom: None, }, blocks=[ Block( txs=[tx], exception=BlockException.INVALID_BAL_EXTRA_ACCOUNT, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), } ).modify( append_account( BalAccountChange( address=phantom, nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ) ) ), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_duplicate_account( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL contains duplicate account entries. """ sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) tx = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), receiver: None, }, blocks=[ Block( txs=[tx], exception=BlockException.INCORRECT_BLOCK_FORMAT, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), receiver: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10**15)], ), } ).modify(duplicate_account(sender)), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_account_order( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL has incorrect account ordering. """ sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) tx = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), receiver: None, }, blocks=[ Block( txs=[tx], exception=BlockException.INCORRECT_BLOCK_FORMAT, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), receiver: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10**15)], ), } ).modify(reverse_accounts()), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_complex_corruption( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """Test complex BAL corruption with multiple transformations.""" sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) storage = Storage({1: 0, 2: 0}) # type: ignore contract = pre.deploy_contract( code=Op.SSTORE(1, 1) + Op.SSTORE(2, 2), storage=storage.canary(), ) tx1 = Transaction( sender=sender, to=contract, gas_limit=100_000, ) tx2 = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), contract: Account(storage=storage.canary()), receiver: None, }, blocks=[ Block( txs=[tx1, tx2], exception=BlockException.INVALID_BLOCK_ACCESS_LIST, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender: BalAccountExpectation( nonce_changes=[ BalNonceChange(tx_index=1, post_nonce=1), BalNonceChange(tx_index=2, post_nonce=2), ], ), contract: BalAccountExpectation( storage_changes=[ BalStorageSlot( slot=0x01, slot_changes=[BalStorageChange(tx_index=1, post_value=0x01)], ), BalStorageSlot( slot=0x02, slot_changes=[BalStorageChange(tx_index=1, post_value=0x02)], ), ], ), receiver: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=2, post_balance=10**15)], ), } ).modify( remove_nonces(sender), modify_storage(contract, tx_index=1, slot=0x01, value=0xFF), remove_balances(receiver), swap_tx_indices(1, 2), ), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_missing_account( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL is missing an entire account. """ sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) tx = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), receiver: None, }, blocks=[ Block( txs=[tx], exception=BlockException.INVALID_BAL_MISSING_ACCOUNT, expected_block_access_list=BlockAccessListExpectation( account_expectations={ sender: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), receiver: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10**15)], ), } ).modify(remove_accounts(receiver)), ) ], ) @pytest.mark.valid_from("Amsterdam") @pytest.mark.exception_test def test_bal_invalid_balance_value( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test that clients reject blocks where BAL contains incorrect balance value. """ sender = pre.fund_eoa(amount=10**18) receiver = pre.fund_eoa(amount=0) tx = Transaction( sender=sender, to=receiver, value=10**15, gas_limit=21_000, ) blockchain_test( pre=pre, post={ sender: Account(balance=10**18, nonce=0), receiver: None, }, blocks=[ Block( txs=[tx], exception=BlockException.INVALID_BLOCK_ACCESS_LIST, expected_block_access_list=BlockAccessListExpectation( account_expectations={ receiver: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10**15)], ), } ).modify(modify_balance(receiver, tx_index=1, balance=999999)), ) ], )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists_eip7702.py
tests/amsterdam/eip7928_block_level_access_lists/test_block_access_lists_eip7702.py
"""Tests for the effects of EIP-7702 transactions on EIP-7928.""" import pytest from ethereum_test_tools import ( Account, Alloc, AuthorizationTuple, Block, BlockchainTestFiller, Transaction, ) from ethereum_test_types.block_access_list import ( BalAccountExpectation, BalBalanceChange, BalCodeChange, BalNonceChange, BalStorageChange, BalStorageSlot, BlockAccessListExpectation, ) from ethereum_test_vm import Opcodes as Op from ...prague.eip7702_set_code_tx.spec import Spec as Spec7702 from .spec import ref_spec_7928 REFERENCE_SPEC_GIT_PATH = ref_spec_7928.git_path REFERENCE_SPEC_VERSION = ref_spec_7928.version pytestmark = pytest.mark.valid_from("Amsterdam") @pytest.mark.parametrize( "self_funded", [ pytest.param(False, id="sponsored"), pytest.param(True, id="self_funded"), ], ) def test_bal_7702_delegation_create( pre: Alloc, blockchain_test: BlockchainTestFiller, self_funded: bool, ) -> None: """Ensure BAL captures creation of EOA delegation.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) if not self_funded: relayer = pre.fund_eoa() sender = relayer else: sender = alice oracle = pre.deploy_contract(code=Op.STOP) tx = Transaction( sender=sender, to=bob, value=10, gas_limit=1_000_000, gas_price=0xA, authorization_list=[ AuthorizationTuple( address=oracle, nonce=1 if self_funded else 0, signer=alice, ) ], ) account_expectations = { alice: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=2 if self_funded else 1)], code_changes=[ BalCodeChange(tx_index=1, new_code=Spec7702.delegation_designation(oracle)) ], ), bob: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10)] ), # Oracle must not be present in BAL - the account is never accessed oracle: None, } # For sponsored variant, relayer must also be included in BAL if not self_funded: account_expectations[relayer] = BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations=account_expectations ), ) post = { alice: Account( nonce=2 if self_funded else 1, code=Spec7702.delegation_designation(oracle) ), # Bob receives 10 wei bob: Account(balance=10), } # For sponsored variant, include relayer in post state if not self_funded: post.update({relayer: Account(nonce=1)}) blockchain_test( pre=pre, blocks=[block], post=post, ) @pytest.mark.parametrize( "self_funded", [ pytest.param(False, id="sponsored"), pytest.param(True, id="self_funded"), ], ) def test_bal_7702_delegation_update( pre: Alloc, blockchain_test: BlockchainTestFiller, self_funded: bool, ) -> None: """Ensure BAL captures update of existing EOA delegation.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) if not self_funded: relayer = pre.fund_eoa() sender = relayer else: sender = alice oracle1 = pre.deploy_contract(code=Op.STOP) oracle2 = pre.deploy_contract(code=Op.STOP) ## Perhaps create pre existing delegation, ## see `test_bal_7702_delegated_storage_access` since ## `test_bal_7702_delegation_create` already tests creation tx_create = Transaction( sender=sender, to=bob, value=10, gas_limit=1_000_000, gas_price=0xA, authorization_list=[ AuthorizationTuple( address=oracle1, nonce=1 if self_funded else 0, signer=alice, ) ], ) tx_update = Transaction( nonce=2 if self_funded else 1, sender=sender, to=bob, value=10, gas_limit=1_000_000, gas_price=0xA, authorization_list=[ AuthorizationTuple( address=oracle2, nonce=3 if self_funded else 1, signer=alice, ) ], ) account_expectations = { alice: BalAccountExpectation( nonce_changes=[ BalNonceChange(tx_index=1, post_nonce=2 if self_funded else 1), BalNonceChange(tx_index=2, post_nonce=4 if self_funded else 2), ], code_changes=[ BalCodeChange(tx_index=1, new_code=Spec7702.delegation_designation(oracle1)), BalCodeChange(tx_index=2, new_code=Spec7702.delegation_designation(oracle2)), ], ), bob: BalAccountExpectation( balance_changes=[ BalBalanceChange(tx_index=1, post_balance=10), BalBalanceChange(tx_index=2, post_balance=20), ] ), # Both delegation targets must not be present in BAL # the account is never accessed oracle1: None, oracle2: None, } # For sponsored variant, relayer must also be included in BAL if not self_funded: account_expectations[relayer] = BalAccountExpectation( nonce_changes=[ BalNonceChange(tx_index=1, post_nonce=1), BalNonceChange(tx_index=2, post_nonce=2), ], ) block = Block( txs=[tx_create, tx_update], expected_block_access_list=BlockAccessListExpectation( account_expectations=account_expectations ), ) post = { # Finally Alice's account should be delegated to oracle2 alice: Account( nonce=4 if self_funded else 2, code=Spec7702.delegation_designation(oracle2) ), # Bob receives 20 wei in total bob: Account(balance=20), } # For sponsored variant, include relayer in post state if not self_funded: post.update({relayer: Account(nonce=2)}) blockchain_test( pre=pre, blocks=[block], post=post, ) @pytest.mark.parametrize( "self_funded", [ pytest.param(False, id="sponsored"), pytest.param(True, id="self_funded"), ], ) def test_bal_7702_delegation_clear( pre: Alloc, blockchain_test: BlockchainTestFiller, self_funded: bool, ) -> None: """Ensure BAL captures clearing of EOA delegation.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) if not self_funded: relayer = pre.fund_eoa() sender = relayer else: sender = alice oracle = pre.deploy_contract(code=Op.STOP) abyss = Spec7702.RESET_DELEGATION_ADDRESS ## Perhaps create pre existing delegation, ## see `test_bal_7702_delegated_storage_access` since ## `test_bal_7702_delegation_create` already tests creation tx_create = Transaction( sender=sender, to=bob, value=10, gas_limit=1_000_000, gas_price=0xA, authorization_list=[ AuthorizationTuple( address=oracle, nonce=1 if self_funded else 0, signer=alice, ) ], ) tx_clear = Transaction( nonce=2 if self_funded else 1, sender=sender, to=bob, value=10, gas_limit=1_000_000, gas_price=0xA, authorization_list=[ AuthorizationTuple( address=abyss, nonce=3 if self_funded else 1, signer=alice, ) ], ) account_expectations = { alice: BalAccountExpectation( nonce_changes=[ BalNonceChange(tx_index=1, post_nonce=2 if self_funded else 1), BalNonceChange(tx_index=2, post_nonce=4 if self_funded else 2), ], code_changes=[ BalCodeChange(tx_index=1, new_code=Spec7702.delegation_designation(oracle)), BalCodeChange(tx_index=2, new_code=""), ], ), bob: BalAccountExpectation( balance_changes=[ BalBalanceChange(tx_index=1, post_balance=10), BalBalanceChange(tx_index=2, post_balance=20), ] ), # Both delegation targets must not be present in BAL # the account is never accessed oracle: None, abyss: None, } # For sponsored variant, relayer must also be included in BAL if not self_funded: account_expectations[relayer] = BalAccountExpectation( nonce_changes=[ BalNonceChange(tx_index=1, post_nonce=1), BalNonceChange(tx_index=2, post_nonce=2), ], ) block = Block( txs=[tx_create, tx_clear], expected_block_access_list=BlockAccessListExpectation( account_expectations=account_expectations ), ) post = { # Finally Alice's account should NOT have any code alice: Account(nonce=4 if self_funded else 2, code=""), # Bob receives 20 wei in total bob: Account(balance=20), } # For sponsored variant, include relayer in post state if not self_funded: post.update({relayer: Account(nonce=2)}) blockchain_test( pre=pre, blocks=[block], post=post, ) def test_bal_7702_delegated_storage_access( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """ Ensure BAL captures storage operations when calling a delegated EIP-7702 account. """ # Oracle contract that reads from slot 0x01 and writes to slot 0x02 oracle = pre.deploy_contract(code=Op.SLOAD(0x01) + Op.PUSH1(0x42) + Op.PUSH1(0x02) + Op.SSTORE) bob = pre.fund_eoa() alice = pre.deploy_contract(nonce=0x1, code=Spec7702.delegation_designation(oracle), balance=0) tx = Transaction( sender=bob, to=alice, # Bob calls Alice (delegated account) value=10, gas_limit=1_000_000, gas_price=0xA, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ alice: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10)], storage_changes=[ BalStorageSlot( slot=0x02, slot_changes=[BalStorageChange(tx_index=1, post_value=0x42)], ) ], storage_reads=[0x01], ), bob: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), # Oracle appears in BAL due to account access # (delegation target) oracle: BalAccountExpectation.empty(), } ), ) post = { alice: Account( balance=10, storage={0x02: 0x42}, ), bob: Account(nonce=1), } blockchain_test( pre=pre, blocks=[block], post=post, ) def test_bal_7702_invalid_nonce_authorization( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """Ensure BAL handles failed authorization due to wrong nonce.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) relayer = pre.fund_eoa() oracle = pre.deploy_contract(code=Op.STOP) tx = Transaction( sender=relayer, # Sponsored transaction to=bob, value=10, gas_limit=1_000_000, gas_price=0xA, authorization_list=[ AuthorizationTuple( address=oracle, nonce=5, # Wrong nonce - Alice's actual nonce is 0 signer=alice, ) ], ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ # Ensuring silent fail bob: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10)] ), relayer: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), # Alice's account was marked warm but no changes were made alice: BalAccountExpectation.empty(), # Oracle must NOT be present - authorization failed so # account is never accessed oracle: None, } ), ) post = { relayer: Account(nonce=1), bob: Account(balance=10), } blockchain_test( pre=pre, blocks=[block], post=post, ) def test_bal_7702_invalid_chain_id_authorization( pre: Alloc, blockchain_test: BlockchainTestFiller, ) -> None: """Ensure BAL handles failed authorization due to wrong chain id.""" alice = pre.fund_eoa() bob = pre.fund_eoa(amount=0) relayer = pre.fund_eoa() oracle = pre.deploy_contract(code=Op.STOP) tx = Transaction( sender=relayer, # Sponsored transaction to=bob, value=10, gas_limit=1_000_000, gas_price=0xA, authorization_list=[ AuthorizationTuple( chain_id=999, # Wrong chain id address=oracle, nonce=0, signer=alice, ) ], ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ # Alice's account must not be read because # authorization fails before loading her account alice: None, # Ensuring silent fail bob: BalAccountExpectation( balance_changes=[BalBalanceChange(tx_index=1, post_balance=10)] ), relayer: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), # Oracle must NOT be present - authorization failed so # account never accessed oracle: None, } ), ) post = { relayer: Account(nonce=1), bob: Account(balance=10), } blockchain_test( # Set chain id here # so this test holds if the default is # ever changed chain_id=1, pre=pre, blocks=[block], post=post, ) @pytest.mark.with_all_call_opcodes def test_bal_7702_delegated_via_call_opcode( pre: Alloc, blockchain_test: BlockchainTestFiller, call_opcode: Op, ) -> None: """ Ensure BAL captures delegation target when a contract uses *CALL opcodes to call a delegated account. """ # `oracle` contract that just returns successfully oracle = pre.deploy_contract(code=Op.STOP) # `alice` is a delegated account pointing to oracle alice = pre.deploy_contract( nonce=1, code=Spec7702.delegation_designation(oracle), balance=0, ) # caller contract that uses `call_opcode` to call `alice` caller = pre.deploy_contract(code=(call_opcode(address=alice) + Op.STOP)) bob = pre.fund_eoa() tx = Transaction( sender=bob, to=caller, # `bob` calls caller contract gas_limit=10_000_000, gas_price=0xA, ) block = Block( txs=[tx], expected_block_access_list=BlockAccessListExpectation( account_expectations={ bob: BalAccountExpectation( nonce_changes=[BalNonceChange(tx_index=1, post_nonce=1)], ), caller: BalAccountExpectation.empty(), # `alice` is accessed due to being the call target alice: BalAccountExpectation.empty(), # `oracle` appears in BAL due to delegation target access oracle: BalAccountExpectation.empty(), } ), ) post = {bob: Account(nonce=1)} blockchain_test( pre=pre, blocks=[block], post=post, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/__init__.py
tests/istanbul/__init__.py
"""Test cases for EVM functionality introduced in Istanbul."""
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip152_blake2/test_blake2.py
tests/istanbul/eip152_blake2/test_blake2.py
""" Tests [EIP-152: BLAKE2b compression precompile](https://eips.ethereum.org/EIPS/eip-152). """ from typing import List import pytest from ethereum_test_forks import Fork from ethereum_test_tools import ( Account, Alloc, Bytecode, Environment, StateTestFiller, Transaction, ) from ethereum_test_vm import Opcodes as Op from .common import Blake2bInput, ExpectedOutput from .spec import SpecTestVectors, ref_spec_152 REFERENCE_SPEC_GIT_PATH = ref_spec_152.git_path REFERENCE_SPEC_VERSION = ref_spec_152.version pytestmark = pytest.mark.ported_from( [ "https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/stPreCompiledContracts/blake2BFiller.yml", "https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/stPreCompiledContracts2/CALLBlake2fFiller.json", "https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/stPreCompiledContracts2/CALLCODEBlake2fFiller.json", "https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/stPreCompiledContracts/delegatecall09UndefinedFiller.yml", ], pr=[ "https://github.com/ethereum/execution-spec-tests/pull/1244", "https://github.com/ethereum/execution-spec-tests/pull/1067", ], coverage_missed_reason=( "No longer used opcodes, SUB, GT, ISZERO, AND, CODESIZE, JUMP, some PUSH opcodes." "Original test calls Blake2b in ConstantinopleFix (activation test), " "which results in empty account code being triggered." ), ) @pytest.mark.valid_from("Istanbul") @pytest.mark.parametrize("call_opcode", [Op.CALL]) @pytest.mark.parametrize( ["data", "output"], [ pytest.param( Blake2bInput( rounds=0, rounds_length=0, h="", m="", t_0="", t_1="", ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="empty-input", ), pytest.param( Blake2bInput( rounds_length=3, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="invalid-rounds-length-short", ), pytest.param( Blake2bInput( rounds_length=5, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="invalid-rounds-length-long", ), pytest.param( Blake2bInput( f=2, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="invalid-final-block-flag-value-0x02", ), pytest.param( Blake2bInput( rounds=0, ), ExpectedOutput( call_succeeds=True, data_1="0x08c9bcf367e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5", data_2="0xd282e6ad7f520e511f6c3e2b8c68059b9442be0454267ce079217e1319cde05b", ), id="valid-rounds-0", ), pytest.param( Blake2bInput(), ExpectedOutput( call_succeeds=True, data_1="0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1", data_2="0x7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923", ), id="valid-rounds-12", ), pytest.param( Blake2bInput( f=False, ), ExpectedOutput( call_succeeds=True, data_1="0x75ab69d3190a562c51aef8d88f1c2775876944407270c42c9844252c26d28752", data_2="0x98743e7f6d5ea2f2d3e8d226039cd31b4e426ac4f2d3d666a610c2116fde4735", ), id="valid-false-final-block-flag", ), pytest.param( Blake2bInput( rounds=1, ), ExpectedOutput( call_succeeds=True, data_1="0xb63a380cb2897d521994a85234ee2c181b5f844d2c624c002677e9703449d2fb", data_2="0xa551b3a8333bcdf5f2f7e08993d53923de3d64fcc68c034e717b9293fed7a421", ), id="valid-rounds-1", ), # Excessive number of rounds expects to run out of gas pytest.param( Blake2bInput( rounds=4294967295, ), ExpectedOutput( call_succeeds=False, data_1="0x0", data_2="0x0", ), id="oog-rounds-4294967295", ), # Case from https://github.com/ethereum/tests/pull/948#issuecomment-925964632 pytest.param( Blake2bInput( m="6162636465000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=5, ), ExpectedOutput( call_succeeds=True, data_1="0xf3e89a60ec4b0b1854744984e421d22b82f181bd4601fb9b1726b2662da61c29", data_2="0xdff09e75814acb2639fd79e56616e55fc135f8476f0302b3dc8d44e082eb83a8", ), id="valid-different-message-offset-0x05", ), pytest.param( Blake2bInput( rounds=16, ), ExpectedOutput( call_succeeds=True, data_1="0xa8ef8236e5f48a74af375df15681d128457891c1cc4706f30747b2d40300b2f4", data_2="0x9d19f80fbd0945fd87736e1fc1ff10a80fd85a7aa5125154f3aaa3789ddff673", ), id="valid-rounds-16", ), pytest.param( Blake2bInput( rounds=32, ), ExpectedOutput( call_succeeds=True, data_1="0xbc5e888ed71b546da7b1506179bdd6c184a6410c40de33f9c330207417797889", data_2="0x5dbe74144468aefe5c2afce693c62dbca99e5e076dd467fe90a41278b16d691e", ), id="valid-rounds-32", ), pytest.param( Blake2bInput( rounds=64, ), ExpectedOutput( call_succeeds=True, data_1="0x74097ae7b16ffd18c742aee5c55dc89d54b6f1a8a19e6139ccfb38afba56b6b0", data_2="0x2cc35c441c19c21194fefb6841e72202f7c9d05eb9c3cfd8f94c67aa77d473c1", ), id="valid-rounds-64", ), pytest.param( Blake2bInput( rounds=128, ), ExpectedOutput( call_succeeds=True, data_1="0xd82c6a670dc90af9d7f77644eacbeddfed91b760c65c927871784abceaab3f81", data_2="0x3759733a1736254fb1cfc515dbfee467930955af56e27ee435f836fc3e65969f", ), id="valid-rounds-128", ), pytest.param( Blake2bInput( rounds=256, ), ExpectedOutput( call_succeeds=True, data_1="0x5d6ff04d5ebaee5687d634613ab21e9a7d36f782033c74f91d562669aaf9d592", data_2="0xc86346cb2df390243a952834306b389e656876a67934e2c023bce4918a016d4e", ), id="valid-rounds-256", ), pytest.param( Blake2bInput( rounds=512, ), ExpectedOutput( call_succeeds=True, data_1="0xa2c1eb780a6e1249156fe0751e5d4687ea9357b0651c78df660ab004cb477363", data_2="0x6298bbbc683e4a0261574b6d857a6a99e06b2eea50b16f86343d2625ff222b98", ), id="valid-rounds-512", ), pytest.param( Blake2bInput( rounds=1024, ), ExpectedOutput( call_succeeds=True, data_1="0x689419d2bf32b5a9901a2c733b9946727026a60d8773117eabb35f04a52cdcf1", data_2="0xb8fb4473454cf03d46c36a10b3f784aae4dc80a24424960e66a8ad5a8c2bfb30", ), id="valid-rounds-1024", ), pytest.param( Blake2bInput( rounds=16, m="6162636465666768696a6b6c6d6e6f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=16, ), ExpectedOutput( call_succeeds=True, data_1="0x4ab6df9d1f57140bbd27b5e164f42102d9e2b0bf4d53da501273f81a37e505c7", data_2="0xf6e136f9ca4b693aa6e990b04c6412296dc09540c23c395f183011a0c5d7392e", ), id="valid-rounds-16-offset-0x10", ), pytest.param( Blake2bInput( rounds=32, m="6162636465666768696a6b6c6d6e6f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=16, ), ExpectedOutput( call_succeeds=True, data_1="0x7af9b4f9c25ba3e3fd4fcb957e703b7b2e648990fe8e24c6ca2a2dfac4ce76e6", data_2="0x18acffc26913d6759843362adeb4c95299777baaa977b5d94dd219d1777e4cb", ), id="valid-rounds-32-offset-0x10", ), pytest.param( Blake2bInput( rounds=64, m="6162636465666768696a6b6c6d6e6f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=16, ), ExpectedOutput( call_succeeds=True, data_1="0x97eb79f7abc085a3da64d6e8643d196cbf522a51985ba2cc6a7ca14289b59df0", data_2="0x73366eb68e41966eb8b33ab5bd6078d0de2fa4edc986b1d2afc4c92f2fc30cda", ), id="valid-rounds-64-offset-0x10", ), pytest.param( Blake2bInput( rounds=128, m="6162636465666768696a6b6c6d6e6f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=16, ), ExpectedOutput( call_succeeds=True, data_1="0x5ef3d6ee148936390a9053e91ab5a92f4de4dfc62ebb95d71485be26d9b78c8d", data_2="0x8989dfe319f2fb5f11784174db63a7bcfc50de04e13fad57bea159e46e8811df", ), id="valid-rounds-128-offset-0x10", ), pytest.param( Blake2bInput( rounds=256, m="6162636465666768696a6b6c6d6e6f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=16, ), ExpectedOutput( call_succeeds=True, data_1="0xa36be13275fec9a91779f0c9b06b1b40d8c8a13ab0786d0764c2eb708cc8eb81", data_2="0xf1acb2a3c7abd2ff5a9fdfe88b81f6f56288dc5260a9c810f023ae83b9b64a1a", ), id="valid-rounds-256-offset-0x10", ), pytest.param( Blake2bInput( rounds=512, m="6162636465666768696a6b6c6d6e6f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=16, ), ExpectedOutput( call_succeeds=True, data_1="0xc987e560e3f90833c0d10ae1282bd9d35a7ba06d8abaa13a994d0962ed2bbaa9", data_2="0xf69c1e1e7c9aedb75e72d1b46e9f1b2ad8f8c2f7f858a04ed8aec16f964a96da", ), id="valid-rounds-512-offset-0x10", ), pytest.param( Blake2bInput( rounds=1024, m="6162636465666768696a6b6c6d6e6f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=16, ), ExpectedOutput( call_succeeds=True, data_1="0x224138a6afa847230ff09c23e2ca66522e22d26884b09d7740e2dd127cb61057", data_2="0x90cecbd4de6a52a733ca4a59583c064ad6ec7653d5d457b681de332f16f3d45", ), id="valid-rounds-1024-offset-0x10", ), pytest.param( Blake2bInput( rounds=16, m="6162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d900000000000000", t_0=120, ), ExpectedOutput( call_succeeds=True, data_1="0xabcd200f2962ede252fc455ea70d12b236ad2f4046b91e17558a7741d9da39a2", data_2="0x548083b610bb8591ca50418eabd15b6489a936b178a435b4c182ffa475eba4d8", ), id="valid-rounds-16-offset-0x78", ), pytest.param( Blake2bInput( rounds=32, m="6162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d900000000000000", t_0=120, ), ExpectedOutput( call_succeeds=True, data_1="0x39fc2077154fba422b3d628d10908c596beebea8dfd90f14566aec4f60bdb2bc", data_2="0xa75d73ab2b224d58c3568cbc7fc8905cc849f10745f00addef02384032d53729", ), id="valid-rounds-32-offset-0x78", ), pytest.param( Blake2bInput( rounds=64, m="6162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d900000000000000", t_0=120, ), ExpectedOutput( call_succeeds=True, data_1="0x5bb981381beb687d5fdbe5e7c096fbd1ce193b780948c1d74ebbb7c58db364c7", data_2="0xb7695d32f918444dbdcbdcff476fc70a926e228c4cbb7d05473711d3b56e5b33", ), id="valid-rounds-64-offset-0x78", ), pytest.param( Blake2bInput( rounds=0, rounds_length=0, h="00", m="00", t_0=0, t_1=SpecTestVectors.BLAKE2_OFFSET_COUNTER_1, f=0, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-RFC-7693-zero-input", ), ], ) @pytest.mark.slow() def test_blake2b( state_test: StateTestFiller, pre: Alloc, call_opcode: Op, blake2b_contract_bytecode: Bytecode, data: Blake2bInput | str | bytes, output: ExpectedOutput, ) -> None: """Test BLAKE2b precompile.""" env = Environment() account = pre.deploy_contract(blake2b_contract_bytecode, storage={0: 0xDEADBEEF}) sender = pre.fund_eoa() if isinstance(data, Blake2bInput): data = data.create_blake2b_tx_data() elif isinstance(data, str): data = bytes.fromhex(data) if isinstance(data, Blake2bInput): data = data.create_blake2b_tx_data() elif isinstance(data, str): data = bytes.fromhex(data) tx = Transaction( ty=0x0, to=account, data=data, gas_limit=1_000_000, protected=True, sender=sender, value=100000, ) post = { account: Account( storage={ 0: 0x1 if output.call_succeeds else 0x0, 1: output.data_1, 2: output.data_2, } ) } state_test(env=env, pre=pre, post=post, tx=tx) @pytest.mark.valid_from("Istanbul") @pytest.mark.parametrize("call_opcode", [Op.CALL, Op.CALLCODE]) @pytest.mark.parametrize("gas_limit", [90_000, 110_000, 200_000]) @pytest.mark.parametrize( ["data", "output"], [ pytest.param( b"", ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case1-data0-invalid-low-gas", ), pytest.param( Blake2bInput( rounds_length=3, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case1-data1-invalid-low-gas", ), pytest.param( Blake2bInput( rounds_length=5, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case1-data2-invalid-low-gas", ), pytest.param( Blake2bInput( f=2, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case1-data3-invalid-low-gas", ), pytest.param( Blake2bInput( rounds=8000000, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case1-data9-invalid-low-gas", ), pytest.param( "000c", ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case1-data10-invalid-low-gas", ), ], ) def test_blake2b_invalid_gas( state_test: StateTestFiller, pre: Alloc, call_opcode: Op, blake2b_contract_bytecode: Bytecode, gas_limit: int, data: Blake2bInput | str | bytes, output: ExpectedOutput, ) -> None: """Test BLAKE2b precompile invalid calls using different gas limits.""" env = Environment() account = pre.deploy_contract(blake2b_contract_bytecode, storage={0: 0xDEADBEEF}) sender = pre.fund_eoa() if isinstance(data, Blake2bInput): data = data.create_blake2b_tx_data() elif isinstance(data, str): data = bytes.fromhex(data) tx = Transaction( ty=0x0, to=account, data=data, gas_limit=gas_limit, protected=True, sender=sender, value=0, ) post = { account: Account( storage={ 0: 0xDEADBEEF, 1: output.data_1, 2: output.data_2, }, nonce=0x1, ) } state_test(env=env, pre=pre, post=post, tx=tx) def max_tx_gas_limit(fork: Fork) -> int: """Maximum gas limit for a transaction (fork agnostic).""" tx_limit = fork.transaction_gas_limit_cap() if tx_limit is not None: return tx_limit return Environment().gas_limit def tx_gas_limits(fork: Fork) -> List[int]: """List of tx gas limits.""" return [max_tx_gas_limit(fork), 90_000, 110_000, 200_000] @pytest.mark.valid_from("Istanbul") @pytest.mark.parametrize("call_opcode", [Op.CALL, Op.CALLCODE]) @pytest.mark.parametrize_by_fork("gas_limit", tx_gas_limits) @pytest.mark.parametrize( ["data", "output"], [ pytest.param( Blake2bInput( rounds=0, ), ExpectedOutput( call_succeeds=True, data_1="0x08c9bcf367e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5", data_2="0xd282e6ad7f520e511f6c3e2b8c68059b9442be0454267ce079217e1319cde05b", ), id="EIP-152-case3-data4-gas-limit", ), pytest.param( Blake2bInput(), ExpectedOutput( call_succeeds=True, data_1="0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1", data_2="0x7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923", ), id="EIP-152-case4-data5-gas-limit", ), pytest.param( Blake2bInput( f=False, ), ExpectedOutput( call_succeeds=True, data_1="0x75ab69d3190a562c51aef8d88f1c2775876944407270c42c9844252c26d28752", data_2="0x98743e7f6d5ea2f2d3e8d226039cd31b4e426ac4f2d3d666a610c2116fde4735", ), id="EIP-152-case5-data6-gas-limit", ), pytest.param( Blake2bInput( rounds=1, ), ExpectedOutput( call_succeeds=True, data_1="0xb63a380cb2897d521994a85234ee2c181b5f844d2c624c002677e9703449d2fb", data_2="0xa551b3a8333bcdf5f2f7e08993d53923de3d64fcc68c034e717b9293fed7a421", ), id="EIP-152-case6-data7-gas-limit", ), pytest.param( Blake2bInput( rounds=0, h="00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", m="0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", t_0=0, t_1=SpecTestVectors.BLAKE2_OFFSET_COUNTER_1, f=0, ), ExpectedOutput( call_succeeds=True, data_1="0x08c9bcf367e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5", data_2="0xd182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b", ), id="EIP-152-case7-data8-gas-limit", ), ], ) def test_blake2b_gas_limit( state_test: StateTestFiller, pre: Alloc, call_opcode: Op, blake2b_contract_bytecode: Bytecode, gas_limit: int, data: Blake2bInput | str | bytes, output: ExpectedOutput, ) -> None: """Test BLAKE2b precompile with different gas limits.""" account = pre.deploy_contract(blake2b_contract_bytecode, storage={0: 0xDEADBEEF}) sender = pre.fund_eoa() if isinstance(data, Blake2bInput): data = data.create_blake2b_tx_data() elif isinstance(data, str): data = bytes.fromhex(data) tx = Transaction( ty=0x0, to=account, data=data, gas_limit=gas_limit, protected=True, sender=sender, value=0, ) post = { account: Account( storage={ 0: 0x1 if output.call_succeeds else 0x0, 1: output.data_1, 2: output.data_2, } ) } state_test( pre=pre, post=post, tx=tx, ) @pytest.mark.valid_from("Istanbul") @pytest.mark.parametrize("call_opcode", [Op.CALL, Op.CALLCODE]) @pytest.mark.parametrize_by_fork("gas_limit", lambda fork: [max_tx_gas_limit(fork)]) @pytest.mark.parametrize( ["data", "output"], [ pytest.param( b"", ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case0-data0-large-gas-limit", ), pytest.param( Blake2bInput( rounds_length=3, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case2-data1-large-gas-limit", ), pytest.param( Blake2bInput( rounds_length=5, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case2-data2-large-gas-limit", ), pytest.param( Blake2bInput( f=2, ), ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case2-data3-large-gas-limit", ), pytest.param( Blake2bInput( rounds=100_000, ), ExpectedOutput( call_succeeds=True, data_1="0x165da71a32e91bca2623bfaeab079f7e6edfba2259028cc854ec497f9fb0fe75", data_2="0xd37f63034b83f4a0a07cd238483874862921ef0c40630826a76e41bf3b02ffe3", ), id="EIP-152-modified-case8-data9-large-gas-limit", ), pytest.param( Blake2bInput( rounds=8000000, ), ExpectedOutput( call_succeeds=True, data_1="0x6d2ce9e534d50e18ff866ae92d70cceba79bbcd14c63819fe48752c8aca87a4b", data_2="0xb7dcc230d22a4047f0486cfcfb50a17b24b2899eb8fca370f22240adb5170189", ), id="EIP-152-case8-data9-large-gas-limit", marks=pytest.mark.skip("Times-out during fill"), ), pytest.param( "000c", ExpectedOutput( call_succeeds=False, data_1="0x00", data_2="0x00", ), id="EIP-152-case9-data10-large-gas-limit", ), ], ) @pytest.mark.slow() def test_blake2b_large_gas_limit( state_test: StateTestFiller, pre: Alloc, call_opcode: Op, gas_limit: int, blake2b_contract_bytecode: Bytecode, data: Blake2bInput | str | bytes, output: ExpectedOutput, ) -> None: """Test BLAKE2b precompile with large gas limit.""" account = pre.deploy_contract(blake2b_contract_bytecode, storage={0: 0xDEADBEEF}) sender = pre.fund_eoa() if isinstance(data, Blake2bInput): data = data.create_blake2b_tx_data() elif isinstance(data, str): data = bytes.fromhex(data) tx = Transaction( ty=0x0, to=account, data=data, gas_limit=gas_limit, protected=True, sender=sender, value=0, ) post = { account: Account( storage={ 0: 0x1 if output.call_succeeds else 0x0, 1: output.data_1, 2: output.data_2, } ) } state_test(pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip152_blake2/common.py
tests/istanbul/eip152_blake2/common.py
"""Common classes used in the BLAKE2b precompile tests.""" from dataclasses import dataclass from ethereum_test_base_types import Bytes from ethereum_test_types.helpers import TestParameterGroup from .spec import Spec, SpecTestVectors class Blake2bInput(TestParameterGroup): """ Helper class that defines the BLAKE2b precompile inputs and creates the call data from them. Returns all inputs encoded as bytes. Attributes: rounds_length (int): An optional integer representing the bytes length for the number of rounds. Defaults to the expected length of 4. rounds (int | str): A hex string or integer value representing the number of rounds. h (str): A hex string that represents the state vector. m (str): A hex string that represents the message block vector. t_0 (int | str): A hex string or integer value that represents the first offset counter. t_1(int | str): A hex string or integer value that represents the second offset counter. f (bool): An optional boolean that represents the final block indicator flag. Defaults to True. """ rounds_length: int = Spec.BLAKE2_PRECOMPILE_ROUNDS_LENGTH rounds: int = Spec.BLAKE2B_PRECOMPILE_ROUNDS h: Bytes = SpecTestVectors.BLAKE2_STATE_VECTOR # type: ignore m: Bytes = SpecTestVectors.BLAKE2_MESSAGE_BLOCK_VECTOR # type: ignore t_0: int | Bytes = SpecTestVectors.BLAKE2_OFFSET_COUNTER_0 t_1: int | Bytes = SpecTestVectors.BLAKE2_OFFSET_COUNTER_1 f: bool | int = True def create_blake2b_tx_data(self) -> bytes: """Generate input for the BLAKE2b precompile.""" _rounds = self.rounds.to_bytes(length=self.rounds_length, byteorder="big") _t_0 = ( self.t_0 if isinstance(self.t_0, bytes) else self.t_0.to_bytes(length=Spec.BLAKE2_PRECOMPILE_T_0_LENGTH, byteorder="little") ) _t_1 = ( self.t_1 if isinstance(self.t_1, bytes) else self.t_1.to_bytes(length=Spec.BLAKE2_PRECOMPILE_T_1_LENGTH, byteorder="little") ) _f = int(self.f).to_bytes(length=Spec.BLAKE2_PRECOMPILE_F_LENGTH, byteorder="big") return _rounds + self.h + self.m + _t_0 + _t_1 + _f @dataclass(kw_only=True, frozen=True, repr=False) class ExpectedOutput(TestParameterGroup): """ Expected test result. Attributes: call_succeeds (str | bool): A hex string or boolean to indicate whether the call was successful or not. data_1 (str): String value of the first updated state vector. data_2 (str): String value of the second updated state vector. """ call_succeeds: str | bool data_1: str data_2: str
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip152_blake2/spec.py
tests/istanbul/eip152_blake2/spec.py
"""Defines EIP-152 specification constants and functions.""" from dataclasses import dataclass @dataclass(frozen=True) class ReferenceSpec: """Defines the reference spec version and git path.""" git_path: str version: str ref_spec_152 = ReferenceSpec("EIPS/eip-152.md", "2762bfcff3e549ef263342e5239ef03ac2b07400") # Constants @dataclass(frozen=True) class Spec: """ Parameters from the EIP-152 specifications as defined at https://eips.ethereum.org/EIPS/eip-152#specification. If the parameter is not currently used within the tests, it is commented out. """ BLAKE2_PRECOMPILE_ADDRESS = 0x09 # The following constants are used to define the bytes length of the # parameters passed to the BLAKE2 precompile. BLAKE2_PRECOMPILE_ROUNDS_LENGTH = 4 # BLAKE2_PRECOMPILE_M_LENGTH = 128 BLAKE2_PRECOMPILE_T_0_LENGTH = 8 BLAKE2_PRECOMPILE_T_1_LENGTH = 8 BLAKE2_PRECOMPILE_F_LENGTH = 1 # Constants for BLAKE2b and BLAKE2s spec defined at # https://datatracker.ietf.org/doc/html/rfc7693#section-3.2 BLAKE2B_PRECOMPILE_ROUNDS = 12 BLAKE2B_PRECOMPILE_H_LENGTH = 64 # BLAKE2S_PRECOMPILE_ROUNDS = 10 # BLAKE2S_PRECOMPILE_H_LENGTH = 32 class SpecTestVectors: """Defines common test parameters for the BLAKE2b precompile.""" # The following constants are used to define common test parameters # Origin of vectors defined at # https://datatracker.ietf.org/doc/html/rfc7693.html#appendix-A BLAKE2_STATE_VECTOR = ( "48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1" "361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f" "79217e1319cde05b" ) BLAKE2_MESSAGE_BLOCK_VECTOR = ( "616263000000000000000000000000000000000" "00000000000000000000000000000000000000000000000000000000000000000" "00000000000000000000000000000000000000000000000000000000000000000" "00000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000" ) BLAKE2_OFFSET_COUNTER_0 = 3 BLAKE2_OFFSET_COUNTER_1 = 0
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip152_blake2/test_blake2_delegatecall.py
tests/istanbul/eip152_blake2/test_blake2_delegatecall.py
""" Test delegatecall to Blake2B Precompile before and after added. """ import pytest from ethereum_test_forks import Fork from ethereum_test_forks.forks.forks import Istanbul from ethereum_test_tools import ( Account, Alloc, Environment, StateTestFiller, Transaction, ) from ethereum_test_tools import Opcodes as Op from .spec import Spec REFERENCE_SPEC_GIT_PATH = "EIPS/eip-152.md" REFERENCE_SPEC_VERSION = "2762bfcff3e549ef263342e5239ef03ac2b07400" @pytest.mark.valid_from("ConstantinopleFix") def test_blake2_precompile_delegatecall( state_test: StateTestFiller, pre: Alloc, fork: Fork ) -> None: """ Test delegatecall consumes specified gas for the Blake2B precompile when it exists. """ env = Environment() account = pre.deploy_contract( Op.SSTORE( 0, Op.DELEGATECALL( gas=1, address=Spec.BLAKE2_PRECOMPILE_ADDRESS, ), ) + Op.STOP, storage={0: 0xDEADBEEF}, ) tx = Transaction( to=account, sender=pre.fund_eoa(), gas_limit=90_000, protected=True, ) # If precompile exists, DELEGATECALL will fail, otherwise DELEGATECALL will # succeed post = { account: Account( storage={ 0: "0x00" if fork >= Istanbul else "0x01", } ) } state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip152_blake2/conftest.py
tests/istanbul/eip152_blake2/conftest.py
"""pytest fixtures for testing the BLAKE2b precompile.""" import pytest from ethereum_test_vm import Bytecode from ethereum_test_vm import Opcodes as Op from .spec import Spec @pytest.fixture def blake2b_contract_bytecode(call_opcode: Op) -> Bytecode: """ Contract code that performs the provided opcode (CALL or CALLCODE) to the BLAKE2b precompile and stores the result. """ return ( Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE()) + Op.SSTORE( 0, call_opcode( address=Spec.BLAKE2_PRECOMPILE_ADDRESS, args_offset=0, args_size=Op.CALLDATASIZE(), ret_offset=0x200, ret_size=0x40, ), ) + Op.SSTORE(1, Op.MLOAD(0x200)) + Op.SSTORE(2, Op.MLOAD(0x220)) + Op.STOP() )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip152_blake2/__init__.py
tests/istanbul/eip152_blake2/__init__.py
""" Tests [EIP-152: BLAKE2 compression precompile](https://eips.ethereum.org/EIPS/eip-152). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip1344_chainid/test_chainid.py
tests/istanbul/eip1344_chainid/test_chainid.py
""" Tests [EIP-1344: CHAINID opcode](https://eips.ethereum.org/EIPS/eip-1344). """ import pytest from ethereum_test_tools import Account, Alloc, ChainConfig, StateTestFiller, Transaction from ethereum_test_vm import Opcodes as Op REFERENCE_SPEC_GIT_PATH = "EIPS/eip-1344.md" REFERENCE_SPEC_VERSION = "02e46aebc80e6e5006ab4d2daa41876139f9a9e2" @pytest.mark.with_all_typed_transactions( marks=lambda tx_type: pytest.mark.execute( pytest.mark.skip(reason="type 3 transactions aren't supported in execute mode") ) if tx_type == 3 else None ) @pytest.mark.valid_from("Istanbul") def test_chainid( state_test: StateTestFiller, pre: Alloc, chain_config: ChainConfig, typed_transaction: Transaction, ) -> None: """Test CHAINID opcode.""" chain_id = chain_config.chain_id contract_address = pre.deploy_contract(Op.SSTORE(1, Op.CHAINID) + Op.STOP) tx = typed_transaction.copy( chain_id=chain_id, to=contract_address, ) post = { contract_address: Account(storage={1: chain_id}), } state_test(pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/istanbul/eip1344_chainid/__init__.py
tests/istanbul/eip1344_chainid/__init__.py
""" Tests for [EIP-1344: ChainID Opcode](https://eips.ethereum.org/EIPS/eip-1344). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/__init__.py
tests/shanghai/__init__.py
"""Test cases for EVM functionality introduced in Shanghai."""
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3860_initcode/test_with_eof.py
tests/shanghai/eip3860_initcode/test_with_eof.py
""" Test CREATE / CREATE2 and EOF interaction for EIP-3860 initcode limits. """ import itertools import pytest from ethereum_test_tools import ( Account, Alloc, Bytecode, Environment, Initcode, StateTestFiller, Transaction, compute_create_address, ) from ethereum_test_types.eof.v1.constants import MAX_BYTECODE_SIZE, MAX_INITCODE_SIZE from ethereum_test_vm import Opcodes as Op from .spec import ref_spec_3860 REFERENCE_SPEC_GIT_PATH = ref_spec_3860.git_path REFERENCE_SPEC_VERSION = ref_spec_3860.version pytestmark = pytest.mark.valid_from("Shanghai") _slot = itertools.count() next(_slot) # don't use slot 0 slot_code_worked = next(_slot) slot_create_address = next(_slot) value_code_worked = 0x2015 @pytest.mark.parametrize( "opcode", [ Op.CREATE, Op.CREATE2, ], ) @pytest.mark.parametrize( "init_code", [ pytest.param(Bytecode(), id="empty_initcode"), pytest.param(Initcode(initcode_length=MAX_INITCODE_SIZE), id="max_initcode"), pytest.param(Initcode(deploy_code=Bytecode()), id="empty_code"), pytest.param(Initcode(deploy_code=Op.STOP * MAX_BYTECODE_SIZE), id="max_code"), ], ) def test_legacy_create_edge_code_size( state_test: StateTestFiller, pre: Alloc, opcode: Op, init_code: Bytecode, ) -> None: """ Test legacy initcode and deployed code edge cases with EOF enabled. Verify that legacy initcode/deploycode having 0 or max size continues to work in the fork where EOF is enabled. Handling of EOF magic prefix and version interferes with the handling of legacy creation, so a specific test was proposed to test behavior doesn't change. """ env = Environment() salt_param = [0] if opcode == Op.CREATE2 else [] factory_code = ( Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE(slot_create_address, opcode(0, 0, Op.CALLDATASIZE, *salt_param)) + Op.SSTORE(slot_code_worked, value_code_worked) ) contract_address = pre.deploy_contract(code=factory_code) new_address = compute_create_address( address=contract_address, initcode=init_code, nonce=1, opcode=opcode ) post = { contract_address: Account( storage={slot_create_address: new_address, slot_code_worked: value_code_worked} ) } tx = Transaction( to=contract_address, gas_limit=10_000_000, data=init_code, sender=pre.fund_eoa(), ) state_test(env=env, pre=pre, post=post, tx=tx)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3860_initcode/spec.py
tests/shanghai/eip3860_initcode/spec.py
"""Defines EIP-3860 specification constants and functions.""" from dataclasses import dataclass @dataclass(frozen=True) class ReferenceSpec: """Defines the reference spec version and git path.""" git_path: str version: str ref_spec_3860 = ReferenceSpec("EIPS/eip-3860.md", "9ee005834d488e381455cf86a56c741a2e854a17") @dataclass(frozen=True) class Spec: """ Define parameters from the EIP-3860 specifications. These are the parameters defined at https://eips.ethereum.org/EIPS/eip-3860#parameters. """ MAX_INITCODE_SIZE = 49152 INITCODE_WORD_COST = 2
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3860_initcode/conftest.py
tests/shanghai/eip3860_initcode/conftest.py
"""Fixtures for the EIP-3860 initcode tests.""" import pytest from ethereum_test_tools import Alloc, Environment @pytest.fixture def env() -> Environment: """Environment fixture.""" return Environment() @pytest.fixture def post() -> Alloc: """Post state fixture.""" return Alloc()
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3860_initcode/helpers.py
tests/shanghai/eip3860_initcode/helpers.py
"""Helpers for the EIP-3860 initcode tests.""" from ethereum_test_tools import Initcode from ethereum_test_vm import Opcodes as Op INITCODE_RESULTING_DEPLOYED_CODE = Op.STOP def get_initcode_name(val: Initcode) -> str: """Return Initcode object's name to generate test ids.""" return val._name_ def get_create_id(opcode: Op) -> str: """Return the opcode name for the test id.""" return opcode._name_.lower()
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3860_initcode/__init__.py
tests/shanghai/eip3860_initcode/__init__.py
""" Test [EIP-3860: Limit and meter initcode](https://eips.ethereum.org/EIPS/eip-3860). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3860_initcode/test_initcode.py
tests/shanghai/eip3860_initcode/test_initcode.py
""" Test [EIP-3860: Limit and meter initcode](https://eips.ethereum.org/EIPS/eip-3860). Tests ported from: - [ethereum/tests/pull/990](https://github.com/ethereum/tests/pull/990) - [ethereum/tests/pull/1012](https://github.com/ethereum/tests/pull/990) """ from typing import List import pytest from ethereum_test_forks import Fork from ethereum_test_tools import ( EOA, AccessList, Account, Address, Alloc, Bytecode, Environment, Initcode, StateTestFiller, Transaction, TransactionException, TransactionReceipt, ceiling_division, compute_create_address, ) from ethereum_test_vm import Opcodes as Op from .helpers import INITCODE_RESULTING_DEPLOYED_CODE, get_create_id, get_initcode_name from .spec import Spec, ref_spec_3860 REFERENCE_SPEC_GIT_PATH = ref_spec_3860.git_path REFERENCE_SPEC_VERSION = ref_spec_3860.version pytestmark = pytest.mark.valid_from("Shanghai") """Initcode templates used throughout the tests""" INITCODE_ONES_MAX_LIMIT = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=Spec.MAX_INITCODE_SIZE, padding_byte=0x01, name="max_size_ones", ) INITCODE_ZEROS_MAX_LIMIT = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=Spec.MAX_INITCODE_SIZE, padding_byte=0x00, name="max_size_zeros", ) INITCODE_ONES_OVER_LIMIT = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=Spec.MAX_INITCODE_SIZE + 1, padding_byte=0x01, name="over_limit_ones", ) INITCODE_ZEROS_OVER_LIMIT = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=Spec.MAX_INITCODE_SIZE + 1, padding_byte=0x00, name="over_limit_zeros", ) INITCODE_ZEROS_32_BYTES = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=32, padding_byte=0x00, name="32_bytes", ) INITCODE_ZEROS_33_BYTES = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=33, padding_byte=0x00, name="33_bytes", ) INITCODE_ZEROS_49120_BYTES = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=49120, padding_byte=0x00, name="49120_bytes", ) INITCODE_ZEROS_49121_BYTES = Initcode( deploy_code=INITCODE_RESULTING_DEPLOYED_CODE, initcode_length=49121, padding_byte=0x00, name="49121_bytes", ) EMPTY_INITCODE = Initcode( name="empty", ) EMPTY_INITCODE._bytes_ = bytes() EMPTY_INITCODE.deployment_gas = 0 EMPTY_INITCODE.execution_gas = 0 SINGLE_BYTE_INITCODE = Initcode( name="single_byte", ) SINGLE_BYTE_INITCODE._bytes_ = bytes(Op.STOP) SINGLE_BYTE_INITCODE.deployment_gas = 0 SINGLE_BYTE_INITCODE.execution_gas = 0 """Test cases using a contract creating transaction""" @pytest.mark.xdist_group(name="bigmem") @pytest.mark.parametrize( "initcode", [ INITCODE_ZEROS_MAX_LIMIT, INITCODE_ONES_MAX_LIMIT, pytest.param(INITCODE_ZEROS_OVER_LIMIT, marks=pytest.mark.exception_test), pytest.param(INITCODE_ONES_OVER_LIMIT, marks=pytest.mark.exception_test), ], ids=get_initcode_name, ) def test_contract_creating_tx( state_test: StateTestFiller, env: Environment, pre: Alloc, post: Alloc, sender: EOA, initcode: Initcode, ) -> None: """ Test creating a contract with initcode that is on/over the allowed limit. """ create_contract_address = compute_create_address( address=sender, nonce=0, ) tx = Transaction( nonce=0, to=None, data=initcode, gas_limit=10000000, gas_price=10, sender=sender, ) if len(initcode) > Spec.MAX_INITCODE_SIZE: # Initcode is above the max size, tx inclusion in the block makes # it invalid. post[create_contract_address] = Account.NONEXISTENT tx.error = TransactionException.INITCODE_SIZE_EXCEEDED else: # Initcode is at or below the max size, tx inclusion in the block # is ok and the contract is successfully created. post[create_contract_address] = Account(code=Op.STOP) state_test( env=env, pre=pre, post=post, tx=tx, ) def valid_gas_test_case(initcode: Initcode, gas_test_case: str) -> bool: """Filter out invalid gas test case/initcode combinations.""" if gas_test_case == "too_little_execution_gas": return (initcode.deployment_gas + initcode.execution_gas) > 0 return True @pytest.mark.parametrize( "initcode,gas_test_case", [ pytest.param( i, g, marks=([pytest.mark.exception_test] if g == "too_little_intrinsic_gas" else []), ) for i in [ INITCODE_ZEROS_MAX_LIMIT, INITCODE_ONES_MAX_LIMIT, EMPTY_INITCODE, SINGLE_BYTE_INITCODE, INITCODE_ZEROS_32_BYTES, INITCODE_ZEROS_33_BYTES, INITCODE_ZEROS_49120_BYTES, INITCODE_ZEROS_49121_BYTES, ] for g in [ "too_little_intrinsic_gas", "exact_intrinsic_gas", "too_little_execution_gas", "exact_execution_gas", ] if valid_gas_test_case(i, g) ], ids=lambda x: f"{get_initcode_name(x[0])}-{x[1]}" if isinstance(x, tuple) else x, ) class TestContractCreationGasUsage: """ Test the gas cost behavior of a contract creating transaction. The following scenarios are tested: 1. Test with exact intrinsic gas minus one, contract create fails and tx is invalid. 2. Test with exact intrinsic gas, contract create fails, but tx is valid. 3. Test with exact execution gas minus one, contract create fails, but tx is valid. 4. Test with exact execution gas, contract create succeeds. Initcode must be within a valid EIP-3860 length. """ @pytest.fixture def tx_access_list(self) -> List[AccessList]: """ Return an access list to raise the intrinsic gas cost. Upon EIP-7623 activation, we need to use an access list to raise the intrinsic gas cost to be above the floor data cost. """ return [AccessList(address=Address(i), storage_keys=[]) for i in range(1, 478)] @pytest.fixture def exact_intrinsic_gas( self, fork: Fork, initcode: Initcode, tx_access_list: List[AccessList] ) -> int: """ Calculate the intrinsic tx gas cost. """ tx_intrinsic_gas_cost_calculator = fork.transaction_intrinsic_cost_calculator() assert tx_intrinsic_gas_cost_calculator( calldata=initcode, contract_creation=True, access_list=tx_access_list, ) == tx_intrinsic_gas_cost_calculator( calldata=initcode, contract_creation=True, access_list=tx_access_list, return_cost_deducted_prior_execution=True, ) return tx_intrinsic_gas_cost_calculator( calldata=initcode, contract_creation=True, access_list=tx_access_list, ) @pytest.fixture def exact_execution_gas(self, exact_intrinsic_gas: int, initcode: Initcode) -> int: """ Calculate total execution gas cost. """ return exact_intrinsic_gas + initcode.deployment_gas + initcode.execution_gas @pytest.fixture def tx_error(self, gas_test_case: str) -> TransactionException | None: """ Return the transaction exception, or None, as expected. Check that the transaction is invalid if too little intrinsic gas is specified, otherwise the tx is valid and succeeds. """ if gas_test_case == "too_little_intrinsic_gas": return TransactionException.INTRINSIC_GAS_TOO_LOW return None @pytest.fixture def tx( self, sender: EOA, initcode: Initcode, gas_test_case: str, tx_access_list: List[AccessList], tx_error: TransactionException | None, exact_intrinsic_gas: int, exact_execution_gas: int, ) -> Transaction: """ Return a tx with `gas_limit` corresponding to the `gas_test_case`. Implement the gas_test_case by setting the `gas_limit` of the tx appropriately and test whether the tx succeeds or fails with appropriate error. """ if gas_test_case == "too_little_intrinsic_gas": gas_limit = exact_intrinsic_gas - 1 elif gas_test_case == "exact_intrinsic_gas": gas_limit = exact_intrinsic_gas elif gas_test_case == "too_little_execution_gas": gas_limit = exact_execution_gas - 1 elif gas_test_case == "exact_execution_gas": gas_limit = exact_execution_gas else: pytest.fail("Invalid gas test case provided.") return Transaction( nonce=0, to=None, access_list=tx_access_list, data=initcode, gas_limit=gas_limit, gas_price=10, error=tx_error, sender=sender, # The entire gas limit is expected to be consumed. expected_receipt=TransactionReceipt(gas_used=gas_limit), ) @pytest.fixture def post( self, sender: EOA, initcode: Initcode, gas_test_case: str, exact_intrinsic_gas: int, exact_execution_gas: int, ) -> Alloc: """ Test contract creation fails unless enough execution gas is provided. """ create_contract_address = compute_create_address( address=sender, nonce=0, ) if gas_test_case == "exact_intrinsic_gas" and exact_intrinsic_gas == exact_execution_gas: # Special scenario where the execution of the initcode and # gas cost to deploy are zero return Alloc({create_contract_address: Account(code=initcode.deploy_code)}) elif gas_test_case == "exact_execution_gas": return Alloc({create_contract_address: Account(code=initcode.deploy_code)}) return Alloc({create_contract_address: Account.NONEXISTENT}) @pytest.mark.slow() def test_gas_usage( self, state_test: StateTestFiller, env: Environment, pre: Alloc, post: Alloc, tx: Transaction, ) -> None: """ Test transaction and contract creation using different gas limits. """ state_test( env=env, pre=pre, post=post, tx=tx, ) @pytest.mark.parametrize( "initcode", [ INITCODE_ZEROS_MAX_LIMIT, INITCODE_ONES_MAX_LIMIT, INITCODE_ZEROS_OVER_LIMIT, INITCODE_ONES_OVER_LIMIT, EMPTY_INITCODE, SINGLE_BYTE_INITCODE, INITCODE_ZEROS_32_BYTES, INITCODE_ZEROS_33_BYTES, INITCODE_ZEROS_49120_BYTES, INITCODE_ZEROS_49121_BYTES, ], ids=get_initcode_name, ) @pytest.mark.parametrize("opcode", [Op.CREATE, Op.CREATE2], ids=get_create_id) class TestCreateInitcode: """ Test contract creation with valid and invalid initcode lengths. Test contract creation via CREATE/CREATE2, parametrized by initcode that is on/over the max allowed limit. """ @pytest.fixture def create2_salt(self) -> int: """ Salt value used for CREATE2 contract creation. """ return 0xDEADBEEF @pytest.fixture def creator_code(self, opcode: Op, create2_salt: int) -> Bytecode: """ Generate code for the creator contract which calls CREATE/CREATE2. """ return ( Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.GAS + ( opcode(size=Op.CALLDATASIZE, salt=create2_salt) if opcode == Op.CREATE2 else opcode(size=Op.CALLDATASIZE) ) + Op.GAS # stack: [Gas 2, Call Result, Gas 1] + Op.SWAP1 # stack: [Call Result, Gas 2, Gas 1] + Op.SSTORE(0, unchecked=True) # stack: [Gas 2, Gas 1] + Op.SWAP1 # stack: [Gas 1, Gas 2] + Op.SUB # stack: [Gas 1 - Gas 2] + Op.SSTORE(1, unchecked=True) ) @pytest.fixture def creator_contract_address(self, pre: Alloc, creator_code: Bytecode) -> Address: """Return address of creator contract.""" return pre.deploy_contract(creator_code) @pytest.fixture def created_contract_address( # noqa: D103 self, opcode: Op, create2_salt: int, initcode: Initcode, creator_contract_address: Address, ) -> Address: """ Calculate address of the contract created by the creator contract. """ return compute_create_address( address=creator_contract_address, nonce=1, salt=create2_salt, initcode=initcode, opcode=opcode, ) @pytest.fixture def caller_code(self, creator_contract_address: Address) -> Bytecode: """ Generate code for the caller contract that calls the creator contract. """ return Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE) + Op.SSTORE( Op.CALL(5000000, creator_contract_address, 0, 0, Op.CALLDATASIZE, 0, 0), 1 ) @pytest.fixture def caller_contract_address(self, pre: Alloc, caller_code: Bytecode) -> Address: """Return address of the caller contract.""" return pre.deploy_contract(caller_code) @pytest.fixture def tx(self, caller_contract_address: Address, initcode: Initcode, sender: EOA) -> Transaction: """Generate transaction that executes the caller contract.""" return Transaction( nonce=0, to=caller_contract_address, data=initcode, gas_limit=10000000, gas_price=10, sender=sender, ) @pytest.fixture def contract_creation_gas_cost(self, fork: Fork, opcode: Op) -> int: """Calculate gas cost of the contract creation operation.""" gas_costs = fork.gas_costs() create_contract_base_gas = gas_costs.G_CREATE gas_opcode_gas = gas_costs.G_BASE push_dup_opcode_gas = gas_costs.G_VERY_LOW calldatasize_opcode_gas = gas_costs.G_BASE contract_creation_gas_usage = ( create_contract_base_gas + gas_opcode_gas + (2 * push_dup_opcode_gas) + calldatasize_opcode_gas ) if opcode == Op.CREATE2: # Extra push operation contract_creation_gas_usage += push_dup_opcode_gas return contract_creation_gas_usage @pytest.fixture def initcode_word_cost(self, fork: Fork, initcode: Initcode) -> int: """Calculate gas cost charged for the initcode length.""" gas_costs = fork.gas_costs() return ceiling_division(len(initcode), 32) * gas_costs.G_INITCODE_WORD @pytest.fixture def create2_word_cost(self, opcode: Op, fork: Fork, initcode: Initcode) -> int: """Calculate gas cost charged for the initcode length.""" if opcode == Op.CREATE: return 0 gas_costs = fork.gas_costs() return ceiling_division(len(initcode), 32) * gas_costs.G_KECCAK_256_WORD @pytest.mark.xdist_group(name="bigmem") @pytest.mark.slow() def test_create_opcode_initcode( self, state_test: StateTestFiller, env: Environment, pre: Alloc, post: Alloc, tx: Transaction, initcode: Initcode, caller_contract_address: Address, creator_contract_address: Address, created_contract_address: Address, contract_creation_gas_cost: int, initcode_word_cost: int, create2_word_cost: int, ) -> None: """ Test contract creation with valid and invalid initcode lengths. Test contract creation via CREATE/CREATE2, parametrized by initcode that is on/over the max allowed limit. """ if len(initcode) > Spec.MAX_INITCODE_SIZE: # Call returns 0 as out of gas s[0]==1 post[caller_contract_address] = Account( nonce=1, storage={ 0: 1, 1: 0, }, ) post[created_contract_address] = Account.NONEXISTENT post[creator_contract_address] = Account( nonce=1, storage={ 0: 0, 1: 0, }, ) else: expected_gas_usage = contract_creation_gas_cost # The initcode is only executed if the length check succeeds expected_gas_usage += initcode.execution_gas # The code is only deployed if the length check succeeds expected_gas_usage += initcode.deployment_gas # CREATE2 hashing cost should only be deducted if the initcode # does not exceed the max length expected_gas_usage += create2_word_cost # Initcode word cost is only deducted if the length check # succeeds expected_gas_usage += initcode_word_cost # Call returns 1 as valid initcode length s[0]==1 && s[1]==1 post[caller_contract_address] = Account( nonce=1, storage={ 0: 0, 1: 1, }, ) post[created_contract_address] = Account(code=initcode.deploy_code) post[creator_contract_address] = Account( nonce=2, storage={ 0: created_contract_address, 1: expected_gas_usage, }, ) state_test( env=env, pre=pre, post=post, tx=tx, )
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip4895_withdrawals/spec.py
tests/shanghai/eip4895_withdrawals/spec.py
"""Defines EIP-4895 specification constants and functions.""" from dataclasses import dataclass @dataclass(frozen=True) class ReferenceSpec: """Defines the reference spec version and git path.""" git_path: str version: str ref_spec_4895 = ReferenceSpec("EIPS/eip-4895.md", "81af3b60b632bc9c03513d1d137f25410e3f4d34")
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip4895_withdrawals/test_withdrawals.py
tests/shanghai/eip4895_withdrawals/test_withdrawals.py
""" Tests for [EIP-4895: Beacon chain withdrawals](https://eips.ethereum.org/EIPS/eip-4895). """ from enum import Enum, unique from typing import Dict, List, Mapping import pytest from ethereum_clis import TransitionTool from ethereum_test_forks import Cancun, Fork from ethereum_test_tools import ( EOA, Account, Address, Alloc, Block, BlockchainTestFiller, Hash, Transaction, TransactionException, Withdrawal, ) from ethereum_test_vm import Opcodes as Op from .spec import ref_spec_4895 REFERENCE_SPEC_GIT_PATH = ref_spec_4895.git_path REFERENCE_SPEC_VERSION = ref_spec_4895.version pytestmark = pytest.mark.valid_from("Shanghai") ONE_GWEI = 10**9 @pytest.mark.parametrize( "test_case", [ pytest.param( "tx_in_withdrawals_block", id="tx_in_withdrawals_block", marks=pytest.mark.exception_test, ), pytest.param("tx_after_withdrawals_block", id="tx_after_withdrawals_block"), ], ) class TestUseValueInTx: """ Test that the value from a withdrawal can be used in a transaction. 1. `tx_in_withdrawals_block`: Test that the withdrawal value can not be used by a transaction in the same block as the withdrawal. 2. `tx_after_withdrawals_block`: Test that the withdrawal value can be used by a transaction in the subsequent block. """ @pytest.fixture def sender(self, pre: Alloc) -> EOA: """Funded EOA used for sending transactions.""" return pre.fund_eoa(1) @pytest.fixture def recipient(self, pre: Alloc) -> EOA: """Funded EOA used for sending transactions.""" return pre.fund_eoa(0) @pytest.fixture def tx(self, sender: EOA, recipient: EOA) -> Transaction: # noqa: D102 # Transaction sent from the `sender`, which has 1 wei balance at start return Transaction( gas_price=ONE_GWEI, gas_limit=21_000, to=recipient, sender=sender, ) @pytest.fixture def withdrawal(self, tx: Transaction, sender: EOA) -> Withdrawal: # noqa: D102 return Withdrawal( index=0, validator_index=0, address=sender, amount=tx.gas_limit + 1, ) @pytest.fixture def blocks(self, tx: Transaction, withdrawal: Withdrawal, test_case: str) -> List[Block]: # noqa: D102 if test_case == "tx_in_withdrawals_block": return [ Block( txs=[tx.with_error(TransactionException.INSUFFICIENT_ACCOUNT_FUNDS)], withdrawals=[ withdrawal, ], exception=TransactionException.INSUFFICIENT_ACCOUNT_FUNDS, ) ] if test_case == "tx_after_withdrawals_block": return [ Block( txs=[], withdrawals=[ withdrawal, ], ), Block( txs=[tx], withdrawals=[], ), ] raise Exception("Invalid test case.") @pytest.fixture def post(self, sender: EOA, test_case: str) -> Dict: # noqa: D102 if test_case == "tx_in_withdrawals_block": return {} if test_case == "tx_after_withdrawals_block": return {sender: Account(balance=ONE_GWEI + 1)} raise Exception("Invalid test case.") def test_use_value_in_tx( self, pre: Alloc, blockchain_test: BlockchainTestFiller, post: dict, blocks: List[Block], ) -> None: """Test sending withdrawal value in a transaction.""" blockchain_test(pre=pre, post=post, blocks=blocks) def test_use_value_in_contract( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """Test sending value from contract that has not received a withdrawal.""" sender = pre.fund_eoa() recipient = pre.fund_eoa(1) contract_address = pre.deploy_contract( Op.SSTORE( Op.NUMBER, Op.CALL(address=recipient, value=1000000000), ) ) (tx_0, tx_1) = ( Transaction( sender=sender, value=0, gas_limit=100_000, to=contract_address, ) for _ in range(2) ) withdrawal = Withdrawal( index=0, validator_index=0, address=contract_address, amount=1, ) blocks = [ Block( txs=[tx_0], withdrawals=[withdrawal], ), Block( txs=[tx_1], # Same tx again, just increase nonce ), ] post = { contract_address: Account( storage={ 0x1: 0x0, # Call fails on the first attempt 0x2: 0x1, # Succeeds on the second attempt } ), recipient: Account( balance=ONE_GWEI + 1, ), } blockchain_test(pre=pre, post=post, blocks=blocks) def test_balance_within_block(blockchain_test: BlockchainTestFiller, pre: Alloc) -> None: """ Test withdrawal balance increase within the same block in a contract call. """ save_balance_on_block_number = Op.SSTORE( Op.NUMBER, Op.BALANCE(Op.CALLDATALOAD(0)), ) sender = pre.fund_eoa() recipient = pre.fund_eoa(ONE_GWEI) contract_address = pre.deploy_contract(save_balance_on_block_number) blocks = [ Block( txs=[ Transaction( sender=sender, gas_limit=100000, to=contract_address, data=Hash(recipient, left_padding=True), ) ], withdrawals=[ Withdrawal( index=0, validator_index=0, address=recipient, amount=1, ) ], ), Block( txs=[ Transaction( sender=sender, gas_limit=100000, to=contract_address, data=Hash(recipient, left_padding=True), ) ] ), ] post = { contract_address: Account( storage={ 1: ONE_GWEI, 2: 2 * ONE_GWEI, } ) } blockchain_test(pre=pre, post=post, blocks=blocks) @pytest.mark.parametrize("test_case", ["single_block", "multiple_blocks"]) class TestMultipleWithdrawalsSameAddress: """ Test that multiple withdrawals can be sent to the same address in. 1. A single block. 2. Multiple blocks. """ @pytest.fixture def addresses(self, fork: Fork) -> List[Address]: # noqa: D102 addresses = [Address(p) for p in fork.precompiles(block_number=0, timestamp=0)] return addresses + [Address(2**160 - 1)] @pytest.fixture def blocks(self, addresses: Address, test_case: str) -> List[Block]: # noqa: D102 if test_case == "single_block": # Many repeating withdrawals of the same accounts in the same # block. return [ Block( withdrawals=[ Withdrawal( index=i, validator_index=i, address=addresses[i % len(addresses)], amount=1, ) for i in range(len(addresses) * 16) ], ), ] if test_case == "multiple_blocks": # Similar test but now use multiple blocks each with multiple # withdrawals to the same withdrawal address. return [ Block( withdrawals=[ Withdrawal( index=i * 16 + j, validator_index=i, address=addresses[i], amount=1, ) for j in range(16) ], ) for i in range(len(addresses)) ] raise Exception("Invalid test case.") def test_multiple_withdrawals_same_address( self, blockchain_test: BlockchainTestFiller, test_case: str, pre: Alloc, addresses: List[Address], blocks: List[Block], ) -> None: """ Test withdrawals to the same address multiple times in the same block. """ # Expected post is the same for both test cases. post = {} for addr in addresses: post[addr] = Account( balance=16 * ONE_GWEI, storage={}, ) blockchain_test(pre=pre, post=post, blocks=blocks, tag=test_case) def test_many_withdrawals( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test an unexpected high number of withdrawals in a single block. """ n = 400 withdrawals = [] post = {} for i in range(n): addr = pre.deploy_contract(Op.SSTORE(Op.NUMBER, 1)) amount = i * 1 withdrawals.append( Withdrawal( index=i, validator_index=i, address=addr, amount=amount, ) ) post[addr] = Account( code=Op.SSTORE(Op.NUMBER, 1), balance=amount * ONE_GWEI, storage={}, ) blocks = [ Block( withdrawals=withdrawals, ), ] blockchain_test(pre=pre, post=post, blocks=blocks) def test_self_destructing_account( blockchain_test: BlockchainTestFiller, pre: Alloc, fork: Fork, ) -> None: """ Test withdrawals can be done to self-destructed accounts. Account `0x100` self-destructs and sends all its balance to `0x200`. Then, a withdrawal is received at `0x100` with 99 wei. """ self_destruct_code = Op.SELFDESTRUCT(Op.CALLDATALOAD(0)) sender = pre.fund_eoa() recipient = pre.fund_eoa(1) self_destruct_contract_address = pre.deploy_contract( self_destruct_code, balance=100 * ONE_GWEI, ) tx_1 = Transaction( # Transaction sent from the `sender`, that calls a # self-destructing contract. sender=sender, gas_limit=100000, to=self_destruct_contract_address, data=Hash(recipient, left_padding=True), ) withdrawal = Withdrawal( index=0, validator_index=0, address=self_destruct_contract_address, amount=(99), ) block = Block( txs=[tx_1], withdrawals=[withdrawal], ) post = { self_destruct_contract_address: Account( code=self_destruct_code if fork >= Cancun else b"", balance=(99 * ONE_GWEI), ), recipient: Account( code=b"", balance=(100 * ONE_GWEI) + 1, ), } blockchain_test(pre=pre, post=post, blocks=[block]) @pytest.mark.parametrize( "include_value_in_tx", [False, True], ids=["without_tx_value", "with_tx_value"], ) def test_newly_created_contract( blockchain_test: BlockchainTestFiller, pre: Alloc, include_value_in_tx: bool, ) -> None: """Test withdrawing to a newly created contract.""" sender = pre.fund_eoa() initcode = Op.RETURN(0, 1) tx = Transaction( # Transaction sent from the `sender`, that creates a # new contract. sender=sender, gas_limit=1000000, to=None, value=ONE_GWEI if include_value_in_tx else 0, data=initcode, ) created_contract = tx.created_contract withdrawal = Withdrawal( index=0, validator_index=0, address=created_contract, amount=1, ) created_contract_balance = ONE_GWEI if include_value_in_tx: created_contract_balance = 2 * ONE_GWEI post = { created_contract: Account( code=Op.STOP, balance=created_contract_balance, ), } block = Block( txs=[tx], withdrawals=[withdrawal], ) blockchain_test(pre=pre, post=post, blocks=[block]) def test_no_evm_execution( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """Test withdrawals don't trigger EVM execution.""" sender = pre.fund_eoa() contracts = [pre.deploy_contract(Op.SSTORE(Op.NUMBER, 1)) for _ in range(4)] blocks = [ Block( txs=[ Transaction( sender=sender, gas_limit=100000, to=contracts[2], ), Transaction( sender=sender, gas_limit=100000, to=contracts[3], ), ], withdrawals=[ Withdrawal( index=0, validator_index=0, address=contracts[0], amount=1, ), Withdrawal( index=1, validator_index=1, address=contracts[1], amount=1, ), ], ), Block( txs=[ Transaction( sender=sender, gas_limit=100000, to=contracts[0], ), Transaction( sender=sender, gas_limit=100000, to=contracts[1], ), ], withdrawals=[ Withdrawal( index=0, validator_index=0, address=contracts[2], amount=1, ), Withdrawal( index=1, validator_index=1, address=contracts[3], amount=1, ), ], ), ] post = { contracts[0]: Account(storage={2: 1}), contracts[1]: Account(storage={2: 1}), contracts[2]: Account(storage={1: 1}), contracts[3]: Account(storage={1: 1}), } blockchain_test(pre=pre, post=post, blocks=blocks) @unique class ZeroAmountTestCases(Enum): # noqa: D101 TWO_ZERO = "two_withdrawals_no_value" THREE_ONE_WITH_VALUE = "three_withdrawals_one_with_value" FOUR_ONE_WITH_MAX = "four_withdrawals_one_with_value_one_with_max" FOUR_ONE_WITH_MAX_REVERSED = "four_withdrawals_one_with_value_one_with_max_reversed_order" @pytest.mark.parametrize( "test_case", list(ZeroAmountTestCases), ids=[case.value for case in ZeroAmountTestCases], ) def test_zero_amount( blockchain_test: BlockchainTestFiller, pre: Alloc, test_case: ZeroAmountTestCases, ) -> None: """ Test withdrawal scenarios with a zero amount in a single block. All the withdrawals in the following scenarios are included in one block. 1. Two withdrawals of zero amount to two different addresses; one to an untouched account, one to an account with a balance. 2. As 1., but with an additional withdrawal with positive value. 3. As 2., but with an additional withdrawal containing the maximum value possible. 4. As 3., but with order of withdrawals in the block reversed. """ empty_accounts = [pre.fund_eoa(0) for _ in range(3)] zero_balance_contract = pre.deploy_contract(Op.STOP) all_withdrawals = [ # No value, untouched account Withdrawal( index=0, validator_index=0, address=empty_accounts[0], amount=0, ), # No value, touched account Withdrawal( index=0, validator_index=0, address=zero_balance_contract, amount=0, ), # Withdrawal with value Withdrawal( index=1, validator_index=0, address=empty_accounts[1], amount=1, ), # Withdrawal with maximum amount Withdrawal( index=2, validator_index=0, address=empty_accounts[2], amount=2**64 - 1, ), ] all_post = { empty_accounts[0]: Account.NONEXISTENT, zero_balance_contract: Account(code=Op.STOP, balance=0), empty_accounts[1]: Account(balance=ONE_GWEI), empty_accounts[2]: Account(balance=(2**64 - 1) * ONE_GWEI), } withdrawals: List[Withdrawal] = [] post: Mapping[Address, Account | object] = {} if test_case == ZeroAmountTestCases.TWO_ZERO: withdrawals = all_withdrawals[0:2] post = { account: all_post[account] for account in post if account in [empty_accounts[0], zero_balance_contract] } elif test_case == ZeroAmountTestCases.THREE_ONE_WITH_VALUE: withdrawals = all_withdrawals[0:3] post = { account: all_post[account] for account in post if account in [ empty_accounts[0], zero_balance_contract, empty_accounts[1], ] } elif test_case == ZeroAmountTestCases.FOUR_ONE_WITH_MAX: withdrawals = all_withdrawals post = all_post elif test_case == ZeroAmountTestCases.FOUR_ONE_WITH_MAX_REVERSED: for i, w in enumerate(reversed(all_withdrawals)): withdrawals.append( Withdrawal( index=i, validator_index=w.validator_index, address=w.address, amount=w.amount, ) ) post = all_post blockchain_test( pre=pre, # TODO: Fix in BlockchainTest? post: Mapping[str, Account | object] # to allow for Account.NONEXISTENT post=post, blocks=[Block(withdrawals=withdrawals)], tag=test_case.value, ) @pytest.mark.xdist_group(name="bigmem") def test_large_amount( blockchain_test: BlockchainTestFiller, pre: Alloc, ) -> None: """ Test withdrawals that have a large gwei amount. Test such that that (gwei * 1e9) could overflow uint64 but not uint256. """ withdrawals: List[Withdrawal] = [] amounts: List[int] = [ (2**35), (2**64) - 1, (2**63) + 1, (2**63), (2**63) - 1, ] post = {} for i, amount in enumerate(amounts): addr = pre.fund_eoa(0) withdrawals.append( Withdrawal( index=i, validator_index=i, address=addr, amount=amount, ) ) post[addr] = Account(balance=(amount * ONE_GWEI)) blocks = [ Block( withdrawals=withdrawals, ) ] blockchain_test(pre=pre, post=post, blocks=blocks) @pytest.mark.xdist_group(name="bigmem") @pytest.mark.parametrize("amount", [0, 1]) @pytest.mark.with_all_precompiles @pytest.mark.slow() def test_withdrawing_to_precompiles( blockchain_test: BlockchainTestFiller, pre: Alloc, precompile: int, amount: int, t8n: TransitionTool, ) -> None: """Test withdrawing to all precompiles for a given fork.""" sender = pre.fund_eoa() post: Dict = {} blocks = [ # First block performs the withdrawal Block( withdrawals=[ Withdrawal( index=0, validator_index=0, address=Address(precompile), amount=amount, ) ] ), # Second block sends a transaction to the precompile Block( txs=[ Transaction( sender=sender, gas_limit=100000, to=Address(precompile), ), ], ), ] blockchain_test(pre=pre, post=post, blocks=blocks)
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip4895_withdrawals/conftest.py
tests/shanghai/eip4895_withdrawals/conftest.py
"""Fixtures for the EIP-4895 withdrawals tests.""" import pytest from ethereum_test_tools import Alloc, Environment @pytest.fixture def env() -> Environment: """Environment fixture.""" return Environment() @pytest.fixture def post() -> Alloc: """Post state fixture.""" return Alloc()
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip4895_withdrawals/__init__.py
tests/shanghai/eip4895_withdrawals/__init__.py
""" Tests [EIP-4895: Beacon chain withdrawals](https://eips.ethereum.org/EIPS/eip-4895). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3651_warm_coinbase/spec.py
tests/shanghai/eip3651_warm_coinbase/spec.py
"""Defines EIP-3651 specification constants and functions.""" from dataclasses import dataclass @dataclass(frozen=True) class ReferenceSpec: """Defines the reference spec version and git path.""" git_path: str version: str ref_spec_3651 = ReferenceSpec("EIPS/eip-3651.md", "d94c694c6f12291bb6626669c3e8587eef3adff1")
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3651_warm_coinbase/conftest.py
tests/shanghai/eip3651_warm_coinbase/conftest.py
"""Fixtures for the EIP-3651 warm coinbase tests.""" import pytest from ethereum_test_tools import Alloc, Environment @pytest.fixture def env() -> Environment: """Environment fixture.""" return Environment() @pytest.fixture def post() -> Alloc: """Post state fixture.""" return Alloc()
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false
ethereum/execution-spec-tests
https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/shanghai/eip3651_warm_coinbase/__init__.py
tests/shanghai/eip3651_warm_coinbase/__init__.py
""" Tests for [EIP-3651: Warm COINBASE](https://eips.ethereum.org/EIPS/eip-3651). """
python
MIT
88e9fb8f10ed89805aa3110d0a2cd5dcadc19689
2026-01-05T06:50:32.790998Z
false