Repository: ethereum/execution-spec-tests
Pull request #1499: Dynamic contract creation
Author: login: marioevz
Created: 2025-04-25T20:52:03Z | Merged: 2025-04-30T22:16:15Z

@jsign I added the dynamic contract creation to your PR.

Basically we insert as many blocks as necessary to deploy contracts from that won't be there in the genesis.

The only three contracts in genesis are the factory, a contract that contains the initcode, and an entry point that calls the factory.

If we want to exhaust the gas using `EXTCODEHASH`/`EXTCODESIZE`, we need about 13,822 contracts deployed and these take around 1,974 blocks to be deployed.

Furthermore, the generated test does contain the contracts in the form of the post-allocation verification, so the fixture is a couple hundred of megabytes even when these contracts are not in the pre-allocation.


Diff:
diff --git a/src/ethereum_test_tools/__init__.py b/src/ethereum_test_tools/__init__.py
index 1f77641daab..39c7f585cdb 100644
--- a/src/ethereum_test_tools/__init__.py
+++ b/src/ethereum_test_tools/__init__.py
@@ -79,6 +79,7 @@
     Conditional,
     Initcode,
     Switch,
+    While,
     Yul,
     YulCompiler,
 )
@@ -145,6 +146,7 @@
     "TransactionTest",
     "TransactionTestFiller",
     "UndefinedOpcodes",
+    "While",
     "Withdrawal",
     "WithdrawalRequest",
     "Yul",
diff --git a/src/ethereum_test_tools/code/__init__.py b/src/ethereum_test_tools/code/__init__.py
index 75aa8dfa2e5..da1c4bf3693 100644
--- a/src/ethereum_test_tools/code/__init__.py
+++ b/src/ethereum_test_tools/code/__init__.py
@@ -1,16 +1,17 @@
 """Code related utilities and classes."""
 
-from .generators import CalldataCase, Case, CodeGasMeasure, Conditional, Initcode, Switch
+from .generators import CalldataCase, Case, CodeGasMeasure, Conditional, Initcode, Switch, While
 from .yul import Solc, Yul, YulCompiler
 
 __all__ = (
-    "Case",
     "CalldataCase",
+    "Case",
     "CodeGasMeasure",
     "Conditional",
     "Initcode",
     "Solc",
     "Switch",
+    "While",
     "Yul",
     "YulCompiler",
 )
diff --git a/src/ethereum_test_tools/code/generators.py b/src/ethereum_test_tools/code/generators.py
index f40eebc6082..dfff1762bb5 100644
--- a/src/ethereum_test_tools/code/generators.py
+++ b/src/ethereum_test_tools/code/generators.py
@@ -237,6 +237,33 @@ def __new__(
         return super().__new__(cls, bytecode)
 
 
+class While(Bytecode):
+    """Helper class used to generate while-loop bytecode."""
+
+    def __new__(
+        cls,
+        *,
+        body: Bytecode | Op,
+        condition: Bytecode | Op,
+        evm_code_type: EVMCodeType = EVMCodeType.LEGACY,
+    ):
+        """
+        Assemble the loop bytecode.
+
+        The condition nor the body can leave a stack item on the stack.
+        """
+        bytecode = Bytecode()
+        if evm_code_type == EVMCodeType.LEGACY:
+            bytecode += Op.JUMPDEST
+            bytecode += body
+            bytecode += Op.JUMPI(
+                Op.SUB(Op.PC, Op.PUSH4[len(body) + len(condition) + 6]), condition
+            )
+        elif evm_code_type == EVMCodeType.EOF_V1:
+            raise NotImplementedError("EOF while loops are not implemented")
+        return super().__new__(cls, bytecode)
+
+
 @dataclass(kw_only=True)
 class Case:
     """
diff --git a/tests/zkevm/test_worst_bytecode.py b/tests/zkevm/test_worst_bytecode.py
index ac342893bd1..d28dfa64e27 100644
--- a/tests/zkevm/test_worst_bytecode.py
+++ b/tests/zkevm/test_worst_bytecode.py
@@ -8,59 +8,172 @@
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import Alloc, Block, BlockchainTestFiller, Environment, Transaction
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
-MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600 + 2)
+MAX_CONTRACT_SIZE = 24 * 1024  # TODO: This could be a fork property
+BLOCK_GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+# OPCODE_GAS_LIMIT = BLOCK_GAS_LIMIT  # TODO: Reduced in order to run the test in a reasonable time
+OPCODE_GAS_LIMIT = 100_000
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts: int,
+    opcode: Op,
 ):
-    """Test a block execution calling contracts with the maximum size of bytecode."""
-    env = Environment(gas_limit=GAS_LIMIT)
+    """
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        contract_addrs.append(
-            pre.deploy_contract(code=Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i))
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
+    """
+    env = Environment(gas_limit=BLOCK_GAS_LIMIT)
+
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
+            body=(
+                Op.SHA3(Op.SUB(Op.MSIZE, 32), 32)
+                # Use a xor table to avoid having to call the "expensive" sha3 opcode as much
+                + sum(
+                    (Op.PUSH32[xor_value] + Op.XOR + Op.DUP1 + Op.MSIZE + Op.MSTORE)
+                    for xor_value in XOR_TABLE
+                )
+                + Op.POP
+            ),
+            condition=Op.LT(Op.MSIZE, MAX_CONTRACT_SIZE),
+        )
+        + Op.RETURN(0, MAX_CONTRACT_SIZE)
+    )
+    initcode_address = pre.deploy_contract(code=initcode)
+
+    # The factory contract will simply use the initcode that is already deployed,
+    # and create a new contract and return its address if successful.
+    factory_code = (
+        Op.EXTCODECOPY(
+            address=initcode_address,
+            dest_offset=0,
+            offset=0,
+            size=Op.EXTCODESIZE(initcode_address),
+        )
+        + Op.MSTORE(
+            0,
+            Op.CREATE(
+                value=0,
+                offset=0,
+                size=Op.MSIZE,
+            ),
         )
+        + Op.RETURN(0, 32)
+    )
+    factory_address = pre.deploy_contract(code=factory_code)
 
-    attack_code = sum(
-        [(Op.EXTCODESIZE(contract_addrs[i]) + Op.POP) for i in range(num_called_contracts)]
+    # The factory caller will call the factory contract N times, creating N new contracts.
+    # Calldata should contain the N value.
+    factory_caller_code = Op.CALLDATALOAD(0) + While(
+        body=Op.POP(Op.CALL(address=factory_address)),
+        condition=Op.PUSH1(1) + Op.SWAP1 + Op.SUB + Op.DUP1 + Op.ISZERO + Op.ISZERO,
     )
-    attack_contract = pre.deploy_contract(code=bytes(attack_code))
+    factory_caller_address = pre.deploy_contract(code=factory_caller_code)
 
-    tx = Transaction(
-        to=attack_contract,
-        gas_limit=GAS_LIMIT,
-        gas_price=10,
+    gas_costs = fork.gas_costs()
+    intrinsic_gas_cost_calc = fork.transaction_intrinsic_cost_calculator()
+    max_number_of_contract_calls = (OPCODE_GAS_LIMIT - intrinsic_gas_cost_calc()) // (
+        gas_costs.G_VERY_LOW + gas_costs.G_BASE + gas_costs.G_COLD_ACCOUNT_ACCESS
+    )
+    total_contracts_to_deploy = max_number_of_contract_calls
+    approximate_gas_per_deployment = 4_970_000  # Obtained from evm tracing
+    contracts_deployed_per_tx = BLOCK_GAS_LIMIT // approximate_gas_per_deployment
+
+    deploy_txs = []
+
+    def generate_deploy_tx(contracts_to_deploy: int):
+        return Transaction(
+            to=factory_caller_address,
+            gas_limit=BLOCK_GAS_LIMIT,
+            gas_price=10**9,  # Bump required due to the amount of full blocks
+            data=Hash(contracts_deployed_per_tx),
+            sender=pre.fund_eoa(),
+        )
+
+    for _ in range(total_contracts_to_deploy // contracts_deployed_per_tx):
+        deploy_txs.append(generate_deploy_tx(contracts_deployed_per_tx))
+
+    if total_contracts_to_deploy % contracts_deployed_per_tx != 0:
+        deploy_txs.append(
+            generate_deploy_tx(total_contracts_to_deploy % contracts_deployed_per_tx)
+        )
+
+    post = {}
+    deployed_contract_addresses = []
+    for i in range(total_contracts_to_deploy):
+        deployed_contract_address = compute_create_address(
+            address=factory_address,
+            nonce=i + 1,
+        )
+        post[deployed_contract_address] = Account(nonce=1)
+        deployed_contract_addresses.append(deployed_contract_address)
+
+    opcode_code = (
+        sum(Op.POP(opcode(address=address)) for address in deployed_contract_addresses) + Op.STOP
+    )
+    if len(opcode_code) > MAX_CONTRACT_SIZE:
+        # TODO: A workaround could be to split the opcode code into multiple contracts
+        # and call them in sequence.
+        raise ValueError(
+            f"Code size {len(opcode_code)} exceeds maximum code size {MAX_CONTRACT_SIZE}"
+        )
+    opcode_address = pre.deploy_contract(code=opcode_code)
+    opcode_tx = Transaction(
+        to=opcode_address,
+        gas_limit=OPCODE_GAS_LIMIT,
+        gas_price=10**9,  # Bump required due to the amount of full blocks
         sender=pre.fund_eoa(),
-        data=[],
-        value=0,
     )
 
     blockchain_test(
-        env=env,
+        genesis_environment=env,
         pre=pre,
-        post={},
-        blocks=[Block(txs=[tx])],
+        post=post,
+        blocks=[
+            *[Block(txs=[deploy_tx]) for deploy_tx in deploy_txs],
+            Block(txs=[opcode_tx]),
+        ],
     )


Reviews:
user: login: jsign
body: This is great! Left some comments for your consideration.
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-25T22:24:30Z
user: login: marioevz
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-28T17:22:54Z
user: login: marioevz
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-28T21:26:54Z
user: login: marioevz
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-28T21:29:56Z

Review comments:
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
path: tests/zkevm/test_worst_bytecode.py
user: login: jsign
body: `Op.EXTCODEHASH` isn't requried for the attack. Actually, is only `Op.EXTCODESIZE` for now, or any cheap way of accesing at least 1 byte of the 24KiB contracts.

`Op.EXTCODEHASH` in particular is not a problem since the code-hash is in the tree. 

So I would say to remove the parametrization of `opcode`. We only need `Op.EXTCODESIZE`.
created_at: 2025-04-25T21:09:29Z
author_association: COLLABORATOR
diff_hunk: @@ -1,3 +1 @@
-"""
-abstract: Tests for zkVMs
-"""
+"""abstract: Tests for zkVMs"""
path: tests/zkevm/__init__.py
user: login: jsign
body: Uhm, this was fixed in the target branch some days ago. Maybe you have to rebase?
created_at: 2025-04-25T21:10:15Z
author_association: COLLABORATOR
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts : int,
+    opcode: Op,
 ):
     """
-    Test a block execution calling contracts with the maximum size of bytecode.
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
+
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
     """
     env = Environment(gas_limit=GAS_LIMIT)
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        code = Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i)
-        contract_addrs.append(pre.deploy_contract(code=code))
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
path: tests/zkevm/test_worst_bytecode.py
user: login: jsign
body: Oh, nice. I didn't know these generators existed, I should probably take a look.
created_at: 2025-04-25T21:14:17Z
author_association: COLLABORATOR
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts : int,
+    opcode: Op,
 ):
     """
-    Test a block execution calling contracts with the maximum size of bytecode.
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
+
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
     """
     env = Environment(gas_limit=GAS_LIMIT)
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        code = Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i)
-        contract_addrs.append(pre.deploy_contract(code=code))
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
+            body=(
+                Op.SHA3(Op.SUB(Op.MSIZE, 32), 32)
+                # Use a xor table to avoid having to call the "expensive" sha3 opcode as much
+                + sum(
+                    (Op.PUSH32[xor_value] + Op.XOR + Op.DUP1 + Op.MSIZE + Op.MSTORE)
+                    for xor_value in XOR_TABLE
+                )
+                + Op.POP
+            ),
+            condition=Op.LT(Op.MSIZE, MAX_CONTRACT_SIZE),
+        )
+        + Op.RETURN(0, MAX_CONTRACT_SIZE)
+    )
+    initcode_address = pre.deploy_contract(code=initcode)
+
+    # The factory contract will simply use the initcode that is already deployed,
+    # and create a new contract and return its address if successful.
+    factory_code = (
+        Op.EXTCODECOPY(
+            address=initcode_address,
+            dest_offset=0,
+            offset=0,
+            size=Op.EXTCODESIZE(initcode_address),
+        )
+        + Op.MSTORE(
+            0,
+            Op.CREATE(
+                value=0,
+                offset=0,
+                size=Op.MSIZE,
+            ),
+        )
+        + Op.RETURN(0, 32)
+    )
+    factory_address = pre.deploy_contract(code=factory_code)
+
+    # The factory caller will call the factory contract N times, creating N new contracts.
+    # Calldata should contain the N value.
+    factory_caller_code = Op.CALLDATALOAD(0) + While(
+        body=Op.POP(Op.CALL(address=factory_address)),
+        condition=Op.PUSH1(1) + Op.SWAP1 + Op.SUB + Op.DUP1 + Op.ISZERO + Op.ISZERO,
+    )
+    factory_caller_address = pre.deploy_contract(code=factory_caller_code)
+
+    # TODO: The correct way to calculate this is to use the gas costs and the transaction
+    # intrinsic cost calculator, but this is generating approx 13,822 calls, and deploying this
+    # many different contracts requires 1,974 blocks.
+    # gas_costs = fork.gas_costs()
+    # intrinsic_gas_cost_calc = fork.transaction_intrinsic_cost_calculator()
+    # max_number_of_contract_calls = (GAS_LIMIT - intrinsic_gas_cost_calc()) // (
+    #     gas_costs.G_VERY_LOW + gas_costs.G_BASE + gas_costs.G_COLD_ACCOUNT_ACCESS
+    # )
path: tests/zkevm/test_worst_bytecode.py
user: login: jsign
body: Ah, much better. What if we uncomment this, and parametrize the `gas_limit` but instead of putting 36M we can start with 1M? (or whatever equivalent to a result of `max_number_of_contracts_calls = 10`.

So the only thing to tune is the parameter of gas limit?
created_at: 2025-04-25T21:56:04Z
author_association: COLLABORATOR
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts : int,
+    opcode: Op,
 ):
     """
-    Test a block execution calling contracts with the maximum size of bytecode.
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
+
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
     """
     env = Environment(gas_limit=GAS_LIMIT)
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        code = Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i)
-        contract_addrs.append(pre.deploy_contract(code=code))
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
+            body=(
+                Op.SHA3(Op.SUB(Op.MSIZE, 32), 32)
+                # Use a xor table to avoid having to call the "expensive" sha3 opcode as much
+                + sum(
+                    (Op.PUSH32[xor_value] + Op.XOR + Op.DUP1 + Op.MSIZE + Op.MSTORE)
+                    for xor_value in XOR_TABLE
+                )
+                + Op.POP
+            ),
+            condition=Op.LT(Op.MSIZE, MAX_CONTRACT_SIZE),
+        )
+        + Op.RETURN(0, MAX_CONTRACT_SIZE)
+    )
+    initcode_address = pre.deploy_contract(code=initcode)
+
+    # The factory contract will simply use the initcode that is already deployed,
+    # and create a new contract and return its address if successful.
+    factory_code = (
+        Op.EXTCODECOPY(
+            address=initcode_address,
+            dest_offset=0,
+            offset=0,
+            size=Op.EXTCODESIZE(initcode_address),
+        )
+        + Op.MSTORE(
+            0,
+            Op.CREATE(
+                value=0,
+                offset=0,
+                size=Op.MSIZE,
+            ),
+        )
+        + Op.RETURN(0, 32)
+    )
+    factory_address = pre.deploy_contract(code=factory_code)
+
+    # The factory caller will call the factory contract N times, creating N new contracts.
+    # Calldata should contain the N value.
+    factory_caller_code = Op.CALLDATALOAD(0) + While(
+        body=Op.POP(Op.CALL(address=factory_address)),
+        condition=Op.PUSH1(1) + Op.SWAP1 + Op.SUB + Op.DUP1 + Op.ISZERO + Op.ISZERO,
+    )
+    factory_caller_address = pre.deploy_contract(code=factory_caller_code)
+
+    # TODO: The correct way to calculate this is to use the gas costs and the transaction
+    # intrinsic cost calculator, but this is generating approx 13,822 calls, and deploying this
+    # many different contracts requires 1,974 blocks.
+    # gas_costs = fork.gas_costs()
+    # intrinsic_gas_cost_calc = fork.transaction_intrinsic_cost_calculator()
+    # max_number_of_contract_calls = (GAS_LIMIT - intrinsic_gas_cost_calc()) // (
+    #     gas_costs.G_VERY_LOW + gas_costs.G_BASE + gas_costs.G_COLD_ACCOUNT_ACCESS
+    # )
+    max_number_of_contract_calls = 10
+    total_contracts_to_deploy = max_number_of_contract_calls
+    approximate_gas_per_deployment = 4_970_000  # Obtained from evm tracing
+    contracts_deployed_per_tx = GAS_LIMIT // approximate_gas_per_deployment
+
+    deploy_txs = []
+
+    def generate_deploy_tx(contracts_to_deploy: int):
+        return Transaction(
+            to=factory_caller_address,
+            gas_limit=GAS_LIMIT,
+            gas_price=10**9,  # Bump required due to the amount of full blocks
+            data=Hash(contracts_deployed_per_tx),
+            sender=pre.fund_eoa(),
+        )
+
+    for _ in range(total_contracts_to_deploy // contracts_deployed_per_tx):
+        deploy_txs.append(generate_deploy_tx(contracts_deployed_per_tx))
+
+    if total_contracts_to_deploy % contracts_deployed_per_tx != 0:
+        deploy_txs.append(
+            generate_deploy_tx(total_contracts_to_deploy % contracts_deployed_per_tx)
+        )
 
-    attack_code = sum([Op.EXTCODESIZE(contract_addrs[i]) for i in range(num_called_contracts)])
-    attack_contract = pre.deploy_contract(code=attack_code)
+    post = {}
+    deployed_contract_addresses = []
+    for i in range(total_contracts_to_deploy):
+        deployed_contract_address = compute_create_address(
+            address=factory_address,
+            nonce=i + 1,
+        )
+        post[deployed_contract_address] = Account(nonce=1)
+        deployed_contract_addresses.append(deployed_contract_address)
 
-    tx = Transaction(
-        to=attack_contract,
+    opcode_code = sum(opcode(address=address) for address in deployed_contract_addresses) + Op.STOP
path: tests/zkevm/test_worst_bytecode.py
user: login: jsign
body: ```suggestion
    opcode_code = sum((opcode(address=address) + Op.POP) for address in deployed_contract_addresses) + Op.STOP
```
to avoid a stack overflow.
created_at: 2025-04-25T22:01:11Z
author_association: COLLABORATOR
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts : int,
+    opcode: Op,
 ):
     """
-    Test a block execution calling contracts with the maximum size of bytecode.
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
+
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
     """
     env = Environment(gas_limit=GAS_LIMIT)
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        code = Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i)
-        contract_addrs.append(pre.deploy_contract(code=code))
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
+            body=(
+                Op.SHA3(Op.SUB(Op.MSIZE, 32), 32)
+                # Use a xor table to avoid having to call the "expensive" sha3 opcode as much
+                + sum(
+                    (Op.PUSH32[xor_value] + Op.XOR + Op.DUP1 + Op.MSIZE + Op.MSTORE)
+                    for xor_value in XOR_TABLE
+                )
+                + Op.POP
+            ),
+            condition=Op.LT(Op.MSIZE, MAX_CONTRACT_SIZE),
+        )
+        + Op.RETURN(0, MAX_CONTRACT_SIZE)
+    )
+    initcode_address = pre.deploy_contract(code=initcode)
+
+    # The factory contract will simply use the initcode that is already deployed,
+    # and create a new contract and return its address if successful.
+    factory_code = (
+        Op.EXTCODECOPY(
+            address=initcode_address,
+            dest_offset=0,
+            offset=0,
+            size=Op.EXTCODESIZE(initcode_address),
+        )
+        + Op.MSTORE(
+            0,
+            Op.CREATE(
+                value=0,
+                offset=0,
+                size=Op.MSIZE,
+            ),
+        )
+        + Op.RETURN(0, 32)
+    )
+    factory_address = pre.deploy_contract(code=factory_code)
+
+    # The factory caller will call the factory contract N times, creating N new contracts.
+    # Calldata should contain the N value.
+    factory_caller_code = Op.CALLDATALOAD(0) + While(
+        body=Op.POP(Op.CALL(address=factory_address)),
+        condition=Op.PUSH1(1) + Op.SWAP1 + Op.SUB + Op.DUP1 + Op.ISZERO + Op.ISZERO,
+    )
+    factory_caller_address = pre.deploy_contract(code=factory_caller_code)
+
+    # TODO: The correct way to calculate this is to use the gas costs and the transaction
+    # intrinsic cost calculator, but this is generating approx 13,822 calls, and deploying this
+    # many different contracts requires 1,974 blocks.
+    # gas_costs = fork.gas_costs()
+    # intrinsic_gas_cost_calc = fork.transaction_intrinsic_cost_calculator()
+    # max_number_of_contract_calls = (GAS_LIMIT - intrinsic_gas_cost_calc()) // (
+    #     gas_costs.G_VERY_LOW + gas_costs.G_BASE + gas_costs.G_COLD_ACCOUNT_ACCESS
+    # )
+    max_number_of_contract_calls = 10
+    total_contracts_to_deploy = max_number_of_contract_calls
+    approximate_gas_per_deployment = 4_970_000  # Obtained from evm tracing
+    contracts_deployed_per_tx = GAS_LIMIT // approximate_gas_per_deployment
+
+    deploy_txs = []
+
+    def generate_deploy_tx(contracts_to_deploy: int):
+        return Transaction(
+            to=factory_caller_address,
+            gas_limit=GAS_LIMIT,
+            gas_price=10**9,  # Bump required due to the amount of full blocks
+            data=Hash(contracts_deployed_per_tx),
+            sender=pre.fund_eoa(),
+        )
+
+    for _ in range(total_contracts_to_deploy // contracts_deployed_per_tx):
+        deploy_txs.append(generate_deploy_tx(contracts_deployed_per_tx))
+
+    if total_contracts_to_deploy % contracts_deployed_per_tx != 0:
+        deploy_txs.append(
+            generate_deploy_tx(total_contracts_to_deploy % contracts_deployed_per_tx)
+        )
 
-    attack_code = sum([Op.EXTCODESIZE(contract_addrs[i]) for i in range(num_called_contracts)])
-    attack_contract = pre.deploy_contract(code=attack_code)
+    post = {}
+    deployed_contract_addresses = []
+    for i in range(total_contracts_to_deploy):
+        deployed_contract_address = compute_create_address(
+            address=factory_address,
+            nonce=i + 1,
+        )
+        post[deployed_contract_address] = Account(nonce=1)
+        deployed_contract_addresses.append(deployed_contract_address)
 
-    tx = Transaction(
-        to=attack_contract,
+    opcode_code = sum(opcode(address=address) for address in deployed_contract_addresses) + Op.STOP
+    opcode_address = pre.deploy_contract(code=opcode_code)
path: tests/zkevm/test_worst_bytecode.py
user: login: jsign
body: I think we need a TODO here (and potentially add an assertion).

For the actual worst case, the would be 13k calls, but that `EXTCODESIZE(address)+POP` is 20+1+1 bytes, so that means takes 13k*22~=286KiB which is bigger than the contract size.

As a sanity check, I would add:
```
if len(opcode_code) > MAX_CODE_SIZE:
        raise ValueError(f"Code size {len(code)} exceeds maximum code size {MAX_CODE_SIZE}")
```
No?

And a TODO to think of a way of working around this limitation. Feels to me we might need to switch to storing the addresses in storage slots and doing some SLOAD+EXTCODESIZE. 

Edit1: Or maybe providing them via CALLDATA, since new costs in Pectra is 40 per byte so 20 bytes is 800gas vs 2100 from SLOAD.

Edit2: Actually, I think the optimal is more like keeping this PUSH20+EXTCODESIZE+POP, but at the end of the contract chain a CALL to another attack contract of the same style, and have a chain of calls. That way you work around the max contract size limit while still benefiting from cheap PUSH20.

BTW, no need to solve this in this PR. Sharing my thinking to double check, I can iterate on this after.
created_at: 2025-04-25T22:14:30Z
author_association: COLLABORATOR
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts : int,
+    opcode: Op,
 ):
     """
-    Test a block execution calling contracts with the maximum size of bytecode.
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
+
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
     """
     env = Environment(gas_limit=GAS_LIMIT)
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        code = Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i)
-        contract_addrs.append(pre.deploy_contract(code=code))
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
path: tests/zkevm/test_worst_bytecode.py
user: login: marioevz
body: It did not exist 😉

It's added in this commit https://github.com/ethereum/execution-spec-tests/pull/1499/commits/a736ea0d7bcf13de7e47d06fed0c4dd27fbd90ac

But perhaps a better idea is to open a separate PR for this.
created_at: 2025-04-28T17:22:54Z
author_association: MEMBER
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts : int,
+    opcode: Op,
 ):
     """
-    Test a block execution calling contracts with the maximum size of bytecode.
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
+
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
     """
     env = Environment(gas_limit=GAS_LIMIT)
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        code = Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i)
-        contract_addrs.append(pre.deploy_contract(code=code))
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
+            body=(
+                Op.SHA3(Op.SUB(Op.MSIZE, 32), 32)
+                # Use a xor table to avoid having to call the "expensive" sha3 opcode as much
+                + sum(
+                    (Op.PUSH32[xor_value] + Op.XOR + Op.DUP1 + Op.MSIZE + Op.MSTORE)
+                    for xor_value in XOR_TABLE
+                )
+                + Op.POP
+            ),
+            condition=Op.LT(Op.MSIZE, MAX_CONTRACT_SIZE),
+        )
+        + Op.RETURN(0, MAX_CONTRACT_SIZE)
+    )
+    initcode_address = pre.deploy_contract(code=initcode)
+
+    # The factory contract will simply use the initcode that is already deployed,
+    # and create a new contract and return its address if successful.
+    factory_code = (
+        Op.EXTCODECOPY(
+            address=initcode_address,
+            dest_offset=0,
+            offset=0,
+            size=Op.EXTCODESIZE(initcode_address),
+        )
+        + Op.MSTORE(
+            0,
+            Op.CREATE(
+                value=0,
+                offset=0,
+                size=Op.MSIZE,
+            ),
+        )
+        + Op.RETURN(0, 32)
+    )
+    factory_address = pre.deploy_contract(code=factory_code)
+
+    # The factory caller will call the factory contract N times, creating N new contracts.
+    # Calldata should contain the N value.
+    factory_caller_code = Op.CALLDATALOAD(0) + While(
+        body=Op.POP(Op.CALL(address=factory_address)),
+        condition=Op.PUSH1(1) + Op.SWAP1 + Op.SUB + Op.DUP1 + Op.ISZERO + Op.ISZERO,
+    )
+    factory_caller_address = pre.deploy_contract(code=factory_caller_code)
+
+    # TODO: The correct way to calculate this is to use the gas costs and the transaction
+    # intrinsic cost calculator, but this is generating approx 13,822 calls, and deploying this
+    # many different contracts requires 1,974 blocks.
+    # gas_costs = fork.gas_costs()
+    # intrinsic_gas_cost_calc = fork.transaction_intrinsic_cost_calculator()
+    # max_number_of_contract_calls = (GAS_LIMIT - intrinsic_gas_cost_calc()) // (
+    #     gas_costs.G_VERY_LOW + gas_costs.G_BASE + gas_costs.G_COLD_ACCOUNT_ACCESS
+    # )
path: tests/zkevm/test_worst_bytecode.py
user: login: marioevz
body: Got it, I split this into two like so:
```python
BLOCK_GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
# OPCODE_GAS_LIMIT = BLOCK_GAS_LIMIT  # TODO: Reduced in order to run the test in a reasonable time
OPCODE_GAS_LIMIT = 100_000
```
Now the block gas limit is separate from the opcode gas limit, but at some point they could be the same (but this would yield the test with hundreds of mb of information).
created_at: 2025-04-28T21:26:54Z
author_association: MEMBER
diff_hunk: @@ -1,59 +1,172 @@
+"""
+Test for zkevm worst case scenarios of overuse of specific opcodes that are expensive
+to execute.
+"""
+
 import pytest
 
 from ethereum_test_forks import Fork
-from ethereum_test_tools import (Alloc, Block, BlockchainTestFiller,
-                                 Environment, Transaction)
+from ethereum_test_tools import (
+    Account,
+    Alloc,
+    Block,
+    BlockchainTestFiller,
+    Environment,
+    Hash,
+    Transaction,
+    While,
+    compute_create_address,
+)
 from ethereum_test_tools.vm.opcode import Opcodes as Op
 
 REFERENCE_SPEC_GIT_PATH = "TODO"
 REFERENCE_SPEC_VERSION = "TODO"
 
 MAX_CONTRACT_SIZE = 24 * 1024
-GAS_LIMIT = 36_000_000
-MAX_NUM_CONTRACT_CALLS = (GAS_LIMIT - 21_000) // (3 + 2600)
+GAS_LIMIT = 36_000_000  # TODO: Parametrize using the (yet to be implemented) block gas limit
+
+XOR_TABLE_SIZE = 256
+XOR_TABLE = [Hash(i).sha256() for i in range(XOR_TABLE_SIZE)]
 
 
+# TODO: Parametrize for EOF
 @pytest.mark.zkevm
-@pytest.mark.valid_from("Cancun")
 @pytest.mark.parametrize(
-    "num_called_contracts",
+    "opcode",
     [
-        1,
-        # 10,
-        # MAX_NUM_CONTRACT_CALLS
+        Op.EXTCODESIZE,
+        Op.EXTCODEHASH,
     ],
 )
-def test_worst_bytecode(
+@pytest.mark.valid_from("Cancun")
+def test_worst_bytecode_single_opcode(
     blockchain_test: BlockchainTestFiller,
     pre: Alloc,
     fork: Fork,
-    num_called_contracts : int,
+    opcode: Op,
 ):
     """
-    Test a block execution calling contracts with the maximum size of bytecode.
+    Test a block execution where a single opcode execution maxes out the gas limit,
+    and the opcodes access a huge amount of contract code.
+
+    We first use a single block to deploy a factory contract that will be used to deploy
+    a large number of contracts.
+
+    This is done to avoid having a big pre-allocation size for the test.
+
+    The test is performed in the last block of the test, and the entire block gas limit is
+    consumed by repeated opcode executions.
     """
     env = Environment(gas_limit=GAS_LIMIT)
 
-    contract_addrs = []
-    for i in range(num_called_contracts):
-        code = Op.JUMPDEST * (MAX_CONTRACT_SIZE - 1 - 10) + Op.PUSH10(i)
-        contract_addrs.append(pre.deploy_contract(code=code))
+    # The initcode will take its address as a starting point to the input to the keccak
+    # hash function.
+    # It will reuse the output of the hash function in a loop to create a large amount of
+    # seemingly random code, until it reaches the maximum contract size.
+    initcode = (
+        Op.MSTORE(0, Op.ADDRESS)
+        + While(
+            body=(
+                Op.SHA3(Op.SUB(Op.MSIZE, 32), 32)
+                # Use a xor table to avoid having to call the "expensive" sha3 opcode as much
+                + sum(
+                    (Op.PUSH32[xor_value] + Op.XOR + Op.DUP1 + Op.MSIZE + Op.MSTORE)
+                    for xor_value in XOR_TABLE
+                )
+                + Op.POP
+            ),
+            condition=Op.LT(Op.MSIZE, MAX_CONTRACT_SIZE),
+        )
+        + Op.RETURN(0, MAX_CONTRACT_SIZE)
+    )
+    initcode_address = pre.deploy_contract(code=initcode)
+
+    # The factory contract will simply use the initcode that is already deployed,
+    # and create a new contract and return its address if successful.
+    factory_code = (
+        Op.EXTCODECOPY(
+            address=initcode_address,
+            dest_offset=0,
+            offset=0,
+            size=Op.EXTCODESIZE(initcode_address),
+        )
+        + Op.MSTORE(
+            0,
+            Op.CREATE(
+                value=0,
+                offset=0,
+                size=Op.MSIZE,
+            ),
+        )
+        + Op.RETURN(0, 32)
+    )
+    factory_address = pre.deploy_contract(code=factory_code)
+
+    # The factory caller will call the factory contract N times, creating N new contracts.
+    # Calldata should contain the N value.
+    factory_caller_code = Op.CALLDATALOAD(0) + While(
+        body=Op.POP(Op.CALL(address=factory_address)),
+        condition=Op.PUSH1(1) + Op.SWAP1 + Op.SUB + Op.DUP1 + Op.ISZERO + Op.ISZERO,
+    )
+    factory_caller_address = pre.deploy_contract(code=factory_caller_code)
+
+    # TODO: The correct way to calculate this is to use the gas costs and the transaction
+    # intrinsic cost calculator, but this is generating approx 13,822 calls, and deploying this
+    # many different contracts requires 1,974 blocks.
+    # gas_costs = fork.gas_costs()
+    # intrinsic_gas_cost_calc = fork.transaction_intrinsic_cost_calculator()
+    # max_number_of_contract_calls = (GAS_LIMIT - intrinsic_gas_cost_calc()) // (
+    #     gas_costs.G_VERY_LOW + gas_costs.G_BASE + gas_costs.G_COLD_ACCOUNT_ACCESS
+    # )
+    max_number_of_contract_calls = 10
+    total_contracts_to_deploy = max_number_of_contract_calls
+    approximate_gas_per_deployment = 4_970_000  # Obtained from evm tracing
+    contracts_deployed_per_tx = GAS_LIMIT // approximate_gas_per_deployment
+
+    deploy_txs = []
+
+    def generate_deploy_tx(contracts_to_deploy: int):
+        return Transaction(
+            to=factory_caller_address,
+            gas_limit=GAS_LIMIT,
+            gas_price=10**9,  # Bump required due to the amount of full blocks
+            data=Hash(contracts_deployed_per_tx),
+            sender=pre.fund_eoa(),
+        )
+
+    for _ in range(total_contracts_to_deploy // contracts_deployed_per_tx):
+        deploy_txs.append(generate_deploy_tx(contracts_deployed_per_tx))
+
+    if total_contracts_to_deploy % contracts_deployed_per_tx != 0:
+        deploy_txs.append(
+            generate_deploy_tx(total_contracts_to_deploy % contracts_deployed_per_tx)
+        )
 
-    attack_code = sum([Op.EXTCODESIZE(contract_addrs[i]) for i in range(num_called_contracts)])
-    attack_contract = pre.deploy_contract(code=attack_code)
+    post = {}
+    deployed_contract_addresses = []
+    for i in range(total_contracts_to_deploy):
+        deployed_contract_address = compute_create_address(
+            address=factory_address,
+            nonce=i + 1,
+        )
+        post[deployed_contract_address] = Account(nonce=1)
+        deployed_contract_addresses.append(deployed_contract_address)
 
-    tx = Transaction(
-        to=attack_contract,
+    opcode_code = sum(opcode(address=address) for address in deployed_contract_addresses) + Op.STOP
+    opcode_address = pre.deploy_contract(code=opcode_code)
path: tests/zkevm/test_worst_bytecode.py
user: login: marioevz
body: Excellent observation, yes I think the last edit should be the way to go, I'm going to add the assertion to check for the size of `opcode_code` in this PR since it's the simplest.
created_at: 2025-04-28T21:29:55Z
author_association: MEMBER

PR comments:
user: login: marioevz
created_at: 2025-04-28T22:40:17Z
body: @spencer-tb there seems to be an issue when generating the documentation for this PR because `zkevm` isn't actually a fork, could you please take a look? 🙏 
author_association: MEMBER
user: login: spencer-tb
created_at: 2025-04-30T17:55:21Z
body: > @spencer-tb there seems to be an issue when generating the documentation for this PR because `zkevm` isn't actually a fork, could you please take a look? 🙏

https://github.com/ethereum/execution-spec-tests/pull/1517 should fix the issue :)
author_association: COLLABORATOR