### Transaction Environment Setup Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/bpo4/bpo5/fork.py.html Creates the transaction environment for execution. ```python tx_env = vm.TransactionEnvironment( origin=sender, gas_price=effective_gas_price, gas=gas, access_list_addresses=access_list_addresses, access_list_storage_keys=access_list_storage_keys, state=tx_state, blob_versioned_hashes=blob_versioned_hashes, authorizations=authorizations, index_in_block=index, tx_hash=get_transaction_hash(encode_transaction(tx)), ) ``` -------------------------------- ### Start interactive ipython session Source: https://steel.ethereum.foundation/docs/execution-specs/dev/interactive_usage Launches an ipython shell with EEST packages installed in editable mode. ```bash uvx --with-editable . ipython ``` -------------------------------- ### Extracting Configurations from Fixtures Source: https://steel.ethereum.foundation/docs/execution-specs/library/cli/extract_config Examples demonstrating how to target specific fixtures, individual clients, or entire directories. ```bash uv run extract_config --fixture fixtures/blockchain_tests/paris/security/test_selfdestruct_balance_bug.json ``` ```bash uv run extract_config --fixture fixtures/blockchain_tests/paris/security/test_selfdestruct_balance_bug.json --client besu ``` ```bash uv run extract_config --fixture fixtures/blockchain_tests/paris/security/ ``` ```bash uv run extract_config --fixture my_fixture.json --output ./my_configs --list-files ``` -------------------------------- ### Consume with Release Specifications Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/consume/cache Examples of using release names and versions to specify test fixtures. ```bash # Latest mainnet (tests) release uv run consume engine --input latest uv run consume rlp --input tests@latest # Mainnet release by version uv run consume engine --input v20.0.0 uv run consume rlp --input tests@v20.0.0 # Feature releases, with or without the tests- tag prefix uv run consume cache --input bal-devnet@v7.0.0 uv run consume cache --input glamsterdam-devnet@latest uv run consume direct --input tests-bal@v7.3.2 --bin ../go-ethereum/build/bin/evm ``` -------------------------------- ### Example Block Structure Source: https://steel.ethereum.foundation/docs/execution-specs/writing_tests/tutorials/blockchain An example of the resulting block list structure. ```python blocks = [ Blocks(txs=[]), Blocks(txs=[next(tx_generator), next(tx_generator)]), Blocks(txs=[next(tx_generator), next(tx_generator), next(tx_generator), next(tx_generator)]) ] ``` -------------------------------- ### Install act extension Source: https://steel.ethereum.foundation/docs/execution-specs/dev/test_actions_locally Installs the nektos/act tool as a Github CLI extension. ```bash gh extension install https://github.com/nektos/gh-act ``` -------------------------------- ### Example env.yaml structure Source: https://steel.ethereum.foundation/docs/execution-specs/dev/configurations The environment configuration file supports remote node definitions and RPC headers. ```yaml remote_nodes: - name: mainnet_archive # Replace with your Ethereum RPC node URL node_url: http://example.com # Optional: Headers for RPC requests rpc_headers: client-secret: ``` -------------------------------- ### Checklist Output Format Example Source: https://steel.ethereum.foundation/docs/execution-specs/writing_tests/eip_checklist An example of the generated markdown output showing progress tracking and item status. ```markdown # EIP-7702 Test Checklist ## Checklist Progress Tracker | Total Checklist Items | Covered Checklist Items | Percentage | | --------------------- | ----------------------- | ---------- | | 45 | 32 | ๐ŸŸก 71.11% | ## General #### Code coverage | ID | Description | Status | Tests | | -- | ----------- | ------ | ----- | | `general/code_coverage/eels` | Run produced tests against EELS... | โœ… | Covered by EELS test suite | | `general/code_coverage/test_coverage` | Run coverage on the test code itself... | โœ… | `tests/prague/eip7702_set_code_tx/test_set_code_txs.py::test_set_code_txs` | ## Transaction Type | ID | Description | Status | Tests | | -- | ----------- | ------ | ----- | | `transaction_type/test/intrinsic_validity/gas_limit/exact` | Provide the exact intrinsic gas... | โœ… | `tests/prague/eip7702_set_code_tx/test_checklist_example.py::test_exact_intrinsic_gas` | | `transaction_type/test/intrinsic_validity/gas_limit/insufficient` | Provide the exact intrinsic gas minus one... | | | ## System Contract | ID | Description | Status | Tests | | -- | ----------- | ------ | ----- | | `system_contract/test/deployment/missing` | Verify block execution behavior... | N/A | EIP-7702 does not introduce a system contract | ``` -------------------------------- ### Test specific network clients Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/execute/eth_config Examples for testing Mainnet and Sepolia clients. ```bash uv run execute eth-config --network Mainnet --rpc-endpoint http://localhost:8545 ``` ```bash uv run execute eth-config --network Sepolia --rpc-endpoint http://localhost:8545 ``` -------------------------------- ### Expected output for fixture download Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/consume/cache Example output showing the cached path and source URL for a fixture release. ```text Path: /home/dtopz/.cache/ethereum-execution-spec-tests/cached_downloads/ethereum/execution-specs/tests%40v20.0.0/fixtures/fixtures Input: https://github.com/ethereum/execution-specs/releases/download/tests%40v20.0.0/fixtures.tar.gz Release page: https://github.com/ethereum/execution-specs/releases/tag/tests%40v20.0.0 ``` -------------------------------- ### Serve Documentation Locally Source: https://steel.ethereum.foundation/docs/execution-specs/dev/docs Starts a local development server with live reloading. Use the fast variant to skip the Test Case Reference generation. ```bash just docs-serve # full build just docs-serve-fast # skips the Test Case Reference, faster iteration ``` -------------------------------- ### Install uv package manager Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/consume/cache Installs the uv Python package manager via a shell script. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Consume with URL Fixtures Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/consume/cache Examples of using direct URLs to .tar.gz archives for test fixtures. ```bash # GitHub release URL uv run consume engine --input https://github.com/ethereum/execution-specs/releases/download/tests%40v20.0.0/fixtures.tar.gz # Direct archive URL uv run consume rlp --input https://example.com/custom-fixtures.tar.gz ``` -------------------------------- ### CREATE2 Stack and Gas Setup Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/paris/shanghai/vm/instructions/system.py.html Pops stack arguments and calculates gas requirements for the CREATE2 opcode. ```python endowment = pop(evm.stack) memory_start_position = pop(evm.stack) memory_size = pop(evm.stack) salt = pop(evm.stack).to_be_bytes32() ``` ```python extend_memory = calculate_gas_extend_memory( evm.memory, [(memory_start_position, memory_size)] ) call_data_words = ceil32(Uint(memory_size)) // Uint(32) init_code_gas = init_code_cost(Uint(memory_size)) charge_gas( evm, GasCosts.OPCODE_CREATE_BASE + GasCosts.OPCODE_KECCAK256_PER_WORD * call_data_words + extend_memory.cost + init_code_gas, ) ``` -------------------------------- ### Run state tests with different clients Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/consume/direct Examples of running state tests from a local fixtures folder using various supported client binaries. ```bash uv run consume direct --input ./fixtures -m state_test --bin=evm ``` ```bash uv run consume direct --input ./fixtures -m state_test --bin=evmtool ``` ```bash uv run consume direct --input ./fixtures -m state_test --bin=nethtest ``` ```bash uv run consume direct --input ./fixtures --bin=evmone-statetest --bin=evmone-blockchaintest ``` -------------------------------- ### Sender Account and Gas Setup Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/muir_glacier/berlin/fork.py.html Retrieves sender account details and calculates initial gas and balance deductions. ```python sender_account = get_account(tx_state, sender) ``` ```python gas = tx.gas - intrinsic_gas increment_nonce(tx_state, sender) gas_fee = tx.gas * tx.gas_price sender_balance_after_gas_fee = Uint(sender_account.balance) - gas_fee set_account_balance(tx_state, sender, U256(sender_balance_after_gas_fee)) ``` -------------------------------- ### Access List and Authorization Setup Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/bpo1/bpo2/fork.py.html Configures the access list and authorizations for the transaction environment. ```python access_list_addresses = set() access_list_storage_keys = set() access_list_addresses.add(block_env.coinbase) if has_access_list(tx): for access in tx.access_list: access_list_addresses.add(access.account) for slot in access.slots: access_list_storage_keys.add((access.account, slot)) ``` ```python authorizations: Tuple[Authorization, ...] = () if isinstance(tx, SetCodeTransaction): authorizations = tx.authorizations ``` -------------------------------- ### Fill test command examples Source: https://steel.ethereum.foundation/docs/execution-specs/writing_tests/tutorials/state_transition Command-line instructions for filling test cases using specific filters or fork ranges. ```bash fill -k test_state_test_example ``` ```bash fill -k test_state_test_example --from London --until Paris ``` -------------------------------- ### Start Hive in Dev Mode Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/execute/hive Initializes Hive in development mode with a specific client. ```bash ./hive --dev --client go-ethereum ``` -------------------------------- ### Network configuration YAML structure Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/execute/eth_config Example structure for defining custom network parameters in a YAML file. ```yaml MyCustomNet: chainId: 0xabcd # Chain ID in hex genesisHash: 0xd4e5674... # Genesis block hash forkActivationTimes: # Fork activation block numbers/times 0: Cancun # Genesis fork, it must be the latest fork activated in the genesis 1742999832: Prague 1742999833: Osaka bpoForkActivationTimes: # Optional: Blob parameter only fork definitions 1742999834: target: 9 max: 12 base_fee_update_fraction: 5007716 1742999835: target: 12 max: 15 base_fee_update_fraction: 5007716 addressOverrides: # Optional: Override addresses for precompiles/contracts 0x00000000219ab540...: 0x7f02c3e3c98b133... ``` -------------------------------- ### Transaction Execution and State Test Setup Source: https://steel.ethereum.foundation/docs/execution-specs/tests/amsterdam/eip7976_increase_calldata_floor_cost/test_additional_coverage/test_exact_threshold_boundary Configures a transaction with specific gas limits and expected receipts, then executes a state test. ```python tx = Transaction( ty=ty, sender=sender, to=to, nonce=0, data=calldata, gas_limit=intrinsic_total, access_list=access_list, authorization_list=authorization_list, ) tx.expected_receipt = TransactionReceipt( cumulative_gas_used=intrinsic_total ) state_test( pre=pre, post={}, tx=tx, ) ``` -------------------------------- ### Starting Hive for Prerequisites Source: https://steel.ethereum.foundation/docs/execution-specs/library/cli/extract_config Hive must be running in the background before executing the extraction command. ```bash ./hive --dev ``` -------------------------------- ### CREATE2 Return Data Test Setup Source: https://steel.ethereum.foundation/docs/execution-specs/tests/constantinople/eip1014_create2/test_create_returndata/test_create2_return_data Defines the post-state expectations and transaction structure for validating CREATE2 return data behavior. ```python post = { address_to: Account( storage={ slot_code_worked: 1, slot_returndatacopy_before_create: expected_returndatacopy, slot_returndatacopy_before_create_2: 0, # # the actual bytes returned by returndatacopy opcode after # create slot_returndatacopy_after_create: ( return_data_in_create if return_type_in_create == Op.REVERT else 0 ), slot_returndatasize_before_create: call_return_size, # # return datasize value after create slot_returndatasize_after_create: ( 0x20 if return_type_in_create == Op.REVERT else 0 ), # slot_return_data_hash_before_create: keccak256( expected_call_return_data ), slot_return_data_hash_after_create: ( keccak256(empty_data) if return_type_in_create == Op.RETURN else keccak256( int.to_bytes( return_data_in_create, 32, byteorder="big" ) ) ), # # check that create 2 didn't mess up with initial memory space # declared for return slot_begin_memory_after_create: expected_returndatacopy, } ) } tx = Transaction( sender=pre.fund_eoa(), to=address_to, protected=False, data=initcode, ) state_test(pre=pre, post=post, tx=tx) ``` -------------------------------- ### Execute unchunkified bytecode benchmark test Source: https://steel.ethereum.foundation/docs/execution-specs/tests/benchmark/compute/scenario/test_unchunkified_bytecode/test_unchunkified_bytecode This snippet demonstrates the setup and execution phases of the benchmark test, including contract deployment and attack transaction generation. ```python # Deploy num_contracts via multiple txs (each capped by tx gas limit). post = {} with TestPhaseManager.setup(): setup_sender = pre.fund_eoa() contracts_deployment_txs: List[ContractDeploymentTransaction] = [] for contract_creating_tx in ( custom_sized_contract_factory.transactions_by_total_contract_count( fork=fork, sender=setup_sender, contract_count=num_contracts, ) ): contracts_deployment_txs.append(contract_creating_tx) if custom_sized_contract_factory.contract_size > 0: post[contract_creating_tx.deployed_contracts[-1]] = Account( nonce=1 ) with TestPhaseManager.execution(): attack_sender = pre.fund_eoa() if fixed_opcode_count is not None: # Fixed opcode count mode. attack_txs = list( attack_code.transactions_by_total_iteration_count( fork=fork, total_iterations=int(fixed_opcode_count * 1000), sender=attack_sender, to=attack_address, calldata=calldata, ) ) else: attack_txs = list( attack_code.transactions_by_gas_limit( fork=fork, gas_limit=attack_gas_limit, sender=attack_sender, to=attack_address, calldata=calldata, ) ) total_gas_cost = sum(tx.gas_cost for tx in attack_txs) benchmark_test( pre=pre, post=post, blocks=[ Block(txs=contracts_deployment_txs), Block(txs=attack_txs), ], target_opcode=opcode, expected_benchmark_gas_used=total_gas_cost, ) ``` -------------------------------- ### Test with custom configuration Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/execute/eth_config Use a custom network configuration file or genesis source. ```bash uv run execute eth-config --network MyCustomNet --rpc-endpoint http://localhost:8545 --network-config-file ./my-networks.yml ``` ```bash uv run execute eth-config --genesis-config-file ./genesis.json --rpc-endpoint http://localhost:8545 ``` ```bash uv run execute eth-config --genesis-config-url https://example.com/genesis.json --rpc-endpoint http://localhost:8545 ``` -------------------------------- ### Transaction and State Test Setup Source: https://steel.ethereum.foundation/docs/execution-specs/tests/amsterdam/eip2780_reduce_intrinsic_tx_gas/test_authorization_charges/test_account_write_authority_is_recipient Defines the transaction parameters and the expected post-state for the account write authority test. ```python tx = Transaction( sender=sender, to=recipient, value=value, authorization_list=[authorization], gas_limit=total_gas_cost, expected_receipt=TransactionReceipt( cumulative_gas_used=total_gas_cost, ), ) post = { recipient: Account( nonce=1, balance=authority_initial_balance + value, code=Spec7702.delegation_designation(delegation_target), ), } state_test(pre=pre, tx=tx, post=post) ``` -------------------------------- ### Define memory input start position Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/paris/shanghai/vm/instructions/system.py.html Represents the starting memory address for input data. ```python memory_input_start_position: U256 ``` -------------------------------- ### Initialize environment configuration Source: https://steel.ethereum.foundation/docs/execution-specs/dev/configurations Use the CLI tool to generate the local env.yaml file. ```bash uv run eest make env ๐ŸŽ‰ Success! Config file created at: /env.yaml ``` -------------------------------- ### Define memory output start position Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/arrow_glacier/gray_glacier/vm/instructions/system.py.html Represents the starting position in memory for output data. ```python memory_output_start_position: U256 ``` -------------------------------- ### Transaction Delegation Installation Test Case Source: https://steel.ethereum.foundation/docs/execution-specs/tests/amsterdam/eip2780_reduce_intrinsic_tx_gas/test_value_moving_with_tx_delegation/test_tx_installs_delegation_on_funded_recipient Defines the post-state expectations for a transaction that installs a delegation designation on a funded recipient account. ```python post = { sender: Account(nonce=1, balance=sender_final_balance), target: Account( nonce=1, balance=target_initial_balance + value, code=Spec7702.delegation_designation(delegated_to), ), } state_test(pre=pre, tx=tx, post=post) ``` -------------------------------- ### CI Execution Command Output Source: https://steel.ethereum.foundation/docs/execution-specs/dev/test_actions_locally Example of the command string printed to logs when the CI environment variable is set. ```text Executing: pytest ... ``` -------------------------------- ### Verify Delegation Installation on Empty Recipient Source: https://steel.ethereum.foundation/docs/execution-specs/tests/amsterdam/eip2780_reduce_intrinsic_tx_gas/test_value_moving_with_tx_delegation/test_tx_installs_delegation_on_empty_recipient Defines the post-state expectation for a transaction that installs a delegation designation on an empty recipient account. ```python post = { sender: Account(nonce=1, balance=sender_final_balance), target: Account( nonce=1, balance=value, code=Spec7702.delegation_designation(delegated_to), ), } state_test(pre=pre, tx=tx, post=post) ``` -------------------------------- ### Sync Project Dependencies Source: https://steel.ethereum.foundation/docs/execution-specs/dev/docs Initializes the project environment by syncing dependencies. ```bash uv sync ``` -------------------------------- ### Test implementation for delegation installation Source: https://steel.ethereum.foundation/docs/execution-specs/tests/amsterdam/eip2780_reduce_intrinsic_tx_gas/test_value_moving_with_tx_delegation/test_tx_installs_delegation_on_funded_recipient The test function sets up a funded EOA recipient and verifies gas costs for installing delegation via a type-4 transaction. ```python @pytest.mark.parametrize( "value", [ pytest.param(0, id="zero_value"), pytest.param(1, id="non-zero_value"), ], ) def test_tx_installs_delegation_on_funded_recipient( fork: Fork, pre: Alloc, state_test: StateTestFiller, value: int, ) -> None: """ Scenario 1: ``tx.to`` is a funded EOA with no prior delegation. The type-4 transaction's authorization installs delegation on ``tx.to``. The authority (``tx.to``) already exists, so it pays no ``NEW_ACCOUNT``; it has no prior code, so writing the delegation indicator pays ``AUTH_BASE``. Whether it pays ``ACCOUNT_WRITE`` depends on the value transfer: with ``zero_value`` the delegation write is the transaction's first write to ``tx.to`` and ``ACCOUNT_WRITE`` is charged; with ``non-zero_value`` the transaction already pays to write ``tx.to`` when it transfers value to it, so no ``ACCOUNT_WRITE`` accrues. The top-frame ``COLD_ACCOUNT_ACCESS`` charge for the now-delegated recipient (its fresh delegation target is cold) still fires. """ sender_initial_balance = 10**18 sender = pre.fund_eoa(sender_initial_balance) target_initial_balance = 100 target = pre.fund_eoa(amount=target_initial_balance) delegated_to = pre.deploy_contract(code=Op.STOP) auth = AuthorizationTuple( address=delegated_to, nonce=0, signer=target, # Funded authority already exists, so no NEW_ACCOUNT. creates_account=False, first_write=not bool(value), ) authorization_list = [auth] # Intrinsic sees the recipient in its pre-tx form (funded EOA); the # delegation only surfaces at the top-frame check. intrinsic_gas = fork.transaction_intrinsic_cost_calculator()( sends_value=bool(value), recipient_type=RecipientType.EOA, authorization_list_or_count=authorization_list, return_cost_deducted_prior_execution=True, ) top_frame_regular = fork.transaction_top_frame_gas_calculator()( sends_value=bool(value), recipient_type=RecipientType.DELEGATION_7702, delegation_warm=False, authorizations=authorization_list, ) top_frame_state = fork.transaction_top_frame_state_gas( sends_value=bool(value), recipient_type=RecipientType.DELEGATION_7702, authorizations=authorization_list, ) # Costs are charged exactly (no refund); under the default zero # state-gas reservoir the state gas spills into regular gas. total_gas_cost = intrinsic_gas + top_frame_regular + top_frame_state tx_gas_limit = total_gas_cost + 1000 gas_price = 1_000_000_000 tx = Transaction( sender=sender, to=target, value=value, authorization_list=authorization_list, gas_limit=tx_gas_limit, max_fee_per_gas=gas_price, max_priority_fee_per_gas=gas_price, ) sender_final_balance = ( sender_initial_balance - value - (total_gas_cost * gas_price) ) ``` -------------------------------- ### Initialize EVM state and execution environment Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/byzantium/constantinople/vm/interpreter.py.html Sets up the initial EVM state, including stack, memory, and jump destinations. ```python tx_state = message.tx_env.state if message.depth > STACK_DEPTH_LIMIT: raise StackDepthLimitError("Stack depth limit reached") code = message.code valid_jump_destinations = get_valid_jump_destinations(code) evm = Evm( pc=Uint(0), stack=[], memory=bytearray(), code=code, gas_left=message.gas, valid_jump_destinations=valid_jump_destinations, logs=(), refund_counter=0, running=True, message=message, output=b"", accounts_to_delete=set(), touched_accounts=set(), return_data=b"", error=None, ) ``` -------------------------------- ### Create Instruction Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/paris/shanghai/vm/instructions/system.py.html Creates a new account with associated code. ```python def create(โ€‹evm: Evmโ€‹) -> None: ``` ```python # STACK endowment = pop(evm.stack) memory_start_position = pop(evm.stack) memory_size = pop(evm.stack) # GAS extend_memory = calculate_gas_extend_memory( evm.memory, [(memory_start_position, memory_size)] ) init_code_gas = init_code_cost(Uint(memory_size)) ``` -------------------------------- ### Get Sigma Length Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/src/ethereum/crypto/blake2.py.html Retrieves the length of the sigma parameter. ```python @property def sigma_len(self) -> int: return len(self.sigma) ``` -------------------------------- ### Get test ID Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_fixtures Returns the unique identifier for the test. ```python def get_id(self) -> str: """Return the test id.""" return self.id ``` -------------------------------- ### Run eth-config standalone Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/execute/eth_config Execute the command directly without cloning the repository by using uv. ```bash uv run --with "git+https://github.com/ethereum/execution-specs.git#subdirectory=packages/testing" execute eth-config --network Mainnet --rpc-endpoint http:// ``` -------------------------------- ### Check for Hex Prefix Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/src/ethereum/utils/hexadecimal.py.html Determines if a string starts with the '0x' prefix. ```python return hex_string.startswith("0x") ``` -------------------------------- ### CREATE Instruction Implementation Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/arrow_glacier/gray_glacier/vm/instructions/system.py.html Handles the creation of a new account using the CREATE opcode logic. ```python def create(evm: Evm) -> None: ``` ```python # STACK endowment = pop(evm.stack) memory_start_position = pop(evm.stack) memory_size = pop(evm.stack) ``` ```python # GAS extend_memory = calculate_gas_extend_memory( evm.memory, [(memory_start_position, memory_size)] ) ``` ```python charge_gas(evm, GasCosts.OPCODE_CREATE_BASE + extend_memory.cost) ``` ```python # OPERATION evm.memory += b"\x00" * extend_memory.expand_by contract_address = compute_contract_address( evm.message.current_target, get_account( evm.message.tx_env.state, evm.message.current_target ).nonce, ) ``` ```python generic_create( evm, endowment, contract_address, memory_start_position, memory_size ) ``` ```python # PROGRAM COUNTER evm.pc += Uint(1) ``` -------------------------------- ### Factory Contract Setup and Gas Simulation Source: https://steel.ethereum.foundation/docs/execution-specs/tests/amsterdam/eip8037_state_creation_gas_cost_increase/test_state_gas_create/test_parent_state_gas_after_child_failure Defines the factory contract bytecode and simulates the gas lifecycle, including CREATE opcode costs, 63/64 retention, and state reservoir refills after an INVALID opcode failure. ```python factory_storage = Storage() factory_code = ( Op.MSTORE(0, Op.PUSH32(bytes(initcode))) + Op.SSTORE( factory_storage.store_next(0, "create_fails"), Op.CREATE( value=0, offset=32 - len(initcode), size=len(initcode), ), original_value=0, new_value=0, ) + Op.SSTORE( factory_storage.store_next(1, "post_create"), 1, original_value=0, new_value=1, ) ) factory = pre.deploy_contract(code=factory_code) gas_limit = ( gas_limit_cap + new_account_state_gas + sstore_state_gas * 2 if with_reservoir else 5_000_000 ) # `bytecode.gas_cost(fork)` accounts for opcode base costs and # state-gas charges, but does NOT track memory-expansion or CREATE # init-code word costs. Add those back to recover runtime regular # gas consumption. init_code_word_count = (len(initcode) + 31) // 32 init_code_word_cost = gas_costs.CODE_INIT_PER_WORD * init_code_word_count mstore_memory_expansion = gas_costs.MEMORY_PER_WORD # 1 word gas_cost_helper_extras = init_code_word_cost + mstore_memory_expansion # Factory bytecode shape costs, derived from fork.gas_costs(): # pre-CREATE: PUSH32 + PUSH1 + MSTORE (with 1-word expansion) # + 3 PUSHes for CREATE inputs # post-CREATE: PUSH key + SSTORE (cold no-op: access cost only) # + 2 PUSHes + SSTORE (cold zero-to-nonzero: # access + write, the compound COLD_STORAGE_WRITE) factory_pre_create_regular = ( gas_costs.VERY_LOW * 2 + gas_costs.OPCODE_MSTORE_BASE + mstore_memory_expansion + gas_costs.VERY_LOW * 3 ) factory_post_create_regular = ( gas_costs.VERY_LOW + gas_costs.COLD_STORAGE_ACCESS + gas_costs.VERY_LOW * 2 + gas_costs.COLD_STORAGE_WRITE ) factory_regular = ( factory_code.gas_cost(fork) - new_account_state_gas - sstore_state_gas + gas_cost_helper_extras ) initcode_regular_revert = initcode.gas_cost(fork) - sstore_state_gas if failure_op == Op.INVALID: # Simulate runtime gas for HALT under EIP-8037 LIFO refills: # 1. Regular pool capped by transaction_gas_limit_cap. The # remainder forms the state reservoir. # 2. CREATE charges new_account state gas, reservoir first # then spilled to gas_left and tracked. # 3. 63/64 retention: parent keeps gas_left // 64. The # reservoir is forwarded to the child frame. # 4. Child initcode SSTORE charges sstore_state_gas, child # reservoir first then spilled to child gas_left. # 5. INVALID refills the child frame LIFO then burns its # gas_left. Only the child's start reservoir survives. # 6. CREATE failure refills new_account LIFO: the spill to # parent gas_left, the rest to the parent reservoir. # 7. Factory post-CREATE SSTORE charges sstore_state_gas, # reservoir first then spilled to gas_left. execution_gas = gas_limit - intrinsic_cost regular_budget = gas_limit_cap - intrinsic_cost sim_gas_left = min(regular_budget, execution_gas) sim_state_gas_left = execution_gas - sim_gas_left sim_gas_left -= factory_pre_create_regular sim_gas_left -= gas_costs.OPCODE_CREATE_BASE + init_code_word_cost # CREATE new_account state gas: reservoir first, spill tracked. new_account_from_reservoir = min( sim_state_gas_left, new_account_state_gas ) new_account_spill = new_account_state_gas - new_account_from_reservoir sim_state_gas_left -= new_account_from_reservoir sim_gas_left -= new_account_spill # 63/64 retention: parent keeps gas_left // 64. The reservoir # is forwarded to the child frame and survives on halt. child_reservoir = sim_state_gas_left sim_gas_left = sim_gas_left // 64 # INVALID burns child gas_left, including any spilled SSTORE # state gas. Only the forwarded reservoir survives. sim_state_gas_left = child_reservoir # CREATE failure refills new_account LIFO: spilled portion to # gas_left, reservoir-funded portion to the reservoir. sim_gas_left += new_account_spill sim_state_gas_left += new_account_from_reservoir sim_gas_left -= factory_post_create_regular # Factory post-CREATE SSTORE: reservoir first, spill otherwise. if sim_state_gas_left >= sstore_state_gas: sim_state_gas_left -= sstore_state_gas else: sim_gas_left -= sstore_state_gas - sim_state_gas_left sim_state_gas_left = 0 ``` -------------------------------- ### CREATE Instruction Implementation Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/osaka/bpo1/vm/instructions/system.py.html Handles the creation of a new account based on the sender's nonce. ```python charge_gas( evm, GasCosts.OPCODE_CREATE_BASE + extend_memory.cost + init_code_gas, ) ``` ```python evm.memory += b"\x00" * extend_memory.expand_by contract_address = compute_contract_address( evm.message.current_target, get_account( evm.message.tx_env.state, evm.message.current_target ).nonce, ) ``` ```python generic_create( evm, endowment, contract_address, memory_start_position, memory_size, ) ``` ```python evm.pc += Uint(1) ``` -------------------------------- ### Define InvalidContractPrefix Exception Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/arrow_glacier/gray_glacier/vm/exceptions.py.html Raised when contract code starts with 0xEF. ```python class InvalidContractPrefix: ``` -------------------------------- ### Parameter execution results Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_tools Expected parameter sets resulting from the extend_with_defaults example. ```text "default_case": {"min_value": 0, "max_value": 100, "average": 50} "min_value_10": {"min_value": 10, "max_value": 100, "average": 50} "max_value_200": {"min_value": 0, "max_value": 200, "average": 50} "min_-10_max_50": {"min_value": -10, "max_value": 50, "average": 50} "min_20_max_80_avg_50": {"min_value": 20, "max_value": 80, "average": 50} # expected to fail "invalid_range": {"min_value": 100, "max_value": 0, "average": 50} ``` -------------------------------- ### Initialize Access List Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/cancun/prague/fork.py.html Sets up the initial access list structures for addresses and storage keys. ```python access_list_addresses = set() ``` ```python access_list_storage_keys = set() ``` ```python access_list_addresses.add(block_env.coinbase) ``` -------------------------------- ### Get or Create Partial File Handles Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_fixtures Utility methods to retrieve or initialize file handles for streaming fixtures and index entries. ```python def _get_partial_fixture_file(self, fixture_path: Path) -> "IO[str]": """Get or create a file handle for streaming fixtures.""" worker_id = self._get_worker_id() suffix = f".{worker_id}" if worker_id else ".main" partial_path = fixture_path.with_suffix(f".partial{suffix}.jsonl") if partial_path not in self._partial_fixture_files: partial_path.parent.mkdir(parents=True, exist_ok=True) self._partial_fixture_files[partial_path] = open(partial_path, "a") return self._partial_fixture_files[partial_path] ``` ```python def _get_partial_index_file(self) -> "IO[str]": """Get or create the file handle for streaming index entries.""" if self._partial_index_file is None: worker_id = self._get_worker_id() suffix = f".{worker_id}" if worker_id else ".main" partial_index_path = ( self.output_dir / ".meta" / f"partial_index{suffix}.jsonl" ) partial_index_path.parent.mkdir(parents=True, exist_ok=True) self._partial_index_file = open(partial_index_path, "a") return self._partial_index_file ``` -------------------------------- ### Build and Verify Documentation Source: https://steel.ethereum.foundation/docs/execution-specs/dev/docs Commands to build the documentation, run spellchecks, and lint markdown files. ```bash just docs ``` ```bash just spellcheck just lint-md just docs ``` -------------------------------- ### Build solc from Source on ARM Source: https://steel.ethereum.foundation/docs/execution-specs/getting_started/installation_troubleshooting Steps to build the Solidity compiler from source to resolve compilation failures on ARM platforms. ```bash git clone --branch v0.8.28 --depth 1 https://github.com/ethereum/solidity.git cd solidity && mkdir build && cd build sudo apt install build-essential libboost-all-dev z3 cmake .. make mv $HOME/Documents/execution-specs/.venv/bin/solc $HOME/Documents/execution-specs/.venv/bin/solc-x86-64 cp ./solc/solc $HOME/Documents/execution-specs/.venv/bin/ chmod +x $HOME/Documents/execution-specs/.venv/bin/solc ``` -------------------------------- ### Clean Generated Files Source: https://steel.ethereum.foundation/docs/execution-specs/library/cli/eest Commands and examples for cleaning generated files and directories. ```text dry_run (bool): Simulate the cleanup without removing files. verbose (bool): Show verbose output. ``` ```bash uv run eest clean --all -v ``` ```text ๐Ÿ—‘๏ธ Deleted: .just ๐Ÿ—‘๏ธ Deleted: .venv ๐Ÿ—‘๏ธ Deleted: src/cli/et/__pycache__ ๐Ÿ—‘๏ธ Deleted: src/cli/et/commands/__pycache__ ๐Ÿ—‘๏ธ Deleted: src/cli/et/make/__pycache__ ๐Ÿ—‘๏ธ Deleted: src/cli/et/make/commands/__pycache__ ... ๐Ÿงน Cleanup complete! ``` ```bash eest clean [OPTIONS] ``` ```bash --all Remove the virtual environment and .just directories as well. --dry-run Simulate the cleanup without removing files. -v, --verbose Show verbose output. -h, --help Show this message and exit. ``` -------------------------------- ### Define TransactionStart Trace Event Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/src/ethereum/trace.py.html Defines the event triggered at the start of a transaction. ```python @final @dataclass class TransactionStart: ``` -------------------------------- ### Initialize block output Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/cancun/prague/fork.py.html Initializes the block output object at the start of execution. ```python block_output = vm.BlockOutput() ``` -------------------------------- ### memory_write Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/bpo3/bpo4/vm/memory.py.html Writes a sequence of bytes to the EVM memory at a specified starting position. ```APIDOC ## memory_write ### Description Writes data to the specified memory location. ### Signature `def memory_write(memory: bytearray, start_position: U256, value: Bytes) -> None:` ### Parameters - **memory** (bytearray) - The current memory contents of the EVM. - **start_position** (U256) - The starting pointer in memory where the write operation begins. - **value** (Bytes) - The data to be written to memory. ``` -------------------------------- ### Get keys from root dict Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_fixtures Returns a view of the keys in the root dictionary. ```python def keys(self) -> KeysView[str]: """Get keys from root dict.""" return self.root.keys() ``` -------------------------------- ### Build the Hive command-line tool Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/hive Clone the repository and compile the Hive binary using the Go toolchain. ```bash git clone https://github.com/ethereum/hive cd hive go build . ``` -------------------------------- ### Get test count Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_fixtures Returns the number of tests associated with the pre-allocation group. ```python def get_test_count(self) -> int: """Return the amount of tests that use this pre-allocation group.""" return len(self.test_ids) ``` -------------------------------- ### CREATE Instruction Implementation Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/src/ethereum/forks/cancun/vm/instructions/system.py.html Executes the CREATE opcode to deploy a new contract, calculating gas based on memory expansion and initialization code costs. ```python # STACK endowment = pop(evm.stack) memory_start_position = pop(evm.stack) memory_size = pop(evm.stack) # GAS extend_memory = calculate_gas_extend_memory( evm.memory, [(memory_start_position, memory_size)] ) init_code_gas = init_code_cost(Uint(memory_size)) charge_gas( evm, GasCosts.OPCODE_CREATE_BASE + extend_memory.cost + init_code_gas ) # OPERATION evm.memory += b"\x00" * extend_memory.expand_by contract_address = compute_contract_address( evm.message.current_target, get_account( evm.message.tx_env.state, evm.message.current_target ).nonce, ) generic_create( evm, endowment, contract_address, memory_start_position, memory_size, ) # PROGRAM COUNTER evm.pc += Uint(1) ``` -------------------------------- ### Define a custom BlockExceptionWithMessage Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_exceptions Example of defining a custom exception model that inherits from ExceptionWithMessage. ```python class BlockExceptionWithMessage(ExceptionWithMessage[BlockException]): pass ``` -------------------------------- ### Initialize EVM Execution Context Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/src/ethereum/forks/amsterdam/vm/interpreter.py.html Sets up the code, jump destinations, and initial state snapshot before execution. ```python assert message.code is not None evm.code = message.code evm.valid_jump_destinations = get_valid_jump_destinations(message.code) snapshot = copy_tx_state(tx_state) ``` -------------------------------- ### Prepare Transaction Environment Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/src/ethereum/forks/amsterdam/fork.py.html Sets up the transaction environment including authorizations for SetCodeTransactions. ```python authorizations: Tuple[Authorization, ...] = () if isinstance(tx, SetCodeTransaction): authorizations = tx.authorizations tx_env = vm.TransactionEnvironment( origin=sender, recipient=tx.to, value=tx.value, gas_price=effective_gas_price, gas=gas, state_gas_reservoir=state_gas_reservoir, access_list_addresses=access_list_addresses, access_list_storage_keys=access_list_storage_keys, state=tx_state, blob_versioned_hashes=blob_versioned_hashes, authorizations=authorizations, index_in_block=index, tx_hash=get_transaction_hash(encode_transaction(tx)), ) ``` -------------------------------- ### Test cold account access at transition Source: https://steel.ethereum.foundation/docs/execution-specs/tests/amsterdam/eip8038_state_access_gas_cost_increase/test_fork_transition/test_cold_account_access_at_transition Implementation of the test case that measures BALANCE opcode gas costs before and after the Amsterdam fork transition. ```python @EIPChecklist.GasCostChanges.Test.ForkTransition.Before() @EIPChecklist.GasCostChanges.Test.ForkTransition.After() def test_cold_account_access_at_transition( blockchain_test: BlockchainTestFiller, pre: Alloc, fork: Fork, ) -> None: """ ``BALANCE`` of a cold account costs ``COLD_ACCOUNT_ACCESS``, which rises across the Amsterdam boundary (2600 -> 3000 on mainnet). The same opcode is measured before and after; each block asserts its regime's derived cost. """ before = fork.fork_at(timestamp=BEFORE_TS) after = fork.fork_at(timestamp=AFTER_TS) cost_before = before.gas_costs().COLD_ACCOUNT_ACCESS cost_after = after.gas_costs().COLD_ACCOUNT_ACCESS assert cost_after > cost_before target = pre.deploy_contract(code=Op.STOP) # A distinct cold target per block keeps each measurement cold. target_after = pre.deploy_contract(code=Op.STOP) # BALANCE has no code-read surcharge, so its bare cost equals # COLD_ACCOUNT_ACCESS in each regime. measure_before = _measure_contract( pre, Op.BALANCE(target), cost_before, before ) measure_after = _measure_contract( pre, Op.BALANCE(target_after), cost_after, after ) blocks = transition_blocks(measure_before, measure_after, pre) post = { measure_before: Account(storage={0: cost_before}), measure_after: Account(storage={0: cost_after}), } blockchain_test(pre=pre, blocks=blocks, post=post) ``` -------------------------------- ### Initialize block environment Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/arrow_glacier/gray_glacier/fork.py.html Sets up the block environment required for transaction execution. ```python block_state = BlockState(pre_state=chain.state) block_env = vm.BlockEnvironment( chain_id=chain.chain_id, state=block_state, block_gas_limit=block.header.gas_limit, block_hashes=get_last_256_block_hashes(chain), coinbase=block.header.coinbase, number=block.header.number, base_fee_per_gas=block.header.base_fee_per_gas, time=block.header.timestamp, difficulty=block.header.difficulty, ) ``` -------------------------------- ### State Test Execution Source: https://steel.ethereum.foundation/docs/execution-specs/tests/prague/eip7702_set_code_tx/test_gas/test_account_warming Setup and execution of state tests for EIP-7702 account warming. ```python callee_code: Bytecode = sum( # type: ignore ( CodeGasMeasure( code=Op.CALL(gas=0, address=check_address), overhead_cost=overhead_cost, extra_stack_items=1, sstore_key=check_address, ) for check_address in addresses_to_check ) ) callee_code += Op.STOP callee_address = pre.deploy_contract( callee_code, storage=dict.fromkeys(addresses_to_check, 0xDEADBEEF), ) tx = Transaction( to=callee_address, authorization_list=authorization_list if authorization_list else None, access_list=access_list, sender=sender, data=data, ) post = { callee_address: Account( storage=addresses_to_check, ), } state_test( pre=pre, tx=tx, post=post, ) ``` -------------------------------- ### Transaction Validation and Sender Setup Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/bpo2/bpo3/fork.py.html Validates the transaction and retrieves sender account details. ```python intrinsic = validate_transaction(tx) ( sender, effective_gas_price, blob_versioned_hashes, tx_blob_gas_used, ) = check_transaction( block_env=block_env, block_output=block_output, tx=tx, tx_state=tx_state, ) ``` ```python sender_account = get_account(tx_state, sender) ``` -------------------------------- ### FixedIterationsBytecode.__new__ Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_tools Creates a new instance of FixedIterationsBytecode with specified setup, iteration, and cleanup bytecode. ```APIDOC ## FixedIterationsBytecode.__new__(*, setup, iterating, cleanup, iteration_count, warm_iterating=None, iterating_subcall=None) ### Description Creates a new FixedIterationsBytecode instance to manage iterative bytecode execution. ### Parameters - **setup** (Bytecode) - Required - Bytecode executed once at the beginning before iterations start. - **iterating** (Bytecode) - Required - Bytecode executed in the first iteration. - **cleanup** (Bytecode) - Required - Bytecode executed once at the end after all iterations complete. - **iteration_count** (int) - Required - The fixed number of times the iterating bytecode will be executed. - **warm_iterating** (Bytecode | None) - Optional - Bytecode executed in subsequent iterations after the first. Defaults to None. - **iterating_subcall** (Bytecode | int | None) - Optional - Analytical bytecode or integer gas cost representing a subcall performed during each iteration. Defaults to None. ### Returns - **Self** - A new FixedIterationsBytecode instance. ``` -------------------------------- ### Get Byte Operation Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/dao_fork/tangerine_whistle/vm/instructions/bitwise.py.html Retrieves a specific byte from a word based on the provided index. ```python def get_byte(evm: Evm) -> None: ``` ```python # STACK byte_index = pop(evm.stack) word = pop(evm.stack) # GAS charge_gas(evm, GasCosts.OPCODE_BYTE) # OPERATION if byte_index >= U256(32): result = U256(0) else: extra_bytes_to_right = U256(31) - byte_index # Remove the extra bytes in the right word = word >> (extra_bytes_to_right * U256(8)) # Remove the extra bytes in the left word = word & U256(0xFF) result = word push(evm.stack, result) # PROGRAM COUNTER evm.pc += Uint(1) ``` -------------------------------- ### Run the consume command Source: https://steel.ethereum.foundation/docs/execution-specs/running_tests/consume Basic syntax for executing the consume command via uv. ```bash uv run consume [OPTIONS] SUBCOMMAND [ARGS]... ``` -------------------------------- ### Initialize Access List Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/berlin/london/fork.py.html Sets up empty sets for tracking addresses and storage keys accessed during transaction execution. ```python access_list_addresses = set() ``` ```python access_list_storage_keys = set() ``` -------------------------------- ### Get length of root dict Source: https://steel.ethereum.foundation/docs/execution-specs/library/execution_testing_fixtures Returns the number of items currently in the root dictionary. ```python def __len__(self) -> int: """Get length of root dict.""" return len(self.root) ``` -------------------------------- ### Test Documentation Generation Source: https://steel.ethereum.foundation/docs/execution-specs/dev/docs Runs the documentation generation plugin directly or serves the site via mkdocs. ```bash uv run fill -p pytest_plugins.filler.gen_test_doc.gen_test_doc --gen-docs --fork= tests ``` ```bash uv run mkdocs serve ``` -------------------------------- ### Get Byte Operation Source: https://steel.ethereum.foundation/docs/execution-specs/specs/reference/diffs/berlin/london/vm/instructions/bitwise.py.html Retrieves the Nth byte from a word based on the stack index. ```python ``` ```python # STACK ``` ```python byte_index = pop(evm.stack) ``` ```python word = pop(evm.stack) ``` ```python # GAS ``` ```python charge_gas(evm, GasCosts.OPCODE_BYTE) ``` ```python # OPERATION ``` ```python if byte_index >= U256(32): result = U256(0) else: extra_bytes_to_right = U256(31) - byte_index # Remove the extra bytes in the right word = word >> (extra_bytes_to_right * U256(8)) # Remove the extra bytes in the left word = word & U256(0xFF) result = word ``` ```python push(evm.stack, result) ``` ```python # PROGRAM COUNTER ``` ```python evm.pc += Uint(1) ``` -------------------------------- ### Generate Project Files Source: https://steel.ethereum.foundation/docs/execution-specs/library/cli/eest General usage for the make subcommand. ```bash eest make [OPTIONS] COMMAND [ARGS]... ``` ```bash -h, --help Show this message and exit. ``` -------------------------------- ### Benchmark NOT instruction implementation Source: https://steel.ethereum.foundation/docs/execution-specs/tests/benchmark/compute/instruction/test_bitwise/test_not_op The test function uses a JumpLoopGenerator to benchmark the NOT opcode with a PUSH0 setup. ```python @pytest.mark.repricing def test_not_op( benchmark_test: BenchmarkTestFiller, ) -> None: """ Benchmark NOT instruction (takes one arg, pushes one value). """ benchmark_test( target_opcode=Op.NOT, code_generator=JumpLoopGenerator(setup=Op.PUSH0, attack_block=Op.NOT), ) ``` -------------------------------- ### List Available Workflows Source: https://steel.ethereum.foundation/docs/execution-specs/dev/test_actions_locally Displays all workflows available for execution. ```bash gh act --list ```