repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stZeroCallsRevert/__init__.py | tests/static/state_tests/stZeroCallsRevert/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stWalletTest/__init__.py | tests/static/state_tests/stWalletTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stPreCompiledContracts2/__init__.py | tests/static/state_tests/stPreCompiledContracts2/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stTimeConsuming/__init__.py | tests/static/state_tests/stTimeConsuming/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/VMTests/__init__.py | tests/static/state_tests/VMTests/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/VMTests/vmBitwiseLogicOperation/__init__.py | tests/static/state_tests/VMTests/vmBitwiseLogicOperation/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/VMTests/vmIOandFlowOperations/__init__.py | tests/static/state_tests/VMTests/vmIOandFlowOperations/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/VMTests/vmTests/__init__.py | tests/static/state_tests/VMTests/vmTests/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/VMTests/vmArithmeticTest/__init__.py | tests/static/state_tests/VMTests/vmArithmeticTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/VMTests/vmLogTest/__init__.py | tests/static/state_tests/VMTests/vmLogTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stStaticFlagEnabled/__init__.py | tests/static/state_tests/stStaticFlagEnabled/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stEIP1559/__init__.py | tests/static/state_tests/stEIP1559/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stTransactionTest/__init__.py | tests/static/state_tests/stTransactionTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stNonZeroCallsTest/__init__.py | tests/static/state_tests/stNonZeroCallsTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stPreCompiledContracts/__init__.py | tests/static/state_tests/stPreCompiledContracts/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stSpecialTest/__init__.py | tests/static/state_tests/stSpecialTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Shanghai/__init__.py | tests/static/state_tests/Shanghai/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Shanghai/stEIP3860_limitmeterinitcode/__init__.py | tests/static/state_tests/Shanghai/stEIP3860_limitmeterinitcode/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Shanghai/stEIP3651_warmcoinbase/__init__.py | tests/static/state_tests/Shanghai/stEIP3651_warmcoinbase/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Shanghai/stEIP3855_push0/__init__.py | tests/static/state_tests/Shanghai/stEIP3855_push0/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stMemoryStressTest/__init__.py | tests/static/state_tests/stMemoryStressTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stSolidityTest/__init__.py | tests/static/state_tests/stSolidityTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stSystemOperationsTest/__init__.py | tests/static/state_tests/stSystemOperationsTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stStackTests/__init__.py | tests/static/state_tests/stStackTests/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stRandom/__init__.py | tests/static/state_tests/stRandom/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Cancun/__init__.py | tests/static/state_tests/Cancun/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Cancun/stEIP4844_blobtransactions/__init__.py | tests/static/state_tests/Cancun/stEIP4844_blobtransactions/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Cancun/stEIP5656_MCOPY/__init__.py | tests/static/state_tests/Cancun/stEIP5656_MCOPY/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/Cancun/stEIP1153_transientStorage/__init__.py | tests/static/state_tests/Cancun/stEIP1153_transientStorage/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stCallCreateCallCodeTest/__init__.py | tests/static/state_tests/stCallCreateCallCodeTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stAttackTest/__init__.py | tests/static/state_tests/stAttackTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stSelfBalance/__init__.py | tests/static/state_tests/stSelfBalance/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stCallDelegateCodesCallCodeHomestead/__init__.py | tests/static/state_tests/stCallDelegateCodesCallCodeHomestead/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stEIP158Specific/__init__.py | tests/static/state_tests/stEIP158Specific/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stSLoadTest/__init__.py | tests/static/state_tests/stSLoadTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stTransitionTest/__init__.py | tests/static/state_tests/stTransitionTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stRevertTest/__init__.py | tests/static/state_tests/stRevertTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stCallDelegateCodesHomestead/__init__.py | tests/static/state_tests/stCallDelegateCodesHomestead/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stExtCodeHash/__init__.py | tests/static/state_tests/stExtCodeHash/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stLogTests/__init__.py | tests/static/state_tests/stLogTests/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stBadOpcode/__init__.py | tests/static/state_tests/stBadOpcode/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stRecursiveCreate/__init__.py | tests/static/state_tests/stRecursiveCreate/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stCallCodes/__init__.py | tests/static/state_tests/stCallCodes/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stBugs/__init__.py | tests/static/state_tests/stBugs/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stZeroKnowledge/__init__.py | tests/static/state_tests/stZeroKnowledge/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stMemoryTest/__init__.py | tests/static/state_tests/stMemoryTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stDelegatecallTestHomestead/__init__.py | tests/static/state_tests/stDelegatecallTestHomestead/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stRefundTest/__init__.py | tests/static/state_tests/stRefundTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stExample/__init__.py | tests/static/state_tests/stExample/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stRandom2/__init__.py | tests/static/state_tests/stRandom2/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stCodeSizeLimit/__init__.py | tests/static/state_tests/stCodeSizeLimit/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stStaticCall/__init__.py | tests/static/state_tests/stStaticCall/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stEIP150singleCodeGasPrices/__init__.py | tests/static/state_tests/stEIP150singleCodeGasPrices/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stShift/__init__.py | tests/static/state_tests/stShift/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stArgsZeroOneBalance/__init__.py | tests/static/state_tests/stArgsZeroOneBalance/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stReturnDataTest/__init__.py | tests/static/state_tests/stReturnDataTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stCodeCopyTest/__init__.py | tests/static/state_tests/stCodeCopyTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stZeroCallsTest/__init__.py | tests/static/state_tests/stZeroCallsTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stEIP150Specific/__init__.py | tests/static/state_tests/stEIP150Specific/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stQuadraticComplexityTest/__init__.py | tests/static/state_tests/stQuadraticComplexityTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stCreateTest/__init__.py | tests/static/state_tests/stCreateTest/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stChainId/__init__.py | tests/static/state_tests/stChainId/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/static/state_tests/stEIP3607/__init__.py | tests/static/state_tests/stEIP3607/__init__.py | """Static State Tests Fillers from ethereum/tests repo."""
REFERENCE_SPEC_GIT_PATH = ""
REFERENCE_SPEC_VERSION = ""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/__init__.py | tests/cancun/__init__.py | """
Test cases for EVM functionality introduced in Cancun.
See [EIP-7659: Hardfork Meta - Dencun](https://eips.ethereum.org/EIPS/eip-7569)
for a list of EIPS included in Dencun (Deneb/Cancun).
"""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip5656_mcopy/test_mcopy_memory_expansion.py | tests/cancun/eip5656_mcopy/test_mcopy_memory_expansion.py | """
Test MCOPY with memory expansion and potential OOG errors.
Test copy operations of [EIP-5656: MCOPY - Memory copying
instruction](https://eips.ethereum.org/EIPS/eip-5656) that produce
a memory expansion, and potentially an out-of-gas error.
"""
import itertools
from typing import List, Mapping
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
AccessList,
Account,
Address,
Alloc,
Bytecode,
Environment,
StateTestFiller,
Transaction,
TransactionReceipt,
)
from ethereum_test_tools import Opcodes as Op
from .common import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION
REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH
REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION
"""Storage addresses for common testing fields"""
_slot = itertools.count(1)
slot_code_worked = next(_slot)
slot_last_slot = next(_slot)
"""Storage values for common testing fields"""
value_code_worked = 0x2015
@pytest.fixture
def callee_bytecode(dest: int, src: int, length: int) -> Bytecode:
"""Callee performs a single mcopy operation and then returns."""
bytecode = Bytecode()
# Copy the initial memory
bytecode += Op.CALLDATACOPY(0x00, 0x00, Op.CALLDATASIZE())
# Pushes for the return operation
bytecode += Op.PUSH1(0x00) + Op.PUSH1(0x00)
bytecode += Op.SSTORE(slot_code_worked, value_code_worked)
# Perform the mcopy operation
bytecode += Op.MCOPY(dest, src, length)
bytecode += Op.RETURN
return bytecode
@pytest.fixture
def tx_access_list() -> List[AccessList]:
"""Access list for the transaction."""
return [AccessList(address=Address(i), storage_keys=[]) for i in range(1, 10)]
@pytest.fixture
def call_exact_cost(
fork: Fork,
initial_memory: bytes,
dest: int,
length: int,
tx_access_list: List[AccessList],
) -> int:
"""
Return the exact cost of the subcall, based on the initial memory and the
length of the copy.
"""
# Starting from EIP-7623, we need to use an access list to raise the
# intrinsic gas cost to be above the floor data cost.
cost_memory_bytes = fork.memory_expansion_gas_calculator()
gas_costs = fork.gas_costs()
tx_intrinsic_gas_cost_calculator = fork.transaction_intrinsic_cost_calculator()
mcopy_cost = 3
mcopy_cost += 3 * ((length + 31) // 32)
if length > 0 and dest + length > len(initial_memory):
mcopy_cost += cost_memory_bytes(
new_bytes=dest + length, previous_bytes=len(initial_memory)
)
calldatacopy_cost = 3
calldatacopy_cost += 3 * ((len(initial_memory) + 31) // 32)
calldatacopy_cost += cost_memory_bytes(new_bytes=len(initial_memory))
pushes_cost = gas_costs.G_VERY_LOW * 9
calldatasize_cost = gas_costs.G_BASE
sstore_cost = 22100
return (
tx_intrinsic_gas_cost_calculator(calldata=initial_memory, access_list=tx_access_list)
+ mcopy_cost
+ calldatacopy_cost
+ pushes_cost
+ calldatasize_cost
+ sstore_cost
)
@pytest.fixture
def block_gas_limit() -> int: # noqa: D103
return 100_000_000
@pytest.fixture
def tx_gas_limit( # noqa: D103
fork: Fork,
call_exact_cost: int,
block_gas_limit: int,
successful: bool,
) -> int:
return min(
call_exact_cost - (0 if successful else 1),
# If the transaction gas limit cap is not set (pre-osaka),
# use the block gas limit
fork.transaction_gas_limit_cap() or block_gas_limit,
)
@pytest.fixture
def env( # noqa: D103
block_gas_limit: int,
) -> Environment:
return Environment(gas_limit=block_gas_limit)
@pytest.fixture
def caller_address(pre: Alloc, callee_bytecode: bytes) -> Address: # noqa: D103
return pre.deploy_contract(code=callee_bytecode)
@pytest.fixture
def tx( # noqa: D103
sender: Address,
caller_address: Address,
initial_memory: bytes,
tx_gas_limit: int,
tx_access_list: List[AccessList],
) -> Transaction:
return Transaction(
sender=sender,
to=caller_address,
access_list=tx_access_list,
data=initial_memory,
gas_limit=tx_gas_limit,
expected_receipt=TransactionReceipt(gas_used=tx_gas_limit),
)
@pytest.fixture
def post( # noqa: D103
caller_address: Address,
successful: bool,
) -> Mapping:
return {
caller_address: Account(
storage={slot_code_worked: value_code_worked} if successful else {}
)
}
@pytest.mark.parametrize(
"dest,src,length",
[
(0x00, 0x00, 0x01),
(0x100, 0x00, 0x01),
(0x1F, 0x00, 0x01),
(0x20, 0x00, 0x01),
(0x1000, 0x00, 0x01),
(0x1000, 0x00, 0x40),
(0x00, 0x00, 0x00),
(2**256 - 1, 0x00, 0x00),
(0x00, 2**256 - 1, 0x00),
(2**256 - 1, 2**256 - 1, 0x00),
],
ids=[
"single_byte_expansion",
"single_byte_expansion_2",
"single_byte_expansion_word_boundary",
"single_byte_expansion_word_boundary_2",
"multi_word_expansion",
"multi_word_expansion_2",
"zero_length_expansion",
"huge_dest_zero_length",
"huge_src_zero_length",
"huge_dest_huge_src_zero_length",
],
)
@pytest.mark.parametrize("successful", [True, False])
@pytest.mark.parametrize(
"initial_memory",
[
bytes(range(0x00, 0x100)),
bytes(),
],
ids=[
"from_existent_memory",
"from_empty_memory",
],
)
@pytest.mark.with_all_evm_code_types
@pytest.mark.valid_from("Cancun")
def test_mcopy_memory_expansion(
state_test: StateTestFiller,
env: Environment,
pre: Alloc,
post: Mapping[str, Account],
tx: Transaction,
) -> None:
"""
Perform MCOPY operations that expand the memory, and verify the gas it
costs to do so.
"""
state_test(
env=env,
pre=pre,
post=post,
tx=tx,
)
@pytest.mark.parametrize(
"dest,src,length",
[
(2**256 - 1, 0x00, 0x01),
(2**256 - 2, 0x00, 0x01),
(2**255 - 1, 0x00, 0x01),
(0x00, 2**256 - 1, 0x01),
(0x00, 2**256 - 2, 0x01),
(0x00, 2**255 - 1, 0x01),
(0x00, 0x00, 2**256 - 1),
(0x00, 0x00, 2**256 - 2),
(0x00, 0x00, 2**255 - 1),
],
ids=[
"max_dest_single_byte_expansion",
"max_dest_minus_one_single_byte_expansion",
"half_max_dest_single_byte_expansion",
"max_src_single_byte_expansion",
"max_src_minus_one_single_byte_expansion",
"half_max_src_single_byte_expansion",
"max_length_expansion",
"max_length_minus_one_expansion",
"half_max_length_expansion",
],
)
@pytest.mark.parametrize(
"call_exact_cost",
[2**128 - 1],
ids=[""],
) # Limit subcall gas, otherwise it would be impossibly large
@pytest.mark.parametrize("successful", [False])
@pytest.mark.parametrize(
"initial_memory",
[
bytes(range(0x00, 0x100)),
bytes(),
],
ids=[
"from_existent_memory",
"from_empty_memory",
],
)
@pytest.mark.with_all_evm_code_types
@pytest.mark.valid_from("Cancun")
def test_mcopy_huge_memory_expansion(
state_test: StateTestFiller,
env: Environment,
pre: Mapping[str, Account],
post: Mapping[str, Account],
tx: Transaction,
) -> None:
"""
Perform MCOPY operations that expand the memory by huge amounts, and verify
that it correctly runs out of gas.
"""
state_test(
env=env,
pre=pre,
post=post,
tx=tx,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip5656_mcopy/common.py | tests/cancun/eip5656_mcopy/common.py | """
Common procedures to test [EIP-5656: MCOPY - Memory copying
instruction](https://eips.ethereum.org/EIPS/eip-5656).
"""
from copy import copy
REFERENCE_SPEC_GIT_PATH = "EIPS/eip-5656.md"
REFERENCE_SPEC_VERSION = "d0cd8902e2243b66e2b9a858b691bc106cebddfc"
def mcopy(*, src: int, dest: int, length: int, memory: bytes) -> bytes:
"""Perform the mcopy routine as the EVM would do it."""
if length == 0:
return memory
res = bytearray(copy(memory))
# If the destination or source are larger than the memory, we need to
# extend the memory
max_byte_index = max(src, dest) + length
if max_byte_index > len(memory):
res.extend(b"\x00" * (max_byte_index - len(memory)))
for i in range(length):
if (src + i) >= len(memory):
src_b = 0
else:
src_b = memory[src + i]
res[dest + i] = src_b
return bytes(res)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip5656_mcopy/test_mcopy_contexts.py | tests/cancun/eip5656_mcopy/test_mcopy_contexts.py | """
Test memory copy under different call contexts.
Tests for [EIP-5656: MCOPY - Memory copying instruction](https://eips.ethereum.org/EIPS/eip-5656).
"""
from itertools import cycle, islice
from typing import Mapping
import pytest
from ethereum_test_tools import (
Account,
Address,
Alloc,
Bytecode,
Environment,
StateTestFiller,
Storage,
Transaction,
ceiling_division,
)
from ethereum_test_tools import Opcodes as Op
from .common import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION
REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH
REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION
@pytest.fixture
def initial_memory_length() -> int: # noqa: D103
return 0x400
@pytest.fixture
def callee_bytecode(
initial_memory_length: int,
call_opcode: Op,
) -> Bytecode:
"""
Callee simply performs mcopy operations that should not have any effect on
the caller context.
"""
bytecode = Bytecode()
# Perform some copy operations
bytecode += Op.MCOPY(0x00, 0x01, 0x01)
bytecode += Op.MCOPY(0x01, 0x00, 0x01)
bytecode += Op.MCOPY(0x01, 0x00, 0x20)
# And a potential memory cleanup
bytecode += Op.MCOPY(0x00, initial_memory_length, initial_memory_length)
# Also try to expand the memory
bytecode += Op.MCOPY(0x00, initial_memory_length * 2, 1)
bytecode += Op.MCOPY(initial_memory_length * 2, 0x00, 1)
if call_opcode != Op.STATICCALL and call_opcode != Op.EXTSTATICCALL:
# Simple sstore to make sure we actually ran the code
bytecode += Op.SSTORE(200_000, 1)
# In case of initcode, return empty code
bytecode += Op.RETURN(0x00, 0x00)
return bytecode
@pytest.fixture
def initial_memory(
callee_bytecode: Bytecode,
initial_memory_length: int,
call_opcode: Op,
) -> bytes:
"""Init memory for the test."""
assert len(callee_bytecode) <= initial_memory_length
ret = bytes(list(islice(cycle(range(0x01, 0x100)), initial_memory_length)))
if call_opcode in [Op.CREATE, Op.CREATE2]:
# We also need to put the callee_bytecode as initcode in memory for
# create operations
ret = bytes(callee_bytecode) + ret[len(callee_bytecode) :]
assert len(ret) == initial_memory_length
return ret
@pytest.fixture
def caller_storage() -> Storage: # noqa: D103
return Storage()
@pytest.fixture
def caller_bytecode(
initial_memory: bytes,
callee_address: Address,
callee_bytecode: Bytecode,
call_opcode: Op,
caller_storage: Storage,
) -> Bytecode:
"""
Prepare bytecode and storage for the test, based on the starting memory and
the final memory that resulted from the copy.
"""
bytecode = Bytecode()
# Fill memory with initial values
for i in range(0, len(initial_memory), 0x20):
bytecode += Op.MSTORE(i, Op.PUSH32(initial_memory[i : i + 0x20]))
# Perform the call to the contract that is going to perform mcopy
if call_opcode in [Op.CREATE, Op.CREATE2]:
bytecode += call_opcode(size=len(callee_bytecode))
else:
bytecode += call_opcode(address=callee_address)
# First save msize
bytecode += Op.SSTORE(100_000, Op.MSIZE())
caller_storage[100_000] = ceiling_division(len(initial_memory), 0x20) * 0x20
# Store all memory in the initial range to verify the MCOPY in the subcall
# did not affect this level's memory
for w in range(0, len(initial_memory) // 0x20):
bytecode += Op.SSTORE(w, Op.MLOAD(w * 0x20))
caller_storage[w] = initial_memory[w * 0x20 : w * 0x20 + 0x20]
return bytecode
@pytest.fixture
def caller_address(pre: Alloc, caller_bytecode: Bytecode) -> Address: # noqa: D103
return pre.deploy_contract(caller_bytecode)
@pytest.fixture
def callee_address(pre: Alloc, callee_bytecode: Bytecode) -> Address: # noqa: D103
return pre.deploy_contract(callee_bytecode)
@pytest.fixture
def tx(pre: Alloc, caller_address: Address) -> Transaction: # noqa: D103
return Transaction(
sender=pre.fund_eoa(),
to=caller_address,
gas_limit=1_000_000,
)
@pytest.fixture
def post( # noqa: D103
caller_address: Address,
caller_storage: Storage,
callee_address: Address,
call_opcode: Op,
) -> Mapping:
callee_storage: Storage.StorageDictType = {}
if call_opcode in [Op.DELEGATECALL, Op.CALLCODE, Op.EXTDELEGATECALL]:
caller_storage[200_000] = 1
elif call_opcode in [Op.CALL, Op.EXTCALL]:
callee_storage[200_000] = 1
return {
caller_address: Account(storage=caller_storage),
callee_address: Account(storage=callee_storage),
}
@pytest.mark.with_all_call_opcodes
@pytest.mark.valid_from("Cancun")
def test_no_memory_corruption_on_upper_call_stack_levels(
state_test: StateTestFiller,
pre: Alloc,
post: Mapping[str, Account],
tx: Transaction,
) -> None:
"""
Perform a subcall with any of the following opcodes, which uses MCOPY
during its execution, and verify that the caller's memory is unaffected.
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
@pytest.mark.parametrize(
"call_opcode",
[
Op.CREATE,
Op.CREATE2,
],
)
@pytest.mark.valid_from("Cancun")
def test_no_memory_corruption_on_upper_create_stack_levels(
state_test: StateTestFiller,
pre: Alloc,
post: Mapping[str, Account],
tx: Transaction,
) -> None:
"""
Perform a subcall with any of the following opcodes, which uses MCOPY
during its execution, and verify that the caller's memory is unaffected:
- `CREATE`
- `CREATE2`.
TODO: [EOF] Add EOFCREATE opcode
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip5656_mcopy/test_mcopy.py | tests/cancun/eip5656_mcopy/test_mcopy.py | """
Tests [EIP-5656: MCOPY - Memory copying instruction](https://eips.ethereum.org/EIPS/eip-5656).
"""
from typing import Mapping
import pytest
from ethereum_test_tools import (
Account,
Address,
Alloc,
Bytecode,
Environment,
Hash,
StateTestFiller,
Storage,
Transaction,
ceiling_division,
keccak256,
)
from ethereum_test_tools import Opcodes as Op
from .common import REFERENCE_SPEC_GIT_PATH, REFERENCE_SPEC_VERSION, mcopy
REFERENCE_SPEC_GIT_PATH = REFERENCE_SPEC_GIT_PATH
REFERENCE_SPEC_VERSION = REFERENCE_SPEC_VERSION
@pytest.fixture
def initial_memory() -> bytes:
"""Init memory for the test."""
return bytes(range(0x00, 0x100))
@pytest.fixture
def final_memory(*, dest: int, src: int, length: int, initial_memory: bytes) -> bytes:
"""Memory after the MCOPY operation."""
return mcopy(dest=dest, src=src, length=length, memory=initial_memory)
@pytest.fixture
def code_storage() -> Storage:
"""Storage for the code contract."""
return Storage()
@pytest.fixture
def code_bytecode(
initial_memory: bytes,
final_memory: bytes,
code_storage: Storage,
) -> Bytecode:
"""
Prepare bytecode and storage for the test, based on the starting memory and
the final memory that resulted from the copy.
"""
bytecode = Bytecode()
# Fill memory with initial values
for i in range(0, len(initial_memory), 0x20):
bytecode += Op.MSTORE(i, Op.PUSH32(initial_memory[i : i + 0x20]))
# Perform the MCOPY according to calldata values
bytecode += Op.MCOPY(
Op.CALLDATALOAD(0x00),
Op.CALLDATALOAD(0x20),
Op.CALLDATALOAD(0x40),
)
final_byte_length = ceiling_division(len(final_memory), 0x20) * 0x20
# First save msize
bytecode += Op.SSTORE(
code_storage.store_next(final_byte_length),
Op.MSIZE,
)
# Then save the hash of the entire memory
bytecode += Op.SSTORE(
code_storage.store_next(keccak256(final_memory.ljust(final_byte_length, b"\x00"))),
Op.SHA3(0, Op.MSIZE),
)
# Store all memory in the initial range to verify the MCOPY
for w in range(0, len(initial_memory) // 0x20):
bytecode += Op.SSTORE(
code_storage.store_next(final_memory[w * 0x20 : w * 0x20 + 0x20]),
Op.MLOAD(w * 0x20),
)
# If the memory was extended beyond the initial range, store the last word
# of the resulting memory into storage too
if len(final_memory) > len(initial_memory):
last_word = ceiling_division(len(final_memory), 0x20) - 1
bytecode += Op.SSTORE(
code_storage.store_next(
final_memory[last_word * 0x20 : (last_word + 1) * 0x20].ljust(32, b"\x00")
),
Op.MLOAD(last_word * 0x20),
)
return bytecode
@pytest.fixture
def code_address(pre: Alloc, code_bytecode: Bytecode) -> Address:
"""Address of the contract that is going to perform the MCOPY operation."""
return pre.deploy_contract(code_bytecode)
@pytest.fixture
def tx( # noqa: D103
pre: Alloc, code_address: Address, dest: int, src: int, length: int
) -> Transaction:
return Transaction(
sender=pre.fund_eoa(),
to=code_address,
data=Hash(dest) + Hash(src) + Hash(length),
gas_limit=1_000_000,
)
@pytest.fixture
def post(code_address: Address, code_storage: Storage) -> Mapping: # noqa: D103
return {
code_address: Account(storage=code_storage),
}
@pytest.mark.parametrize(
"dest,src,length",
[
(0x00, 0x00, 0x00),
(2**256 - 1, 0x00, 0x00),
(0x00, 0x00, 0x01),
(0x00, 0x00, 0x20),
(0x01, 0x00, 0x01),
(0x01, 0x00, 0x20),
(0x11, 0x11, 0x01),
(0x11, 0x11, 0x20),
(0x11, 0x11, 0x40),
(0x10, 0x00, 0x40),
(0x00, 0x10, 0x40),
(0x0F, 0x10, 0x40),
(0x100, 0x01, 0x01),
(0x100, 0x01, 0x20),
(0x100, 0x01, 0x1F),
(0x100, 0x01, 0x21),
(0x00, 0x00, 0x100),
(0x100, 0x00, 0x100),
(0x200, 0x00, 0x100),
(0x00, 0x100, 0x100),
(0x100, 0x100, 0x01),
],
ids=[
"zero_inputs",
"zero_length_out_of_bounds_destination",
"single_byte_rewrite",
"full_word_rewrite",
"single_byte_forward_overwrite",
"full_word_forward_overwrite",
"mid_word_single_byte_rewrite",
"mid_word_single_word_rewrite",
"mid_word_multi_word_rewrite",
"two_words_forward_overwrite",
"two_words_backward_overwrite",
"two_words_backward_overwrite_single_byte_offset",
"single_byte_memory_extension",
"single_word_memory_extension",
"single_word_minus_one_byte_memory_extension",
"single_word_plus_one_byte_memory_extension",
"full_memory_rewrite",
"full_memory_copy",
"full_memory_copy_offset",
"full_memory_clean",
"out_of_bounds_memory_extension",
],
)
@pytest.mark.with_all_evm_code_types
@pytest.mark.valid_from("Cancun")
def test_valid_mcopy_operations(
state_test: StateTestFiller,
pre: Alloc,
post: Mapping[str, Account],
tx: Transaction,
) -> None:
"""
Perform MCOPY operations using different offsets and lengths.
- Zero inputs
- Memory rewrites (copy from and to the same location)
- Memory overwrites (copy from and to different locations)
- Memory extensions (copy to a location that is out of bounds)
- Memory clear (copy from a location that is out of bounds).
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
@pytest.mark.parametrize("dest", [0x00, 0x20])
@pytest.mark.parametrize("src", [0x00, 0x20])
@pytest.mark.parametrize("length", [0x00, 0x01])
@pytest.mark.parametrize("initial_memory", [bytes()], ids=["empty_memory"])
@pytest.mark.with_all_evm_code_types
@pytest.mark.valid_from("Cancun")
def test_mcopy_on_empty_memory(
state_test: StateTestFiller,
pre: Alloc,
post: Mapping[str, Account],
tx: Transaction,
) -> None:
"""
Perform MCOPY operations on an empty memory, using different offsets and
lengths.
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip5656_mcopy/__init__.py | tests/cancun/eip5656_mcopy/__init__.py | """Cross-client EIP-5656 Tests."""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4788_beacon_root/spec.py | tests/cancun/eip4788_beacon_root/spec.py | """Defines EIP-4788 specification constants and functions."""
from dataclasses import dataclass
from ethereum_test_tools import Storage
@dataclass(frozen=True)
class ReferenceSpec:
"""Defines the reference spec version and git path."""
git_path: str
version: str
ref_spec_4788 = ReferenceSpec("EIPS/eip-4788.md", "efcac43ef9aadd87dd4e0a2fbd14d5d1317eddf3")
# Constants
@dataclass(frozen=True)
class Spec:
"""
Parameters from the EIP-4788 specifications as defined at
https://eips.ethereum.org/EIPS/eip-4788#specification.
"""
BEACON_ROOTS_ADDRESS = 0x000F3DF6D732807EF1319FB7B8BB8522D0BEAC02
BEACON_ROOTS_CALL_GAS = 100_000
BEACON_ROOTS_DEPLOYER_ADDRESS = 0x0B799C86A49DEEB90402691F1041AA3AF2D3C875
HISTORY_BUFFER_LENGTH = 8_191
SYSTEM_ADDRESS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE
FORK_TIMESTAMP = 15_000 # ShanghaiToCancun timestamp
@dataclass(frozen=True)
class SpecHelpers:
"""Helper functions closely related to the EIP-4788 specification."""
def timestamp_index(self, timestamp: int) -> int:
"""Derive the timestamp index into the timestamp ring buffer."""
return timestamp % Spec.HISTORY_BUFFER_LENGTH
def root_index(self, timestamp: int) -> int:
"""Derive the root index into the root ring buffer."""
return self.timestamp_index(timestamp) + Spec.HISTORY_BUFFER_LENGTH
@staticmethod
def expected_storage(
*,
beacon_root: bytes,
valid_call: bool,
valid_input: bool,
) -> Storage:
"""
Derive expected storage for a given beacon root contract call
dependent on:
- success or failure of the call
- validity of the timestamp input used within the call.
"""
# By default assume the call is unsuccessful and all keys are zero
storage = Storage(dict.fromkeys(range(4), 0)) # type: ignore
if valid_call and valid_input:
# beacon root contract call is successful
storage[0] = 1
storage[1] = beacon_root
storage[2] = 32
storage[3] = beacon_root
return storage
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4788_beacon_root/test_beacon_root_contract.py | tests/cancun/eip4788_beacon_root/test_beacon_root_contract.py | """
Tests beacon block root for [EIP-4788: Beacon block root in the EVM](https://eips.ethereum.org/EIPS/eip-4788).
Note: To add a new test, add a function that is named `test_<test_name>`.
It must take at least the following arguments:
- `state_test`
- `env`
- `pre`
- `tx`
- `post`
- `valid_call`
All other `pytest.fixtures` can be parametrized to generate new
combinations and test cases.
"""
from itertools import count
from typing import Callable, Dict, Iterator, List
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
Account,
Address,
Alloc,
Block,
BlockchainTestFiller,
Bytecode,
Hash,
Storage,
Transaction,
Withdrawal,
)
from ethereum_test_vm import Opcodes as Op
from .spec import Spec, ref_spec_4788
REFERENCE_SPEC_GIT_PATH = ref_spec_4788.git_path
REFERENCE_SPEC_VERSION = ref_spec_4788.version
def count_factory(start: int, step: int = 1) -> Callable[[], Iterator[int]]:
"""
Create a factory that returns fresh count iterators to avoid state
persistence.
"""
return lambda: count(start, step)
pytestmark = pytest.mark.pre_alloc_group(
"beacon_root_tests", reason="Tests beacon root contract functionality using system contract"
)
@pytest.mark.parametrize(
"call_gas, valid_call",
[
pytest.param(Spec.BEACON_ROOTS_CALL_GAS, True),
pytest.param(int(Spec.BEACON_ROOTS_CALL_GAS / 100), False),
],
)
@pytest.mark.parametrize(
"call_type,call_value,valid_input",
[
(Op.CALL, 1, True),
(Op.CALL, 0, True),
(Op.CALLCODE, 0, False),
(Op.DELEGATECALL, 0, False),
(Op.STATICCALL, 0, True),
],
)
@pytest.mark.valid_from("Cancun")
def test_beacon_root_contract_calls(
blockchain_test: BlockchainTestFiller,
beacon_root: bytes,
timestamp: int,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Test calling the beacon root contract in various call contexts.
These call contexts are tested:
- `CALL`
- `DELEGATECALL`
- `CALLCODE`
- `STATICCALL`
for different call gas amounts:
- exact gas (valid call)
- extra gas (valid call)
- insufficient gas (invalid call).
The expected result is that the contract call will be executed if the gas
amount is met and return the correct`parent_beacon_block_root`. Otherwise
the call will be invalid, and not be executed. This is highlighted within
storage by storing the return value of each call context.
"""
blockchain_test(
pre=pre,
blocks=[Block(txs=[tx], parent_beacon_block_root=beacon_root, timestamp=timestamp)],
post=post,
)
@pytest.mark.parametrize(
"timestamp, valid_input",
[
(0x0C, True), # twelve
(2**32, True), # arbitrary
(2**64 - 2, True), # near-max
(2**64 - 1, True), # max
# TODO: Update t8n to un marshal > 64-bit int
# Exception: failed to evaluate: ERROR(10): failed un marshaling stdin
# (2**64, False), # overflow
# Exception: failed to evaluate: ERROR(10): failed un marshaling stdin
# (2**64 + 1, False), # overflow+1
],
)
@pytest.mark.parametrize("auto_access_list", [False, True])
@pytest.mark.parametrize(
"system_address_balance",
[
pytest.param(
0,
id="empty_system_address",
marks=pytest.mark.pre_alloc_group(
"beacon_root_empty_system", reason="Tests with empty system address balance"
),
),
pytest.param(
1,
id="one_wei_system_address",
marks=pytest.mark.pre_alloc_group(
"beacon_root_one_wei_system", reason="Tests with 1 wei system address balance"
),
),
pytest.param(
int(1e18),
id="one_eth_system_address",
marks=pytest.mark.pre_alloc_group(
"beacon_root_one_eth_system", reason="Tests with 1 ETH system address balance"
),
),
],
)
@pytest.mark.valid_from("Cancun")
def test_beacon_root_contract_timestamps(
blockchain_test: BlockchainTestFiller,
beacon_root: bytes,
timestamp: int,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Tests the beacon root contract call across for various valid and invalid
timestamps.
The expected result is that the contract call will return the correct
`parent_beacon_block_root` for a valid input timestamp and return the
zero'd 32 bytes value for an invalid input timestamp.
"""
blockchain_test(
pre=pre,
blocks=[Block(txs=[tx], parent_beacon_block_root=beacon_root, timestamp=timestamp)],
post=post,
)
@pytest.mark.parametrize(
"tx_data",
[
pytest.param(bytes(), id="empty_calldata"),
pytest.param(int.to_bytes(12, length=1, byteorder="big"), id="one_byte"),
pytest.param(int.to_bytes(12, length=31, byteorder="big"), id="31_bytes"),
pytest.param(int.to_bytes(12, length=33, byteorder="big"), id="33_bytes"),
pytest.param(int.to_bytes(12, length=1024, byteorder="big"), id="1024_bytes"),
],
)
@pytest.mark.parametrize("valid_call,valid_input", [(False, False)])
@pytest.mark.parametrize("timestamp", [12])
@pytest.mark.valid_from("Cancun")
def test_calldata_lengths(
blockchain_test: BlockchainTestFiller,
beacon_root: bytes,
timestamp: int,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Tests the beacon root contract call using multiple invalid input lengths.
"""
blockchain_test(
pre=pre,
blocks=[Block(txs=[tx], parent_beacon_block_root=beacon_root, timestamp=timestamp)],
post=post,
)
@pytest.mark.parametrize(
"beacon_root, timestamp",
[
(12, 12), # twelve
(2**32, 2**32), # arbitrary
(2**64 - 2, 2**64 - 2), # near-max
(2**64 - 1, 2**64 - 1), # max
],
indirect=["beacon_root"],
)
@pytest.mark.parametrize("auto_access_list", [False, True])
@pytest.mark.valid_from("Cancun")
def test_beacon_root_equal_to_timestamp(
blockchain_test: BlockchainTestFiller,
beacon_root: bytes,
timestamp: int,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Tests the beacon root contract call where the beacon root is equal to the
timestamp.
The expected result is that the contract call will return the
`parent_beacon_block_root`, as all timestamps used are valid.
"""
blockchain_test(
pre=pre,
blocks=[Block(txs=[tx], parent_beacon_block_root=beacon_root, timestamp=timestamp)],
post=post,
)
@pytest.mark.parametrize("auto_access_list", [False, True])
@pytest.mark.parametrize("call_beacon_root_contract", [True])
@pytest.mark.with_all_tx_types
@pytest.mark.valid_from("Cancun")
def test_tx_to_beacon_root_contract(
blockchain_test: BlockchainTestFiller,
beacon_root: bytes,
timestamp: int,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Tests the beacon root contract using a transaction with different types and
data lengths.
"""
blockchain_test(
pre=pre,
blocks=[Block(txs=[tx], parent_beacon_block_root=beacon_root, timestamp=timestamp)],
post=post,
)
@pytest.mark.parametrize(
"tx_data",
[
pytest.param(int.to_bytes(0, length=32, byteorder="big"), id="zero_calldata"),
],
)
@pytest.mark.parametrize("valid_call,valid_input", [(False, False)])
@pytest.mark.parametrize("timestamp", [12])
@pytest.mark.valid_from("Cancun")
def test_invalid_beacon_root_calldata_value(
blockchain_test: BlockchainTestFiller,
beacon_root: bytes,
timestamp: int,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Tests the beacon root contract call using invalid input values:
- zero calldata.
Contract should revert.
"""
blockchain_test(
pre=pre,
blocks=[Block(txs=[tx], parent_beacon_block_root=beacon_root, timestamp=timestamp)],
post=post,
)
@pytest.mark.parametrize("timestamp", [12])
@pytest.mark.valid_from("Cancun")
def test_beacon_root_selfdestruct(
blockchain_test: BlockchainTestFiller,
beacon_root: bytes,
timestamp: int,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Tests that self destructing the beacon root address transfers actors
balance correctly.
"""
# self destruct actor
self_destruct_actor_address = pre.deploy_contract(
Op.SELFDESTRUCT(Spec.BEACON_ROOTS_ADDRESS),
balance=0xBA1,
)
# self destruct caller
self_destruct_caller_address = pre.deploy_contract(
Op.CALL(gas=100_000, address=self_destruct_actor_address)
+ Op.SSTORE(0, Op.BALANCE(Spec.BEACON_ROOTS_ADDRESS))
)
post = {
self_destruct_caller_address: Account(
storage=Storage({0: 0xBA1}), # type: ignore
)
}
blockchain_test(
pre=pre,
blocks=[
Block(
txs=[
Transaction(
sender=pre.fund_eoa(),
to=self_destruct_caller_address,
gas_limit=100_000,
)
]
)
],
post=post,
)
@pytest.mark.parametrize(
"timestamps_factory",
[
pytest.param(
count_factory(
start=Spec.HISTORY_BUFFER_LENGTH - 5,
step=1,
),
id="buffer_wraparound",
),
pytest.param(
count_factory(
start=12,
step=Spec.HISTORY_BUFFER_LENGTH,
),
id="buffer_wraparound_overwrite",
),
pytest.param(
count_factory(
start=2**32,
step=Spec.HISTORY_BUFFER_LENGTH,
),
id="buffer_wraparound_overwrite_high_timestamp",
),
pytest.param(
count_factory(
start=5,
step=Spec.HISTORY_BUFFER_LENGTH - 1,
),
id="buffer_wraparound_no_overwrite",
),
pytest.param(
count_factory(
start=Spec.HISTORY_BUFFER_LENGTH - 3,
step=Spec.HISTORY_BUFFER_LENGTH + 1,
),
id="buffer_wraparound_no_overwrite_2",
),
],
)
@pytest.mark.parametrize("block_count", [10]) # All tests use 10 blocks
@pytest.mark.valid_from("Cancun")
def test_multi_block_beacon_root_timestamp_calls(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
timestamps_factory: Callable[[], Iterator[int]],
beacon_roots: Iterator[bytes],
block_count: int,
call_gas: int,
call_value: int,
) -> None:
"""
Tests multiple blocks where each block writes a timestamp to storage and
contains one transaction that calls the beacon root contract multiple
times.
The blocks might overwrite the historical roots buffer, or not, depending
on the `timestamps`, and whether they increment in multiples of
`Spec.HISTORY_BUFFER_LENGTH` or not.
By default, the beacon roots are the keccak of the block number.
Each transaction checks the current timestamp and also all previous
timestamps, and verifies that the beacon root is correct for all of them if
the timestamp is supposed to be in the buffer, which might have been
overwritten by a later block.
"""
# Create fresh iterator to avoid state persistence between test phases
timestamps = timestamps_factory()
blocks: List[Block] = []
post = {}
timestamps_storage: Dict[int, int] = {}
roots_storage: Dict[int, bytes] = {}
all_timestamps: List[int] = []
sender = pre.fund_eoa()
for timestamp, beacon_root, _i in zip(
timestamps,
beacon_roots,
range(block_count),
strict=False,
):
timestamp_index = timestamp % Spec.HISTORY_BUFFER_LENGTH
timestamps_storage[timestamp_index] = timestamp
roots_storage[timestamp_index] = beacon_root
all_timestamps.append(timestamp)
withdraw_index = count(0)
current_call_account_code = Bytecode()
current_call_account_expected_storage = Storage()
# We are going to call the beacon roots contract once for every
# timestamp of the current and all previous blocks, and check that the
# returned beacon root is still correct only if it was not overwritten.
for t in all_timestamps:
current_call_account_code += Op.MSTORE(0, t)
call_valid = (
timestamp_index in timestamps_storage
and timestamps_storage[t % Spec.HISTORY_BUFFER_LENGTH] == t
)
current_call_account_code += Op.SSTORE(
current_call_account_expected_storage.store_next(0x01 if call_valid else 0x00),
Op.CALL(
call_gas,
Spec.BEACON_ROOTS_ADDRESS,
call_value,
0x00,
0x20,
0x20,
0x20,
),
)
current_call_account_code += Op.SSTORE(
current_call_account_expected_storage.store_next(
roots_storage[t % Spec.HISTORY_BUFFER_LENGTH] if call_valid else 0x00
),
Op.MLOAD(0x20),
)
current_call_account_address = pre.deploy_contract(current_call_account_code)
post[current_call_account_address] = Account(
storage=current_call_account_expected_storage,
)
blocks.append(
Block(
txs=[
Transaction(
sender=sender,
to=current_call_account_address,
data=Hash(timestamp),
gas_limit=1_000_000,
)
],
parent_beacon_block_root=beacon_root,
timestamp=timestamp,
withdrawals=[
# Also withdraw to the beacon root contract and the system
# address
Withdrawal(
address=Spec.BEACON_ROOTS_ADDRESS,
amount=1,
index=next(withdraw_index),
validator_index=0,
),
Withdrawal(
address=Spec.SYSTEM_ADDRESS,
amount=1,
index=next(withdraw_index),
validator_index=1,
),
],
)
)
blockchain_test(
pre=pre,
blocks=blocks,
post=post,
)
@pytest.mark.parametrize(
"timestamps_factory",
[pytest.param(count_factory(start=1000, step=1000), id="fork_transition")],
)
@pytest.mark.parametrize("block_count", [20])
@pytest.mark.valid_at_transition_to("Cancun")
def test_beacon_root_transition(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
timestamps_factory: Callable[[], Iterator[int]],
beacon_roots: Iterator[bytes],
block_count: int,
call_gas: int,
call_value: int,
fork: Fork,
) -> None:
"""
Tests the fork transition to cancun and verifies that blocks with timestamp
lower than the transition timestamp do not contain beacon roots in the
pre-deployed contract.
"""
# Create fresh iterator to avoid state persistence between test phases
timestamps = timestamps_factory()
blocks: List[Block] = []
post = {}
timestamps_storage: Dict[int, int] = {}
roots_storage: Dict[int, bytes] = {}
all_timestamps: List[int] = []
timestamps_in_beacon_root_contract: List[int] = []
sender = pre.fund_eoa()
for timestamp, beacon_root, i in zip(
timestamps, beacon_roots, range(block_count), strict=False
):
timestamp_index = timestamp % Spec.HISTORY_BUFFER_LENGTH
transitioned = fork.header_beacon_root_required(block_number=i, timestamp=timestamp)
if transitioned:
# We've transitioned, the current timestamp must contain a value in
# the contract
timestamps_in_beacon_root_contract.append(timestamp)
timestamps_storage[timestamp_index] = timestamp
roots_storage[timestamp_index] = beacon_root
all_timestamps.append(timestamp)
withdraw_index = count(0)
current_call_account_code = Bytecode()
current_call_account_expected_storage = Storage()
# We are going to call the beacon roots contract once for every
# timestamp of the current and all previous blocks, and check that the
# returned beacon root is correct only if it was after the transition
# timestamp.
for t in all_timestamps:
current_call_account_code += Op.MSTORE(0, t)
call_valid = (
t in timestamps_in_beacon_root_contract
and timestamp_index in timestamps_storage
and timestamps_storage[t % Spec.HISTORY_BUFFER_LENGTH] == t
)
current_call_account_code += Op.SSTORE(
current_call_account_expected_storage.store_next(0x01 if call_valid else 0x00),
Op.CALL(
call_gas,
Spec.BEACON_ROOTS_ADDRESS,
call_value,
0x00,
0x20,
0x20,
0x20,
),
)
current_call_account_code += Op.SSTORE(
current_call_account_expected_storage.store_next(
roots_storage[t % Spec.HISTORY_BUFFER_LENGTH] if call_valid else 0x00
),
Op.MLOAD(0x20),
)
current_call_account_address = pre.deploy_contract(current_call_account_code)
post[current_call_account_address] = Account(
storage=current_call_account_expected_storage,
)
blocks.append(
Block(
txs=[
Transaction(
sender=sender,
to=current_call_account_address,
data=Hash(timestamp),
gas_limit=1_000_000,
)
],
parent_beacon_block_root=beacon_root if transitioned else None,
timestamp=timestamp,
withdrawals=[
# Also withdraw to the beacon root contract and the system
# address
Withdrawal(
address=Spec.BEACON_ROOTS_ADDRESS,
amount=1,
index=next(withdraw_index),
validator_index=0,
),
Withdrawal(
address=Spec.SYSTEM_ADDRESS,
amount=1,
index=next(withdraw_index),
validator_index=1,
),
],
)
)
blockchain_test(
pre=pre,
blocks=blocks,
post=post,
)
@pytest.mark.parametrize("timestamp", [15_000])
@pytest.mark.valid_at_transition_to("Cancun")
@pytest.mark.pre_alloc_group(
"beacon_root_no_contract", reason="This test removes the beacon root system contract"
)
def test_no_beacon_root_contract_at_transition(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
beacon_roots: Iterator[bytes],
tx: Transaction,
timestamp: int,
caller_address: Address,
fork: Fork,
) -> None:
"""
Tests the fork transition to cancun in the case where the beacon root
pre-deploy was not deployed in time for the fork.
"""
assert fork.header_beacon_root_required(block_number=1, timestamp=timestamp)
blocks: List[Block] = [
Block(
txs=[tx],
parent_beacon_block_root=next(beacon_roots),
timestamp=timestamp,
withdrawals=[
# Also withdraw to the beacon root contract and the system
# address
Withdrawal(
address=Spec.BEACON_ROOTS_ADDRESS,
amount=1,
index=0,
validator_index=0,
),
Withdrawal(
address=Spec.SYSTEM_ADDRESS,
amount=1,
index=1,
validator_index=1,
),
],
)
]
pre[Spec.BEACON_ROOTS_ADDRESS] = Account(
code=b"", # Remove the code that is automatically allocated on Cancun
# fork
nonce=0,
balance=0,
)
post = {
Spec.BEACON_ROOTS_ADDRESS: Account(
storage={
timestamp % Spec.HISTORY_BUFFER_LENGTH: 0,
(timestamp % Spec.HISTORY_BUFFER_LENGTH) + Spec.HISTORY_BUFFER_LENGTH: 0,
},
code=b"",
nonce=0,
balance=int(1e9),
),
caller_address: Account(
storage={0: 1}, # Successful call because the contract is not there, but
# nothing else is stored
),
}
blockchain_test(
pre=pre,
blocks=blocks,
post=post,
)
@pytest.mark.parametrize(
"timestamp",
[
pytest.param(15_000, id="deploy_on_shanghai"),
pytest.param(30_000, id="deploy_on_cancun"),
],
)
@pytest.mark.valid_at_transition_to("Cancun")
@pytest.mark.pre_alloc_group(
"beacon_root_deploy_contract",
reason=(
"This test is parametrized with a hard-coded address (the beacon root contract deployer "
"address); they can't be in the same pre alloc group."
),
)
def test_beacon_root_contract_deploy(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
beacon_root: bytes,
tx: Transaction,
timestamp: int,
post: Dict,
fork: Fork,
) -> None:
"""
Tests the fork transition to cancun deploying the contract during Shanghai
and verifying the code deployed and its functionality after Cancun.
"""
assert fork.header_beacon_root_required(block_number=1, timestamp=timestamp)
tx_gas_limit = 0x3D090
tx_gas_price = 0xE8D4A51000
deployer_required_balance = tx_gas_limit * tx_gas_price
deploy_tx = Transaction(
ty=0,
nonce=0,
to=None,
gas_limit=tx_gas_limit,
gas_price=tx_gas_price,
value=0,
data=bytes.fromhex(
"60618060095f395ff33373fffffffffffffffffffffffffffffffffffffffe14604d576020361460"
"24575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f526020"
"5ff35b5f5ffd5b62001fff42064281555f359062001fff015500"
),
v=0x1B,
r=0x539,
s=0x1B9B6EB1F0,
protected=False,
).with_signature_and_sender()
deployer_address = deploy_tx.sender
assert deployer_address is not None
assert Address(deployer_address) == Spec.BEACON_ROOTS_DEPLOYER_ADDRESS
blocks: List[Block] = []
beacon_root_contract_storage: Dict = {}
for i, current_timestamp in enumerate(range(timestamp // 2, timestamp + 1, timestamp // 2)):
if i == 0:
blocks.append(
Block( # Deployment block
txs=[deploy_tx],
parent_beacon_block_root=(
beacon_root
if fork.header_beacon_root_required(
block_number=1, timestamp=current_timestamp
)
else None
),
timestamp=timestamp // 2,
withdrawals=[
# Also withdraw to the beacon root contract and the
# system address
Withdrawal(
address=Spec.BEACON_ROOTS_ADDRESS,
amount=1,
index=0,
validator_index=0,
),
Withdrawal(
address=Spec.SYSTEM_ADDRESS,
amount=1,
index=1,
validator_index=1,
),
],
)
)
beacon_root_contract_storage[current_timestamp % Spec.HISTORY_BUFFER_LENGTH] = 0
beacon_root_contract_storage[
(current_timestamp % Spec.HISTORY_BUFFER_LENGTH) + Spec.HISTORY_BUFFER_LENGTH
] = 0
elif i == 1:
blocks.append(
Block( # Contract already deployed
txs=[tx],
parent_beacon_block_root=beacon_root,
timestamp=timestamp,
withdrawals=[
# Also withdraw to the beacon root contract and the
# system address
Withdrawal(
address=Spec.BEACON_ROOTS_ADDRESS,
amount=1,
index=2,
validator_index=0,
),
Withdrawal(
address=Spec.SYSTEM_ADDRESS,
amount=1,
index=3,
validator_index=1,
),
],
),
)
beacon_root_contract_storage[current_timestamp % Spec.HISTORY_BUFFER_LENGTH] = (
current_timestamp
)
beacon_root_contract_storage[
(current_timestamp % Spec.HISTORY_BUFFER_LENGTH) + Spec.HISTORY_BUFFER_LENGTH
] = beacon_root
else:
raise AssertionError("This test should only have two blocks")
expected_code = fork.pre_allocation_blockchain()[Spec.BEACON_ROOTS_ADDRESS]["code"]
pre[Spec.BEACON_ROOTS_ADDRESS] = Account(
code=b"", # Remove the code that is automatically allocated on Cancun
# fork
nonce=0,
balance=0,
)
pre[deployer_address] = Account(
balance=deployer_required_balance,
)
post[Spec.BEACON_ROOTS_ADDRESS] = Account(
storage=beacon_root_contract_storage,
code=expected_code,
nonce=1,
balance=int(2e9),
)
post[Spec.SYSTEM_ADDRESS] = Account(
storage={},
code=b"",
nonce=0,
balance=int(2e9),
)
post[deployer_address] = Account(
balance=175916000000000000, # It doesn't consume all the balance :(
nonce=1,
)
blockchain_test(
pre=pre,
blocks=blocks,
post=post,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4788_beacon_root/conftest.py | tests/cancun/eip4788_beacon_root/conftest.py | """Shared pytest definitions local to EIP-4788 tests."""
from itertools import count
from typing import Dict, Iterator, List
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
AccessList,
Account,
Address,
Alloc,
AuthorizationTuple,
Bytecode,
Environment,
Hash,
Storage,
Transaction,
add_kzg_version,
keccak256,
)
from ethereum_test_tools import Opcodes as Op
from .spec import Spec, SpecHelpers
BLOB_COMMITMENT_VERSION_KZG = 1
@pytest.fixture
def timestamp() -> int: # noqa: D103
return 12
@pytest.fixture
def beacon_roots() -> Iterator[bytes]:
"""
By default, return an iterator that returns the keccak of an internal
counter.
"""
class BeaconRoots:
def __init__(self) -> None:
self._counter = count(1)
def __iter__(self) -> "BeaconRoots":
# Create a fresh iterator with a new counter each time
return BeaconRoots()
def __next__(self) -> bytes:
return keccak256(int.to_bytes(next(self._counter), length=8, byteorder="big"))
return BeaconRoots()
@pytest.fixture
def beacon_root(request: pytest.FixtureRequest, beacon_roots: Iterator[bytes]) -> bytes: # noqa: D103
return Hash(request.param) if hasattr(request, "param") else next(beacon_roots)
@pytest.fixture
def env(timestamp: int, beacon_root: bytes) -> Environment: # noqa: D103
return Environment(
timestamp=timestamp,
parent_beacon_block_root=beacon_root,
)
@pytest.fixture
def call_beacon_root_contract() -> bool:
"""By default, do not directly call the beacon root contract."""
return False
@pytest.fixture
def call_type() -> Op: # noqa: D103
return Op.CALL
@pytest.fixture
def call_value() -> int: # noqa: D103
return 0
@pytest.fixture
def call_gas() -> int: # noqa: D103
return Spec.BEACON_ROOTS_CALL_GAS
@pytest.fixture
def caller_address(pre: Alloc, contract_call_code: Bytecode) -> Address: # noqa: D103
return pre.deploy_contract(contract_call_code, balance=0x10**10)
@pytest.fixture
def contract_call_code(call_type: Op, call_value: int, call_gas: int) -> Bytecode:
"""Code to call the beacon root contract."""
args_start, args_length, return_start, return_length = 0x20, Op.CALLDATASIZE, 0x00, 0x20
contract_call_code = Op.CALLDATACOPY(args_start, 0x00, args_length)
if call_type == Op.CALL or call_type == Op.CALLCODE:
contract_call_code += Op.SSTORE(
0x00, # store the result of the contract call in storage[0]
# https://github.com/ethereum/execution-spec-tests/issues/348
call_type(
call_gas,
Spec.BEACON_ROOTS_ADDRESS,
call_value,
args_start,
args_length,
return_start,
return_length,
),
)
elif call_type == Op.DELEGATECALL or call_type == Op.STATICCALL:
# delegatecall and staticcall use one less argument
contract_call_code += Op.SSTORE(
0x00,
# https://github.com/ethereum/execution-spec-tests/issues/348
call_type(
call_gas,
Spec.BEACON_ROOTS_ADDRESS,
args_start,
args_length,
return_start,
return_length,
),
)
contract_call_code += (
Op.SSTORE( # Save the return value of the contract call
0x01,
Op.MLOAD(return_start),
)
+ Op.SSTORE( # Save the length of the return value of the contract call
0x02,
Op.RETURNDATASIZE,
)
+ Op.RETURNDATACOPY(
return_start,
0x00,
Op.RETURNDATASIZE,
)
+ Op.SSTORE(
0x03,
Op.MLOAD(return_start),
)
)
return contract_call_code
@pytest.fixture
def valid_call() -> bool:
"""Beacon root contract call validity: defaults to True."""
return True
@pytest.fixture
def valid_input() -> bool:
"""Timestamp input to contract call validity: defaults to True."""
return True
@pytest.fixture
def system_address_balance() -> int:
"""Balance of the system address."""
return 0
@pytest.fixture(autouse=True)
def pre_fund_system_address(pre: Alloc, system_address_balance: int) -> None:
"""Whether to fund the system address."""
if system_address_balance > 0:
pre.fund_address(Address(Spec.SYSTEM_ADDRESS), system_address_balance)
@pytest.fixture
def tx_to_address(caller_address: Address) -> Address:
"""Specify the address for the `Transaction`'s `to` field."""
return caller_address
@pytest.fixture
def auto_access_list() -> bool:
"""Whether to append the accessed storage keys to the transaction."""
return False
@pytest.fixture
def access_list(auto_access_list: bool, timestamp: int) -> List[AccessList]:
"""
Access list included in the transaction to call the beacon root contract.
"""
if auto_access_list:
return [
AccessList(
address=Spec.BEACON_ROOTS_ADDRESS,
storage_keys=[
timestamp,
timestamp + Spec.HISTORY_BUFFER_LENGTH,
],
),
]
return []
@pytest.fixture
def tx_data(timestamp: int) -> bytes:
"""Tx data included in the to call the beacon root contract."""
return Hash(timestamp)
@pytest.fixture
def tx_type() -> int:
"""
Transaction type to call the caller contract or the beacon root contract
directly.
By default use a type 2 transaction.
"""
return 2
@pytest.fixture
def tx(
pre: Alloc,
fork: Fork,
tx_to_address: Address,
tx_data: bytes,
tx_type: int,
access_list: List[AccessList],
call_beacon_root_contract: bool,
) -> Transaction:
"""Prepare transaction to call the beacon root contract caller account."""
to = Spec.BEACON_ROOTS_ADDRESS if call_beacon_root_contract else tx_to_address
kwargs: Dict = {
"ty": tx_type,
"sender": pre.fund_eoa(),
"data": tx_data,
"to": to,
"gas_limit": 1_000_000,
}
if tx_type > 0:
kwargs["access_list"] = access_list
if tx_type == 3:
kwargs["max_fee_per_blob_gas"] = fork.min_base_fee_per_blob_gas()
kwargs["blob_versioned_hashes"] = add_kzg_version([0], BLOB_COMMITMENT_VERSION_KZG)
if tx_type == 4:
signer = pre.fund_eoa(amount=0)
kwargs["authorization_list"] = [
AuthorizationTuple(
signer=signer,
address=Address(0),
nonce=0,
)
]
if tx_type > 4:
raise Exception(f"Unexpected transaction type: '{tx_type}'. Test requires update.")
return Transaction(**kwargs)
@pytest.fixture
def post(
caller_address: Address,
beacon_root: bytes,
valid_call: bool,
valid_input: bool,
call_beacon_root_contract: bool,
) -> Dict:
"""
Prepare expected post state for a single contract call based upon the
success or failure of the call, and the validity of the timestamp input.
"""
storage = Storage()
if not call_beacon_root_contract:
storage = SpecHelpers.expected_storage(
beacon_root=beacon_root,
valid_call=valid_call,
valid_input=valid_input,
)
return {
caller_address: Account(
storage=storage,
),
}
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4788_beacon_root/__init__.py | tests/cancun/eip4788_beacon_root/__init__.py | """Cross-client EIP-4788 Tests."""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_point_evaluation_precompile_gas.py | tests/cancun/eip4844_blobs/test_point_evaluation_precompile_gas.py | """
Tests gas usage on point evaluation precompile for EIP-4844.
Tests gas usage on point evaluation precompile for
[EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844).
"""
from typing import Dict, Literal
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
Account,
Address,
Alloc,
Bytecode,
CodeGasMeasure,
Environment,
StateTestFiller,
Transaction,
ceiling_division,
)
from ethereum_test_vm import Opcodes as Op
from .common import INF_POINT, Z
from .spec import Spec, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
@pytest.fixture
def precompile_input(proof: Literal["correct", "incorrect"]) -> bytes:
"""Format depending on whether we want a correct proof or not."""
kzg_commitment = INF_POINT
kzg_proof = INF_POINT
z = Z
# INF_POINT commitment and proof evaluate to 0 on all z values
y = 0 if proof == "correct" else 1
versioned_hash = Spec.kzg_to_versioned_hash(kzg_commitment)
return (
versioned_hash
+ z.to_bytes(32, "little")
+ y.to_bytes(32, "little")
+ kzg_commitment
+ kzg_proof
)
@pytest.fixture
def call_type() -> Op:
"""
Type of call to use to call the precompile.
Defaults to Op.CALL, but can be parametrized to use other opcode types.
"""
return Op.CALL
@pytest.fixture
def call_gas() -> int:
"""
Amount of gas to pass to the precompile.
Defaults to POINT_EVALUATION_PRECOMPILE_GAS, but can be parametrized to
test different amounts.
"""
return Spec.POINT_EVALUATION_PRECOMPILE_GAS
def copy_opcode_cost(fork: Fork, length: int) -> int:
"""
Calculate the cost of the COPY opcodes, assuming memory expansion from
empty memory, based on the costs specified in the yellow paper.
https://ethereum.github.io/yellowpaper/paper.pdf.
"""
cost_memory_bytes = fork.memory_expansion_gas_calculator()
return (
3
+ (ceiling_division(length, 32) * 3)
+ cost_memory_bytes(new_bytes=length, previous_bytes=0)
)
@pytest.fixture
def precompile_caller_code(
fork: Fork,
call_type: Op,
call_gas: int,
precompile_input: bytes,
) -> Bytecode:
"""Code to call the point evaluation precompile and evaluate gas usage."""
calldatasize_cost = 2
push_operations_cost = 3
warm_storage_read_cost = 100
precompile_caller_code = Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
overhead_cost = (
warm_storage_read_cost
+ (calldatasize_cost * 1)
+ (push_operations_cost * 2)
+ copy_opcode_cost(fork, len(precompile_input))
)
if call_type == Op.CALL or call_type == Op.CALLCODE:
# https://github.com/ethereum/execution-spec-tests/issues/348
precompile_caller_code += call_type(
call_gas,
Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS,
0x00,
0x00,
Op.CALLDATASIZE,
0x00,
0x00,
)
overhead_cost += (push_operations_cost * 6) + (calldatasize_cost * 1)
elif call_type == Op.DELEGATECALL or call_type == Op.STATICCALL:
# Delegatecall and staticcall use one less argument
# https://github.com/ethereum/execution-spec-tests/issues/348
precompile_caller_code += call_type(
call_gas,
Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS,
0x00,
Op.CALLDATASIZE,
0x00,
0x00,
)
overhead_cost += (push_operations_cost * 5) + (calldatasize_cost * 1)
gas_measure_code = CodeGasMeasure(
code=precompile_caller_code,
overhead_cost=overhead_cost,
extra_stack_items=1,
)
return gas_measure_code
@pytest.fixture
def precompile_caller_address(pre: Alloc, precompile_caller_code: Bytecode) -> Address:
"""Address of the precompile caller account."""
return pre.deploy_contract(precompile_caller_code)
@pytest.fixture
def tx(
pre: Alloc,
precompile_caller_address: Address,
precompile_input: bytes,
) -> Transaction:
"""Prepare transaction used to call the precompile caller account."""
return Transaction(
sender=pre.fund_eoa(),
data=precompile_input,
to=precompile_caller_address,
value=0,
gas_limit=Spec.POINT_EVALUATION_PRECOMPILE_GAS * 20,
)
@pytest.fixture
def post(
precompile_caller_address: Address,
proof: Literal["correct", "incorrect"],
call_gas: int,
) -> Dict:
"""
Prepare expected post for each test, depending on the success or failure of
the precompile call and the gas usage.
"""
if proof == "correct":
expected_gas_usage = (
call_gas
if call_gas < Spec.POINT_EVALUATION_PRECOMPILE_GAS
else Spec.POINT_EVALUATION_PRECOMPILE_GAS
)
else:
expected_gas_usage = call_gas
return {
precompile_caller_address: Account(
storage={
0: expected_gas_usage,
},
),
}
@pytest.mark.parametrize(
"call_type",
[Op.CALL, Op.DELEGATECALL, Op.CALLCODE, Op.STATICCALL],
)
@pytest.mark.parametrize(
"call_gas",
[
Spec.POINT_EVALUATION_PRECOMPILE_GAS,
Spec.POINT_EVALUATION_PRECOMPILE_GAS - 1,
Spec.POINT_EVALUATION_PRECOMPILE_GAS + 1,
],
ids=["exact_gas", "insufficient_gas", "extra_gas"],
)
@pytest.mark.parametrize("proof", ["correct", "incorrect"])
@pytest.mark.valid_from("Cancun")
def test_point_evaluation_precompile_gas_usage(
state_test: StateTestFiller,
pre: Dict,
tx: Transaction,
post: Dict,
) -> None:
"""
Test point evaluation precompile gas usage under different call contexts
and gas limits.
- Test using all call types (CALL, DELEGATECALL, CALLCODE, STATICCALL) -
Test using different gas limits (exact gas, insufficient gas, extra gas) -
Test using correct and incorrect proofs
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/common.py | tests/cancun/eip4844_blobs/common.py | """Common constants, classes & functions local to EIP-4844 tests."""
from typing import Literal
INF_POINT = (0xC0 << 376).to_bytes(48, byteorder="big")
Z = 0x623CE31CF9759A5C8DAF3A357992F9F3DD7F9339D8998BC8E68373E54F00B75E
Z_Y_INVALID_ENDIANNESS: Literal["little", "big"] = "little"
Z_Y_VALID_ENDIANNESS: Literal["little", "big"] = "big"
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/spec.py | tests/cancun/eip4844_blobs/spec.py | """Defines EIP-4844 specification constants and functions."""
import itertools
from dataclasses import dataclass
from hashlib import sha256
from typing import List, Optional, Tuple
from ethereum_test_forks import Fork
from ethereum_test_tools import Transaction
@dataclass(frozen=True)
class ReferenceSpec:
"""Defines the reference spec version and git path."""
git_path: str
version: str
ref_spec_4844 = ReferenceSpec("EIPS/eip-4844.md", "de2e4a46ad93fc04e6fe3174dc6e90a3307bdb5f")
# Constants
@dataclass(frozen=True)
class Spec:
"""
Parameters from the EIP-4844 specifications as defined at
https://eips.ethereum.org/EIPS/eip-4844#parameters.
If the parameter is not currently used within the tests, it is commented
out.
"""
BLOB_TX_TYPE = 0x03
FIELD_ELEMENTS_PER_BLOB = 4096
BLS_MODULUS = 0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001
BLOB_COMMITMENT_VERSION_KZG = 1
POINT_EVALUATION_PRECOMPILE_ADDRESS = 10
POINT_EVALUATION_PRECOMPILE_GAS = 50_000
# MAX_VERSIONED_HASHES_LIST_SIZE = 2**24
# MAX_CALLDATA_SIZE = 2**24
# MAX_ACCESS_LIST_SIZE = 2**24
# MAX_ACCESS_LIST_STORAGE_KEYS = 2**24
# MAX_TX_WRAP_COMMITMENTS = 2**12
# LIMIT_BLOBS_PER_TX = 2**12
HASH_OPCODE_BYTE = 0x49
HASH_GAS_COST = 3
GAS_PER_BLOB = 2**17
@classmethod
def kzg_to_versioned_hash(
cls,
kzg_commitment: bytes | int, # 48 bytes
blob_commitment_version_kzg: Optional[bytes | int] = None,
) -> bytes:
"""Calculate versioned hash for a given KZG commitment."""
if blob_commitment_version_kzg is None:
blob_commitment_version_kzg = cls.BLOB_COMMITMENT_VERSION_KZG
if isinstance(kzg_commitment, int):
kzg_commitment = kzg_commitment.to_bytes(48, "big")
if isinstance(blob_commitment_version_kzg, int):
blob_commitment_version_kzg = blob_commitment_version_kzg.to_bytes(1, "big")
return blob_commitment_version_kzg + sha256(kzg_commitment).digest()[1:]
@classmethod
def get_total_blob_gas(cls, *, tx: Transaction, blob_gas_per_blob: int) -> int:
"""Calculate the total blob gas for a transaction."""
if tx.blob_versioned_hashes is None:
return 0
return blob_gas_per_blob * len(tx.blob_versioned_hashes)
@dataclass(frozen=True)
class SpecHelpers:
"""
Define parameters and helper functions that are tightly coupled to the 4844
spec but not strictly part of it.
"""
BYTES_PER_FIELD_ELEMENT = 32
@classmethod
def get_min_excess_blob_gas_for_blob_gas_price(
cls,
*,
fork: Fork,
blob_gas_price: int,
) -> int:
"""
Get the minimum required excess blob gas value to get a given blob gas
cost in a block.
"""
current_excess_blob_gas = 0
current_blob_gas_price = 1
get_blob_gas_price = fork.blob_gas_price_calculator()
gas_per_blob = fork.blob_gas_per_blob()
while current_blob_gas_price < blob_gas_price:
current_excess_blob_gas += gas_per_blob
current_blob_gas_price = get_blob_gas_price(excess_blob_gas=current_excess_blob_gas)
return current_excess_blob_gas
@classmethod
def get_min_excess_blobs_for_blob_gas_price(
cls,
*,
fork: Fork,
blob_gas_price: int,
) -> int:
"""
Get the minimum required excess blobs to get a given blob gas cost in a
block.
"""
gas_per_blob = fork.blob_gas_per_blob()
return (
cls.get_min_excess_blob_gas_for_blob_gas_price(
fork=fork,
blob_gas_price=blob_gas_price,
)
// gas_per_blob
)
@classmethod
def get_blob_combinations(
cls,
blob_count: int,
max_blobs_per_tx: int,
) -> List[Tuple[int, ...]]:
"""
Get all possible combinations of blobs that result in a given blob
count.
"""
combinations = [
seq
for i in range(
blob_count + 1, 0, -1
) # We can have from 1 to at most MAX_BLOBS_PER_BLOCK blobs per
# block
for seq in itertools.combinations_with_replacement(
range(1, min(blob_count + 1, max_blobs_per_tx) + 1), i
) # We iterate through all possible combinations
# And we only keep the ones that match the expected blob count
if sum(seq) == blob_count and all(tx_blobs <= max_blobs_per_tx for tx_blobs in seq)
# Validate each tx
]
# We also add the reversed version of each combination, only if it's
# not already in the list. E.g. (4, 1) is added from (1, 4) but not (1,
# 1, 1, 1, 1) because its reversed version is identical.
combinations += [
tuple(reversed(x)) for x in combinations if tuple(reversed(x)) not in combinations
]
return combinations
@classmethod
def all_valid_blob_combinations(cls, fork: Fork) -> List[Tuple[int, ...]]:
"""
Return all valid blob tx combinations for a given block, assuming the
given MAX_BLOBS_PER_BLOCK, whilst respecting MAX_BLOBS_PER_TX.
"""
max_blobs_per_block = fork.max_blobs_per_block()
max_blobs_per_tx = fork.max_blobs_per_tx()
combinations: List[Tuple[int, ...]] = []
for i in range(1, max_blobs_per_block + 1):
combinations += cls.get_blob_combinations(i, max_blobs_per_tx)
return combinations
@classmethod
def invalid_blob_combinations(cls, fork: Fork) -> List[Tuple[int, ...]]:
"""
Return invalid blob tx combinations for a given block that use up to
MAX_BLOBS_PER_BLOCK+1 blobs.
"""
max_blobs_per_block = fork.max_blobs_per_block()
max_blobs_per_tx = fork.max_blobs_per_tx()
invalid_combinations = cls.get_blob_combinations(
max_blobs_per_block + 1,
max_blobs_per_tx,
)
invalid_combinations.append((max_blobs_per_block + 1,))
return invalid_combinations
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_excess_blob_gas.py | tests/cancun/eip4844_blobs/test_excess_blob_gas.py | """
Tests `excessBlobGas` and `blobGasUsed` block fields for EIP-4844.
Tests `excessBlobGas` and `blobGasUsed` block fields for
[EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844)
Note: Adding a new test Add a function that is named `test_<test_name>` and
takes at least the following arguments.
Required arguments:
- `blockchain_test`
- `env`
- `pre`
- `blocks`
- `post`
- `correct_excess_blob_gas`
The following arguments can be parametrized to generate new combinations
and
test cases:
- new_blobs: Number of blobs in the block (automatically split across
transactions as needed)
All other `pytest.fixture` fixtures can be parametrized to generate new
combinations and test cases.
"""
import itertools
from typing import Callable, Dict, Iterator, List, Mapping, Optional, Tuple
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
EOA,
Account,
Address,
Alloc,
Block,
BlockchainTestFiller,
BlockException,
Bytecode,
Environment,
Hash,
Header,
Transaction,
add_kzg_version,
)
from ethereum_test_tools import Opcodes as Op
from .spec import Spec, SpecHelpers, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
# All tests run from Cancun fork
pytestmark = pytest.mark.valid_from("Cancun")
@pytest.fixture
def parent_excess_blobs(fork: Fork) -> int: # noqa: D103
"""
By default we start with an intermediate value between the target and max.
"""
return (fork.max_blobs_per_block() + fork.target_blobs_per_block()) // 2 + 1
@pytest.fixture
def header_excess_blobs_delta() -> Optional[int]: # noqa: D103
return None
@pytest.fixture
def header_excess_blob_gas_delta() -> Optional[int]: # noqa: D103
return None
@pytest.fixture
def header_excess_blob_gas( # noqa: D103
correct_excess_blob_gas: int,
header_excess_blobs_delta: Optional[int],
header_excess_blob_gas_delta: Optional[int],
blob_gas_per_blob: int,
) -> Optional[int]:
if header_excess_blobs_delta is not None:
modified_excess_blob_gas = correct_excess_blob_gas + (
header_excess_blobs_delta * blob_gas_per_blob
)
if modified_excess_blob_gas < 0:
modified_excess_blob_gas = 2**64 + (modified_excess_blob_gas)
return modified_excess_blob_gas
if header_excess_blob_gas_delta is not None:
return correct_excess_blob_gas + header_excess_blob_gas_delta
return None
@pytest.fixture
def tx_blob_data_cost(
tx_max_fee_per_blob_gas: int,
new_blobs: int,
blob_gas_per_blob: int,
) -> int:
"""Calculate total blob data cost for all blobs in block."""
return tx_max_fee_per_blob_gas * blob_gas_per_blob * new_blobs
@pytest.fixture
def tx_gas_limit() -> int: # noqa: D103
return 45000
@pytest.fixture
def tx_exact_cost(
tx_value: int,
tx_max_fee_per_gas: int,
tx_blob_data_cost: int,
tx_gas_limit: int,
new_blobs: int,
fork: Fork,
) -> int:
"""Calculate exact cost for all transactions."""
if new_blobs == 0:
num_transactions = 1
else:
num_transactions = (new_blobs + fork.max_blobs_per_tx() - 1) // fork.max_blobs_per_tx()
base_cost_per_tx = (tx_gas_limit * tx_max_fee_per_gas) + tx_value
total_base_cost = base_cost_per_tx * num_transactions
return total_base_cost + tx_blob_data_cost
@pytest.fixture
def destination_account_bytecode() -> Bytecode: # noqa: D103
# Verify that the BLOBBASEFEE opcode reflects the current blob gas cost
return Op.SSTORE(0, Op.BLOBBASEFEE)
@pytest.fixture
def destination_account( # noqa: D103
pre: Alloc,
destination_account_bytecode: Bytecode,
) -> Address:
return pre.deploy_contract(destination_account_bytecode)
@pytest.fixture
def sender(pre: Alloc, tx_exact_cost: int) -> Address: # noqa: D103
return pre.fund_eoa(tx_exact_cost)
@pytest.fixture
def txs( # noqa: D103
sender: EOA,
new_blobs: int,
tx_max_fee_per_gas: int,
tx_max_fee_per_blob_gas: int,
tx_gas_limit: int,
destination_account: Address,
fork: Fork,
) -> List[Transaction]:
if new_blobs == 0:
# Send a normal type two tx instead
return [
Transaction(
ty=2,
sender=sender,
to=destination_account,
value=1,
gas_limit=tx_gas_limit,
max_fee_per_gas=tx_max_fee_per_gas,
max_priority_fee_per_gas=0,
access_list=[],
)
]
# Split into multi txs for forks where max per tx < max per block
txs = []
blob_index = 0
remaining_blobs = new_blobs
while remaining_blobs > 0:
tx_blobs = min(remaining_blobs, fork.max_blobs_per_tx())
txs.append(
Transaction(
ty=Spec.BLOB_TX_TYPE,
sender=sender,
to=destination_account,
value=1,
gas_limit=tx_gas_limit,
max_fee_per_gas=tx_max_fee_per_gas,
max_priority_fee_per_gas=0,
max_fee_per_blob_gas=tx_max_fee_per_blob_gas,
access_list=[],
blob_versioned_hashes=add_kzg_version(
[Hash(blob_index + x) for x in range(tx_blobs)],
Spec.BLOB_COMMITMENT_VERSION_KZG,
),
)
)
blob_index += tx_blobs
remaining_blobs -= tx_blobs
return txs
@pytest.fixture
def header_blob_gas_used() -> Optional[int]: # noqa: D103
return None
@pytest.fixture
def correct_blob_gas_used(
txs: List[Transaction],
blob_gas_per_blob: int,
) -> int:
"""Calculate the correct `blobGasUsed` for all txs."""
total_blob_gas = 0
for tx in txs:
total_blob_gas += Spec.get_total_blob_gas(tx=tx, blob_gas_per_blob=blob_gas_per_blob)
return total_blob_gas
@pytest.fixture
def blocks( # noqa: D103
txs: List[Transaction],
header_excess_blob_gas: Optional[int],
header_blob_gas_used: Optional[int],
correct_excess_blob_gas: int,
correct_blob_gas_used: int,
non_zero_blob_gas_used_genesis_block: Block,
max_blobs_per_block: int,
blob_gas_per_blob: int,
) -> List[Block]:
blocks = (
[]
if non_zero_blob_gas_used_genesis_block is None
else [non_zero_blob_gas_used_genesis_block]
)
def add_block(
header_modifier: Optional[Dict] = None,
exception_message: Optional[BlockException | List[BlockException]] = None,
) -> None:
"""Add a block to the blocks list."""
blocks.append(
Block(
txs=txs,
rlp_modifier=Header(**header_modifier) if header_modifier else None,
header_verify=Header(
excess_blob_gas=correct_excess_blob_gas,
blob_gas_used=correct_blob_gas_used,
),
exception=exception_message,
)
)
if header_excess_blob_gas is not None:
add_block(
header_modifier={"excess_blob_gas": header_excess_blob_gas},
exception_message=BlockException.INCORRECT_EXCESS_BLOB_GAS,
)
elif header_blob_gas_used is not None:
if header_blob_gas_used > (max_blobs_per_block * blob_gas_per_blob):
add_block(
header_modifier={"blob_gas_used": header_blob_gas_used},
exception_message=[
BlockException.BLOB_GAS_USED_ABOVE_LIMIT,
BlockException.INCORRECT_BLOB_GAS_USED,
],
)
else:
add_block(
header_modifier={"blob_gas_used": header_blob_gas_used},
exception_message=BlockException.INCORRECT_BLOB_GAS_USED,
)
else:
add_block()
return blocks
@pytest.fixture
def post( # noqa: D103
destination_account: Address,
tx_value: int,
blob_gas_price: int,
txs: List[Transaction],
) -> Mapping[Address, Account]:
return {
destination_account: Account(
storage={0: blob_gas_price},
balance=tx_value * len(txs),
),
}
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: range(0, fork.max_blobs_per_block() + 1),
)
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs",
lambda fork: range(0, fork.target_blobs_per_block() + 1),
)
@pytest.mark.parametrize("new_blobs", [1])
def test_correct_excess_blob_gas_calculation(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
post: Mapping[Address, Account],
correct_excess_blob_gas: int,
) -> None:
"""
Test calculation of the `excessBlobGas` increase/decrease across multiple
blocks with and without blobs.
- With parent block containing `[0, MAX_BLOBS_PER_BLOCK]` blobs
- With parent block containing `[0, TARGET_BLOBS_PER_BLOCK]` equivalent
value of excess blob gas
"""
blockchain_test(
pre=pre,
post=post,
blocks=blocks,
genesis_environment=env,
tag=f"expected_excess_blob_gas:{hex(correct_excess_blob_gas)}",
)
def generate_blob_gas_cost_increases_tests(delta: int) -> Callable[[Fork], List[int]]:
"""
Generate a list of block excess blob gas values where the blob gas price
increases based on fork properties.
"""
def generator_function(fork: Fork) -> List[int]:
gas_per_blob = fork.blob_gas_per_blob()
return [
SpecHelpers.get_min_excess_blobs_for_blob_gas_price(
fork=fork, blob_gas_price=blob_gas_price
)
+ delta
for blob_gas_price in [
2, # First blob gas cost increase
2**32 // gas_per_blob, # Data tx wei cost 2^32
2**32, # blob gas cost 2^32
2**64 // gas_per_blob, # Data tx wei cost 2^64
2**64, # blob gas cost 2^64
(
120_000_000 * (10**18) // gas_per_blob
), # Data tx wei is current total Ether supply
]
]
return generator_function
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs",
generate_blob_gas_cost_increases_tests(-1),
)
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: [fork.target_blobs_per_block() + 1],
)
@pytest.mark.parametrize("new_blobs", [1])
def test_correct_increasing_blob_gas_costs(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
post: Mapping[Address, Account],
correct_excess_blob_gas: int,
) -> None:
"""
Test calculation of the `excessBlobGas` and blob gas tx costs at value
points where the cost increases to interesting amounts.
- At the first blob gas cost increase (1 to 2)
- At total transaction data cost increase to `> 2^32`
- At blob gas wei cost increase to `> 2^32`
- At total transaction data cost increase to `> 2^64`
- At blob gas wei cost increase to `> 2^64`
- At blob gas wei cost increase of around current total Ether supply
"""
blockchain_test(
pre=pre,
post=post,
blocks=blocks,
genesis_environment=env,
tag=f"expected_excess_blob_gas:{hex(correct_excess_blob_gas)}",
)
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs",
generate_blob_gas_cost_increases_tests(0),
)
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: [fork.target_blobs_per_block() - 1],
)
@pytest.mark.parametrize("new_blobs", [1])
def test_correct_decreasing_blob_gas_costs(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
post: Mapping[Address, Account],
correct_excess_blob_gas: int,
) -> None:
"""
Test calculation of the `excessBlobGas` and blob gas tx costs at value
points where the cost decreases to interesting amounts.
See test_correct_increasing_blob_gas_costs.
"""
blockchain_test(
pre=pre,
post=post,
blocks=blocks,
genesis_environment=env,
tag=f"expected_excess_blob_gas:{hex(correct_excess_blob_gas)}",
)
@pytest.mark.parametrize("header_excess_blob_gas", [0])
@pytest.mark.parametrize("new_blobs", [0, 1])
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: range(0, fork.max_blobs_per_block() + 1),
)
@pytest.mark.exception_test
def test_invalid_zero_excess_blob_gas_in_header(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
header_excess_blob_gas: Optional[int],
) -> None:
"""
Test rejection of blocks where the `excessBlobGas` in the header drops to
zero in a block with or without data blobs, but the excess blobs in the
parent are greater than target.
"""
if header_excess_blob_gas is None:
raise Exception("test case is badly formatted")
if header_excess_blob_gas == correct_excess_blob_gas:
raise Exception("invalid test case")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(header_excess_blob_gas)}",
]
),
)
def all_invalid_blob_gas_used_combinations(fork: Fork) -> Iterator[Tuple[int, int]]:
"""Return all invalid blob gas used combinations."""
gas_per_blob = fork.blob_gas_per_blob()
for new_blobs in range(0, fork.max_blobs_per_block() + 1):
for header_blob_gas_used in range(0, fork.max_blobs_per_block() + 1):
if new_blobs != header_blob_gas_used:
yield (new_blobs, header_blob_gas_used * gas_per_blob)
yield (new_blobs, 2**64 - 1)
@pytest.mark.parametrize_by_fork(
"new_blobs,header_blob_gas_used",
all_invalid_blob_gas_used_combinations,
)
@pytest.mark.parametrize("parent_blobs", [0])
@pytest.mark.exception_test
@pytest.mark.slow()
def test_invalid_blob_gas_used_in_header(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
new_blobs: int,
header_blob_gas_used: Optional[int],
blob_gas_per_blob: int,
) -> None:
"""
Test rejection of blocks where the `blobGasUsed` in the header is invalid.
- `blobGasUsed` is not equal to the number of data blobs in the block
- `blobGasUsed` is the max uint64 value
"""
if header_blob_gas_used is None:
raise Exception("test case is badly formatted")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(new_blobs * blob_gas_per_blob)}",
f"header:{hex(header_blob_gas_used)}",
]
),
)
def generate_invalid_excess_blob_gas_above_target_change_tests(fork: Fork) -> List:
"""Return all invalid excess blob gas above target change tests."""
return [
pytest.param(-1, 0, id="zero_blobs_decrease_more_than_expected"),
pytest.param(+1, fork.max_blobs_per_block(), id="max_blobs_increase_more_than_expected"),
]
@pytest.mark.parametrize_by_fork(
"header_excess_blobs_delta,parent_blobs",
generate_invalid_excess_blob_gas_above_target_change_tests,
)
@pytest.mark.parametrize("new_blobs", [1])
@pytest.mark.exception_test
def test_invalid_excess_blob_gas_above_target_change(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
header_excess_blob_gas: Optional[int],
) -> None:
"""
Test rejection of blocks where the `excessBlobGas`.
- decreases more than `TARGET_BLOB_GAS_PER_BLOCK` in a single block
with zero blobs.
- increases more than `TARGET_BLOB_GAS_PER_BLOCK` in a single block
with max blobs.
"""
if header_excess_blob_gas is None:
raise Exception("test case is badly formatted")
if header_excess_blob_gas == correct_excess_blob_gas:
raise Exception("invalid test case")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(header_excess_blob_gas)}",
]
),
)
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: [
b for b in range(0, fork.max_blobs_per_block() + 1) if b != fork.target_blobs_per_block()
],
)
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs", lambda fork: [1, fork.target_blobs_per_block()]
)
@pytest.mark.parametrize("new_blobs", [1])
@pytest.mark.exception_test
def test_invalid_static_excess_blob_gas(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
parent_excess_blob_gas: int,
) -> None:
"""
Test rejection of blocks where the `excessBlobGas` remains unchanged but
the parent blobs included are not `TARGET_BLOBS_PER_BLOCK`.
Test is parametrized to `MAX_BLOBS_PER_BLOCK` and `TARGET_BLOBS_PER_BLOCK`.
"""
blocks[-1].rlp_modifier = Header(excess_blob_gas=parent_excess_blob_gas)
blocks[-1].header_verify = None
blocks[-1].exception = BlockException.INCORRECT_EXCESS_BLOB_GAS
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(parent_excess_blob_gas)}",
]
),
)
@pytest.mark.parametrize_by_fork(
"header_excess_blobs_delta",
lambda fork: range(1, fork.max_blobs_per_block()),
)
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: range(0, fork.target_blobs_per_block() + 1),
)
@pytest.mark.parametrize("parent_excess_blobs", [0]) # Start at 0
@pytest.mark.parametrize("new_blobs", [1])
@pytest.mark.exception_test
def test_invalid_excess_blob_gas_target_blobs_increase_from_zero(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
header_excess_blob_gas: Optional[int],
) -> None:
"""
Test rejection of blocks where the `excessBlobGas` increases from zero,
even when the included blobs are on or below target.
Test is parametrized according to `[0, TARGET_BLOBS_PER_BLOCK` new blobs.
"""
if header_excess_blob_gas is None:
raise Exception("test case is badly formatted")
if header_excess_blob_gas == correct_excess_blob_gas:
raise Exception("invalid test case")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(header_excess_blob_gas)}",
]
),
)
@pytest.mark.parametrize("header_excess_blob_gas", [0])
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: range(fork.target_blobs_per_block() + 1, fork.max_blobs_per_block() + 1),
)
@pytest.mark.parametrize("parent_excess_blobs", [0]) # Start at 0
@pytest.mark.parametrize("new_blobs", [1])
@pytest.mark.exception_test
def test_invalid_static_excess_blob_gas_from_zero_on_blobs_above_target(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
header_excess_blob_gas: Optional[int],
) -> None:
"""
Test rejection of blocks where the `excessBlobGas` does not increase from
zero, even when the included blobs is above target.
Test is parametrized to `[TARGET_BLOBS_PER_BLOCK+1, MAX_BLOBS_PER_BLOCK]`
new blobs.
"""
if header_excess_blob_gas is None:
raise Exception("test case is badly formatted")
if header_excess_blob_gas == correct_excess_blob_gas:
raise Exception("invalid test case")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(header_excess_blob_gas)}",
]
),
)
@pytest.mark.parametrize_by_fork(
"parent_blobs,header_excess_blobs_delta",
lambda fork: itertools.product(
# parent_blobs
range(0, fork.max_blobs_per_block() + 1),
# header_excess_blobs_delta (from correct value)
[
x
for x in range(-fork.target_blobs_per_block(), fork.target_blobs_per_block() + 1)
if x != 0
],
),
)
@pytest.mark.parametrize("new_blobs", [1])
@pytest.mark.exception_test
def test_invalid_excess_blob_gas_change(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
header_excess_blob_gas: Optional[int],
) -> None:
"""
Test rejection of blocks where the `excessBlobGas` changes to an invalid
value.
Given a parent block containing `[0, MAX_BLOBS_PER_BLOCK]` blobs, test an
invalid `excessBlobGas` value by changing it by `[-TARGET_BLOBS_PER_BLOCK,
TARGET_BLOBS_PER_BLOCK]` from the correct value.
"""
if header_excess_blob_gas is None:
raise Exception("test case is badly formatted")
if header_excess_blob_gas == correct_excess_blob_gas:
raise Exception("invalid test case")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(header_excess_blob_gas)}",
]
),
)
@pytest.mark.parametrize_by_fork(
"header_excess_blob_gas",
lambda fork: [
(2**64 + (x * fork.blob_gas_per_blob())) for x in range(-fork.target_blobs_per_block(), 0)
],
)
@pytest.mark.parametrize_by_fork(
"parent_blobs",
lambda fork: range(fork.target_blobs_per_block()),
)
@pytest.mark.parametrize("new_blobs", [1])
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs",
lambda fork: range(fork.target_blobs_per_block()),
)
@pytest.mark.exception_test
@pytest.mark.slow()
def test_invalid_negative_excess_blob_gas(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
header_excess_blob_gas: Optional[int],
) -> None:
"""
Test rejection of blocks where the `excessBlobGas` changes to the two's
complement equivalent of the negative value after subtracting target blobs.
Reasoning is that the `excessBlobGas` is a `uint64`, so it cannot be
negative, and we test for a potential underflow here.
"""
if header_excess_blob_gas is None:
raise Exception("test case is badly formatted")
if header_excess_blob_gas == correct_excess_blob_gas:
raise Exception("invalid test case")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(header_excess_blob_gas)}",
]
),
)
@pytest.mark.parametrize_by_fork(
"parent_blobs,header_excess_blob_gas_delta",
lambda fork: [
(fork.target_blobs_per_block() + 1, 1),
(fork.target_blobs_per_block() + 1, fork.blob_gas_per_blob() - 1),
(fork.target_blobs_per_block() - 1, -1),
(fork.target_blobs_per_block() - 1, -(fork.blob_gas_per_blob() - 1)),
],
)
@pytest.mark.parametrize("new_blobs", [1])
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs",
lambda fork: [fork.target_blobs_per_block() + 1],
)
@pytest.mark.exception_test
@pytest.mark.slow()
def test_invalid_non_multiple_excess_blob_gas(
blockchain_test: BlockchainTestFiller,
env: Environment,
pre: Mapping[Address, Account],
blocks: List[Block],
correct_excess_blob_gas: int,
header_excess_blob_gas: Optional[int],
) -> None:
"""
Test rejection of blocks where the `excessBlobGas` changes to a value that
is not a multiple of Spec.GAS_PER_BLOB`.
- Parent block contains `TARGET_BLOBS_PER_BLOCK + 1` blobs, but
`excessBlobGas` is off by +/-1
- Parent block contains `TARGET_BLOBS_PER_BLOCK - 1` blobs, but
`excessBlobGas` is off by +/-1
"""
if header_excess_blob_gas is None:
raise Exception("test case is badly formatted")
if header_excess_blob_gas == correct_excess_blob_gas:
raise Exception("invalid test case")
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
tag="-".join(
[
f"correct:{hex(correct_excess_blob_gas)}",
f"header:{hex(header_excess_blob_gas)}",
]
),
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_blob_txs_full.py | tests/cancun/eip4844_blobs/test_blob_txs_full.py | """Tests full blob type transactions for [EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844)."""
from typing import List, Optional
import pytest
from ethereum_test_base_types.base_types import Hash
from ethereum_test_forks import Fork
from ethereum_test_tools import (
Address,
Alloc,
Blob,
Block,
BlockchainTestFiller,
BlockException,
Environment,
Header,
NetworkWrappedTransaction,
Transaction,
TransactionException,
)
from .spec import Spec, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
@pytest.fixture
def destination_account() -> Address:
"""Destination account for the blob transactions."""
return Address(0x100)
@pytest.fixture
def tx_value() -> int:
"""
Value contained by the transactions sent during test.
Can be overloaded by a test case to provide a custom transaction value.
"""
return 1
@pytest.fixture
def tx_gas() -> int:
"""Gas allocated to transactions sent during test."""
return 21_000
@pytest.fixture
def tx_calldata() -> bytes:
"""Calldata in transactions sent during test."""
return b""
@pytest.fixture(autouse=True)
def parent_excess_blobs() -> int:
"""
Excess blobs of the parent block.
Can be overloaded by a test case to provide a custom parent excess blob
count.
"""
return 10 # Defaults to a blob gas price of 1.
@pytest.fixture(autouse=True)
def parent_blobs() -> int:
"""
Blobs of the parent blob.
Can be overloaded by a test case to provide a custom parent blob count.
"""
return 0
@pytest.fixture
def tx_max_priority_fee_per_gas() -> int:
"""
Max priority fee per gas for transactions sent during test.
Can be overloaded by a test case to provide a custom max priority fee per
gas.
"""
return 0
@pytest.fixture
def txs_versioned_hashes(txs_blobs: List[List[Blob]]) -> List[List[Hash]]:
"""List of blob versioned hashes derived from the blobs."""
version_hashes: List[List[Hash]] = [
[blob.versioned_hash for blob in blob_tx] for blob_tx in txs_blobs
]
return version_hashes
@pytest.fixture(autouse=True)
def tx_max_fee_per_gas(
block_base_fee_per_gas: int,
) -> int:
"""
Max fee per gas value used by all transactions sent during test.
By default the max fee per gas is the same as the block fee per gas.
Can be overloaded by a test case to test rejection of transactions where
the max fee per gas is insufficient.
"""
return block_base_fee_per_gas
@pytest.fixture
def tx_max_fee_per_blob_gas( # noqa: D103
blob_gas_price: Optional[int],
) -> int:
"""
Max fee per blob gas for transactions sent during test.
By default, it is set to the blob gas price of the block.
Can be overloaded by a test case to test rejection of transactions where
the max fee per blob gas is insufficient.
"""
if blob_gas_price is None:
# When fork transitioning, the default blob gas price is 1.
return 1
return blob_gas_price
@pytest.fixture
def tx_error() -> Optional[TransactionException]:
"""
Even though the final block we are producing in each of these tests is
invalid, and some of the transactions will be invalid due to the format in
the final block, none of the transactions should be rejected by the
transition tool because they are being sent to it with the correct format.
"""
return None
@pytest.fixture(autouse=True)
def txs( # noqa: D103
pre: Alloc,
destination_account: Optional[Address],
tx_gas: int,
tx_value: int,
tx_calldata: bytes,
tx_max_fee_per_gas: int,
tx_max_fee_per_blob_gas: int,
tx_max_priority_fee_per_gas: int,
txs_versioned_hashes: List[List[Hash]],
tx_error: Optional[TransactionException],
txs_blobs: List[List[Blob]],
txs_wrapped_blobs: List[bool],
fork: Fork,
) -> List[Transaction]:
"""Prepare the list of transactions that are sent during the test."""
if len(txs_blobs) != len(txs_versioned_hashes) or len(txs_blobs) != len(txs_wrapped_blobs):
raise ValueError("txs_blobs and txs_versioned_hashes should have the same length")
txs: List[Transaction] = []
sender = pre.fund_eoa()
for tx_blobs, tx_versioned_hashes, tx_wrapped_blobs in zip(
txs_blobs, txs_versioned_hashes, txs_wrapped_blobs, strict=False
):
tx = Transaction(
ty=Spec.BLOB_TX_TYPE,
sender=sender,
to=destination_account,
value=tx_value,
gas_limit=tx_gas,
data=tx_calldata,
max_fee_per_gas=tx_max_fee_per_gas,
max_priority_fee_per_gas=tx_max_priority_fee_per_gas,
max_fee_per_blob_gas=tx_max_fee_per_blob_gas,
access_list=[],
blob_versioned_hashes=tx_versioned_hashes,
error=tx_error,
wrapped_blob_transaction=tx_wrapped_blobs,
)
if tx_wrapped_blobs:
network_wrapped_tx = NetworkWrappedTransaction(
tx=tx,
blob_objects=tx_blobs,
wrapper_version=fork.full_blob_tx_wrapper_version(),
)
tx.rlp_override = network_wrapped_tx.rlp()
txs.append(tx)
return txs
@pytest.fixture
def env(
parent_excess_blob_gas: int,
) -> Environment:
"""Prepare the environment for all test cases."""
return Environment(
excess_blob_gas=parent_excess_blob_gas,
blob_gas_used=0,
)
@pytest.fixture
def blocks(
txs: List[Transaction],
txs_wrapped_blobs: List[bool],
blob_gas_per_blob: int,
) -> List[Block]:
"""Prepare the list of blocks for all test cases."""
header_blob_gas_used = 0
block_error = None
if any(txs_wrapped_blobs):
# This is a block exception because the invalid block is only created
# in the RLP version, not in the transition tool.
block_error = [
BlockException.RLP_STRUCTURES_ENCODING,
TransactionException.TYPE_3_TX_WITH_FULL_BLOBS,
]
if len(txs) > 0:
header_blob_gas_used = (
sum(
[
len(tx.blob_versioned_hashes)
for tx in txs
if tx.blob_versioned_hashes is not None
]
)
* blob_gas_per_blob
)
return [
Block(
txs=txs, exception=block_error, rlp_modifier=Header(blob_gas_used=header_blob_gas_used)
)
]
def generate_full_blob_tests(
fork: Fork,
) -> List:
"""Return a list of test cases for full blob transactions."""
max_blobs = fork.max_blobs_per_tx()
return [
pytest.param(
[ # Txs
[ # Blobs per transaction
Blob.from_fork(fork),
]
],
[True],
id="one_full_blob_one_tx",
),
pytest.param(
[ # Txs
[ # Blobs per transaction
Blob.from_fork(fork, s),
]
for s in range(max_blobs)
],
[True] + ([False] * (max_blobs - 1)),
id="one_full_blob_max_txs",
),
pytest.param(
[ # Txs
[ # Blobs per transaction
Blob.from_fork(fork, s),
]
for s in range(max_blobs)
],
([False] * (max_blobs - 1)) + [True],
id="one_full_blob_at_the_end_max_txs",
),
]
@pytest.mark.parametrize_by_fork(
"txs_blobs,txs_wrapped_blobs",
generate_full_blob_tests,
)
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_reject_valid_full_blob_in_block_rlp(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
env: Environment,
blocks: List[Block],
) -> None:
"""
Test valid blob combinations where one or more txs in the block serialized
version contain a full blob (network version) tx.
"""
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_blob_txs.py | tests/cancun/eip4844_blobs/test_blob_txs.py | """
Tests blob type transactions for [EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844).
Note: To add a new test, add a function that is named `test_<test_name>`.
It must at least use the following arguments:
- `blockchain_test` or `state_test`
- `pre`
- `env`
- `block` or `txs`.
All other `pytest.fixture` fixtures can be parametrized to generate new
combinations and test cases.
"""
from typing import List, Optional, Tuple
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
EOA,
AccessList,
Account,
Address,
Alloc,
Block,
BlockchainTestFiller,
BlockException,
Bytecode,
EngineAPIError,
Environment,
Hash,
Header,
Removable,
StateTestFiller,
Storage,
Transaction,
TransactionException,
add_kzg_version,
)
from ethereum_test_tools import Opcodes as Op
from .spec import Spec, SpecHelpers, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
@pytest.fixture
def destination_account_code() -> Bytecode | None:
"""Code in the destination account for the blob transactions."""
return None
@pytest.fixture
def destination_account_balance() -> int:
"""Balance in the destination account for the blob transactions."""
return 0
@pytest.fixture
def destination_account(
pre: Alloc, destination_account_code: Bytecode | None, destination_account_balance: int
) -> Address:
"""Destination account for the blob transactions."""
if destination_account_code is not None:
return pre.deploy_contract(
code=destination_account_code,
balance=destination_account_balance,
)
return pre.fund_eoa(destination_account_balance)
@pytest.fixture
def tx_gas(
fork: Fork,
tx_calldata: bytes,
tx_access_list: List[AccessList],
) -> int:
"""Gas allocated to transactions sent during test."""
tx_intrinsic_cost_calculator = fork.transaction_intrinsic_cost_calculator()
return tx_intrinsic_cost_calculator(calldata=tx_calldata, access_list=tx_access_list)
@pytest.fixture
def blobs_per_tx() -> List[int]:
"""
Return list of integers that each represent the number of blobs in each
transaction in the block of the test.
Used to automatically generate a list of correctly versioned blob hashes.
Default is to have one transaction with one blob.
Can be overloaded by a test case to provide a custom list of blob counts.
"""
return [1]
@pytest.fixture
def blob_hashes_per_tx(blobs_per_tx: List[int]) -> List[List[Hash]]:
"""
Produce the list of blob hashes that are sent during the test.
Can be overloaded by a test case to provide a custom list of blob hashes.
"""
return [
add_kzg_version(
[Hash(x) for x in range(blob_count)],
Spec.BLOB_COMMITMENT_VERSION_KZG,
)
for blob_count in blobs_per_tx
]
@pytest.fixture
def total_account_minimum_balance( # noqa: D103
blob_gas_per_blob: int,
tx_gas: int,
tx_value: int,
tx_max_fee_per_gas: int,
tx_max_fee_per_blob_gas: int,
blob_hashes_per_tx: List[List[bytes]],
) -> int:
"""
Calculate minimum balance required for the account to be able to send the
transactions in the block of the test.
"""
minimum_cost = 0
for tx_blob_count in [len(x) for x in blob_hashes_per_tx]:
blob_cost = tx_max_fee_per_blob_gas * blob_gas_per_blob * tx_blob_count
minimum_cost += (tx_gas * tx_max_fee_per_gas) + tx_value + blob_cost
return minimum_cost
@pytest.fixture
def total_account_transactions_fee( # noqa: D103
tx_gas: int,
tx_value: int,
blob_gas_price: int,
block_base_fee_per_gas: int,
blob_gas_per_blob: int,
tx_max_fee_per_gas: int,
tx_max_priority_fee_per_gas: int,
blob_hashes_per_tx: List[List[bytes]],
) -> int:
"""
Calculate actual fee for the blob transactions in the block of the test.
"""
total_cost = 0
for tx_blob_count in [len(x) for x in blob_hashes_per_tx]:
blob_cost = blob_gas_price * blob_gas_per_blob * tx_blob_count
block_producer_fee = (
tx_max_fee_per_gas - block_base_fee_per_gas if tx_max_priority_fee_per_gas else 0
)
total_cost += (
(tx_gas * (block_base_fee_per_gas + block_producer_fee)) + tx_value + blob_cost
)
return total_cost
@pytest.fixture
def tx_access_list() -> List[AccessList]:
"""
Access list for transactions sent during test.
Can be overloaded by a test case to provide a custom access list.
"""
return []
@pytest.fixture
def tx_error() -> Optional[TransactionException]:
"""
Error produced by the block transactions (no error).
Can be overloaded on test cases where the transactions are expected to
fail.
"""
return None
@pytest.fixture
def sender_initial_balance( # noqa: D103
total_account_minimum_balance: int, account_balance_modifier: int
) -> int:
return total_account_minimum_balance + account_balance_modifier
@pytest.fixture
def sender(pre: Alloc, sender_initial_balance: int) -> Address: # noqa: D103
return pre.fund_eoa(sender_initial_balance)
@pytest.fixture
def txs( # noqa: D103
sender: EOA,
destination_account: Optional[Address],
tx_gas: int,
tx_value: int,
tx_calldata: bytes,
tx_max_fee_per_gas: int,
tx_max_fee_per_blob_gas: int,
tx_max_priority_fee_per_gas: int,
tx_access_list: List[AccessList],
blob_hashes_per_tx: List[List[bytes]],
tx_error: Optional[TransactionException],
) -> List[Transaction]:
"""Prepare the list of transactions that are sent during the test."""
return [
Transaction(
ty=Spec.BLOB_TX_TYPE,
sender=sender,
to=destination_account,
value=tx_value,
gas_limit=tx_gas,
data=tx_calldata,
max_fee_per_gas=tx_max_fee_per_gas,
max_priority_fee_per_gas=tx_max_priority_fee_per_gas,
max_fee_per_blob_gas=tx_max_fee_per_blob_gas,
access_list=tx_access_list,
blob_versioned_hashes=blob_hashes,
error=tx_error if tx_i == (len(blob_hashes_per_tx) - 1) else None,
)
for tx_i, blob_hashes in enumerate(blob_hashes_per_tx)
]
@pytest.fixture
def account_balance_modifier() -> int:
"""
Account balance modifier for the source account of all tests. See `pre`
fixture.
"""
return 0
@pytest.fixture
def state_env(
excess_blob_gas: Optional[int],
) -> Environment:
"""
Prepare the environment for all state test cases.
Main difference is that the excess blob gas is not increased by the target,
as there is no genesis block -> block 1 transition, and therefore the
excess blob gas is not decreased by the target.
"""
return Environment(
excess_blob_gas=excess_blob_gas if excess_blob_gas else 0,
)
@pytest.fixture
def engine_api_error_code() -> Optional[EngineAPIError]:
"""
Engine API error code to be returned by the client on consumption of the
erroneous block in hive.
"""
return None
@pytest.fixture
def block_error(
tx_error: Optional[TransactionException],
) -> Optional[TransactionException | BlockException]:
"""
Error produced by the block transactions (no error).
Can be overloaded on test cases where the transactions are expected to
fail.
"""
return tx_error
@pytest.fixture
def block_number() -> int:
"""First block number."""
return 1
@pytest.fixture
def block_timestamp() -> int:
"""Timestamp of the first block."""
return 1
@pytest.fixture
def expected_blob_gas_used(
fork: Fork,
txs: List[Transaction],
block_number: int,
block_timestamp: int,
) -> Optional[int | Removable]:
"""Calculate blob gas used by the test block."""
if not fork.header_blob_gas_used_required(
block_number=block_number, timestamp=block_timestamp
):
return Header.EMPTY_FIELD
blob_gas_per_blob = fork.blob_gas_per_blob(
block_number=block_number,
timestamp=block_timestamp,
)
return sum([Spec.get_total_blob_gas(tx=tx, blob_gas_per_blob=blob_gas_per_blob) for tx in txs])
@pytest.fixture
def expected_excess_blob_gas(
fork: Fork,
parent_excess_blobs: Optional[int],
parent_blobs: Optional[int],
block_number: int,
block_timestamp: int,
block_base_fee_per_gas: int,
) -> Optional[int | Removable]:
"""Calculate blob gas used by the test block."""
if not fork.header_excess_blob_gas_required(
block_number=block_number, timestamp=block_timestamp
):
return Header.EMPTY_FIELD
excess_blob_gas = fork.excess_blob_gas_calculator()
return excess_blob_gas(
parent_excess_blobs=parent_excess_blobs if parent_excess_blobs else 0,
parent_blob_count=parent_blobs if parent_blobs else 0,
parent_base_fee_per_gas=block_base_fee_per_gas,
)
@pytest.fixture
def header_verify(
txs: List[Transaction],
expected_blob_gas_used: Optional[int | Removable],
expected_excess_blob_gas: Optional[int | Removable],
) -> Header:
"""Header fields to verify from the transition tool."""
header_verify = Header(
blob_gas_used=expected_blob_gas_used,
excess_blob_gas=expected_excess_blob_gas,
gas_used=0 if len([tx for tx in txs if not tx.error]) == 0 else None,
)
return header_verify
@pytest.fixture
def rlp_modifier(
expected_blob_gas_used: Optional[int | Removable],
) -> Optional[Header]:
"""Header fields to modify on the output block in the BlockchainTest."""
if expected_blob_gas_used == Header.EMPTY_FIELD:
return None
return Header(
blob_gas_used=expected_blob_gas_used,
)
@pytest.fixture
def block(
txs: List[Transaction],
block_error: Optional[TransactionException | BlockException],
engine_api_error_code: Optional[EngineAPIError],
header_verify: Optional[Header],
rlp_modifier: Optional[Header],
) -> Block:
"""Test block for all blockchain test cases."""
return Block(
txs=txs,
exception=block_error,
engine_api_error_code=engine_api_error_code,
header_verify=header_verify,
rlp_modifier=rlp_modifier,
)
@pytest.mark.parametrize_by_fork(
"blobs_per_tx",
SpecHelpers.all_valid_blob_combinations,
)
@pytest.mark.parametrize("block_base_fee_per_gas", [7, 100])
@pytest.mark.valid_from("Cancun")
def test_valid_blob_tx_combinations(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
env: Environment,
block: Block,
) -> None:
"""
Test all valid blob combinations in a single block, assuming a given value
of `MAX_BLOBS_PER_BLOCK`.
This assumes a block can include from 1 and up to `MAX_BLOBS_PER_BLOCK`
transactions where all transactions contain at least 1 blob, and the sum of
all blobs in a block is at most `MAX_BLOBS_PER_BLOCK`.
This test is parametrized with all valid blob transaction combinations for
a given block, and therefore if value of `MAX_BLOBS_PER_BLOCK` changes,
this test is automatically updated.
"""
blockchain_test(
pre=pre,
post={},
blocks=[block],
genesis_environment=env,
)
def generate_invalid_tx_max_fee_per_blob_gas_tests(
fork: Fork,
) -> List:
"""
Return a list of tests for invalid blob transactions due to insufficient
max fee per blob gas parametrized for each different fork.
"""
min_base_fee_per_blob_gas = fork.min_base_fee_per_blob_gas()
minimum_excess_blobs_for_first_increment = SpecHelpers.get_min_excess_blobs_for_blob_gas_price(
fork=fork,
blob_gas_price=min_base_fee_per_blob_gas + 1,
)
next_base_fee_per_blob_gas = fork.blob_gas_price_calculator()(
excess_blob_gas=minimum_excess_blobs_for_first_increment,
)
tests = []
tests.append(
pytest.param(
# blob gas price is 1
minimum_excess_blobs_for_first_increment - 1,
# blob gas cost increases to above the minimum
fork.target_blobs_per_block() + 1,
# tx max_blob_gas_cost is the minimum
min_base_fee_per_blob_gas,
TransactionException.INSUFFICIENT_MAX_FEE_PER_BLOB_GAS,
id="insufficient_max_fee_per_blob_gas",
marks=pytest.mark.exception_test,
)
)
if (next_base_fee_per_blob_gas - min_base_fee_per_blob_gas) > 1:
tests.append(
pytest.param(
# blob gas price is one less than the minimum
minimum_excess_blobs_for_first_increment - 1,
# blob gas cost increases to above the minimum
fork.target_blobs_per_block() + 1,
# tx max_blob_gas_cost is one less than the minimum
next_base_fee_per_blob_gas - 1,
TransactionException.INSUFFICIENT_MAX_FEE_PER_BLOB_GAS,
id="insufficient_max_fee_per_blob_gas_one_less_than_next",
marks=pytest.mark.exception_test,
)
)
if min_base_fee_per_blob_gas > 1:
tests.append(
pytest.param(
0, # blob gas price is the minimum
0, # blob gas cost stays put at 1
# tx max_blob_gas_cost is one less than the minimum
min_base_fee_per_blob_gas - 1,
TransactionException.INSUFFICIENT_MAX_FEE_PER_BLOB_GAS,
id="insufficient_max_fee_per_blob_gas_one_less_than_min",
marks=pytest.mark.exception_test,
)
)
tests.append(
pytest.param(
0, # blob gas price is the minimum
0, # blob gas cost stays put at 1
0, # tx max_blob_gas_cost is 0
TransactionException.INSUFFICIENT_MAX_FEE_PER_BLOB_GAS,
id="invalid_max_fee_per_blob_gas",
marks=pytest.mark.exception_test,
)
)
return tests
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs,parent_blobs,tx_max_fee_per_blob_gas,tx_error",
generate_invalid_tx_max_fee_per_blob_gas_tests,
)
@pytest.mark.parametrize(
"account_balance_modifier",
[1_000_000_000],
) # Extra balance to cover block blob gas cost
@pytest.mark.valid_from("Cancun")
def test_invalid_tx_max_fee_per_blob_gas(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
env: Environment,
block: Block,
non_zero_blob_gas_used_genesis_block: Optional[Block],
) -> None:
"""
Reject blocks with invalid blob txs.
- tx max_fee_per_blob_gas is barely not enough
- tx max_fee_per_blob_gas is zero
"""
if non_zero_blob_gas_used_genesis_block is not None:
blocks = [non_zero_blob_gas_used_genesis_block, block]
else:
blocks = [block]
blockchain_test(
pre=pre,
post={},
blocks=blocks,
genesis_environment=env,
)
@pytest.mark.parametrize_by_fork(
"parent_excess_blobs,parent_blobs,tx_max_fee_per_blob_gas,tx_error",
generate_invalid_tx_max_fee_per_blob_gas_tests,
)
@pytest.mark.state_test_only
@pytest.mark.valid_from("Cancun")
def test_invalid_tx_max_fee_per_blob_gas_state(
state_test: StateTestFiller,
state_env: Environment,
pre: Alloc,
txs: List[Transaction],
) -> None:
"""
Reject an invalid blob transaction.
- tx max_fee_per_blob_gas is barely not enough
- tx max_fee_per_blob_gas is zero
"""
assert len(txs) == 1
state_test(
pre=pre,
post={},
tx=txs[0],
env=state_env,
)
@pytest.mark.parametrize(
"tx_max_fee_per_gas,tx_error",
[
# max blob gas is ok, but max fee per gas is less than base fee per gas
(
6,
TransactionException.INSUFFICIENT_MAX_FEE_PER_GAS,
),
],
ids=["insufficient_max_fee_per_gas"],
)
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_invalid_normal_gas(
state_test: StateTestFiller,
state_env: Environment,
pre: Alloc,
txs: List[Transaction],
header_verify: Optional[Header],
rlp_modifier: Optional[Header],
) -> None:
"""
Reject an invalid blob transaction.
- Sufficient max fee per blob gas, but insufficient max fee per gas
"""
assert len(txs) == 1
state_test(
pre=pre,
post={},
tx=txs[0],
env=state_env,
blockchain_test_header_verify=header_verify,
blockchain_test_rlp_modifier=rlp_modifier,
)
@pytest.mark.parametrize_by_fork(
"blobs_per_tx",
SpecHelpers.invalid_blob_combinations,
)
@pytest.mark.parametrize(
"tx_error",
[
[
TransactionException.TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED,
TransactionException.TYPE_3_TX_BLOB_COUNT_EXCEEDED,
]
],
ids=[""],
)
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_invalid_block_blob_count(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
env: Environment,
block: Block,
) -> None:
"""
Test all invalid blob combinations in a single block, where the sum of all
blobs in a block is at `MAX_BLOBS_PER_BLOCK + 1`.
This test is parametrized with all blob transaction combinations exceeding
`MAX_BLOBS_PER_BLOCK` by one for a given block, and therefore if value of
`MAX_BLOBS_PER_BLOCK` changes, this test is automatically updated.
"""
blockchain_test(
pre=pre,
post={},
blocks=[block],
genesis_environment=env,
)
@pytest.mark.parametrize(
"tx_access_list",
[[], [AccessList(address=100, storage_keys=[100, 200])]],
ids=["no_access_list", "access_list"],
)
@pytest.mark.parametrize("tx_max_fee_per_gas", [7, 14])
@pytest.mark.parametrize("tx_max_priority_fee_per_gas", [0, 7])
@pytest.mark.parametrize("tx_value", [0, 1])
@pytest.mark.parametrize(
"tx_calldata",
[b"", b"\x00", b"\x01"],
ids=["no_calldata", "single_zero_calldata", "single_one_calldata"],
)
@pytest.mark.parametrize("tx_max_fee_per_blob_gas_multiplier", [1, 100, 10000])
@pytest.mark.parametrize("account_balance_modifier", [-1], ids=["exact_balance_minus_1"])
@pytest.mark.parametrize("tx_error", [TransactionException.INSUFFICIENT_ACCOUNT_FUNDS], ids=[""])
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
@pytest.mark.slow()
def test_insufficient_balance_blob_tx(
state_test: StateTestFiller,
state_env: Environment,
pre: Alloc,
txs: List[Transaction],
) -> None:
"""
Reject blocks where user cannot afford the blob gas specified (but
max_fee_per_gas would be enough for current block).
- Transactions with max fee equal or higher than current block base fee
- Transactions with and without priority fee
- Transactions with and without value
- Transactions with and without calldata
- Transactions with max fee per blob gas lower or higher than the priority
fee
"""
assert len(txs) == 1
state_test(
pre=pre,
post={},
tx=txs[0],
env=state_env,
)
@pytest.mark.parametrize_by_fork(
"blobs_per_tx",
lambda fork: [
pytest.param([1], id="single_blob"),
pytest.param([fork.max_blobs_per_tx()], id="max_blobs"),
],
)
@pytest.mark.parametrize(
"tx_access_list",
[[], [AccessList(address=100, storage_keys=[100, 200])]],
ids=["no_access_list", "access_list"],
)
@pytest.mark.parametrize("tx_max_fee_per_gas", [7, 14])
@pytest.mark.parametrize("tx_max_priority_fee_per_gas", [0, 7])
@pytest.mark.parametrize("tx_value", [0, 1])
@pytest.mark.parametrize(
"tx_calldata",
[b"", b"\x00", b"\x01"],
ids=["no_calldata", "single_zero_calldata", "single_one_calldata"],
)
@pytest.mark.parametrize("block_base_fee_per_gas", [7, 100])
@pytest.mark.parametrize("tx_max_fee_per_blob_gas_multiplier", [1, 100, 10000])
@pytest.mark.valid_from("Cancun")
def test_sufficient_balance_blob_tx(
state_test: StateTestFiller,
state_env: Environment,
pre: Alloc,
txs: List[Transaction],
) -> None:
"""
Check that transaction is accepted when user can exactly afford the blob
gas specified (and max_fee_per_gas would be enough for current block).
- Transactions with max fee equal or higher than current block base fee
- Transactions with and without priority fee
- Transactions with and without value
- Transactions with and without calldata
- Transactions with max fee per blob gas lower or higher than the priority
fee
"""
assert len(txs) == 1
state_test(
pre=pre,
post={},
tx=txs[0],
env=state_env,
)
@pytest.mark.parametrize_by_fork(
"blobs_per_tx",
lambda fork: [
pytest.param([1], id="single_blob"),
pytest.param([fork.max_blobs_per_tx()], id="max_blobs"),
],
)
@pytest.mark.parametrize(
"tx_access_list",
[[], [AccessList(address=100, storage_keys=[100, 200])]],
ids=["no_access_list", "access_list"],
)
@pytest.mark.parametrize("tx_max_fee_per_gas", [7, 14])
@pytest.mark.parametrize("tx_max_priority_fee_per_gas", [0, 7])
@pytest.mark.parametrize("tx_value", [0, 1])
@pytest.mark.parametrize(
"tx_calldata",
[b"", b"\x00", b"\x01"],
ids=["no_calldata", "single_zero_calldata", "single_one_calldata"],
)
@pytest.mark.parametrize("tx_max_fee_per_blob_gas_multiplier", [1, 100, 10000])
@pytest.mark.parametrize("sender_initial_balance", [0])
@pytest.mark.valid_from("Cancun")
def test_sufficient_balance_blob_tx_pre_fund_tx(
blockchain_test: BlockchainTestFiller,
total_account_minimum_balance: int,
sender: EOA,
env: Environment,
pre: Alloc,
txs: List[Transaction],
header_verify: Optional[Header],
) -> None:
"""
Check that transaction is accepted when user can exactly afford the blob
gas specified (and max_fee_per_gas would be enough for current block)
because a funding transaction is prepended in the same block.
- Transactions with max fee equal or higher than current block base fee
- Transactions with and without priority fee
- Transactions with and without value
- Transactions with and without calldata
- Transactions with max fee per blob gas lower or higher than the priority
fee
"""
pre_funding_sender = pre.fund_eoa(amount=(21_000 * 100) + total_account_minimum_balance)
txs = [
Transaction(
sender=pre_funding_sender,
to=sender,
value=total_account_minimum_balance,
gas_limit=21_000,
)
] + txs
blockchain_test(
pre=pre,
post={},
blocks=[
Block(
txs=txs,
header_verify=header_verify,
)
],
genesis_environment=env,
)
@pytest.mark.parametrize_by_fork(
"blobs_per_tx",
lambda fork: [
pytest.param([1], id="single_blob"),
pytest.param([fork.max_blobs_per_tx()], id="max_blobs"),
],
)
@pytest.mark.parametrize(
"tx_access_list",
[[], [AccessList(address=100, storage_keys=[100, 200])]],
ids=["no_access_list", "access_list"],
)
@pytest.mark.parametrize("tx_max_fee_per_gas", [7, 14])
@pytest.mark.parametrize("tx_max_priority_fee_per_gas", [0, 7])
@pytest.mark.parametrize("tx_value", [0, 1])
@pytest.mark.parametrize(
"tx_calldata",
[b"", b"\x01"],
ids=["no_calldata", "single_non_zero_byte_calldata"],
)
@pytest.mark.parametrize("tx_max_fee_per_blob_gas_multiplier", [1, 100])
@pytest.mark.parametrize(
"tx_gas", [500_000], ids=[""]
) # Increase gas to account for contract code
@pytest.mark.parametrize(
"destination_account_balance", [100], ids=["100_wei_mid_execution"]
) # Amount sent by the contract to the sender mid execution
@pytest.mark.parametrize(
"destination_account_code",
[
Op.SSTORE(0, Op.BALANCE(Op.ORIGIN))
+ Op.CALL(Op.GAS, Op.ORIGIN, Op.SUB(Op.SELFBALANCE, Op.CALLVALUE), 0, 0, 0, 0)
+ Op.SSTORE(1, Op.BALANCE(Op.ORIGIN))
],
ids=[""],
) # Amount sent by the contract to the sender mid execution
@pytest.mark.valid_from("Cancun")
def test_blob_gas_subtraction_tx(
state_test: StateTestFiller,
state_env: Environment,
pre: Alloc,
sender_initial_balance: int,
txs: List[Transaction],
destination_account: Address,
destination_account_balance: int,
total_account_transactions_fee: int,
) -> None:
"""
Check that the blob gas fee for a transaction is subtracted from the sender
balance before the transaction is executed.
- Transactions with max fee equal or higher than current block base fee
- Transactions with and without value
- Transactions with and without calldata
- Transactions with max fee per blob gas lower or higher than the priority
fee
- Transactions where an externally owned account sends funds to the sender
mid execution
"""
assert len(txs) == 1
post = {
destination_account: Account(
storage={
0: sender_initial_balance - total_account_transactions_fee,
1: sender_initial_balance
- total_account_transactions_fee
+ destination_account_balance,
}
)
}
state_test(
pre=pre,
post=post,
tx=txs[0],
env=state_env,
)
@pytest.mark.parametrize_by_fork(
"blobs_per_tx",
SpecHelpers.all_valid_blob_combinations,
)
@pytest.mark.parametrize("account_balance_modifier", [-1], ids=["exact_balance_minus_1"])
@pytest.mark.parametrize("tx_error", [TransactionException.INSUFFICIENT_ACCOUNT_FUNDS], ids=[""])
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_insufficient_balance_blob_tx_combinations(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
env: Environment,
block: Block,
) -> None:
"""
Reject all valid blob transaction combinations in a block, but block is
invalid.
- The amount of blobs is correct but the user cannot afford the transaction
total cost
"""
blockchain_test(
pre=pre,
post={},
blocks=[block],
genesis_environment=env,
)
def generate_invalid_tx_blob_count_tests(
fork: Fork,
) -> List:
"""
Return a list of tests for invalid blob transactions due to invalid blob
counts.
"""
return [
pytest.param(
[0],
TransactionException.TYPE_3_TX_ZERO_BLOBS,
id="too_few_blobs",
),
pytest.param(
[fork.max_blobs_per_tx() + 1],
[
TransactionException.TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED,
TransactionException.TYPE_3_TX_BLOB_COUNT_EXCEEDED,
],
id="too_many_blobs",
),
]
@pytest.mark.parametrize_by_fork(
"blobs_per_tx,tx_error",
generate_invalid_tx_blob_count_tests,
)
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_invalid_tx_blob_count(
state_test: StateTestFiller,
state_env: Environment,
pre: Alloc,
txs: List[Transaction],
header_verify: Optional[Header],
rlp_modifier: Optional[Header],
) -> None:
"""
Reject blocks that include blob transactions with invalid blob counts.
- `blob count == 0` in type 3 transaction
- `blob count > MAX_BLOBS_PER_BLOCK` in type 3 transaction
"""
assert len(txs) == 1
state_test(
pre=pre,
post={},
tx=txs[0],
env=state_env,
blockchain_test_header_verify=header_verify,
blockchain_test_rlp_modifier=rlp_modifier,
)
@pytest.mark.parametrize(
"blob_hashes_per_tx",
[
[[Hash(1)]],
[[Hash(x) for x in range(2)]],
[add_kzg_version([Hash(1)], Spec.BLOB_COMMITMENT_VERSION_KZG) + [Hash(2)]],
[[Hash(1)] + add_kzg_version([Hash(2)], Spec.BLOB_COMMITMENT_VERSION_KZG)],
],
ids=[
"single_blob",
"multiple_blobs",
"multiple_blobs_single_bad_hash_1",
"multiple_blobs_single_bad_hash_2",
],
)
@pytest.mark.parametrize(
"tx_error", [TransactionException.TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH], ids=[""]
)
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_invalid_blob_hash_versioning_single_tx(
state_test: StateTestFiller,
state_env: Environment,
pre: Alloc,
txs: List[Transaction],
header_verify: Optional[Header],
rlp_modifier: Optional[Header],
) -> None:
"""
Reject blob transactions with invalid blob hash version.
- Transaction with single blob with invalid version
- Transaction with multiple blobs all with invalid version
- Transaction with multiple blobs either with invalid version
"""
assert len(txs) == 1
state_test(
pre=pre,
post={},
tx=txs[0],
env=state_env,
blockchain_test_header_verify=header_verify,
blockchain_test_rlp_modifier=rlp_modifier,
)
@pytest.mark.parametrize(
"blob_hashes_per_tx",
[
[
add_kzg_version([Hash(1)], Spec.BLOB_COMMITMENT_VERSION_KZG),
[Hash(2)],
],
[
add_kzg_version([Hash(1)], Spec.BLOB_COMMITMENT_VERSION_KZG),
[Hash(x) for x in range(1, 3)],
],
[
add_kzg_version([Hash(1)], Spec.BLOB_COMMITMENT_VERSION_KZG),
[Hash(2)] + add_kzg_version([Hash(3)], Spec.BLOB_COMMITMENT_VERSION_KZG),
],
[
add_kzg_version([Hash(1)], Spec.BLOB_COMMITMENT_VERSION_KZG),
add_kzg_version([Hash(2)], Spec.BLOB_COMMITMENT_VERSION_KZG),
[Hash(3)],
],
],
ids=[
"single_blob",
"multiple_blobs",
"multiple_blobs_single_bad_hash_1",
"multiple_blobs_single_bad_hash_2",
],
)
@pytest.mark.parametrize(
"tx_error", [TransactionException.TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH], ids=[""]
)
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_invalid_blob_hash_versioning_multiple_txs(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
env: Environment,
block: Block,
) -> None:
"""
Reject blocks that include blob transactions with invalid blob hash
version.
- Multiple blob transactions with single blob all with invalid version
- Multiple blob transactions with multiple blobs all with invalid version
- Multiple blob transactions with multiple blobs only one with invalid
version
"""
blockchain_test(
pre=pre,
post={},
blocks=[block],
genesis_environment=env,
)
@pytest.mark.parametrize(
"tx_gas", [500_000], ids=[""]
) # Increase gas to account for contract creation
@pytest.mark.exception_test
@pytest.mark.valid_from("Cancun")
def test_invalid_blob_tx_contract_creation(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
env: Environment,
txs: List[Transaction],
header_verify: Optional[Header],
) -> None:
"""
Reject blocks that include blob transactions that have nil to value
(contract creating).
"""
assert len(txs) == 1
assert txs[0].blob_versioned_hashes is not None and len(txs[0].blob_versioned_hashes) == 1
# Replace the transaction with a contract creating one, only in the RLP
# version
contract_creating_tx = txs[0].copy(to=None).with_signature_and_sender()
txs[0].rlp_override = contract_creating_tx.rlp()
blockchain_test(
pre=pre,
post={},
blocks=[
Block(
txs=txs,
exception=[
BlockException.RLP_STRUCTURES_ENCODING,
TransactionException.TYPE_3_TX_CONTRACT_CREATION,
],
header_verify=header_verify,
# Skipped due to the T8N not receiving the invalid transaction,
# instead we are passing a valid transaction to T8N and then
# the transaction is replaced directly in the block RLP.
skip_exception_verification=True,
)
],
genesis_environment=env,
)
# # ----------------------------------------
# # Opcode Tests in Blob Transaction Context
# # ----------------------------------------
@pytest.fixture
def opcode(
request: pytest.FixtureRequest,
sender: EOA,
tx_calldata: bytes,
block_base_fee_per_gas: int,
tx_max_fee_per_gas: int,
tx_max_priority_fee_per_gas: int,
tx_value: int,
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | true |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/conftest.py | tests/cancun/eip4844_blobs/conftest.py | """Pytest (plugin) definitions local to EIP-4844 tests."""
from typing import Iterable
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import Alloc, Block, Environment, Hash, Transaction, add_kzg_version
from .spec import Spec
@pytest.fixture
def block_base_fee_per_gas() -> int:
"""Return default max fee per gas for transactions sent during test."""
return 7
@pytest.fixture
def target_blobs_per_block(fork: Fork) -> int:
"""Return default number of blobs to be included in the block."""
return fork.target_blobs_per_block()
@pytest.fixture
def max_blobs_per_block(fork: Fork) -> int:
"""Return default number of blobs to be included in the block."""
return fork.max_blobs_per_block()
@pytest.fixture
def max_blobs_per_tx(fork: Fork) -> int:
"""Return max number of blobs per transaction."""
return fork.max_blobs_per_tx()
@pytest.fixture
def blob_gas_per_blob(fork: Fork) -> int:
"""Return default blob gas cost per blob."""
return fork.blob_gas_per_blob()
@pytest.fixture(autouse=True)
def parent_excess_blobs() -> int | None:
"""
Return default excess blobs of the parent block.
Can be overloaded by a test case to provide a custom parent excess blob
count.
"""
return 10 # Defaults to a blob gas price of 1.
@pytest.fixture(autouse=True)
def parent_blobs() -> int | None:
"""
Return default data blobs of the parent blob.
Can be overloaded by a test case to provide a custom parent blob count.
"""
return 0
@pytest.fixture
def parent_excess_blob_gas(
parent_excess_blobs: int | None,
blob_gas_per_blob: int,
) -> int | None:
"""
Calculate the excess blob gas of the parent block from the excess blobs.
"""
if parent_excess_blobs is None:
return None
assert parent_excess_blobs >= 0
return parent_excess_blobs * blob_gas_per_blob
@pytest.fixture
def excess_blob_gas(
fork: Fork,
parent_excess_blobs: int | None,
parent_blobs: int | None,
block_base_fee_per_gas: int,
) -> int | None:
"""
Calculate the excess blob gas of the block under test from the parent
block.
Value can be overloaded by a test case to provide a custom excess blob gas.
"""
if parent_excess_blobs is None or parent_blobs is None:
return None
return fork.excess_blob_gas_calculator()(
parent_excess_blobs=parent_excess_blobs,
parent_blob_count=parent_blobs,
parent_base_fee_per_gas=block_base_fee_per_gas,
)
@pytest.fixture
def correct_excess_blob_gas(
fork: Fork,
parent_excess_blobs: int | None,
parent_blobs: int | None,
block_base_fee_per_gas: int,
) -> int:
"""
Calculate the correct excess blob gas of the block under test from the
parent block.
Should not be overloaded by a test case.
"""
if parent_excess_blobs is None or parent_blobs is None:
return 0
return fork.excess_blob_gas_calculator()(
parent_excess_blobs=parent_excess_blobs,
parent_blob_count=parent_blobs,
parent_base_fee_per_gas=block_base_fee_per_gas,
)
@pytest.fixture
def block_fee_per_blob_gas(
fork: Fork,
correct_excess_blob_gas: int,
) -> int:
"""Calculate the blob gas price for the current block."""
get_blob_gas_price = fork.blob_gas_price_calculator()
return get_blob_gas_price(excess_blob_gas=correct_excess_blob_gas)
@pytest.fixture
def blob_gas_price(
fork: Fork,
excess_blob_gas: int | None,
) -> int | None:
"""Return blob gas price for the block of the test."""
if excess_blob_gas is None:
return None
get_blob_gas_price = fork.blob_gas_price_calculator()
return get_blob_gas_price(
excess_blob_gas=excess_blob_gas,
)
@pytest.fixture
def genesis_excess_blob_gas(
parent_excess_blob_gas: int | None,
parent_blobs: int,
target_blobs_per_block: int,
blob_gas_per_blob: int,
) -> int:
"""Return default excess blob gas for the genesis block."""
excess_blob_gas = parent_excess_blob_gas if parent_excess_blob_gas else 0
if parent_blobs:
# We increase the excess blob gas of the genesis because
# we cannot include blobs in the genesis, so the
# test blobs are actually in block 1.
excess_blob_gas += target_blobs_per_block * blob_gas_per_blob
return excess_blob_gas
@pytest.fixture
def env(
block_base_fee_per_gas: int,
genesis_excess_blob_gas: int,
) -> Environment:
"""
Prepare the environment of the genesis block for all blockchain tests.
"""
return Environment(
excess_blob_gas=genesis_excess_blob_gas,
blob_gas_used=0,
base_fee_per_gas=block_base_fee_per_gas,
)
@pytest.fixture
def tx_value() -> int:
"""
Return default value contained by the transactions sent during test.
Can be overloaded by a test case to provide a custom transaction value.
"""
return 1
@pytest.fixture
def tx_calldata() -> bytes:
"""Return default calldata in transactions sent during test."""
return b""
@pytest.fixture(autouse=True)
def tx_max_fee_per_gas(
block_base_fee_per_gas: int,
) -> int:
"""
Max fee per gas value used by all transactions sent during test.
By default the max fee per gas is the same as the block fee per gas.
Can be overloaded by a test case to test rejection of transactions where
the max fee per gas is insufficient.
"""
return block_base_fee_per_gas
@pytest.fixture
def tx_max_priority_fee_per_gas() -> int:
"""
Return default max priority fee per gas for transactions sent during test.
Can be overloaded by a test case to provide a custom max priority fee per
gas.
"""
return 0
@pytest.fixture
def tx_max_fee_per_blob_gas_multiplier() -> int:
"""
Return default max fee per blob gas multiplier for transactions sent during
test.
Can be overloaded by a test case to provide a custom max fee per blob gas
multiplier.
"""
return 1
@pytest.fixture
def tx_max_fee_per_blob_gas_delta() -> int:
"""
Return default max fee per blob gas delta for transactions sent during
test.
Can be overloaded by a test case to provide a custom max fee per blob gas
delta.
"""
return 0
@pytest.fixture
def tx_max_fee_per_blob_gas( # noqa: D103
blob_gas_price: int | None,
tx_max_fee_per_blob_gas_multiplier: int,
tx_max_fee_per_blob_gas_delta: int,
) -> int:
"""
Return default max fee per blob gas for transactions sent during test.
By default, it is set to the blob gas price of the block.
Can be overloaded by a test case to test rejection of transactions where
the max fee per blob gas is insufficient.
"""
if blob_gas_price is None:
# When fork transitioning, the default blob gas price is 1.
return 1
return (blob_gas_price * tx_max_fee_per_blob_gas_multiplier) + tx_max_fee_per_blob_gas_delta
@pytest.fixture
def non_zero_blob_gas_used_genesis_block(
pre: Alloc,
parent_blobs: int,
fork: Fork,
genesis_excess_blob_gas: int,
parent_excess_blob_gas: int,
tx_max_fee_per_gas: int,
block_base_fee_per_gas: int,
) -> Block | None:
"""
For test cases with a non-zero blobGasUsed field in the original genesis
block header we must instead utilize an intermediate block to act on its
behalf.
Genesis blocks with a non-zero blobGasUsed field are invalid as they do not
have any blob txs.
For the intermediate block to align with default genesis values, we must
add TARGET_BLOB_GAS_PER_BLOCK to the excessBlobGas of the genesis value,
expecting an appropriate drop to the intermediate block. Similarly, we must
add parent_blobs to the intermediate block within a blob tx such that an
equivalent blobGasUsed field is wrote.
For forks >= Osaka where the MAX_BLOBS_PER_TX is introduced, we split the
blobs across multiple transactions to respect the MAX_BLOBS_PER_TX limit.
"""
if parent_blobs == 0:
return None
excess_blob_gas_calculator = fork.excess_blob_gas_calculator(block_number=1)
calculated_excess_blob_gas = excess_blob_gas_calculator(
parent_excess_blob_gas=genesis_excess_blob_gas,
parent_blob_count=0,
parent_base_fee_per_gas=block_base_fee_per_gas,
)
assert parent_excess_blob_gas == calculated_excess_blob_gas, (
f"parent excess blob gas mismatch: expected {parent_excess_blob_gas}, "
f"got {calculated_excess_blob_gas} for {parent_blobs} blobs "
f"with base_fee_per_gas {block_base_fee_per_gas}"
)
sender = pre.fund_eoa(10**27)
empty_account_destination = pre.fund_eoa(0)
blob_gas_price_calculator = fork.blob_gas_price_calculator(block_number=1)
# Split blobs into chunks when MAX_BLOBS_PER_TX < MAX_BLOBS_PER_BLOCK to
# respect per-tx limits. Allows us to keep single txs for forks where per-
# tx and per-block limits are equal, hitting coverage for block level blob
# gas validation when parent_blobs > MAX_BLOBS_PER_BLOCK.
max_blobs_per_tx = (
fork.max_blobs_per_tx()
if fork.max_blobs_per_tx() < fork.max_blobs_per_block()
else parent_blobs
)
blob_chunks = [
range(i, min(i + max_blobs_per_tx, parent_blobs))
for i in range(0, parent_blobs, max_blobs_per_tx)
]
def create_blob_transaction(blob_range: Iterable[int]) -> Transaction:
return Transaction(
ty=Spec.BLOB_TX_TYPE,
sender=sender,
to=empty_account_destination,
value=1,
gas_limit=21_000,
max_fee_per_gas=tx_max_fee_per_gas,
max_priority_fee_per_gas=0,
max_fee_per_blob_gas=blob_gas_price_calculator(
excess_blob_gas=parent_excess_blob_gas,
),
access_list=[],
blob_versioned_hashes=add_kzg_version(
[Hash(x) for x in blob_range],
Spec.BLOB_COMMITMENT_VERSION_KZG,
),
)
txs = [create_blob_transaction(chunk) for chunk in blob_chunks]
return Block(txs=txs)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_excess_blob_gas_fork_transition.py | tests/cancun/eip4844_blobs/test_excess_blob_gas_fork_transition.py | """
Test `excessBlobGas` & `blobGasUsed` block fields at fork transition.
Tests for [EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844).
"""
from typing import List, Mapping
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
EOA,
Account,
Address,
Alloc,
Block,
BlockchainTestFiller,
BlockException,
EngineAPIError,
Environment,
Hash,
Header,
Transaction,
add_kzg_version,
)
from ethereum_test_tools import Opcodes as Op
from .spec import Spec, SpecHelpers, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
# Timestamp of the fork
FORK_TIMESTAMP = 15_000
BASE_FEE_MAX_CHANGE_DENOMINATOR = 8
@pytest.fixture
def block_gas_limit(fork: Fork) -> int: # noqa: D103
gas_limit = int(Environment().gas_limit)
tx_gas_limit_cap = fork.transaction_gas_limit_cap()
if tx_gas_limit_cap is not None:
# Below transaction gas limit cap to reach gas limit easily
gas_limit = min(gas_limit, tx_gas_limit_cap * 2)
return gas_limit
@pytest.fixture
def genesis_environment(block_gas_limit: int, block_base_fee_per_gas: int) -> Environment:
"""
Genesis environment that enables existing transition tests to be used of
BPO forks. Compatible with all fork transitions.
"""
return Environment(
base_fee_per_gas=(block_base_fee_per_gas * BASE_FEE_MAX_CHANGE_DENOMINATOR) // 7,
gas_limit=block_gas_limit,
)
@pytest.fixture
def pre_fork_blobs_per_block(fork: Fork) -> int:
"""Amount of blobs to produce with the pre-fork rules."""
if fork.supports_blobs(timestamp=0):
return fork.max_blobs_per_block(timestamp=0)
return 0
@pytest.fixture
def post_fork_blobs_per_block(fork: Fork) -> int:
"""Amount of blobs to produce with the post-fork rules."""
return fork.target_blobs_per_block(timestamp=FORK_TIMESTAMP) + 1
@pytest.fixture
def pre_fork_blocks(
pre_fork_blobs_per_block: int,
destination_account: Address,
gas_spender_account: Address,
sender: EOA,
fork: Fork,
block_base_fee_per_gas: int,
block_gas_limit: int,
) -> List[Block]:
"""Generate blocks to reach the fork."""
blocks = []
for t in range(999, FORK_TIMESTAMP, 1_000):
remaining_gas = block_gas_limit // 2
if pre_fork_blobs_per_block == 0:
blocks.append(
Block(
txs=[
Transaction(
to=gas_spender_account,
value=0,
gas_limit=remaining_gas,
max_fee_per_gas=1_000_000,
max_priority_fee_per_gas=10,
sender=sender,
)
],
timestamp=t,
)
)
continue
# Split into multi txs for forks where max per tx < max per block
txs = []
blob_index = 0
remaining_blobs = pre_fork_blobs_per_block
max_blobs_per_tx = fork.max_blobs_per_tx(timestamp=0)
while remaining_blobs > 0:
tx_blobs = min(remaining_blobs, max_blobs_per_tx)
blob_tx_gas_limit = 21_000
txs.append(
Transaction(
ty=Spec.BLOB_TX_TYPE,
to=destination_account,
value=1,
gas_limit=blob_tx_gas_limit,
max_fee_per_gas=1_000_000,
max_priority_fee_per_gas=10,
max_fee_per_blob_gas=100,
access_list=[],
blob_versioned_hashes=add_kzg_version(
[Hash(blob_index + x) for x in range(tx_blobs)],
Spec.BLOB_COMMITMENT_VERSION_KZG,
),
sender=sender,
)
)
remaining_gas -= blob_tx_gas_limit
blob_index += tx_blobs
remaining_blobs -= tx_blobs
txs.append(
Transaction(
to=gas_spender_account,
value=0,
gas_limit=remaining_gas,
max_fee_per_gas=1_000_000,
max_priority_fee_per_gas=10,
sender=sender,
)
)
block = Block(
txs=txs, timestamp=t, header_verify=Header(base_fee_per_gas=block_base_fee_per_gas)
)
blocks.append(block)
return blocks
@pytest.fixture
def pre_fork_excess_blobs(
fork: Fork,
pre_fork_blobs_per_block: int,
pre_fork_blocks: List[Block],
) -> int:
"""
Return the cumulative excess blobs up until the fork given the
pre_fork_blobs_per_block and the target blobs in the fork prior.
"""
if not fork.supports_blobs(timestamp=0):
return 0
target_blobs = fork.target_blobs_per_block(timestamp=0)
if pre_fork_blobs_per_block > target_blobs:
return (pre_fork_blobs_per_block - target_blobs) * (len(pre_fork_blocks) - 1)
return 0
@pytest.fixture
def post_fork_block_count(fork: Fork) -> int:
"""Amount of blocks to produce with the post-fork rules."""
return SpecHelpers.get_min_excess_blobs_for_blob_gas_price(fork=fork, blob_gas_price=2) // (
fork.max_blobs_per_block(timestamp=FORK_TIMESTAMP)
- fork.target_blobs_per_block(timestamp=FORK_TIMESTAMP)
)
@pytest.fixture
def destination_account(pre: Alloc) -> Address: # noqa: D103
# Empty account to receive the blobs
return pre.fund_eoa(amount=0)
@pytest.fixture
def gas_spender_account(pre: Alloc) -> Address: # noqa: D103
# Account that when called consumes the entirety of the transaction's gas
return pre.deploy_contract(code=Op.INVALID)
@pytest.fixture
def fork_block_excess_blob_gas(
fork: Fork,
pre_fork_excess_blobs: int,
pre_fork_blobs_per_block: int,
block_base_fee_per_gas: int,
) -> int:
"""Calculate the expected excess blob gas for the fork block."""
if pre_fork_blobs_per_block == 0:
return 0
calc_excess_blob_gas_post_fork = fork.excess_blob_gas_calculator(timestamp=FORK_TIMESTAMP)
return calc_excess_blob_gas_post_fork(
parent_excess_blobs=pre_fork_excess_blobs,
parent_blob_count=pre_fork_blobs_per_block,
parent_base_fee_per_gas=block_base_fee_per_gas,
)
@pytest.fixture
def post_fork_blocks(
destination_account: Address,
post_fork_block_count: int,
post_fork_blobs_per_block: int,
fork_block_excess_blob_gas: int,
sender: EOA,
pre_fork_blocks: List[Block],
fork: Fork,
) -> list[Block]:
"""Generate blocks after the fork."""
blocks = []
for i in range(post_fork_block_count):
if post_fork_blobs_per_block == 0:
if i == 0:
blocks.append(
Block(
txs=[],
header_verify=Header(
excess_blob_gas=fork_block_excess_blob_gas,
),
)
)
else:
blocks.append(Block(txs=[]))
continue
# Split into multi txs for forks where max per tx < max per block
txs = []
blob_index = 0
remaining_blobs = post_fork_blobs_per_block
max_blobs_per_tx = fork.max_blobs_per_tx(timestamp=FORK_TIMESTAMP)
while remaining_blobs > 0:
tx_blobs = min(remaining_blobs, max_blobs_per_tx)
txs.append(
Transaction(
ty=Spec.BLOB_TX_TYPE,
to=destination_account,
value=1,
gas_limit=100_000,
max_fee_per_gas=1_000_000,
max_priority_fee_per_gas=10,
max_fee_per_blob_gas=100,
blob_versioned_hashes=add_kzg_version(
[Hash(blob_index + x) for x in range(tx_blobs)],
Spec.BLOB_COMMITMENT_VERSION_KZG,
),
sender=sender,
)
)
blob_index += tx_blobs
remaining_blobs -= tx_blobs
if i == 0:
blocks.append(
Block(
txs=txs,
header_verify=Header(
excess_blob_gas=fork_block_excess_blob_gas,
),
)
)
else:
blocks.append(Block(txs=txs))
return blocks
@pytest.fixture
def post( # noqa: D103
pre_fork_blocks: List[Block],
pre_fork_blobs_per_block: int,
post_fork_block_count: int,
post_fork_blobs_per_block: int,
destination_account: Address,
fork: Fork,
) -> Mapping[Address, Account]:
pre_fork_tx_count_per_block = 0
if pre_fork_blobs_per_block > 0:
max_blobs_per_tx_pre = fork.max_blobs_per_tx(timestamp=0)
pre_fork_tx_count_per_block = (
pre_fork_blobs_per_block + max_blobs_per_tx_pre - 1
) // max_blobs_per_tx_pre
post_fork_tx_count_per_block = 0
if post_fork_blobs_per_block > 0:
max_blobs_per_tx_post = fork.max_blobs_per_tx(timestamp=FORK_TIMESTAMP)
post_fork_tx_count_per_block = (
post_fork_blobs_per_block + max_blobs_per_tx_post - 1
) // max_blobs_per_tx_post
pre_fork_value = len(pre_fork_blocks) * pre_fork_tx_count_per_block
post_fork_value = post_fork_block_count * post_fork_tx_count_per_block
total_value = pre_fork_value + post_fork_value
if total_value == 0:
return {}
return {
destination_account: Account(balance=total_value),
}
@pytest.mark.valid_at_transition_to("Cancun", subsequent_forks=False)
@pytest.mark.parametrize(
"excess_blob_gas_present,blob_gas_used_present",
[
(True, False),
(False, True),
(True, True),
],
)
@pytest.mark.exception_test
def test_invalid_pre_fork_block_with_blob_fields(
blockchain_test: BlockchainTestFiller,
genesis_environment: Environment,
pre: Alloc,
pre_fork_blocks: List[Block],
excess_blob_gas_present: bool,
blob_gas_used_present: bool,
) -> None:
"""
Test block rejection when `excessBlobGas` and/or `blobGasUsed` fields are
present on a pre-fork block.
Blocks sent by NewPayloadV2 (Shanghai) that contain `excessBlobGas` and
`blobGasUsed` fields must be rejected with the appropriate
`EngineAPIError.InvalidParams` error error.
"""
header_modifier = Header(
excess_blob_gas=0 if excess_blob_gas_present else None,
blob_gas_used=0 if blob_gas_used_present else None,
)
blockchain_test(
pre=pre,
post={},
blocks=pre_fork_blocks[:-1]
+ [
Block(
timestamp=(FORK_TIMESTAMP - 1),
rlp_modifier=header_modifier,
exception=BlockException.INCORRECT_BLOCK_FORMAT,
engine_api_error_code=EngineAPIError.InvalidParams,
)
],
genesis_environment=genesis_environment,
)
@pytest.mark.valid_at_transition_to("Cancun", subsequent_forks=False)
@pytest.mark.parametrize(
"excess_blob_gas_missing,blob_gas_used_missing",
[
(True, False),
(False, True),
(True, True),
],
)
@pytest.mark.exception_test
def test_invalid_post_fork_block_without_blob_fields(
blockchain_test: BlockchainTestFiller,
genesis_environment: Environment,
pre: Alloc,
pre_fork_blocks: List[Block],
excess_blob_gas_missing: bool,
blob_gas_used_missing: bool,
) -> None:
"""
Test block rejection when `excessBlobGas` and/or `blobGasUsed` fields are
missing on a post-fork block.
Blocks sent by NewPayloadV3 (Cancun) without `excessBlobGas` and
`blobGasUsed` fields must be rejected with the appropriate
`EngineAPIError.InvalidParams` error.
"""
header_modifier = Header()
if excess_blob_gas_missing:
header_modifier.excess_blob_gas = Header.REMOVE_FIELD
if blob_gas_used_missing:
header_modifier.blob_gas_used = Header.REMOVE_FIELD
blockchain_test(
pre=pre,
post={},
blocks=pre_fork_blocks
+ [
Block(
timestamp=FORK_TIMESTAMP,
rlp_modifier=header_modifier,
exception=BlockException.INCORRECT_BLOCK_FORMAT,
engine_api_error_code=EngineAPIError.InvalidParams,
)
],
genesis_environment=genesis_environment,
)
@pytest.mark.valid_at_transition_to("Cancun", subsequent_forks=False)
@pytest.mark.parametrize_by_fork(
"post_fork_block_count,post_fork_blobs_per_block",
lambda fork: [
pytest.param(
SpecHelpers.get_min_excess_blobs_for_blob_gas_price(fork=fork, blob_gas_price=2)
// (
fork.max_blobs_per_block(timestamp=FORK_TIMESTAMP)
- fork.target_blobs_per_block(timestamp=FORK_TIMESTAMP)
)
+ 2,
fork.max_blobs_per_block(timestamp=FORK_TIMESTAMP),
id="max_blobs",
),
pytest.param(10, 0, id="no_blobs"),
pytest.param(10, fork.target_blobs_per_block(timestamp=FORK_TIMESTAMP), id="target_blobs"),
],
)
def test_fork_transition_excess_blob_gas_at_blob_genesis(
blockchain_test: BlockchainTestFiller,
genesis_environment: Environment,
pre: Alloc,
pre_fork_blocks: List[Block],
post_fork_blocks: List[Block],
post: Mapping[Address, Account],
) -> None:
"""
Test `excessBlobGas` calculation in the header when the fork is activated.
Also produce enough blocks to test the blob gas price increase when the
block is full with `SpecHelpers.max_blobs_per_block()` blobs.
"""
blockchain_test(
pre=pre,
post=post,
blocks=pre_fork_blocks + post_fork_blocks,
genesis_environment=genesis_environment,
)
@pytest.mark.valid_at_transition_to("Prague", subsequent_forks=True)
@pytest.mark.parametrize_by_fork(
"post_fork_block_count,pre_fork_blobs_per_block,post_fork_blobs_per_block",
lambda fork: [
pytest.param(
SpecHelpers.get_min_excess_blobs_for_blob_gas_price(fork=fork, blob_gas_price=2)
// (
fork.max_blobs_per_block(timestamp=FORK_TIMESTAMP)
- fork.target_blobs_per_block(timestamp=FORK_TIMESTAMP)
)
+ 2,
fork.max_blobs_per_block(timestamp=0),
fork.max_blobs_per_block(timestamp=FORK_TIMESTAMP),
id="max_blobs_before_and_after",
),
pytest.param(
10,
0,
fork.max_blobs_per_block(timestamp=FORK_TIMESTAMP),
id="no_blobs_before_and_max_blobs_after",
),
pytest.param(
10,
fork.max_blobs_per_block(timestamp=0),
0,
id="max_blobs_before_and_no_blobs_after",
),
pytest.param(
10,
fork.target_blobs_per_block(timestamp=0),
fork.target_blobs_per_block(timestamp=FORK_TIMESTAMP),
id="target_blobs_before_and_after",
),
pytest.param(
10,
1,
fork.max_blobs_per_block(timestamp=FORK_TIMESTAMP),
id="single_blob_before_and_max_blobs_after",
),
pytest.param(
10,
fork.max_blobs_per_block(timestamp=0),
1,
id="max_blobs_before_and_single_blob_after",
),
],
)
@pytest.mark.parametrize("block_base_fee_per_gas", [7, 16, 23])
def test_fork_transition_excess_blob_gas_post_blob_genesis(
blockchain_test: BlockchainTestFiller,
genesis_environment: Environment,
pre: Alloc,
pre_fork_blocks: List[Block],
post_fork_blocks: List[Block],
post: Mapping[Address, Account],
) -> None:
"""
Test `excessBlobGas` calculation in the header when the fork is activated.
"""
blockchain_test(
pre=pre,
post=post,
blocks=pre_fork_blocks + post_fork_blocks,
genesis_environment=genesis_environment,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_blobhash_opcode_contexts.py | tests/cancun/eip4844_blobs/test_blobhash_opcode_contexts.py | """
Tests `BLOBHASH` opcode in [EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844).
"""
from enum import Enum
from typing import Iterable, List
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
Account,
Address,
Alloc,
AuthorizationTuple,
Bytecode,
Hash,
StateTestFiller,
Transaction,
add_kzg_version,
compute_create_address,
)
from ethereum_test_tools import Opcodes as Op
from .spec import Spec, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
pytestmark = pytest.mark.valid_from("Cancun")
class BlobhashContext(Enum):
"""
A utility class for mapping common EVM opcodes in different contexts to
specific bytecode (with BLOBHASH), addresses and contracts.
"""
BLOBHASH_SSTORE = "blobhash_sstore"
BLOBHASH_RETURN = "blobhash_return"
CALL = "call"
DELEGATECALL = "delegatecall"
CALLCODE = "callcode"
STATICCALL = "staticcall"
CREATE = "create"
CREATE2 = "create2"
INITCODE = "initcode"
def code(self, *, indexes: Iterable[int]) -> Bytecode:
"""
Map opcode context to bytecode that utilizes the BLOBHASH opcode.
Args: indexes: The indexes to request using the BLOBHASH opcode
"""
match self:
case BlobhashContext.BLOBHASH_SSTORE:
return (
sum(Op.SSTORE(index, Op.BLOBHASH(index=index)) for index in indexes) + Op.STOP
)
case BlobhashContext.BLOBHASH_RETURN:
return Op.MSTORE(
offset=0, value=Op.BLOBHASH(index=Op.CALLDATALOAD(offset=0))
) + Op.RETURN(offset=0, size=32)
case BlobhashContext.INITCODE:
return (
sum(Op.SSTORE(index, Op.BLOBHASH(index=index)) for index in indexes) + Op.STOP
)
case _:
raise ValueError(f"Invalid context: {self}")
def deploy_contract(
self,
*,
pre: Alloc,
indexes: Iterable[int],
) -> Address:
"""
Deploy a contract with the given context and indexes.
Args:
pre: The pre state to deploy the contract on
indexes: The indexes to request using the BLOBHASH opcode
"""
match self:
case BlobhashContext.BLOBHASH_SSTORE | BlobhashContext.BLOBHASH_RETURN:
return pre.deploy_contract(self.code(indexes=indexes))
case BlobhashContext.CALL | BlobhashContext.CALLCODE | BlobhashContext.STATICCALL:
blobhash_return_address = BlobhashContext.BLOBHASH_RETURN.deploy_contract(
pre=pre, indexes=indexes
)
call_opcode = (
Op.CALL
if self == BlobhashContext.CALL
else (Op.CALLCODE if self == BlobhashContext.CALLCODE else Op.STATICCALL)
)
bytecode = (
sum(
Op.MSTORE(offset=0, value=index)
+ Op.POP(
call_opcode(
address=blobhash_return_address,
args_offset=0,
args_size=32,
ret_offset=32,
ret_size=32,
)
)
+ Op.SSTORE(index, Op.MLOAD(offset=32))
for index in indexes
)
+ Op.STOP
)
return pre.deploy_contract(bytecode)
case BlobhashContext.DELEGATECALL:
blobhash_sstore_address = pre.deploy_contract(
BlobhashContext.BLOBHASH_SSTORE.code(indexes=indexes)
)
bytecode = Op.POP(
Op.DELEGATECALL(
address=blobhash_sstore_address, args_offset=0, args_size=Op.CALLDATASIZE()
)
)
return pre.deploy_contract(bytecode)
case BlobhashContext.CREATE | BlobhashContext.CREATE2:
initcode = BlobhashContext.INITCODE.code(indexes=indexes)
initcode_address = pre.deploy_contract(initcode)
create_opcode = Op.CREATE if self == BlobhashContext.CREATE else Op.CREATE2
create_bytecode = Op.EXTCODECOPY(
address=initcode_address, dest_offset=0, offset=0, size=len(initcode)
) + Op.POP(
create_opcode(value=0, offset=0, size=len(initcode), salt=0)
if create_opcode == Op.CREATE2
else create_opcode(value=0, offset=0, size=len(initcode))
)
return pre.deploy_contract(create_bytecode)
case _:
raise ValueError(f"Invalid context: {self}")
@pytest.fixture()
def simple_blob_hashes(
max_blobs_per_tx: int,
) -> List[Hash]:
"""
Return a simple list of blob versioned hashes ranging from bytes32(1 to 4).
"""
return add_kzg_version(
[(1 << x) for x in range(max_blobs_per_tx)],
Spec.BLOB_COMMITMENT_VERSION_KZG,
)
@pytest.mark.parametrize(
"test_case",
[
"on_top_level_call_stack",
"on_max_value",
"on_CALL",
"on_DELEGATECALL",
"on_STATICCALL",
"on_CALLCODE",
"on_CREATE",
"on_CREATE2",
],
ids=lambda x: x,
)
def test_blobhash_opcode_contexts(
pre: Alloc,
test_case: str,
max_blobs_per_tx: int,
simple_blob_hashes: List[bytes],
fork: Fork,
state_test: StateTestFiller,
) -> None:
"""
Tests that the `BLOBHASH` opcode functions correctly when called in
different contexts.
- `BLOBHASH` opcode on the top level of the call stack.
- `BLOBHASH` opcode on the max value.
- `BLOBHASH` opcode on `CALL`, `DELEGATECALL`, `STATICCALL`, and
`CALLCODE`.
- `BLOBHASH` opcode on Initcode.
- `BLOBHASH` opcode on `CREATE` and `CREATE2`.
- `BLOBHASH` opcode on transaction types 0, 1 and 2.
"""
tx_to: Address
post: dict[Address, Account]
match test_case:
case "on_top_level_call_stack":
blobhash_sstore_address = BlobhashContext.BLOBHASH_SSTORE.deploy_contract(
pre=pre, indexes=range(max_blobs_per_tx + 1)
)
tx_to = blobhash_sstore_address
post = {
blobhash_sstore_address: Account(
storage=dict(
zip(
range(len(simple_blob_hashes)),
simple_blob_hashes,
strict=False,
)
)
),
}
case "on_max_value":
blobhash_sstore_address = BlobhashContext.BLOBHASH_SSTORE.deploy_contract(
pre=pre, indexes=[2**256 - 1]
)
tx_to = blobhash_sstore_address
post = {
blobhash_sstore_address: Account(storage={}),
}
case "on_CALL" | "on_DELEGATECALL" | "on_STATICCALL" | "on_CALLCODE":
call_context: BlobhashContext
match test_case:
case "on_CALL":
call_context = BlobhashContext.CALL
case "on_DELEGATECALL":
call_context = BlobhashContext.DELEGATECALL
case "on_STATICCALL":
call_context = BlobhashContext.STATICCALL
case "on_CALLCODE":
call_context = BlobhashContext.CALLCODE
call_address = call_context.deploy_contract(
pre=pre, indexes=range(max_blobs_per_tx + 1)
)
tx_to = call_address
post = {
call_address: Account(
storage=dict(
zip(
range(len(simple_blob_hashes)),
simple_blob_hashes,
strict=False,
)
)
),
}
case "on_CREATE" | "on_CREATE2":
create_context: BlobhashContext
opcode: Op
match test_case:
case "on_CREATE":
create_context = BlobhashContext.CREATE
opcode = Op.CREATE
case "on_CREATE2":
create_context = BlobhashContext.CREATE2
opcode = Op.CREATE2
factory_address = create_context.deploy_contract(
pre=pre, indexes=range(max_blobs_per_tx + 1)
)
created_contract_address = compute_create_address(
address=factory_address,
nonce=1, # the create contract will have nonce 1 for its first create
salt=0,
initcode=BlobhashContext.INITCODE.code(indexes=range(max_blobs_per_tx + 1)),
opcode=opcode,
)
tx_to = factory_address
post = {
created_contract_address: Account(
storage=dict(
zip(range(len(simple_blob_hashes)), simple_blob_hashes, strict=False)
)
),
}
case _:
raise Exception(f"Unknown test case {test_case}")
state_test(
pre=pre,
tx=Transaction(
ty=Spec.BLOB_TX_TYPE,
to=tx_to,
gas_limit=500_000,
max_fee_per_blob_gas=fork.min_base_fee_per_blob_gas() * 10,
blob_versioned_hashes=simple_blob_hashes,
sender=pre.fund_eoa(),
),
post=post,
)
@pytest.mark.with_all_tx_types(selector=lambda x: x != 3)
def test_blobhash_opcode_contexts_tx_types(
pre: Alloc,
tx_type: int,
state_test: StateTestFiller,
) -> None:
"""
Tests that the `BLOBHASH` opcode functions correctly when called in
different contexts.
- `BLOBHASH` opcode on the top level of the call stack.
- `BLOBHASH` opcode on the max value.
- `BLOBHASH` opcode on `CALL`, `DELEGATECALL`, `STATICCALL`, and
`CALLCODE`.
- `BLOBHASH` opcode on Initcode.
- `BLOBHASH` opcode on `CREATE` and `CREATE2`.
- `BLOBHASH` opcode on transaction types 0, 1 and 2.
"""
blobhash_sstore_address = BlobhashContext.BLOBHASH_SSTORE.deploy_contract(pre=pre, indexes=[0])
tx_kwargs = {
"ty": tx_type,
"to": blobhash_sstore_address,
"sender": pre.fund_eoa(),
"gas_limit": 500_000,
}
if tx_type == 4:
signer = pre.fund_eoa(amount=0)
tx_kwargs["authorization_list"] = [
AuthorizationTuple(
signer=signer,
address=Address(0),
nonce=0,
)
]
state_test(
pre=pre,
tx=Transaction(**tx_kwargs),
post={
blobhash_sstore_address: Account(storage={0: 0}),
},
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_point_evaluation_precompile.py | tests/cancun/eip4844_blobs/test_point_evaluation_precompile.py | """
Tests point evaluation precompile for [EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844).
Note: Adding a new test Add a function that is named `test_<test_name>` and
takes at least the following arguments.
Required arguments:
- `blockchain_test` or `state_test`
- `pre`
- `tx`
- `post`
The following arguments *need* to be parametrized or the test will not be
generated:
- `versioned_hash`
- `kzg_commitment`
- `z`
- `y`
- `kzg_proof`
- `result`
These values correspond to a single call of the precompile, and `result`
refers to whether the call should succeed or fail.
All other `pytest.fixture` fixtures can be parametrized to generate new
combinations and test cases.
"""
import glob
import json
import os
from enum import Enum
from itertools import count
from typing import Any, Dict, List, Optional
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
EOA,
AccessList,
Account,
Address,
Alloc,
Block,
BlockchainTestFiller,
Bytecode,
Environment,
StateTestFiller,
Storage,
Transaction,
TransactionReceipt,
call_return_code,
)
from ethereum_test_vm import Opcodes as Op
from .common import INF_POINT, Z_Y_VALID_ENDIANNESS, Z
from .spec import Spec, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
class Result(str, Enum):
"""Result of the point evaluation precompile."""
SUCCESS = "success"
FAILURE = "failure"
OUT_OF_GAS = "out_of_gas"
@pytest.fixture
def precompile_input(
versioned_hash: Optional[bytes | int],
kzg_commitment: bytes | int,
z: bytes | int,
y: bytes | int,
kzg_proof: bytes | int,
) -> bytes:
"""Format the input for the point evaluation precompile."""
if isinstance(z, int):
z = z.to_bytes(32, Z_Y_VALID_ENDIANNESS)
if isinstance(y, int):
y = y.to_bytes(32, Z_Y_VALID_ENDIANNESS)
if isinstance(kzg_commitment, int):
kzg_commitment = kzg_commitment.to_bytes(48, "big")
if isinstance(kzg_proof, int):
kzg_proof = kzg_proof.to_bytes(48, "big")
if versioned_hash is None:
versioned_hash = Spec.kzg_to_versioned_hash(kzg_commitment)
elif isinstance(versioned_hash, int):
versioned_hash = versioned_hash.to_bytes(32, "big")
return versioned_hash + z + y + kzg_commitment + kzg_proof
@pytest.fixture
def call_opcode() -> Op:
"""
Type of call to use to call the precompile.
Defaults to Op.CALL, but can be parametrized to use other opcode types.
"""
return Op.CALL
@pytest.fixture
def call_gas() -> int:
"""
Amount of gas to pass to the precompile.
Defaults to Spec.POINT_EVALUATION_PRECOMPILE_GAS, but can be parametrized
to test different amounts.
"""
return Spec.POINT_EVALUATION_PRECOMPILE_GAS
precompile_caller_storage_keys = count()
key_call_return_code = next(precompile_caller_storage_keys)
key_return_1 = next(precompile_caller_storage_keys)
key_return_2 = next(precompile_caller_storage_keys)
key_return_length = next(precompile_caller_storage_keys)
key_return_copy_1 = next(precompile_caller_storage_keys)
key_return_copy_2 = next(precompile_caller_storage_keys)
@pytest.fixture
def precompile_caller_storage() -> Storage.StorageDictType:
"""Storage for the precompile caller contract."""
return {
key_call_return_code: 0xBA5E,
key_return_1: 0xBA5E,
key_return_2: 0xBA5E,
key_return_length: 0xBA5E,
key_return_copy_1: 0xBA5E,
key_return_copy_2: 0xBA5E,
}
@pytest.fixture
def precompile_caller_code(call_opcode: Op, call_gas: int) -> Bytecode:
"""Code to call the point evaluation precompile."""
precompile_caller_code = Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
precompile_caller_code += Op.SSTORE(
key_call_return_code,
# https://github.com/ethereum/execution-spec-tests/issues/348
call_opcode(
gas=call_gas,
address=Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS,
args_offset=0x00,
args_size=Op.CALLDATASIZE,
ret_offset=0x00,
ret_size=0x40,
),
) # Store the result of the precompile call in storage slot 0
precompile_caller_code += (
# Save the returned values into storage
Op.SSTORE(key_return_1, Op.MLOAD(0x00))
+ Op.SSTORE(key_return_2, Op.MLOAD(0x20))
# Save the returned data length into storage
+ Op.SSTORE(key_return_length, Op.RETURNDATASIZE)
# Save the returned data using RETURNDATACOPY into storage
+ Op.RETURNDATACOPY(0, 0, Op.RETURNDATASIZE)
+ Op.SSTORE(key_return_copy_1, Op.MLOAD(0x00))
+ Op.SSTORE(key_return_copy_2, Op.MLOAD(0x20))
+ Op.STOP
)
return precompile_caller_code
@pytest.fixture
def precompile_caller_balance() -> int:
"""Storage for the precompile caller contract."""
return 0
@pytest.fixture
def precompile_caller_address(
pre: Alloc,
precompile_caller_code: Bytecode,
precompile_caller_storage: Storage.StorageDictType,
precompile_caller_balance: int,
) -> Address:
"""Address of the code to call the point evaluation precompile."""
return pre.deploy_contract(
precompile_caller_code,
storage=precompile_caller_storage,
balance=precompile_caller_balance,
)
@pytest.fixture
def tx(
precompile_caller_address: Address,
precompile_input: bytes,
sender: EOA,
) -> Transaction:
"""Prepare transaction used to call the precompile caller account."""
return Transaction(
sender=sender,
data=precompile_input,
to=precompile_caller_address,
gas_limit=Spec.POINT_EVALUATION_PRECOMPILE_GAS * 100,
)
@pytest.fixture
def success(
result: Result,
call_opcode: Op,
) -> bool:
"""Prepare expected success or failure for each test."""
if call_opcode == Op.EXTDELEGATECALL:
return False
if result == Result.OUT_OF_GAS and call_opcode in [Op.EXTCALL, Op.EXTSTATICCALL]:
return True
return result == Result.SUCCESS
@pytest.fixture
def post(
success: bool,
call_opcode: Op,
precompile_caller_address: Address,
precompile_input: bytes,
) -> Dict:
"""
Prepare expected post for each test, depending on the success or failure of
the precompile call.
"""
expected_storage: Storage.StorageDictType = {}
# CALL operation return code
expected_storage[key_call_return_code] = call_return_code(
call_opcode, success, revert=call_opcode == Op.EXTDELEGATECALL
)
if success:
# Success return values
expected_storage[key_return_1] = Spec.FIELD_ELEMENTS_PER_BLOB
expected_storage[key_return_2] = Spec.BLS_MODULUS
# Success return values size
expected_storage[key_return_length] = 64
# Success return values from RETURNDATACOPY
expected_storage[key_return_copy_1] = Spec.FIELD_ELEMENTS_PER_BLOB
expected_storage[key_return_copy_2] = Spec.BLS_MODULUS
else:
# Failure returns zero values
expected_storage[key_return_length] = 0
# Input parameters were not overwritten since the CALL failed
expected_storage[key_return_1] = precompile_input[0:32]
expected_storage[key_return_2] = precompile_input[32:64]
expected_storage[key_return_copy_1] = expected_storage[1]
expected_storage[key_return_copy_2] = expected_storage[2]
if call_opcode in [Op.EXTCALL, Op.EXTSTATICCALL, Op.EXTDELEGATECALL]:
# Input parameters were not overwritten
expected_storage[key_return_1] = precompile_input[0:32]
expected_storage[key_return_2] = precompile_input[32:64]
return {
precompile_caller_address: Account(
storage=expected_storage,
),
}
@pytest.mark.parametrize(
"z,y,kzg_commitment,kzg_proof,versioned_hash",
[
pytest.param(Spec.BLS_MODULUS - 1, 0, INF_POINT, INF_POINT, None, id="in_bounds_z"),
pytest.param(
# Example valid input from a Mainnet transaction
# https://etherscan.io/tx/0xcb3dc8f3b14f1cda0c16a619a112102a8ec70dce1b3f1b28272227cf8d5fbb0e
0x019123BCB9D06356701F7BE08B4494625B87A7B02EDC566126FB81F6306E915F,
0x6C2EB1E94C2532935B8465351BA1BD88EABE2B3FA1AADFF7D1CD816E8315BD38,
0xA9546D41993E10DF2A7429B8490394EA9EE62807BAE6F326D1044A51581306F58D4B9DFD5931E044688855280FF3799E,
0xA2EA83D9391E0EE42E0C650ACC7A1F842A7D385189485DDB4FD54ADE3D9FD50D608167DCA6C776AAD4B8AD5C20691BFE,
0x018156B94FE9735E573BAB36DAD05D60FEB720D424CCD20AAF719343C31E4246,
id="mainnet_1",
),
],
)
@pytest.mark.parametrize("result", [Result.SUCCESS])
@pytest.mark.valid_from("Cancun")
def test_valid_inputs(
state_test: StateTestFiller,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Test valid sanity precompile calls that are expected to succeed.
- `kzg_commitment` and `kzg_proof` are set to values such that `p(z)==0`
for all values of `z`, hence `y` is tested to be zero, and call to be
successful.
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
@pytest.mark.parametrize(
"z,y,kzg_commitment,kzg_proof,versioned_hash",
[
(Spec.BLS_MODULUS, 0, INF_POINT, INF_POINT, None),
(0, Spec.BLS_MODULUS, INF_POINT, INF_POINT, None),
(Z, 0, INF_POINT, INF_POINT[:-1], None),
(Z, 0, INF_POINT, INF_POINT[0:1], None),
(Z, 0, INF_POINT, INF_POINT + bytes([0]), None),
(Z, 0, INF_POINT, INF_POINT + bytes([0] * 1023), None),
(bytes(), bytes(), bytes(), bytes(), bytes()),
(0, 0, 0, 0, 0),
(0, 0, 0, 0, None),
(Z, 0, INF_POINT, INF_POINT, Spec.kzg_to_versioned_hash(0xC0 << 376, 0x00)),
(Z, 0, INF_POINT, INF_POINT, Spec.kzg_to_versioned_hash(0xC0 << 376, 0x02)),
(Z, 0, INF_POINT, INF_POINT, Spec.kzg_to_versioned_hash(0xC0 << 376, 0xFF)),
],
ids=[
"out_of_bounds_z",
"out_of_bounds_y",
"correct_proof_1_input_too_short",
"correct_proof_1_input_too_short_2",
"correct_proof_1_input_too_long",
"correct_proof_1_input_extra_long",
"null_inputs",
"zeros_inputs",
"zeros_inputs_correct_versioned_hash",
"correct_proof_1_incorrect_versioned_hash_version_0x00",
"correct_proof_1_incorrect_versioned_hash_version_0x02",
"correct_proof_1_incorrect_versioned_hash_version_0xff",
],
)
@pytest.mark.parametrize("result", [Result.FAILURE])
@pytest.mark.valid_from("Cancun")
def test_invalid_inputs(
state_test: StateTestFiller,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Test invalid precompile calls.
- Out of bounds inputs `z` and `y`
- Correct proof, commitment, z and y, but incorrect lengths
- Null inputs
- Zero inputs
- Correct proof, commitment, z and y, but incorrect version versioned
hash
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
def kzg_point_evaluation_vector_from_dict(data: dict) -> Any:
"""Create a KZGPointEvaluation from a dictionary."""
if "input" not in data:
raise ValueError("Missing 'input' key in data")
if "output" not in data:
raise ValueError("Missing 'output' key in data")
output = data["output"]
if isinstance(output, bool):
result = Result.SUCCESS if output else Result.FAILURE
else:
result = Result.FAILURE
input_value = data["input"]
if "commitment" not in input_value or not isinstance(input_value["commitment"], str):
raise ValueError("Missing 'commitment' key in data['input']")
commitment = bytes.fromhex(input_value["commitment"][2:])
if "proof" not in input_value or not isinstance(input_value["proof"], str):
raise ValueError("Missing 'proof' key in data['input']")
proof = bytes.fromhex(input_value["proof"][2:])
if "z" not in input_value or not isinstance(input_value["z"], str):
raise ValueError("Missing 'z' key in data['input']")
z = bytes.fromhex(input_value["z"][2:])
if "y" not in input_value or not isinstance(input_value["y"], str):
raise ValueError("Missing 'y' key in data['input']")
y = bytes.fromhex(input_value["y"][2:])
name = data["name"] if "name" in data else ""
return pytest.param(
z,
y,
commitment,
proof,
result,
id=name,
)
def load_kzg_point_evaluation_test_vectors_from_file(
file_path: str,
) -> List:
"""Load KZG Point Evaluations from a directory."""
test_vectors = []
# Load the json file as a dictionary
with open(file_path, "r") as file:
data = json.load(file)
if not isinstance(data, list):
raise ValueError("Expected a list of point evaluations")
for item in data:
if not isinstance(item, dict):
continue
test_vectors.append(kzg_point_evaluation_vector_from_dict(item))
return test_vectors
def current_python_script_directory() -> str:
"""Get the current Python script directory."""
return os.path.dirname(os.path.realpath(__file__))
def get_point_evaluation_test_files_in_directory(path: str) -> list[str]:
"""Get the point evaluation files in a directory."""
return glob.glob(os.path.join(path, "*.json"))
def all_external_vectors() -> List:
"""
Test for the Point Evaluation Precompile from external sources, contained
in ./point_evaluation_vectors/.
"""
test_cases = []
for test_file in get_point_evaluation_test_files_in_directory(
os.path.join(current_python_script_directory(), "point_evaluation_vectors")
):
file_loaded_tests = load_kzg_point_evaluation_test_vectors_from_file(test_file)
assert len(file_loaded_tests) > 0
test_cases += file_loaded_tests
return test_cases
@pytest.mark.parametrize(
"z,y,kzg_commitment,kzg_proof,result",
all_external_vectors(),
)
@pytest.mark.parametrize("versioned_hash", [None])
@pytest.mark.valid_from("Cancun")
@pytest.mark.slow()
def test_external_vectors(
state_test: StateTestFiller,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Test precompile calls using external test vectors compiled from different
sources.
- `go_kzg_4844_verify_kzg_proof.json`: test vectors from the
[go-kzg-4844](https://github.com/crate-crypto/go-kzg-4844) repository.
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
@pytest.mark.parametrize(
"call_gas,y,result",
[
(Spec.POINT_EVALUATION_PRECOMPILE_GAS, 0, Result.SUCCESS),
(Spec.POINT_EVALUATION_PRECOMPILE_GAS, 1, Result.FAILURE),
(Spec.POINT_EVALUATION_PRECOMPILE_GAS - 1, 0, Result.OUT_OF_GAS),
],
ids=["correct", "incorrect", "insufficient_gas"],
)
@pytest.mark.with_all_call_opcodes
@pytest.mark.parametrize(
"z,kzg_commitment,kzg_proof,versioned_hash",
[[Z, INF_POINT, INF_POINT, None]],
ids=[""],
)
@pytest.mark.valid_from("Cancun")
def test_call_opcode_types(
state_test: StateTestFiller,
pre: Alloc,
tx: Transaction,
post: Dict,
) -> None:
"""
Test calling the Point Evaluation Precompile with different call types, gas
and parameter configuration.
- Using CALL, DELEGATECALL, CALLCODE and STATICCALL.
- Using correct and incorrect proofs
- Using barely insufficient gas
"""
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
@pytest.mark.parametrize(
"call_gas",
[
(Spec.POINT_EVALUATION_PRECOMPILE_GAS),
(Spec.POINT_EVALUATION_PRECOMPILE_GAS + 1),
(Spec.POINT_EVALUATION_PRECOMPILE_GAS - 1),
],
ids=["exact_gas", "extra_gas", "insufficient_gas"],
)
@pytest.mark.parametrize(
"z,y,kzg_commitment,kzg_proof,versioned_hash,proof_correct",
[
[Z, 0, INF_POINT, INF_POINT, None, True],
[Z, 1, INF_POINT, INF_POINT, None, False],
],
ids=["correct_proof", "incorrect_proof"],
)
@pytest.mark.valid_from("Cancun")
def test_tx_entry_point(
fork: Fork,
state_test: StateTestFiller,
precompile_input: bytes,
call_gas: int,
pre: Alloc,
proof_correct: bool,
) -> None:
"""
Test calling the Point Evaluation Precompile directly as transaction entry
point, and measure the gas consumption.
- Using `gas_limit` with exact necessary gas, insufficient gas and extra
gas.
- Using correct and incorrect proofs
"""
sender = pre.fund_eoa()
# Starting from EIP-7623, we need to use an access list to raise the
# intrinsic gas cost to be above the floor data cost.
access_list = [AccessList(address=Address(i), storage_keys=[]) for i in range(1, 10)]
# Gas is appended the intrinsic gas cost of the transaction
tx_intrinsic_gas_cost_calculator = fork.transaction_intrinsic_cost_calculator()
intrinsic_gas_cost = tx_intrinsic_gas_cost_calculator(
calldata=precompile_input, access_list=access_list
)
# Consumed gas will only be the precompile gas if the proof is correct and
# the call gas is sufficient.
# Otherwise, the call gas will be consumed in full.
consumed_gas = (
Spec.POINT_EVALUATION_PRECOMPILE_GAS
if call_gas >= Spec.POINT_EVALUATION_PRECOMPILE_GAS and proof_correct
else call_gas
) + tx_intrinsic_gas_cost_calculator(
calldata=precompile_input,
access_list=access_list,
return_cost_deducted_prior_execution=True,
)
tx = Transaction(
sender=sender,
data=precompile_input,
access_list=access_list,
to=Address(Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS),
gas_limit=call_gas + intrinsic_gas_cost,
expected_receipt=TransactionReceipt(gas_used=consumed_gas),
)
post = {
sender: Account(
nonce=1,
)
}
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
@pytest.mark.parametrize(
"z,y,kzg_commitment,kzg_proof,versioned_hash",
[[Z, 0, INF_POINT, INF_POINT, None]],
ids=["correct_proof"],
)
@pytest.mark.parametrize("precompile_caller_storage", [{}], ids=[""])
@pytest.mark.parametrize("precompile_caller_balance", [1], ids=[""])
@pytest.mark.parametrize(
"precompile_caller_code",
[
Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
+ Op.SSTORE(
Op.NUMBER,
Op.CALL(
address=Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS,
value=1,
args_size=Op.CALLDATASIZE,
),
)
],
ids=[""],
)
@pytest.mark.valid_at_transition_to("Cancun")
def test_precompile_before_fork(
state_test: StateTestFiller,
pre: Alloc,
tx: Transaction,
precompile_caller_address: Address,
) -> None:
"""
Test calling the Point Evaluation Precompile before the appropriate fork.
"""
post = {
precompile_caller_address: Account(
storage={1: 1},
# The call succeeds because precompile is not there yet
),
Address(Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS): Account(
balance=1,
),
}
state_test(
pre=pre,
env=Environment(timestamp=7_500),
post=post,
tx=tx,
)
FORK_TIMESTAMP = 15_000
PRE_FORK_BLOCK_RANGE = range(999, FORK_TIMESTAMP, 1_000)
@pytest.mark.parametrize(
"z,y,kzg_commitment,kzg_proof,versioned_hash",
[[Z, 0, INF_POINT, INF_POINT, None]],
ids=["correct_proof"],
)
@pytest.mark.parametrize("precompile_caller_storage", [{}], ids=[""])
@pytest.mark.parametrize("precompile_caller_balance", [len(PRE_FORK_BLOCK_RANGE)], ids=[""])
@pytest.mark.parametrize(
"precompile_caller_code",
[
Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
+ Op.SSTORE(
Op.NUMBER,
Op.CALL(
address=Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS,
value=1,
args_size=Op.CALLDATASIZE,
),
)
],
ids=[""],
)
@pytest.mark.valid_at_transition_to("Cancun")
def test_precompile_during_fork(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
precompile_caller_address: Address,
precompile_input: bytes,
sender: EOA,
) -> None:
"""
Test calling the Point Evaluation Precompile during the appropriate fork.
"""
# Blocks before fork
blocks = [
Block(
timestamp=t,
txs=[
Transaction(
sender=sender,
data=precompile_input,
to=precompile_caller_address,
gas_limit=Spec.POINT_EVALUATION_PRECOMPILE_GAS * 100,
)
],
)
for t in PRE_FORK_BLOCK_RANGE
]
# Block after fork
blocks += [
Block(
timestamp=FORK_TIMESTAMP,
txs=[
Transaction(
sender=sender,
data=precompile_input,
to=precompile_caller_address,
gas_limit=Spec.POINT_EVALUATION_PRECOMPILE_GAS * 100,
)
],
)
]
post = {
precompile_caller_address: Account(
storage=dict.fromkeys(range(1, len(PRE_FORK_BLOCK_RANGE) + 1), 1),
# Only the call in the last block's tx fails; storage 0 by default.
),
Address(Spec.POINT_EVALUATION_PRECOMPILE_ADDRESS): Account(
balance=len(PRE_FORK_BLOCK_RANGE),
),
}
blockchain_test(
pre=pre,
post=post,
blocks=blocks,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/__init__.py | tests/cancun/eip4844_blobs/__init__.py | """Cross-client EIP-4844 Tests."""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/test_blobhash_opcode.py | tests/cancun/eip4844_blobs/test_blobhash_opcode.py | """
Tests `BLOBHASH` opcode in [EIP-4844: Shard Blob Transactions](https://eips.ethereum.org/EIPS/eip-4844).
Note: Adding a new test Add a function that is named `test_<test_name>` and
takes at least the following arguments.
Required arguments:
- `blockchain_test`
- `pre`
- `tx`
- `post`
Additional custom `pytest.fixture` fixtures can be added and parametrized
for
new test cases.
There is no specific structure to follow within this test module.
"""
from typing import List
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
Account,
Address,
Alloc,
AuthorizationTuple,
Block,
BlockchainTestFiller,
Bytecode,
CodeGasMeasure,
Environment,
Hash,
StateTestFiller,
Transaction,
add_kzg_version,
)
from ethereum_test_tools import Opcodes as Op
from .spec import Spec, ref_spec_4844
REFERENCE_SPEC_GIT_PATH = ref_spec_4844.git_path
REFERENCE_SPEC_VERSION = ref_spec_4844.version
pytestmark = pytest.mark.valid_from("Cancun")
# Blobhash index values for test_blobhash_gas_cost
blobhash_index_values = [
0x00,
0x01,
0x02,
0x03,
0x04,
2**256 - 1,
0xA12C8B6A8B11410C7D98D790E1098F1ED6D93CB7A64711481AAAB1848E13212F,
]
# Random fixed list of blob versioned hashes
random_blob_hashes = add_kzg_version(
[
"0x00b8c5b09810b5fc07355d3da42e2c3a3e200c1d9a678491b7e8e256fc50cc4f",
"0x005b4c8cc4f86aa2d2cf9e9ce97fca704a11a6c20f6b1d6c00a6e15f6d60a6df",
"0x00878f80eaf10be1a6f618e6f8c071b10a6c14d9b89a3bf2a3f3cf2db6c5681d",
"0x004eb72b108d562c639faeb6f8c6f366a28b0381c7d30431117ec8c7bb89f834",
"0x00a9b2a6c3f3f0675b768d49b5f5dc5b5d988f88d55766247ba9e40b125f16bb",
"0x00a4d4cde4aa01e57fb2c880d1d9c778c33bdf85e48ef4c4d4b4de51abccf4ed",
"0x0071c9b8a0c72d38f5e5b5d08e5cb5ce5e23fb1bc5d75f9c29f7b94df0bceeb7",
"0x002c8b6a8b11410c7d98d790e1098f1ed6d93cb7a64711481aaab1848e13212f",
"0x00d78c25f8a1d6aa04d0e2e2a71cf8dfaa4239fa0f301eb57c249d1e6bfe3c3d",
"0x00c778eb1348a73b9c30c7b1d282a5f8b2c5b5a12d5c5e4a4a35f9c5f639b4a4",
],
Spec.BLOB_COMMITMENT_VERSION_KZG,
)
class BlobhashScenario:
"""A utility class for generating blobhash calls."""
@staticmethod
def create_blob_hashes_list(length: int, max_blobs_per_tx: int) -> List[List[Hash]]:
"""
Create list of MAX_BLOBS_PER_TX blob hashes using `random_blob_hashes`.
Cycle over random_blob_hashes to get a large list of length:
MAX_BLOBS_PER_TX * length
-> [0x01, 0x02, 0x03, 0x04, ..., 0x0A, 0x0B, 0x0C, 0x0D]
Then split list into smaller chunks of MAX_BLOBS_PER_TX
-> [[0x01, 0x02, 0x03, 0x04], ..., [0x0a, 0x0b, 0x0c, 0x0d]]
"""
b_hashes = [
random_blob_hashes[i % len(random_blob_hashes)]
for i in range(max_blobs_per_tx * length)
]
return [
b_hashes[i : i + max_blobs_per_tx] for i in range(0, len(b_hashes), max_blobs_per_tx)
]
@staticmethod
def blobhash_sstore(index: int, max_blobs_per_tx: int) -> Bytecode:
"""
Return BLOBHASH sstore to the given index.
If the index is out of the valid bounds, 0x01 is written in storage, as
we later check it is overwritten by the BLOBHASH sstore.
"""
invalidity_check = Op.SSTORE(index, 0x01)
if index < 0 or index >= max_blobs_per_tx:
return invalidity_check + Op.SSTORE(index, Op.BLOBHASH(index))
return Op.SSTORE(index, Op.BLOBHASH(index))
@classmethod
def generate_blobhash_bytecode(cls, scenario_name: str, max_blobs_per_tx: int) -> Bytecode:
"""Return BLOBHASH bytecode for the given scenario."""
scenarios = {
"single_valid": sum(
(cls.blobhash_sstore(i, max_blobs_per_tx) for i in range(max_blobs_per_tx)),
Bytecode(),
),
"repeated_valid": sum(
(
sum((cls.blobhash_sstore(i, max_blobs_per_tx) for _ in range(10)), Bytecode())
for i in range(max_blobs_per_tx)
),
Bytecode(),
),
"valid_invalid": sum(
(
cls.blobhash_sstore(i, max_blobs_per_tx)
+ cls.blobhash_sstore(max_blobs_per_tx, max_blobs_per_tx)
+ cls.blobhash_sstore(i, max_blobs_per_tx)
for i in range(max_blobs_per_tx)
),
Bytecode(),
),
"varied_valid": sum(
(
cls.blobhash_sstore(i, max_blobs_per_tx)
+ cls.blobhash_sstore(i + 1, max_blobs_per_tx)
+ cls.blobhash_sstore(i, max_blobs_per_tx)
for i in range(max_blobs_per_tx - 1)
),
Bytecode(),
),
"invalid_calls": sum(
(
cls.blobhash_sstore(i, max_blobs_per_tx)
for i in range(-5, max_blobs_per_tx + 5)
),
Bytecode(),
),
}
scenario = scenarios.get(scenario_name)
if scenario is None:
raise ValueError(f"Invalid scenario: {scenario_name}")
return scenario
@pytest.mark.parametrize("blobhash_index", blobhash_index_values)
@pytest.mark.with_all_tx_types
def test_blobhash_gas_cost(
pre: Alloc,
fork: Fork,
tx_type: int,
blobhash_index: int,
state_test: StateTestFiller,
) -> None:
"""
Tests `BLOBHASH` opcode gas cost using a variety of indexes.
Asserts that the gas consumption of the `BLOBHASH` opcode is correct by
ensuring it matches `HASH_OPCODE_GAS = 3`. Includes both valid and invalid
random index sizes from the range `[0, 2**256-1]`, for tx types 2 and 3.
"""
gas_measure_code = CodeGasMeasure(
code=Op.BLOBHASH(blobhash_index),
overhead_cost=3,
extra_stack_items=1,
)
address = pre.deploy_contract(gas_measure_code)
sender = pre.fund_eoa()
tx_kwargs = {
"ty": tx_type,
"sender": sender,
"to": address,
"data": Hash(0),
"gas_limit": 500_000,
"max_fee_per_blob_gas": (fork.min_base_fee_per_blob_gas() * 10) if tx_type == 3 else None,
"blob_versioned_hashes": random_blob_hashes[0 : fork.max_blobs_per_tx()]
if tx_type == 3
else None,
}
if tx_type == 4:
signer = pre.fund_eoa(amount=0)
tx_kwargs["authorization_list"] = [
AuthorizationTuple(
signer=signer,
address=Address(0),
nonce=0,
)
]
tx = Transaction(**tx_kwargs)
post = {address: Account(storage={0: Spec.HASH_GAS_COST})}
state_test(
env=Environment(),
pre=pre,
tx=tx,
post=post,
)
@pytest.mark.parametrize(
"scenario",
[
"single_valid",
"repeated_valid",
"valid_invalid",
"varied_valid",
],
)
def test_blobhash_scenarios(
pre: Alloc,
fork: Fork,
scenario: str,
blockchain_test: BlockchainTestFiller,
max_blobs_per_tx: int,
) -> None:
"""
Tests that the `BLOBHASH` opcode returns the correct versioned hash for
various valid indexes.
Covers various scenarios with random `blob_versioned_hash` values within
the valid range `[0, 2**256-1]`.
"""
total_blocks = 5
b_hashes_list = BlobhashScenario.create_blob_hashes_list(
length=total_blocks, max_blobs_per_tx=max_blobs_per_tx
)
blobhash_calls = BlobhashScenario.generate_blobhash_bytecode(
scenario_name=scenario, max_blobs_per_tx=max_blobs_per_tx
)
sender = pre.fund_eoa()
blocks: List[Block] = []
post = {}
for i in range(total_blocks):
address = pre.deploy_contract(blobhash_calls)
blocks.append(
Block(
txs=[
Transaction(
ty=Spec.BLOB_TX_TYPE,
sender=sender,
to=address,
data=Hash(0),
gas_limit=500_000,
access_list=[],
max_fee_per_blob_gas=(fork.min_base_fee_per_blob_gas() * 10),
blob_versioned_hashes=b_hashes_list[i],
)
]
)
)
post[address] = Account(
storage={index: b_hashes_list[i][index] for index in range(max_blobs_per_tx)}
)
blockchain_test(
pre=pre,
blocks=blocks,
post=post,
)
@pytest.mark.parametrize(
"scenario",
[
"invalid_calls",
],
)
def test_blobhash_invalid_blob_index(
pre: Alloc,
fork: Fork,
blockchain_test: BlockchainTestFiller,
scenario: str,
max_blobs_per_tx: int,
) -> None:
"""
Tests that the `BLOBHASH` opcode returns a zeroed `bytes32` value for
invalid indexes.
Includes cases where the index is negative (`index < 0`) or exceeds the
maximum number of `blob_versioned_hash` values stored:
(`index >= len(tx.message.blob_versioned_hashes)`).
It confirms that the returned value is a zeroed `bytes32` for each case.
"""
total_blocks = 5
blobhash_calls = BlobhashScenario.generate_blobhash_bytecode(
scenario_name=scenario, max_blobs_per_tx=max_blobs_per_tx
)
sender = pre.fund_eoa()
blocks: List[Block] = []
post = {}
for i in range(total_blocks):
address = pre.deploy_contract(blobhash_calls)
blob_per_block = (i % max_blobs_per_tx) + 1
blobs = [random_blob_hashes[blob] for blob in range(blob_per_block)]
blocks.append(
Block(
txs=[
Transaction(
ty=Spec.BLOB_TX_TYPE,
sender=sender,
to=address,
gas_limit=500_000,
data=Hash(0),
access_list=[],
max_fee_per_blob_gas=(fork.min_base_fee_per_blob_gas() * 10),
blob_versioned_hashes=blobs,
)
]
)
)
post[address] = Account(
storage={
index: (0 if index < 0 or index >= blob_per_block else blobs[index])
for index in range(
-total_blocks,
blob_per_block + (total_blocks - (i % max_blobs_per_tx)),
)
}
)
blockchain_test(
pre=pre,
blocks=blocks,
post=post,
)
def test_blobhash_multiple_txs_in_block(
pre: Alloc,
fork: Fork,
blockchain_test: BlockchainTestFiller,
max_blobs_per_tx: int,
) -> None:
"""
Tests that the `BLOBHASH` opcode returns the appropriate values when there
is more than 1 blob tx type within a block (for tx types 2 and 3).
Scenarios involve tx type 3 followed by tx type 2 running the same code
within a block, including the opposite.
"""
blobhash_bytecode = BlobhashScenario.generate_blobhash_bytecode(
scenario_name="single_valid", max_blobs_per_tx=max_blobs_per_tx
)
addresses = [pre.deploy_contract(blobhash_bytecode) for _ in range(4)]
sender = pre.fund_eoa()
def blob_tx(address: Address, tx_type: int) -> Transaction:
return Transaction(
ty=tx_type,
sender=sender,
to=address,
data=Hash(0),
gas_limit=500_000,
access_list=[] if tx_type >= 1 else None,
max_fee_per_blob_gas=(fork.min_base_fee_per_blob_gas() * 10) if tx_type >= 3 else None,
blob_versioned_hashes=random_blob_hashes[0:max_blobs_per_tx] if tx_type >= 3 else None,
)
blocks = [
Block(
txs=[
blob_tx(address=addresses[0], tx_type=3),
blob_tx(address=addresses[0], tx_type=2),
]
),
Block(
txs=[
blob_tx(address=addresses[1], tx_type=2),
blob_tx(address=addresses[1], tx_type=3),
]
),
Block(
txs=[
blob_tx(address=addresses[2], tx_type=2),
blob_tx(address=addresses[3], tx_type=3),
],
),
]
post = {
Address(address): Account(
storage={i: random_blob_hashes[i] for i in range(max_blobs_per_tx)}
)
if address in (addresses[1], addresses[3])
else Account(storage=dict.fromkeys(range(max_blobs_per_tx), 0))
for address in addresses
}
blockchain_test(
pre=pre,
blocks=blocks,
post=post,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip4844_blobs/point_evaluation_vectors/concat_kzg_vectors_to_json.py | tests/cancun/eip4844_blobs/point_evaluation_vectors/concat_kzg_vectors_to_json.py | """
Helper script to concatenate all the point evaluation test data.yaml files in
a directory into a single JSON file for easier consumption in tests.
"""
import argparse
import json
from pathlib import Path
import yaml
def gather_yaml_data(directory: Path) -> list[dict[str, str]]: # noqa: D103
all_data = []
# Loop through each directory in the main directory
for sub_dir in sorted(directory.iterdir()):
if sub_dir.is_dir():
yaml_file_path = sub_dir / "data.yaml"
# Check if data.yaml exists in the directory
if yaml_file_path.exists():
with yaml_file_path.open("r") as yaml_file:
yaml_data = yaml.safe_load(yaml_file)
# Append the data along with the directory name
all_data.append(
{
"input": yaml_data["input"],
"output": yaml_data["output"],
"name": sub_dir.name,
}
)
return all_data
def main() -> None: # noqa: D103
parser = argparse.ArgumentParser(
description="Concatenate the data from multiple data.yaml files into one JSON file."
)
parser.add_argument(
"-i",
"--input",
type=Path,
required=True,
help="Input directory containing the YAML files.",
)
parser.add_argument(
"-o", "--output", type=Path, required=True, help="Path to the output JSON file."
)
args = parser.parse_args()
data = gather_yaml_data(args.input)
with args.output.open("w") as json_file:
json.dump(data, json_file, indent=2)
if __name__ == "__main__":
main()
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip7516_blobgasfee/test_blobgasfee_opcode.py | tests/cancun/eip7516_blobgasfee/test_blobgasfee_opcode.py | """
BLOBBASEFEE opcode tests.
Tests for [EIP-7516: BLOBBASEFEE opcode](https://eips.ethereum.org/EIPS/eip-7516).
"""
from itertools import count
import pytest
from ethereum_test_tools import (
Account,
Address,
Alloc,
Block,
BlockchainTestFiller,
Bytecode,
Environment,
StateTestFiller,
Storage,
Transaction,
)
from ethereum_test_tools import Opcodes as Op
REFERENCE_SPEC_GIT_PATH = "EIPS/eip-7516.md"
REFERENCE_SPEC_VERSION = "dcd2f4ede58a6ed908acd3cc2c198e9f605cbf3b"
BLOBBASEFEE_GAS = 2
@pytest.fixture
def call_gas() -> int:
"""Amount of gas to use when calling the callee code."""
return 0xFFFF
@pytest.fixture
def callee_code() -> Bytecode:
"""Bytecode under test, by default, only call the BLOBBASEFEE opcode."""
return Op.BLOBBASEFEE + Op.STOP
@pytest.fixture
def callee_address(pre: Alloc, callee_code: Bytecode) -> Address:
"""Address of the account containing the bytecode under test."""
return pre.deploy_contract(callee_code)
@pytest.fixture
def caller_code(
call_gas: int,
callee_address: Address,
) -> Bytecode:
"""Bytecode used to call the bytecode containing the BLOBBASEFEE opcode."""
return Op.SSTORE(Op.SELFBALANCE, Op.CALL(gas=call_gas, address=callee_address))
@pytest.fixture
def caller_pre_storage() -> Storage:
"""
Storage of the account containing the bytecode that calls the test
contract.
"""
return Storage()
@pytest.fixture
def caller_address(pre: Alloc, caller_code: Bytecode, caller_pre_storage: Storage) -> Address:
"""
Address of the account containing the bytecode that calls the test
contract.
"""
return pre.deploy_contract(caller_code)
@pytest.fixture
def tx(pre: Alloc, caller_address: Address) -> Transaction:
"""
Prepare test transaction, by setting the destination account, the
transaction value, the transaction gas limit, and the transaction data.
"""
return Transaction(
sender=pre.fund_eoa(),
gas_limit=1_000_000,
to=caller_address,
value=1,
)
@pytest.mark.parametrize(
"callee_code,call_fails",
[
pytest.param(Op.BLOBBASEFEE * 1024, False, id="no_stack_overflow"),
pytest.param(Op.BLOBBASEFEE * 1025, True, id="stack_overflow"),
],
)
@pytest.mark.valid_from("Cancun")
def test_blobbasefee_stack_overflow(
state_test: StateTestFiller,
pre: Alloc,
caller_address: Address,
callee_address: Address,
tx: Transaction,
call_fails: bool,
) -> None:
"""
Tests that the BLOBBASEFEE opcode produces a stack overflow by using it
repeatedly.
"""
post = {
caller_address: Account(
storage={1: 0 if call_fails else 1},
),
callee_address: Account(
balance=0,
),
}
state_test(
env=Environment(),
pre=pre,
tx=tx,
post=post,
)
@pytest.mark.parametrize(
"call_gas,call_fails",
[
pytest.param(BLOBBASEFEE_GAS, False, id="enough_gas"),
pytest.param(BLOBBASEFEE_GAS - 1, True, id="out_of_gas"),
],
)
@pytest.mark.valid_from("Cancun")
def test_blobbasefee_out_of_gas(
state_test: StateTestFiller,
pre: Alloc,
caller_address: Address,
callee_address: Address,
tx: Transaction,
call_fails: bool,
) -> None:
"""Tests that the BLOBBASEFEE opcode fails with insufficient gas."""
post = {
caller_address: Account(
storage={1: 0 if call_fails else 1},
),
callee_address: Account(
balance=0,
),
}
state_test(
env=Environment(),
pre=pre,
tx=tx,
post=post,
)
@pytest.mark.parametrize("caller_pre_storage", [{1: 1}], ids=[""])
@pytest.mark.valid_at_transition_to("Cancun")
def test_blobbasefee_before_fork(
state_test: StateTestFiller,
pre: Alloc,
caller_address: Address,
callee_address: Address,
tx: Transaction,
) -> None:
"""
Tests that the BLOBBASEFEE opcode results on exception when called before
the fork.
"""
# Fork happens at timestamp 15_000
timestamp = 7_500
post = {
caller_address: Account(
storage={1: 0},
),
callee_address: Account(
balance=0,
),
}
state_test(
env=Environment(
timestamp=timestamp,
),
pre=pre,
tx=tx,
post=post,
)
timestamps = [7_500, 14_999, 15_000]
@pytest.mark.parametrize(
"caller_pre_storage",
[{block_number: 0xFF for block_number, _ in enumerate(timestamps, start=1)}],
ids=[""],
)
@pytest.mark.valid_at_transition_to("Cancun")
def test_blobbasefee_during_fork(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
caller_address: Address,
callee_address: Address,
tx: Transaction,
) -> None:
"""
Tests that the BLOBBASEFEE opcode results on exception when called before
the fork and succeeds when called after the fork.
"""
code_caller_post_storage = Storage()
nonce = count(0)
blocks = []
for block_number, timestamp in enumerate(timestamps, start=1):
blocks.append(
Block(
txs=[tx.with_nonce(next(nonce))],
timestamp=timestamp,
),
)
# pre-set storage just to make sure we detect the change
code_caller_post_storage[block_number] = 0 if timestamp < 15_000 else 1
post = {
caller_address: Account(
storage=code_caller_post_storage,
),
callee_address: Account(
balance=0,
),
}
blockchain_test(
genesis_environment=Environment(),
pre=pre,
blocks=blocks,
post=post,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip7516_blobgasfee/__init__.py | tests/cancun/eip7516_blobgasfee/__init__.py | """Tests for EIP-7516: BLOBBASEFEE opcode."""
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tstorage_selfdestruct.py | tests/cancun/eip1153_tstore/test_tstorage_selfdestruct.py | """
EIP-1153 Transient Storage with selfdestruct tests.
Test cases for `TSTORE` and `TLOAD` opcode calls in reentrancy after
self-destruct, taking into account the changes in EIP-6780.
"""
from enum import unique
from typing import Dict
import pytest
from ethereum_test_tools import (
Account,
Alloc,
Bytecode,
CalldataCase,
Environment,
Hash,
Initcode,
StateTestFiller,
Switch,
Transaction,
compute_create_address,
)
from ethereum_test_tools import Opcodes as Op
from . import PytestParameterEnum
from .spec import ref_spec_1153
REFERENCE_SPEC_GIT_PATH = ref_spec_1153.git_path
REFERENCE_SPEC_VERSION = ref_spec_1153.version
pytestmark = [pytest.mark.valid_from("Cancun")]
CREATE_CODE = Op.CALLDATACOPY(size=Op.CALLDATASIZE) + Op.CREATE(size=Op.CALLDATASIZE)
def call_option(option_number: int) -> Bytecode:
"""
Return the bytecode for a call to the callee contract with the given option
number.
"""
return Op.MSTORE(value=option_number) + Op.CALL(
address=Op.SLOAD(0),
args_offset=0,
args_size=32,
ret_offset=0,
ret_size=32,
)
@unique
class SelfDestructCases(PytestParameterEnum):
"""
Transient storage test cases for different reentrancy calls which involve
the contract self-destructing.
"""
TLOAD_AFTER_SELFDESTRUCT_PRE_EXISTING_CONTRACT = {
"description": (
"Use TSTORE to store a transient value and self-destruct in a contract that was"
"deployed in a transaction prior to the one currently executing."
"Then re-enter the contract and attempt to TLOAD the transient value.",
),
"pre_existing_contract": True,
"caller_bytecode": Op.SSTORE(0, Op.CALLDATALOAD(0))
+ Op.SSTORE(1, call_option(1))
+ Op.SSTORE(2, call_option(2))
+ Op.SSTORE(3, Op.MLOAD(0)),
"callee_bytecode": Switch(
cases=[
CalldataCase(value=1, action=Op.TSTORE(0xFF, 0x100) + Op.SELFDESTRUCT(0)),
CalldataCase(value=2, action=Op.MSTORE(0, Op.TLOAD(0xFF)) + Op.RETURN(0, 32)),
],
),
"expected_storage": {
1: 0x01,
2: 0x01,
3: 0x100,
},
}
TLOAD_AFTER_SELFDESTRUCT_NEW_CONTRACT = {
"description": (
"Use TSTORE to store a transient value and self-destruct in a contract that was"
"deployed in the current transaction."
"Then re-enter the contract and attempt to TLOAD the transient value.",
),
"pre_existing_contract": False,
"caller_bytecode": Op.SSTORE(0, CREATE_CODE)
+ Op.SSTORE(1, call_option(1))
+ Op.SSTORE(2, call_option(2))
+ Op.SSTORE(3, Op.MLOAD(0)),
"callee_bytecode": Switch(
cases=[
CalldataCase(value=1, action=Op.TSTORE(0xFF, 0x100) + Op.SELFDESTRUCT(0)),
CalldataCase(value=2, action=Op.MSTORE(0, Op.TLOAD(0xFF)) + Op.RETURN(0, 32)),
],
),
"expected_storage": {
1: 0x01,
2: 0x01,
3: 0x100,
},
}
TLOAD_AFTER_INNER_SELFDESTRUCT_PRE_EXISTING_CONTRACT = {
"description": (
"Use TSTORE to store a transient value and then call for re-entry and self-destruct,"
"and use TLOAD upon return from the inner self-destructing call.",
),
"pre_existing_contract": True,
"caller_bytecode": Op.SSTORE(0, Op.CALLDATALOAD(0))
+ Op.SSTORE(1, call_option(1))
+ Op.SSTORE(2, Op.MLOAD(0)),
"callee_bytecode": Switch(
cases=[
CalldataCase(
value=1,
action=Op.TSTORE(0xFF, 0x100)
+ call_option(2)
+ Op.MSTORE(0, Op.TLOAD(0xFF))
+ Op.RETURN(0, 32),
),
CalldataCase(value=2, action=Op.SELFDESTRUCT(0)),
],
),
"expected_storage": {
1: 0x01,
2: 0x100,
},
}
TLOAD_AFTER_INNER_SELFDESTRUCT_NEW_CONTRACT = {
"description": (
"In a newly created contract, use TSTORE to store a transient value and then call "
"for re-entry and self-destruct, and use TLOAD upon return from the inner "
"self-destructing call.",
),
"pre_existing_contract": False,
"caller_bytecode": (
Op.SSTORE(0, CREATE_CODE) + Op.SSTORE(1, call_option(1)) + Op.SSTORE(2, Op.MLOAD(0))
),
"callee_bytecode": Switch(
cases=[
CalldataCase(
value=1,
action=Op.TSTORE(0xFF, 0x100)
+ Op.MSTORE(value=2)
+ Op.CALL(
address=Op.ADDRESS,
args_offset=0,
args_size=32,
ret_offset=0,
ret_size=32,
)
+ Op.MSTORE(0, Op.TLOAD(0xFF))
+ Op.RETURN(0, 32),
),
CalldataCase(value=2, action=Op.SELFDESTRUCT(0)),
],
),
"expected_storage": {
1: 0x01,
2: 0x100,
},
}
TSTORE_AFTER_SELFDESTRUCT_PRE_EXISTING_CONTRACT = {
"description": (
"Use self-destruct in a pre-existing contract and then use TSTORE upon a re-entry."
"Lastly use TLOAD on another re-entry",
),
"pre_existing_contract": True,
"caller_bytecode": Op.SSTORE(0, Op.CALLDATALOAD(0))
+ Op.SSTORE(1, call_option(1))
+ Op.SSTORE(2, call_option(2))
+ Op.SSTORE(3, call_option(3))
+ Op.SSTORE(4, Op.MLOAD(0)),
"callee_bytecode": Switch(
cases=[
CalldataCase(value=1, action=Op.SELFDESTRUCT(0)),
CalldataCase(value=2, action=Op.TSTORE(0xFF, 0x100)),
CalldataCase(value=3, action=Op.MSTORE(0, Op.TLOAD(0xFF)) + Op.RETURN(0, 32)),
],
),
"expected_storage": {
1: 0x01,
2: 0x01,
3: 0x01,
4: 0x100,
},
}
TSTORE_AFTER_SELFDESTRUCT_NEW_CONTRACT = {
"description": (
"Use self-destruct in a newly created contract and then use TSTORE upon a re-entry."
"Lastly use TLOAD on another re-entry",
),
"pre_existing_contract": False,
"caller_bytecode": Op.SSTORE(0, CREATE_CODE)
+ Op.SSTORE(1, call_option(1))
+ Op.SSTORE(2, call_option(2))
+ Op.SSTORE(3, call_option(3))
+ Op.SSTORE(4, Op.MLOAD(0)),
"callee_bytecode": Switch(
cases=[
CalldataCase(value=1, action=Op.SELFDESTRUCT(0)),
CalldataCase(value=2, action=Op.TSTORE(0xFF, 0x100)),
CalldataCase(value=3, action=Op.MSTORE(0, Op.TLOAD(0xFF)) + Op.RETURN(0, 32)),
],
),
"expected_storage": {
1: 0x01,
2: 0x01,
3: 0x01,
4: 0x100,
},
}
@SelfDestructCases.parametrize()
def test_reentrant_selfdestructing_call(
state_test: StateTestFiller,
pre: Alloc,
pre_existing_contract: bool,
caller_bytecode: Bytecode,
callee_bytecode: Bytecode,
expected_storage: Dict,
) -> None:
"""
Test transient storage in different reentrancy contexts after
selfdestructing.
"""
env = Environment()
caller_address = pre.deploy_contract(code=caller_bytecode)
data: bytes | Bytecode
if pre_existing_contract:
callee_address = pre.deploy_contract(code=callee_bytecode)
data = Hash(callee_address, left_padding=True)
else:
callee_address = compute_create_address(address=caller_address, nonce=1)
data = Initcode(deploy_code=callee_bytecode)
tx = Transaction(
sender=pre.fund_eoa(),
to=caller_address,
gas_limit=1_000_000,
data=data,
)
expected_storage[0] = callee_address
post: Dict = {caller_address: Account(storage=expected_storage)}
if pre_existing_contract:
post[callee_address] = Account(code=callee_bytecode)
else:
post[callee_address] = Account.NONEXISTENT
state_test(env=env, pre=pre, post=post, tx=tx)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_basic_tload.py | tests/cancun/eip1153_tstore/test_basic_tload.py | """
Ethereum Transient Storage EIP Tests
https://eips.ethereum.org/EIPS/eip-1153.
"""
from typing import Dict, Union
import pytest
from ethereum_test_tools import Account, Address, Alloc, Environment, StateTestFiller, Transaction
from ethereum_test_vm import Opcodes as Op
from .spec import Spec, ref_spec_1153
REFERENCE_SPEC_GIT_PATH = ref_spec_1153.git_path
REFERENCE_SPEC_VERSION = ref_spec_1153.version
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/01_tloadBeginningTxnFiller.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
def test_basic_tload_transaction_begin(
state_test: StateTestFiller,
pre: Alloc,
) -> None:
"""
Ported .json vectors.
(01_tloadBeginningTxnFiller.yml)
load arbitrary value is 0 at beginning of transaction
"""
slot_tload_at_transaction_begin_result = 1
slot_code_worked = 2
address_to = pre.deploy_contract(
code=Op.JUMPDEST()
# 01 test
+ Op.SSTORE(slot_tload_at_transaction_begin_result, Op.TLOAD(0))
+ Op.SSTORE(slot_code_worked, 1),
storage={
slot_tload_at_transaction_begin_result: 0xFF,
},
)
post = {
address_to: Account(
storage={
slot_tload_at_transaction_begin_result: 0x00,
slot_code_worked: 0x01,
}
)
}
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=b"",
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/02_tloadAfterTstoreFiller.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
def test_basic_tload_works(
state_test: StateTestFiller,
pre: Alloc,
) -> None:
"""
Ported .json vectors.
(02_tloadAfterTstoreFiller.yml)
tload from same slot after tstore returns correct value
"""
tstore_value = 88
slot_tload_after_tstore_result = 0
slot_tload_after_tstore_result_second_time = 1
slot_code_worked = 2
address_to = pre.deploy_contract(
code=Op.JUMPDEST()
# 02 test
+ Op.TSTORE(2, tstore_value)
+ Op.SSTORE(slot_tload_after_tstore_result, Op.TLOAD(2))
+ Op.SSTORE(slot_tload_after_tstore_result_second_time, Op.TLOAD(2))
+ Op.SSTORE(slot_code_worked, 1),
storage={
slot_tload_after_tstore_result: 0xFF,
slot_tload_after_tstore_result_second_time: 0xFF,
},
)
post = {
address_to: Account(
storage={
slot_tload_after_tstore_result: tstore_value,
slot_tload_after_tstore_result_second_time: tstore_value,
slot_code_worked: 0x01,
}
)
}
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=b"",
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/03_tloadAfterStoreIs0Filler.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
def test_basic_tload_other_after_tstore(
state_test: StateTestFiller,
pre: Alloc,
) -> None:
"""
Ported .json vectors.
(03_tloadAfterStoreIs0Filler.yml)
Loading any other slot after storing to a slot returns 0.
"""
tstore_value = 88
slot_tload_untouched_slot_after_tstore_result = 1
slot_code_worked = 2
address_to = pre.deploy_contract(
code=Op.JUMPDEST()
# 03 test
+ Op.TSTORE(3, tstore_value)
+ Op.SSTORE(slot_tload_untouched_slot_after_tstore_result, Op.TLOAD(0))
+ Op.SSTORE(slot_code_worked, 1),
storage={
slot_tload_untouched_slot_after_tstore_result: 0xFF,
},
)
post = {
address_to: Account(
storage={
slot_tload_untouched_slot_after_tstore_result: 0x00,
slot_code_worked: 0x01,
}
)
}
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=b"",
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/16_tloadGasFiller.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
def test_basic_tload_gasprice(
state_test: StateTestFiller,
pre: Alloc,
) -> None:
"""
Ported .json vectors.
(16_tloadGasFiller.yml)
tload costs 100 gas same as a warm sload
"""
slot_tload_nonzero_gas_price_result = 1
slot_tload_zero_gas_price_result = 2
slot_code_worked = 3
"""
N OPNAME GAS_COST TOTAL_GAS REMAINING_GAS STACK
28-1 MSTORE 2 20748 4958252 2:[4ba82f,0,]
MSTORE [0] = 4958255
29-1 PUSH1 3 20754 4958246
30-1 TLOAD 100 20757 4958243 1:[10,]
31-1 GAS 2 20857 4958143 1:[2,]
32-1 PUSH1 3 20859 4958141 2:[2,4ba7bd,]
33-1 MSTORE 6 20862 4958138 3:[2,4ba7bd,20,]
MSTORE [32] = 4958141
"""
extra_opcode_gas = 11 # mstore(3), push1(3),gas(2),push1(3)
address_to = pre.deploy_contract(
code=Op.JUMPDEST()
# 16 test
+ Op.TSTORE(16, 2)
+ Op.MSTORE(0, Op.GAS()) # hot load the memory to make the extra_opcode_gas be 11
+ Op.MSTORE(0, Op.GAS())
+ Op.TLOAD(16)
+ Op.MSTORE(32, Op.GAS())
+ Op.SSTORE(slot_tload_nonzero_gas_price_result, Op.SUB(Op.MLOAD(0), Op.MLOAD(32)))
+ Op.SSTORE(
slot_tload_nonzero_gas_price_result,
Op.SUB(Op.SLOAD(slot_tload_nonzero_gas_price_result), extra_opcode_gas),
)
+ Op.MSTORE(0, Op.GAS())
+ Op.TLOAD(5) # tload slot at 5 is 0
+ Op.MSTORE(32, Op.GAS())
+ Op.SSTORE(slot_tload_zero_gas_price_result, Op.SUB(Op.MLOAD(0), Op.MLOAD(32)))
+ Op.SSTORE(
slot_tload_zero_gas_price_result,
Op.SUB(Op.SLOAD(slot_tload_zero_gas_price_result), extra_opcode_gas),
)
+ Op.SSTORE(slot_code_worked, 1),
storage={
slot_tload_nonzero_gas_price_result: 0xFF,
slot_tload_zero_gas_price_result: 0xFF,
},
)
post = {
address_to: Account(
storage={
slot_tload_nonzero_gas_price_result: Spec.TLOAD_GAS_COST,
slot_tload_zero_gas_price_result: Spec.TLOAD_GAS_COST,
slot_code_worked: 0x01,
}
)
}
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=b"",
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/18_tloadAfterStoreFiller.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
def test_basic_tload_after_store(
state_test: StateTestFiller,
pre: Alloc,
) -> None:
"""
Ported .json vectors.
(18_tloadAfterStoreFiller.yml)
tload from same slot after store returns 0
"""
slot_tload_from_sstore_result = 1
slot_code_worked = 2
address_to = pre.deploy_contract(
code=Op.JUMPDEST()
# 18 test
+ Op.SSTORE(slot_tload_from_sstore_result, 22)
+ Op.SSTORE(slot_tload_from_sstore_result, Op.TLOAD(slot_tload_from_sstore_result))
+ Op.SSTORE(slot_code_worked, 1),
storage={
slot_tload_from_sstore_result: 0xFF,
},
)
post: Dict[Address, Union[Account, object]] = {}
post[address_to] = Account(
storage={
slot_tload_from_sstore_result: 0x00,
slot_code_worked: 0x01,
}
)
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=b"",
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tstore_reentrancy.py | tests/cancun/eip1153_tstore/test_tstore_reentrancy.py | """EIP-1153 Transient Storage tests."""
from enum import Enum
import pytest
from ethereum_test_tools import (
Account,
Address,
Alloc,
Case,
Environment,
Hash,
StateTestFiller,
Switch,
Transaction,
)
from ethereum_test_vm import Bytecode
from ethereum_test_vm import Macros as Om
from ethereum_test_vm import Opcodes as Op
REFERENCE_SPEC_GIT_PATH = "EIPS/eip-1153.md"
REFERENCE_SPEC_VERSION = "1eb863b534a5a3e19e9c196ab2a7f3db4bb9da17"
class CallDestType(Enum):
"""Call dest type."""
REENTRANCY = 1
EXTERNAL_CALL = 2
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/06_tstoreInReentrancyCallFiller.yml",
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/07_tloadAfterReentrancyStoreFiller.yml",
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/08_revertUndoesTransientStoreFiller.yml",
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/09_revertUndoesAllFiller.yml",
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/11_tstoreDelegateCallFiller.yml",
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/13_tloadStaticCallFiller.yml",
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/20_oogUndoesTransientStoreInCallFiller.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
@pytest.mark.parametrize("call_type", [Op.CALL, Op.CALLCODE, Op.DELEGATECALL, Op.STATICCALL])
@pytest.mark.parametrize("call_return", [Op.RETURN, Op.REVERT, Om.OOG])
@pytest.mark.parametrize("call_dest_type", [CallDestType.REENTRANCY, CallDestType.EXTERNAL_CALL])
def test_tstore_reentrancy(
state_test: StateTestFiller,
pre: Alloc,
call_type: Op,
call_return: Op,
call_dest_type: CallDestType,
) -> None:
"""
Ported .json vectors.
(06_tstoreInReentrancyCallFiller.yml)
Reentrant calls access the same transient storage
(07_tloadAfterReentrancyStoreFiller.yml)
Successfully returned calls do not revert transient storage writes
(08_revertUndoesTransientStoreFiller.yml)
Revert undoes the transient storage writes from a call.
(09_revertUndoesAllFiller.yml)
Revert undoes all the transient storage writes to the same key
from the failed call.
(11_tstoreDelegateCallFiller.yml)
delegatecall manipulates transient storage in the context of
the current address.
(13_tloadStaticCallFiller.yml)
Transient storage cannot be manipulated in a static context, tstore reverts
(20_oogUndoesTransientStoreInCallFiller.yml)
Out of gas undoes the transient storage writes from a call.
"""
tload_value_set_before_call = 80
tload_value_set_in_call = 90
# Storage cells
slot_tload_before_call = 0
slot_tload_in_subcall_result = 1
slot_tload_after_call = 2
slot_subcall_worked = 3
slot_tload_1_after_call = 4
slot_tstore_overwrite = 5
slot_code_worked = 6
# Function names
do_tstore = 1
do_reenter = 2
call_dest_address: Bytecode | Address
call_dest_address = Op.ADDRESS()
def make_call(call_type: Op) -> Bytecode:
if call_type == Op.DELEGATECALL or call_type == Op.STATICCALL:
return call_type(Op.GAS(), call_dest_address, 0, 32, 32, 32)
else:
return call_type(Op.GAS(), call_dest_address, 0, 0, 32, 32, 32)
subcall_code = (
Op.TSTORE(0, 89)
+ Op.TSTORE(0, tload_value_set_in_call)
+ Op.TSTORE(1, 11)
+ Op.TSTORE(1, 12)
+ Op.MSTORE(0, Op.TLOAD(0))
+ call_return(0, 32)
)
address_code = pre.deploy_contract(
balance=0,
code=subcall_code,
storage={},
)
if call_dest_type == CallDestType.EXTERNAL_CALL:
call_dest_address = address_code
address_to = pre.deploy_contract(
balance=1_000_000_000_000_000_000,
code=Switch(
cases=[
Case(
condition=Op.EQ(Op.CALLDATALOAD(0), do_tstore),
action=subcall_code,
),
Case(
condition=Op.EQ(Op.CALLDATALOAD(0), do_reenter),
action=Op.TSTORE(0, tload_value_set_before_call)
+ Op.SSTORE(slot_tload_before_call, Op.TLOAD(0))
+ Op.MSTORE(0, do_tstore)
+ Op.MSTORE(32, 0xFF)
+ Op.SSTORE(slot_subcall_worked, make_call(call_type))
+ Op.SSTORE(slot_tload_in_subcall_result, Op.MLOAD(32))
+ Op.SSTORE(slot_tload_after_call, Op.TLOAD(0))
+ Op.SSTORE(slot_tload_1_after_call, Op.TLOAD(1))
+ Op.TSTORE(0, 50)
+ Op.SSTORE(slot_tstore_overwrite, Op.TLOAD(0))
+ Op.SSTORE(slot_code_worked, 1),
),
],
default_action=None,
),
storage={
slot_tload_before_call: 0xFF,
slot_tload_in_subcall_result: 0xFF,
slot_tload_after_call: 0xFF,
slot_subcall_worked: 0xFF,
slot_tload_1_after_call: 0xFF,
slot_tstore_overwrite: 0xFF,
slot_code_worked: 0xFF,
},
)
on_failing_calls = call_type == Op.STATICCALL or call_return in [Op.REVERT, Om.OOG]
on_successful_delegate_or_callcode = call_type in [
Op.DELEGATECALL,
Op.CALLCODE,
] and call_return not in [Op.REVERT, Om.OOG]
if call_dest_type == CallDestType.REENTRANCY:
post = {
address_to: Account(
storage={
slot_code_worked: 1,
slot_tload_before_call: tload_value_set_before_call,
slot_tload_in_subcall_result: (
# we fail to obtain in call result if it fails
0xFF
if call_type == Op.STATICCALL or call_return == Om.OOG
else tload_value_set_in_call
),
# reentrant tstore overrides value in upper level
slot_tload_after_call: (
tload_value_set_before_call
if on_failing_calls
else tload_value_set_in_call
),
slot_tload_1_after_call: 0 if on_failing_calls else 12,
slot_tstore_overwrite: 50,
# tstore in static call not allowed
slot_subcall_worked: 0 if on_failing_calls else 1,
}
)
}
else:
post = {
address_to: Account(
storage={
slot_code_worked: 1,
slot_tload_before_call: tload_value_set_before_call,
slot_tload_in_subcall_result: (
# we fail to obtain in call result if it fails
0xFF
if call_type == Op.STATICCALL or call_return == Om.OOG
else tload_value_set_in_call
),
# external tstore overrides value in upper level only in
# delegate and callcode
slot_tload_after_call: (
tload_value_set_in_call
if on_successful_delegate_or_callcode
else tload_value_set_before_call
),
slot_tload_1_after_call: 12 if on_successful_delegate_or_callcode else 0,
slot_tstore_overwrite: 50,
# tstore in static call not allowed, reentrancy means
# external call here
slot_subcall_worked: 0 if on_failing_calls else 1,
}
)
}
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=Hash(do_reenter),
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tstorage_create_contexts.py | tests/cancun/eip1153_tstore/test_tstorage_create_contexts.py | """
Test transient storage in contract creation contexts.
"""
from enum import unique
import pytest
from ethereum_test_tools import (
Account,
Address,
Alloc,
Bytecode,
Environment,
Initcode,
StateTestFiller,
Transaction,
compute_create_address,
)
from ethereum_test_tools import Opcodes as Op
from . import CreateOpcodeParams, PytestParameterEnum
from .spec import ref_spec_1153
REFERENCE_SPEC_GIT_PATH = ref_spec_1153.git_path
REFERENCE_SPEC_VERSION = ref_spec_1153.version
pytestmark = [pytest.mark.valid_from("Cancun")]
@unique
class InitcodeTestCases(PytestParameterEnum):
"""
Defines test cases for transient storage opcode usage in contract
constructor and deployed code.
"""
ONLY_CONSTRUCTOR_CODE = {
"description": (
"Test TLOAD and TSTORE behavior in contract constructor without deployed code"
),
"constructor_code": (
# test creator's transient storage inaccessible from constructor
# code
Op.SSTORE(0, Op.TLOAD(0))
# test constructor code can use its own transient storage & creator
# storage unaffected
+ Op.TSTORE(0, 1)
+ Op.SSTORE(1, Op.TLOAD(0))
),
"deploy_code": Bytecode(),
"expected_storage": {0: 0x0000, 1: 0x0001},
}
IN_CONSTRUCTOR_AND_DEPLOYED_CODE = {
"description": "Test TLOAD and TSTORE behavior in contract constructor and deployed code",
"constructor_code": (
# test creator's transient storage inaccessible from constructor
# code
Op.SSTORE(0, Op.TLOAD(0))
),
"deploy_code": (
# test creator's transient storage inaccessible from deployed code
Op.SSTORE(1, Op.TLOAD(0))
# test deploy code can use its own transient storage & creator
# storage unaffected
+ Op.TSTORE(1, 1)
+ Op.SSTORE(2, Op.TLOAD(1))
),
"expected_storage": {0: 0x0000, 1: 0x0000, 2: 0x0001},
}
ACROSS_CONSTRUCTOR_AND_DEPLOYED_CODE_V0 = {
"description": ("Test TSTORE behavior across contract constructor and deploy code. "),
"constructor_code": (
# constructor code should be able to store its own transient
# storage
Op.TSTORE(1, 1)
),
"deploy_code": (
# test creator's transient storage inaccessible from deployed code
Op.SSTORE(0, Op.TLOAD(0))
# test deploy code can use its own transient storage stored from
# constructor code
+ Op.SSTORE(1, Op.TLOAD(1))
# test deploy code can use its own transient storage stored from
# deployed code
+ Op.TSTORE(2, 1)
+ Op.SSTORE(2, Op.TLOAD(2))
),
"expected_storage": {0: 0x0000, 1: 0x0001, 2: 0x0001},
}
ACROSS_CONSTRUCTOR_AND_DEPLOYED_CODE_V1 = {
"description": (
"Test TSTORE and TLOAD behavior across contract constructor and deploy code",
),
"constructor_code": (
# test creator's transient storage inaccessible from constructor
Op.SSTORE(0, Op.TLOAD(0))
# constructor code should be able to use its own transient storage
# / creator storage unaffected
+ Op.TSTORE(1, 1)
+ Op.SSTORE(1, Op.TLOAD(1))
),
"deploy_code": (
# test creator's transient storage inaccessible from deployed code
Op.SSTORE(2, Op.TLOAD(0))
# test deploy code can use its own transient storage stored from
# constructor code
+ Op.SSTORE(3, Op.TLOAD(1))
# test deploy code can use its own transient storage stored from
# deployed code
+ Op.TSTORE(2, 1)
+ Op.SSTORE(4, Op.TLOAD(2))
),
"expected_storage": {0: 0x0000, 1: 0x0001, 2: 0x0000, 3: 0x0001, 4: 0x0001},
}
NO_CONSTRUCTOR_CODE = {
"description": (
"Test TLOAD and TSTORE behavior in contract deployed code with no constructor code"
),
"constructor_code": Bytecode(),
"deploy_code": (
# test creator's transient storage inaccessible from deployed code
Op.SSTORE(0, Op.TLOAD(0))
# test deployed code can use its own transient storage & creator
# storage unaffected
+ Op.TSTORE(0, 1)
+ Op.SSTORE(1, Op.TLOAD(0))
),
"expected_storage": {0: 0x0000, 1: 0x0001},
}
@CreateOpcodeParams.parametrize()
@InitcodeTestCases.parametrize()
class TestTransientStorageInContractCreation:
"""
Test transient storage in contract creation contexts.
- TSTORE/TLOAD in initcode should not be able to access the creator's
transient storage.
- TSTORE/TLOAD in initcode should be able to access the created contract's
transient storage.
- TSTORE/TLOAD in creator contract should be able to use its own
transient storage.
"""
@pytest.fixture()
def create2_salt(self) -> int: # noqa: D102
return 0xDEADBEEF
@pytest.fixture()
def initcode( # noqa: D102
self,
deploy_code: Bytecode,
constructor_code: Bytecode,
) -> Initcode:
return Initcode(deploy_code=deploy_code, initcode_prefix=constructor_code)
@pytest.fixture()
def creator_contract_code( # noqa: D102
self,
opcode: Op,
create2_salt: int,
) -> Bytecode:
return (
Op.TSTORE(0, 0x0100)
+ Op.TSTORE(1, 0x0200)
+ Op.TSTORE(2, 0x0300)
+ Op.CALLDATACOPY(0, 0, Op.CALLDATASIZE)
+ Op.SSTORE(
4,
Op.CALL(
address=(
opcode(size=Op.CALLDATASIZE, salt=create2_salt)
if opcode == Op.CREATE2
else opcode(size=Op.CALLDATASIZE)
)
),
)
# Save the state of transient storage following call to storage;
# the transient storage should not have been overwritten
+ Op.SSTORE(0, Op.TLOAD(0))
+ Op.SSTORE(1, Op.TLOAD(1))
+ Op.SSTORE(2, Op.TLOAD(2))
)
@pytest.fixture()
def creator_address(self, pre: Alloc, creator_contract_code: Bytecode) -> Address:
"""Address that creates the contract with create/create2."""
return pre.deploy_contract(creator_contract_code)
@pytest.fixture()
def expected_creator_storage(self) -> dict: # noqa: D102
return {0: 0x0100, 1: 0x0200, 2: 0x0300, 4: 0x0001}
@pytest.fixture()
def created_contract_address( # noqa: D102
self, creator_address: Address, opcode: Op, create2_salt: int, initcode: Initcode
) -> Address:
return compute_create_address(
address=creator_address,
nonce=1,
salt=create2_salt,
initcode=initcode,
opcode=opcode,
)
def test_contract_creation(
self,
state_test: StateTestFiller,
pre: Alloc,
creator_address: Address,
created_contract_address: Address,
initcode: Initcode,
deploy_code: Bytecode,
expected_creator_storage: dict,
expected_storage: dict,
) -> None:
"""Test transient storage in contract creation contexts."""
sender = pre.fund_eoa()
tx = Transaction(
sender=sender,
to=creator_address,
data=initcode,
gas_limit=1_000_000,
)
post = {
creator_address: Account(
nonce=2,
storage=expected_creator_storage,
),
created_contract_address: Account(
nonce=1,
code=deploy_code,
storage=expected_storage,
),
}
state_test(
env=Environment(),
pre=pre,
post=post,
tx=tx,
)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/spec.py | tests/cancun/eip1153_tstore/spec.py | """Defines EIP-1153 specification constants and functions."""
from dataclasses import dataclass
@dataclass(frozen=True)
class ReferenceSpec:
"""Defines the reference spec version and git path."""
git_path: str
version: str
ref_spec_1153 = ReferenceSpec("EIPS/eip-1153.md", "1eb863b534a5a3e19e9c196ab2a7f3db4bb9da17")
@dataclass(frozen=True)
class Spec:
"""
Parameters from the EIP-1153 specifications as defined at
https://eips.ethereum.org/EIPS/eip-1153.
"""
TLOAD_OPCODE_BYTE = 0x5C
TSTORE_OPCODE_BYTE = 0x5D
TLOAD_GAS_COST = 100
TSTORE_GAS_COST = 100
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tload_calls.py | tests/cancun/eip1153_tstore/test_tload_calls.py | """
[EIP-1153](https://eips.ethereum.org/EIPS/eip-1153) Transient Storage tests.
"""
import pytest
from ethereum_test_tools import Account, Address, Alloc, Environment, StateTestFiller, Transaction
from ethereum_test_vm import Bytecode
from ethereum_test_vm import Opcodes as Op
REFERENCE_SPEC_GIT_PATH = "EIPS/eip-1153.md"
REFERENCE_SPEC_VERSION = "1eb863b534a5a3e19e9c196ab2a7f3db4bb9da17"
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/04_tloadAfterCallFiller.yml",
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/12_tloadDelegateCallFiller.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
@pytest.mark.parametrize("call_type", [Op.CALL, Op.CALLCODE, Op.DELEGATECALL])
def test_tload_calls(state_test: StateTestFiller, pre: Alloc, call_type: Op) -> None:
"""
Ported .json vectors.
(04_tloadAfterCallFiller.yml) Loading a slot after a call to another
contract is 0.
(12_tloadDelegateCallFiller.yml) delegatecall reads transient storage in
the context of the current address
"""
# Storage variables
slot_a_tload_after_subcall_result = 0
slot_a_subcall_result = 1
slot_b_subcall_tload_result = 2
slot_b_subcall_updated_tload_result = 3
def make_call(call_type: Op, address: Address) -> Bytecode:
if call_type == Op.DELEGATECALL or call_type == Op.STATICCALL:
return call_type(Op.GAS(), address, 0, 32, 0, 0)
else:
return call_type(Op.GAS(), address, 0, 0, 32, 0, 0)
address_call = pre.deploy_contract(
balance=1_000_000_000_000_000_000,
code=Op.JUMPDEST()
+ Op.SSTORE(slot_b_subcall_tload_result, Op.TLOAD(0))
+ Op.TSTORE(0, 20)
+ Op.SSTORE(slot_b_subcall_updated_tload_result, Op.TLOAD(0)),
storage={
slot_b_subcall_tload_result: 0xFF,
slot_b_subcall_updated_tload_result: 0xFF,
},
)
address_to = pre.deploy_contract(
balance=1_000_000_000_000_000_000,
code=Op.JUMPDEST()
+ Op.TSTORE(0, 10)
+ Op.SSTORE(slot_a_subcall_result, make_call(call_type, address_call))
+ Op.SSTORE(slot_a_tload_after_subcall_result, Op.TLOAD(0)),
storage={
slot_a_subcall_result: 0xFF,
slot_a_tload_after_subcall_result: 0xFF,
},
)
post = {
address_to: Account(
storage={
# other calls don't change context, there for tload updated in
# this account
slot_a_tload_after_subcall_result: 10 if call_type == Op.CALL else 20,
slot_a_subcall_result: 1,
# since context unchanged the subcall works as if continued
# execution
slot_b_subcall_tload_result: 0 if call_type == Op.CALL else 10,
slot_b_subcall_updated_tload_result: 0 if call_type == Op.CALL else 20,
}
),
address_call: Account(
storage={
slot_b_subcall_tload_result: 0 if call_type == Op.CALL else 0xFF,
slot_b_subcall_updated_tload_result: 20 if call_type == Op.CALL else 0xFF,
}
),
}
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=b"",
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tstorage_execution_contexts.py | tests/cancun/eip1153_tstore/test_tstorage_execution_contexts.py | """
Test EIP-1153 Transient Storage in execution contexts.
"""
from enum import EnumMeta, unique
from typing import Any, Dict, Mapping
import pytest
from ethereum_test_tools import (
Account,
Address,
Alloc,
Bytecode,
Environment,
Hash,
StateTestFiller,
Transaction,
)
from ethereum_test_tools import Opcodes as Op
from . import PytestParameterEnum
from .spec import Spec, ref_spec_1153
REFERENCE_SPEC_GIT_PATH = ref_spec_1153.git_path
REFERENCE_SPEC_VERSION = ref_spec_1153.version
pytestmark = [pytest.mark.valid_from("Cancun")]
PUSH_OPCODE_COST = 3
class DynamicCallContextTestCases(EnumMeta):
"""
Create dynamic transient storage test cases for contract sub-calls using
CALLCODE and DELEGATECALL (these opcodes share the same signatures and test
cases).
"""
def __new__(cls, name: str, bases: tuple[type, ...], classdict: Any) -> Any: # noqa: D102
for call_opcode in [Op.CALLCODE, Op.DELEGATECALL]:
contract_call = call_opcode(address=Op.CALLDATALOAD(0))
classdict[call_opcode._name_] = {
"description": (
"Caller and callee contracts share transient storage when callee is "
f"called via {call_opcode._name_}."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(4, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": (
Op.SSTORE(2, Op.TLOAD(0))
+ Op.TSTORE(1, 69)
+ Op.SSTORE(3, Op.TLOAD(1))
+ Op.STOP
),
"expected_caller_storage": {0: 1, 1: 420, 2: 420, 3: 69, 4: 69},
"expected_callee_storage": {},
}
for call_opcode in [Op.CALL, Op.CALLCODE, Op.DELEGATECALL]:
contract_call = call_opcode(address=Op.CALLDATALOAD(0))
classdict[f"{call_opcode._name_}_WITH_REVERT"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon REVERT."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE(1, 69) + Op.REVERT(0, 0),
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
contract_call = call_opcode(gas=0xFF, address=Op.CALLDATALOAD(0))
classdict[f"{call_opcode._name_}_WITH_INVALID"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon REVERT. Note: Gas passed to sub-call is capped."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE(1, 69) + Op.INVALID(),
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
contract_call = call_opcode(gas=0xFFFF, address=Op.CALLDATALOAD(0))
classdict[f"{call_opcode._name_}_WITH_STACK_OVERFLOW"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon stack overflow."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE(1, 69) + Op.PUSH0() * 1025 + Op.STOP,
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
classdict[f"{call_opcode._name_}_WITH_TSTORE_STACK_UNDERFLOW"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon stack underflow because of TSTORE parameters (1)."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE(1, unchecked=True) + Op.STOP,
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
classdict[f"{call_opcode._name_}_WITH_TSTORE_STACK_UNDERFLOW_2"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon stack underflow because of TSTORE parameters (0)."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE + Op.STOP,
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
classdict[f"{call_opcode._name_}_WITH_TLOAD_STACK_UNDERFLOW"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon stack underflow because of TLOAD parameters (0)."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TLOAD + Op.TSTORE(0, 1) + Op.STOP,
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
gas_limit = Spec.TSTORE_GAS_COST + (PUSH_OPCODE_COST * 2) - 1
contract_call = call_opcode(gas=gas_limit, address=Op.CALLDATALOAD(0))
classdict[f"{call_opcode._name_}_WITH_OUT_OF_GAS"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon out of gas during TSTORE. "
"Note: Gas passed to sub-call is capped."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE(1, 69) + Op.STOP,
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
contract_call = call_opcode(gas=0xFF, address=Op.CALLDATALOAD(0))
classdict[f"{call_opcode._name_}_WITH_OUT_OF_GAS_2"] = {
"description": (
"Transient storage usage is discarded from sub-call with "
f"{call_opcode._name_} upon out of gas after TSTORE. "
"Note: Gas passed to sub-call is capped."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.TSTORE(1, 420)
+ Op.SSTORE(0, contract_call)
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE(1, 69) + (Op.PUSH0() + Op.POP) * 512 + Op.STOP,
"expected_caller_storage": {0: 0, 1: 420, 2: 420},
"expected_callee_storage": {},
}
return super().__new__(cls, name, bases, classdict)
@unique
class CallContextTestCases(PytestParameterEnum, metaclass=DynamicCallContextTestCases):
"""Transient storage test cases for different contract subcall contexts."""
CALL = {
"description": (
"Caller and callee contracts use their own transient storage when callee "
"is called via CALL."
),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.SSTORE(0, Op.CALL(address=Op.CALLDATALOAD(0)))
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.SSTORE(2, Op.TLOAD(1))
+ Op.STOP
),
"callee_bytecode": (
Op.SSTORE(0, Op.TLOAD(0)) + Op.TSTORE(1, 69) + Op.SSTORE(1, Op.TLOAD(1)) + Op.STOP
),
"expected_caller_storage": {0: 1, 1: 420, 2: 0},
"expected_callee_storage": {0: 0, 1: 69},
}
STATICCALL_CANT_CALL_TSTORE = {
"description": ("TA STATICCALL callee can not use transient storage."),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.SSTORE(0, Op.STATICCALL(gas=0xFFFF, address=Op.CALLDATALOAD(0))) # limit gas
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.STOP
),
"callee_bytecode": Op.TSTORE(0, 69) + Op.STOP, # calling tstore fails
"expected_caller_storage": {0: 0, 1: 420},
"expected_callee_storage": {},
}
STATICCALL_CANT_CALL_TSTORE_WITH_STACK_UNDERFLOW = {
"description": ("TA STATICCALL callee can not use transient storage."),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.SSTORE(0, Op.STATICCALL(gas=0xFFFF, address=Op.CALLDATALOAD(0))) # limit gas
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.STOP
),
# calling with stack underflow still fails
"callee_bytecode": Op.TSTORE(0, unchecked=True) + Op.STOP,
"expected_caller_storage": {0: 0, 1: 420},
"expected_callee_storage": {},
}
STATICCALL_CAN_CALL_TLOAD = {
# TODO: Not a very useful test; consider removing after implementing
# ethereum/tests staticcall tests
"pytest_id": "staticcalled_context_can_call_tload",
"description": ("A STATICCALL callee can not use transient storage."),
"caller_bytecode": (
Op.TSTORE(0, 420)
+ Op.SSTORE(0, Op.STATICCALL(address=Op.CALLDATALOAD(0)))
+ Op.SSTORE(1, Op.TLOAD(0))
+ Op.STOP
),
# calling tload does not cause the call to fail
"callee_bytecode": Op.TLOAD(0) + Op.STOP,
"expected_caller_storage": {0: 1, 1: 420},
"expected_callee_storage": {},
}
def __init__(self, value: dict[str, Any]) -> None:
"""Initialize the test case with the given value."""
value = {
"env": Environment(),
"caller_bytecode": value["caller_bytecode"],
"callee_bytecode": value["callee_bytecode"],
"expected_caller_storage": value["expected_caller_storage"],
"expected_callee_storage": value["expected_callee_storage"],
} | {k: value[k] for k in value.keys() if k in self.special_keywords()}
super().__init__(value)
@pytest.fixture()
def caller_address(pre: Alloc, caller_bytecode: Bytecode) -> Address:
"""Address used to call the test bytecode on every test case."""
return pre.deploy_contract(caller_bytecode)
@pytest.fixture()
def callee_address(pre: Alloc, callee_bytecode: Bytecode) -> Address:
"""Address called by the test bytecode on every test case."""
return pre.deploy_contract(callee_bytecode)
@pytest.fixture()
def tx(pre: Alloc, caller_address: Address, callee_address: Address) -> Transaction: # noqa: D103
return Transaction(
sender=pre.fund_eoa(),
to=caller_address,
data=Hash(callee_address, left_padding=True),
gas_limit=1_000_000,
)
@pytest.fixture()
def post( # noqa: D103
caller_address: Address,
callee_address: Address,
expected_caller_storage: Dict,
expected_callee_storage: Dict,
) -> Dict:
return {
caller_address: Account(storage=expected_caller_storage),
callee_address: Account(storage=expected_callee_storage),
}
@CallContextTestCases.parametrize()
def test_subcall(
state_test: StateTestFiller,
env: Environment,
pre: Alloc,
tx: Transaction,
post: Mapping,
) -> None:
"""
Test transient storage with a subcall using the following opcodes.
- `CALL`
- `CALLCODE`
- `DELEGATECALL`
- `STATICCALL`
"""
state_test(env=env, pre=pre, post=post, tx=tx)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tload_reentrancy.py | tests/cancun/eip1153_tstore/test_tload_reentrancy.py | """
[EIP-1153](https://eips.ethereum.org/EIPS/eip-1153) Transient Storage tests.
"""
from enum import Enum
import pytest
from ethereum_test_tools import (
Account,
Address,
Alloc,
Case,
Environment,
Hash,
StateTestFiller,
Switch,
Transaction,
)
from ethereum_test_vm import Bytecode
from ethereum_test_vm import Macros as Om
from ethereum_test_vm import Opcodes as Op
REFERENCE_SPEC_GIT_PATH = "EIPS/eip-1153.md"
REFERENCE_SPEC_VERSION = "1eb863b534a5a3e19e9c196ab2a7f3db4bb9da17"
class CallDestType(Enum):
"""Call dest type."""
REENTRANCY = 1
EXTERNAL_CALL = 2
@pytest.mark.ported_from(
[
"https://github.com/ethereum/tests/blob/v13.3/src/GeneralStateTestsFiller/Cancun/stEIP1153-transientStorage/05_tloadReentrancyFiller.yml",
],
pr=["https://github.com/ethereum/execution-spec-tests/pull/440"],
)
@pytest.mark.valid_from("Cancun")
@pytest.mark.parametrize("call_type", [Op.CALL, Op.CALLCODE, Op.DELEGATECALL, Op.STATICCALL])
@pytest.mark.parametrize("call_return", [Op.RETURN, Op.REVERT, Om.OOG])
@pytest.mark.parametrize("call_dest_type", [CallDestType.REENTRANCY, CallDestType.EXTERNAL_CALL])
def test_tload_reentrancy(
state_test: StateTestFiller,
pre: Alloc,
call_type: Op,
call_return: Op,
call_dest_type: CallDestType,
) -> None:
"""
Ported .json vectors.
(05_tloadReentrancyFiller.yml) Reentrant calls access the same transient
storage
"""
tload_value = 44
empty_value = 0
# Storage variables
slot_tload_in_subcall_result = 1
slot_tload_after_subcall_result = 2
slot_subcall_worked = 3
slot_code_worked = 4
# Function names
do_load = 1
do_reenter = 2
call_dest_address: Bytecode | Address
call_dest_address = Op.ADDRESS()
def make_call(call_type: Op) -> Bytecode:
if call_type == Op.DELEGATECALL or call_type == Op.STATICCALL:
return call_type(Op.GAS(), call_dest_address, 0, 32, 32, 32)
else:
return call_type(Op.GAS(), call_dest_address, 0, 0, 32, 32, 32)
subcall_code = Op.MSTORE(0, Op.TLOAD(0)) + call_return(0, 32)
address_code = pre.deploy_contract(
balance=0,
code=subcall_code,
storage={},
)
if call_dest_type == CallDestType.EXTERNAL_CALL:
call_dest_address = address_code
address_to = pre.deploy_contract(
balance=1_000_000_000_000_000_000,
code=Switch(
cases=[
Case(
condition=Op.EQ(Op.CALLDATALOAD(0), do_load),
action=subcall_code,
),
Case(
condition=Op.EQ(Op.CALLDATALOAD(0), do_reenter),
action=Op.TSTORE(0, tload_value)
+ Op.MSTORE(0, do_load)
+ Op.MSTORE(32, 0xFF)
+ Op.SSTORE(slot_subcall_worked, make_call(call_type))
+ Op.SSTORE(slot_tload_in_subcall_result, Op.MLOAD(32))
+ Op.SSTORE(slot_tload_after_subcall_result, Op.TLOAD(0))
+ Op.SSTORE(slot_code_worked, 1),
),
],
default_action=None,
),
storage={
slot_tload_in_subcall_result: 0xFF,
slot_tload_after_subcall_result: 0xFF,
slot_subcall_worked: 0xFF,
slot_code_worked: 0xFF,
},
)
if call_dest_type == CallDestType.REENTRANCY:
post = {
address_to: Account(
storage={
slot_code_worked: 1,
# if call OOG, we fail to obtain the result
slot_tload_in_subcall_result: 0xFF if call_return == Om.OOG else tload_value,
slot_tload_after_subcall_result: tload_value,
slot_subcall_worked: (
0 if call_return == Op.REVERT or call_return == Om.OOG else 1
),
}
)
}
else:
post = {
address_to: Account(
storage={
slot_code_worked: 1,
slot_tload_in_subcall_result: (
0xFF # if call OOG, we fail to obtain the result
if call_return == Om.OOG
# else delegate and callcode are working in the same
# context so tload works
else (
tload_value
if call_type == Op.DELEGATECALL or call_type == Op.CALLCODE
else empty_value
)
),
# no subcall errors can change the tload result
slot_tload_after_subcall_result: 44,
slot_subcall_worked: (
0 if call_return == Op.REVERT or call_return == Om.OOG else 1
),
}
)
}
tx = Transaction(
sender=pre.fund_eoa(7_000_000_000_000_000_000),
to=address_to,
gas_price=10,
data=Hash(do_reenter),
gas_limit=5000000,
value=0,
)
state_test(env=Environment(), pre=pre, post=post, tx=tx)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/__init__.py | tests/cancun/eip1153_tstore/__init__.py | """
[EIP-1153](https://eips.ethereum.org/EIPS/eip-1153) Tests.
"""
from enum import Enum, unique
from pprint import pprint
from typing import Any, List
import pytest
from ethereum_test_tools import Opcodes as Op
class PytestParameterEnum(Enum):
"""
Helper class for defining Pytest parameters used in test cases.
This class helps define enum `value`s as `pytest.param` objects that then
can be used to create a parametrize decorator that can be applied to tests,
for example,
```python
@TStorageCallContextTestCases.parametrize()
def test_function(test_value):
pass
```
Classes which derive from this class must define each test case as a
different enum field with a dictionary as value.
The dictionary must contain:
i. A `description` key with a string value describing the test case.
ii. (Optional) A `pytest_marks` key with a single mark or list of pytest
marks to apply to the test case. For example:
```
pytest_marks=pytest.mark.xfail
```
or
```
pytest_marks=[pytest.mark.xfail, pytest.mark.skipif]
```
iii. (Optional) An `id` key with the name of the test.
The rest of the keys in the dictionary are the parameters of the test case.
The test case ID is set as the enum name converted to lowercase.
"""
def __init__(self, value: dict[str, Any]) -> None:
"""Initialize the enum value."""
assert isinstance(value, dict)
assert "description" in value
self._value_ = value
def param(self, names: List[str]) -> Any:
"""Return the `pytest.param` value for this test case."""
value = self._value_
if "pytest_marks" in value:
marks = {"marks": value["pytest_marks"]}
else:
marks = {}
if "pytest_id" in value:
pytest_id = value["pytest_id"]
else:
pytest_id = self.name.lower()
return pytest.param(*[value[name] for name in names], id=pytest_id, **marks)
@classmethod
def special_keywords(cls) -> List[str]:
"""
Return the special dictionary keywords that are not test parameters.
"""
return ["description", "pytest_marks", "pytest_id"]
def names(self) -> List[str]:
"""
Return the names of all the parameters included in the enum value dict.
"""
return sorted([k for k in self._value_.keys() if k not in self.special_keywords()])
@property
def description(self) -> str:
"""Returns the description of this test case."""
return self._value_["description"]
@classmethod
def parametrize(cls) -> Any:
"""Return decorator to parametrize a test with this enum."""
names = None
for test_case_names in [test_case.names() for test_case in cls]:
if names is None:
names = test_case_names
else:
if set(names) != set(test_case_names):
pprint(names)
pprint(test_case_names)
assert set(names) == set(test_case_names), (
"All test cases must have the same parameter names."
)
assert names is not None, "Enum must have at least one test case."
return pytest.mark.parametrize(names, [test_case.param(names) for test_case in cls])
@unique
class CreateOpcodeParams(PytestParameterEnum):
"""
Helper enum class to parametrize tests with different contract creation
opcodes: CREATE and CREATE2.
"""
CREATE = {"opcode": Op.CREATE, "description": "Test CREATE opcode."}
CREATE2 = {"opcode": Op.CREATE2, "description": "Test CREATE2 opcode."}
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tstorage_clear_after_tx.py | tests/cancun/eip1153_tstore/test_tstorage_clear_after_tx.py | """EIP-1153 Transient Storage tests."""
from typing import Optional
import pytest
from ethereum_test_tools import (
Account,
Alloc,
Block,
BlockchainTestFiller,
Environment,
EVMCodeType,
Initcode,
Transaction,
)
from ethereum_test_types.eof.v1 import Container
from ethereum_test_vm import Opcodes as Op
from .spec import ref_spec_1153
REFERENCE_SPEC_GIT_PATH = ref_spec_1153.git_path
REFERENCE_SPEC_VERSION = ref_spec_1153.version
@pytest.mark.valid_from("Cancun")
@pytest.mark.with_all_evm_code_types
def test_tstore_clear_after_deployment_tx(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
evm_code_type: EVMCodeType,
) -> None:
"""
First creates a contract, which TSTOREs a value 1 in slot 1. After creating
the contract, a new tx will call this contract, storing TLOAD(1) into slot
1. The transient storage should be cleared after creating the contract (at
tx-level), so the storage should stay empty.
"""
env = Environment()
init_code = Op.TSTORE(1, 1)
deploy_code = Op.SSTORE(1, Op.TLOAD(1))
code: Optional[Container | Initcode] = None
if evm_code_type == EVMCodeType.EOF_V1:
code = Container.Init(
deploy_container=Container.Code(deploy_code + Op.STOP), initcode_prefix=init_code
)
else:
code = Initcode(deploy_code=deploy_code, initcode_prefix=init_code)
sender = pre.fund_eoa()
deployment_tx = Transaction(
gas_limit=100000,
data=code,
to=None,
sender=sender,
)
address = deployment_tx.created_contract
invoke_contract_tx = Transaction(gas_limit=100000, to=address, sender=sender)
txs = [deployment_tx, invoke_contract_tx]
post = {
address: Account(storage={0x01: 0x00}),
}
blockchain_test(genesis_environment=env, pre=pre, post=post, blocks=[Block(txs=txs)])
@pytest.mark.valid_from("Cancun")
@pytest.mark.with_all_evm_code_types
def test_tstore_clear_after_tx(
blockchain_test: BlockchainTestFiller,
pre: Alloc,
) -> None:
"""
First SSTOREs the TLOAD value of key 1 in slot 1. Then, it TSTOREs 1 in
slot 1. The second tx will re-call the contract. The storage should stay
empty, because the transient storage is cleared after the transaction.
"""
env = Environment()
code = Op.SSTORE(1, Op.TLOAD(1)) + Op.TSTORE(1, 1)
account = pre.deploy_contract(code)
sender = pre.fund_eoa()
poke_tstore_tx = Transaction(
gas_limit=100000,
to=account,
sender=sender,
)
re_poke_tstore_tx = Transaction(gas_limit=100000, to=account, sender=sender)
txs = [poke_tstore_tx, re_poke_tstore_tx]
post = {
account: Account(storage={0x01: 0x00}),
}
blockchain_test(genesis_environment=env, pre=pre, post=post, blocks=[Block(txs=txs)])
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tstorage.py | tests/cancun/eip1153_tstore/test_tstorage.py | """
EIP-1153 Transient Storage opcode tests.
Ports and extends some tests from
[ethereum/tests/src/EIPTestsFiller/StateTests/stEIP1153-transientStorage/](https://github.com/ethereum/tests/blob/9b00b68593f5869eb51a6659e1cc983e875e616b/src/EIPTestsFiller/StateTests/stEIP1153-transientStorage).
"""
from enum import unique
import pytest
from ethereum_test_forks import Fork
from ethereum_test_tools import (
Account,
Alloc,
Bytecode,
CodeGasMeasure,
Environment,
StateTestFiller,
Transaction,
)
from ethereum_test_tools import Opcodes as Op
from . import PytestParameterEnum
from .spec import Spec, ref_spec_1153
REFERENCE_SPEC_GIT_PATH = ref_spec_1153.git_path
REFERENCE_SPEC_VERSION = ref_spec_1153.version
pytestmark = [pytest.mark.valid_from("Cancun")]
code_address = 0x100
def test_transient_storage_unset_values(state_test: StateTestFiller, pre: Alloc) -> None:
"""
Test that tload returns zero for unset values. Loading an arbitrary value
is 0 at beginning of transaction: TLOAD(x) is 0.
Based on
[ethereum/tests/.../01_tloadBeginningTxnFiller.yml]
(https://github.com/ethereum/tests/blob/
9b00b68593f5869eb51a6659e1cc983e875e616b/src/EIPTestsFiller/StateTests/
stEIP1153-transientStorage/01_tloadBeginningTxnFiller.yml)",
"""
env = Environment()
slots_under_test = [0, 1, 2, 2**128, 2**256 - 1]
code = sum(Op.SSTORE(slot, Op.TLOAD(slot)) for slot in slots_under_test)
code_address = pre.deploy_contract(
code=code, # type: ignore
storage=dict.fromkeys(slots_under_test, 1),
)
tx = Transaction(
sender=pre.fund_eoa(),
to=code_address,
gas_limit=1_000_000,
)
post = {code_address: Account(storage=dict.fromkeys(slots_under_test, 0))}
state_test(
env=env,
pre=pre,
post=post,
tx=tx,
)
def test_tload_after_tstore(state_test: StateTestFiller, pre: Alloc) -> None:
"""
Loading after storing returns the stored value: TSTORE(x, y), TLOAD(x)
returns y.
Based on
[ethereum/tests/.../02_tloadAfterTstoreFiller.yml]
(https://github.com/ethereum/tests/blob/
9b00b68593f5869eb51a6659e1cc983e875e616b/src/EIPTestsFiller/StateTests/
stEIP1153-transientStorage/02_tloadAfterTstoreFiller.yml)",
"""
env = Environment()
slots_under_test = [0, 1, 2, 2**128, 2**256 - 1]
code = sum(
Op.TSTORE(slot, slot) + Op.SSTORE(slot, Op.TLOAD(slot)) for slot in slots_under_test
)
code_address = pre.deploy_contract(
code=code, # type: ignore
storage=dict.fromkeys(slots_under_test, 0xFF),
)
tx = Transaction(
sender=pre.fund_eoa(),
to=code_address,
gas_limit=1_000_000,
)
post = {code_address: Account(storage={slot: slot for slot in slots_under_test})}
state_test(
env=env,
pre=pre,
post=post,
tx=tx,
)
def test_tload_after_sstore(state_test: StateTestFiller, pre: Alloc) -> None:
"""
Loading after storing returns the stored value: TSTORE(x, y), TLOAD(x)
returns y.
Based on
[ethereum/tests/.../18_tloadAfterStoreFiller.yml]
(https://github.com/ethereum/tests/blob/
9b00b68593f5869eb51a6659e1cc983e875e616b/src/
EIPTestsFiller/StateTests/stEIP1153-transientStorage/
18_tloadAfterStoreFiller.yml)",
"""
env = Environment()
slots_under_test = [1, 3, 2**128, 2**256 - 1]
code = sum(
Op.SSTORE(slot - 1, 0xFF) + Op.SSTORE(slot, Op.TLOAD(slot - 1))
for slot in slots_under_test
)
code_address = pre.deploy_contract(
code=code, # type: ignore
storage=dict.fromkeys(slots_under_test, 1),
)
tx = Transaction(
sender=pre.fund_eoa(),
to=code_address,
gas_limit=1_000_000,
)
post = {
code_address: Account(
code=code,
storage={slot - 1: 0xFF for slot in slots_under_test}
| dict.fromkeys(slots_under_test, 0),
)
}
state_test(
env=env,
pre=pre,
post=post,
tx=tx,
)
def test_tload_after_tstore_is_zero(state_test: StateTestFiller, pre: Alloc) -> None:
"""
Test that tload returns zero after tstore is called with zero.
Based on [ethereum/tests/.../03_tloadAfterStoreIs0Filler.yml]
(https://github.com/ethereum/tests/blob/
9b00b68593f5869eb51a6659e1cc983e875e616b/src/
EIPTestsFiller/StateTests/
stEIP1153-transientStorage/03_tloadAfterStoreIs0Filler.yml)",
"""
env = Environment()
slots_to_write = [1, 4, 2**128, 2**256 - 2]
slots_to_read = [slot - 1 for slot in slots_to_write] + [slot + 1 for slot in slots_to_write]
assert set.intersection(set(slots_to_write), set(slots_to_read)) == set()
code = sum(Op.TSTORE(slot, 1234) for slot in slots_to_write) + sum(
Op.SSTORE(slot, Op.TLOAD(slot)) for slot in slots_to_read
)
code_address = pre.deploy_contract(
code=code, # type: ignore
storage=dict.fromkeys(slots_to_write + slots_to_read, 0xFFFF),
)
tx = Transaction(
sender=pre.fund_eoa(),
to=code_address,
gas_limit=1_000_000,
)
post = {
code_address: Account(
storage=dict.fromkeys(slots_to_read, 0) | dict.fromkeys(slots_to_write, 0xFFFF)
)
}
state_test(
env=env,
pre=pre,
post=post,
tx=tx,
)
@unique
class GasMeasureTestCases(PytestParameterEnum):
"""Test cases for gas measurement."""
TLOAD = {
"description": "Test that tload() of an empty slot consumes the expected gas.",
"bytecode": Op.TLOAD(10),
"overhead_cost": 3, # 1 x PUSH1
"extra_stack_items": 1,
"expected_gas": Spec.TLOAD_GAS_COST,
}
TSTORE_TLOAD = {
"description": "Test that tload() of a used slot consumes the expected gas.",
"bytecode": Op.TSTORE(10, 10) + Op.TLOAD(10),
"overhead_cost": 3 * 3, # 3 x PUSH1
"extra_stack_items": 1,
"expected_gas": Spec.TSTORE_GAS_COST + Spec.TLOAD_GAS_COST,
}
TSTORE_COLD = {
"description": "Test that tstore() of a previously unused slot consumes the expected gas.",
"bytecode": Op.TSTORE(10, 10),
"overhead_cost": 2 * 3, # 2 x PUSH1
"extra_stack_items": 0,
"expected_gas": Spec.TSTORE_GAS_COST,
}
TSTORE_WARM = {
"description": "Test that tstore() of a previously used slot consumes the expected gas.",
"bytecode": Op.TSTORE(10, 10) + Op.TSTORE(10, 11),
"overhead_cost": 4 * 3, # 4 x PUSH1
"extra_stack_items": 0,
"expected_gas": 2 * Spec.TSTORE_GAS_COST,
}
@GasMeasureTestCases.parametrize()
def test_gas_usage(
state_test: StateTestFiller,
pre: Alloc,
bytecode: Bytecode,
expected_gas: int,
overhead_cost: int,
extra_stack_items: int,
) -> None:
"""Test that tstore and tload consume the expected gas."""
gas_measure_bytecode = CodeGasMeasure(
code=bytecode, overhead_cost=overhead_cost, extra_stack_items=extra_stack_items
)
env = Environment()
code_address = pre.deploy_contract(code=gas_measure_bytecode)
tx = Transaction(
sender=pre.fund_eoa(),
to=code_address,
gas_limit=1_000_000,
)
post = {
code_address: Account(code=gas_measure_bytecode, storage={0: expected_gas}),
}
state_test(env=env, pre=pre, tx=tx, post=post)
@unique
class LoopRunUntilOutOfGasCases(PytestParameterEnum):
"""Test cases to run until out of gas."""
TSTORE = {
"description": "Run tstore in loop until out of gas",
"repeat_bytecode": Op.TSTORE(Op.GAS, Op.GAS),
"bytecode_repeat_times": 1000,
}
TSTORE_WIDE_ADDRESS_SPACE = {
"description": "Run tstore in loop until out of gas, using a wide address space",
"repeat_bytecode": Op.TSTORE(Op.ADD(Op.SHL(Op.PC, 1), Op.GAS), Op.GAS),
"bytecode_repeat_times": 32,
}
TSTORE_TLOAD = {
"description": "Run tstore and tload in loop until out of gas",
"repeat_bytecode": Op.GAS + Op.DUP1 + Op.DUP1 + Op.TSTORE + Op.TLOAD + Op.POP,
"bytecode_repeat_times": 1000,
}
def max_tx_gas_limit(fork: Fork) -> list[int]:
"""Return the maximum transaction gas limit for the given fork."""
tx_limit = fork.transaction_gas_limit_cap()
return [tx_limit if tx_limit is not None else Environment().gas_limit]
@LoopRunUntilOutOfGasCases.parametrize()
@pytest.mark.slow()
@pytest.mark.parametrize_by_fork("tx_gas_limit", max_tx_gas_limit)
def test_run_until_out_of_gas(
state_test: StateTestFiller,
pre: Alloc,
tx_gas_limit: int,
repeat_bytecode: Bytecode,
bytecode_repeat_times: int,
) -> None:
"""Use TSTORE over and over to different keys until we run out of gas."""
bytecode = Op.JUMPDEST + repeat_bytecode * bytecode_repeat_times + Op.JUMP(Op.PUSH0)
code_address = pre.deploy_contract(code=bytecode)
tx = Transaction(sender=pre.fund_eoa(), to=code_address, gas_limit=tx_gas_limit)
post = {
code_address: Account(code=bytecode, storage={}),
}
state_test(pre=pre, tx=tx, post=post)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
ethereum/execution-spec-tests | https://github.com/ethereum/execution-spec-tests/blob/88e9fb8f10ed89805aa3110d0a2cd5dcadc19689/tests/cancun/eip1153_tstore/test_tstorage_reentrancy_contexts.py | tests/cancun/eip1153_tstore/test_tstorage_reentrancy_contexts.py | """
Tests transient storage in reentrancy contexts.
"""
from enum import EnumMeta, unique
from typing import Any, Dict
import pytest
from ethereum_test_tools import (
Account,
Alloc,
Bytecode,
CalldataCase,
Conditional,
Environment,
Hash,
StateTestFiller,
Switch,
Transaction,
)
from ethereum_test_tools import Opcodes as Op
from . import PytestParameterEnum
from .spec import ref_spec_1153
REFERENCE_SPEC_GIT_PATH = ref_spec_1153.git_path
REFERENCE_SPEC_VERSION = ref_spec_1153.version
pytestmark = [pytest.mark.valid_from("Cancun")]
SETUP_CONDITION: Bytecode = Op.EQ(Op.CALLDATALOAD(0), 0x01)
REENTRANT_CALL: Bytecode = Op.MSTORE(0, 2) + Op.SSTORE(
0, Op.CALL(address=Op.ADDRESS, args_size=32)
)
class DynamicReentrancyTestCases(EnumMeta):
"""
Create dynamic transient storage test cases which REVERT or receive INVALID
(these opcodes should share the same behavior).
"""
def __new__(cls, name: str, bases: tuple[type, ...], classdict: Any) -> Any: # noqa: D102
for opcode in [Op.REVERT, Op.INVALID]:
if opcode == Op.REVERT:
opcode_call = Op.REVERT(0, 0)
subcall_gas = Op.GAS()
elif opcode == Op.INVALID:
opcode_call = Op.INVALID()
subcall_gas = Op.PUSH2(0xFFFF)
else:
raise ValueError(f"Unknown opcode: {opcode}.")
reentrant_call = Op.MSTORE(0, 2) + Op.SSTORE(
0, Op.CALL(gas=subcall_gas, address=Op.ADDRESS, args_size=32)
)
classdict[f"TSTORE_BEFORE_{opcode._name_}_HAS_NO_EFFECT"] = {
"description": (
f"{opcode._name_} undoes the transient storage write "
"from the failed call: "
"TSTORE(x, y), CALL(self, ...), TSTORE(x, z), "
f"{opcode._name_}, TLOAD(x) returns y.",
"Based on [ethereum/tests/.../08_revertUndoes"
"TransientStoreFiller.yml](https://github.com/ethereum/"
"tests/blob/9b00b68593f5869eb51a6659e1cc983e875e616b/src"
"/EIPTestsFiller/StateTests/stEIP1153-transientStorage/"
"08_revertUndoesTransientStoreFiller.yml)",
),
"bytecode": Conditional(
condition=SETUP_CONDITION,
# setup
if_true=(
Op.TSTORE(0xFF, 0x100)
+ Op.SSTORE(1, Op.TLOAD(0xFF))
+ reentrant_call
+ Op.SSTORE(
2, Op.TLOAD(0xFF)
) # test value not updated during reentrant call
),
# reenter
if_false=Op.TSTORE(0xFF, 0x101) + opcode_call,
),
"expected_storage": {0: 0x00, 1: 0x100, 2: 0x100},
}
classdict[f"{opcode._name_}_UNDOES_ALL"] = {
"description": (
f"{opcode._name_} undoes all the transient storage writes "
"to the same key from a failed call. "
"TSTORE(x, y), CALL(self, ...), TSTORE(x, z), "
f"TSTORE(x, z + 1) {opcode._name_}, TLOAD(x) returns y."
"",
"Based on "
"[ethereum/tests/.../09_revertUndoesAllFiller.yml](https://github.com/ethereum/tests/blob/9b00b68593f5869eb51a6659e1cc983e875e616b/src/EIPTestsFiller/StateTests/stEIP1153-transientStorage/09_revertUndoesAllFiller.yml).",
),
"bytecode": Conditional(
condition=SETUP_CONDITION,
# setup
if_true=(
Op.TSTORE(0xFE, 0x100)
+ Op.TSTORE(0xFF, 0x101)
+ reentrant_call
+ Op.SSTORE(
1, Op.TLOAD(0xFE)
) # test value not updated during reentrant call
+ Op.SSTORE(
2, Op.TLOAD(0xFF)
) # test value not updated during reentrant call
),
# reenter
if_false=(
# store twice and revert/invalid; none of the stores
# should take effect
Op.TSTORE(0xFE, 0x201)
+ Op.TSTORE(0xFE, 0x202)
+ Op.TSTORE(0xFF, 0x201)
+ Op.TSTORE(0xFF, 0x202)
+ opcode_call
),
),
"expected_storage": {0: 0x00, 1: 0x100, 2: 0x101},
}
if opcode == Op.REVERT:
opcode_call = Op.REVERT(0, 32)
second_call_return_value = 1
elif opcode == Op.INVALID:
opcode_call = Op.INVALID()
second_call_return_value = 0
else:
raise ValueError(f"Unknown opcode: {opcode}.")
classdict[f"{opcode._name_}_UNDOES_TSTORAGE_AFTER_SUCCESSFUL_CALL"] = {
"description": (
f"{opcode._name_} undoes transient storage writes from "
"inner calls that successfully returned. "
"TSTORE(x, y), CALL(self, ...), CALL(self, ...), "
f"TSTORE(x, y + 1), RETURN, {opcode._name_}, TLOAD(x) "
"returns y.",
"Based on [ethereum/tests/.../"
"10_revertUndoesStoreAfterReturnFiller.yml]"
"(https://github.com/ethereum/tests/blob/"
"9b00b68593f5869eb51a6659e1cc983e875e616b/src/"
"EIPTestsFiller/StateTests/stEIP1153-transientStorage/"
"10_revertUndoesStoreAfterReturnFiller.yml).",
),
"bytecode": Switch(
default_action=( # setup; make first reentrant sub-call
Op.TSTORE(0xFF, 0x100)
+ Op.SSTORE(2, Op.TLOAD(0xFF))
+ Op.MSTORE(0, 2)
+ Op.SSTORE(
0,
Op.CALL(
gas=subcall_gas,
address=Op.ADDRESS,
args_size=32,
ret_offset=32,
ret_size=32,
),
)
+ Op.SSTORE(1, Op.MLOAD(32)) # should be 1 (successful
# call)
+ Op.SSTORE(3, Op.TLOAD(0xFF))
),
cases=[
# the first, reentrant call, which reverts/receives
# invalid
CalldataCase(
value=2,
action=(
Op.MSTORE(0, 3)
+ Op.MSTORE(0, Op.CALL(address=Op.ADDRESS, args_size=32))
+ opcode_call
),
),
# the second, reentrant call, which returns
# successfully
CalldataCase(
value=3,
action=Op.TSTORE(0xFF, 0x101),
),
],
),
"expected_storage": {0: 0x00, 1: second_call_return_value, 2: 0x100, 3: 0x100},
}
return super().__new__(cls, name, bases, classdict)
@unique
class ReentrancyTestCases(PytestParameterEnum, metaclass=DynamicReentrancyTestCases):
"""Transient storage test cases for different reentrancy call contexts."""
TSTORE_IN_REENTRANT_CALL = {
"description": (
"Reentrant calls access the same transient storage: "
"TSTORE(x, y), CALL(self, ...), TLOAD(x) returns y."
""
"Based on [ethereum/tests/.../05_tloadReentrancyFiller.yml]"
"(https://github.com/ethereum/tests/tree/"
"9b00b68593f5869eb51a6659e1cc983e875e616b/src/"
"EIPTestsFiller/StateTests/stEIP1153-transientStorage).",
),
"bytecode": Conditional(
condition=SETUP_CONDITION,
# setup
if_true=(Op.TSTORE(0, 0x100) + REENTRANT_CALL + Op.SSTORE(2, Op.TLOAD(0))),
# reenter
if_false=Op.SSTORE(1, Op.TLOAD(0)),
),
"expected_storage": {0: 0x01, 1: 0x100, 2: 0x100},
}
TLOAD_AFTER_REENTRANT_TSTORE = {
"description": (
"Successfully returned calls do not revert transient "
"storage writes: "
"TSTORE(x, y), CALL(self, ...), TSTORE(x, z), RETURN, TLOAD(x) "
"returns z."
"Based on [ethereum/tests/.../"
"07_tloadAfterReentrancyStoreFiller.yml](https://github.com/"
"ethereum/tests/blob/"
"9b00b68593f5869eb51a6659e1cc983e875e616b/src/"
"EIPTestsFiller/StateTests/stEIP1153-transientStorage/"
"07_tloadAfterReentrancyStoreFiller.yml).",
),
"bytecode": Conditional(
condition=SETUP_CONDITION,
# setup
if_true=(
Op.TSTORE(0xFF, 0x100)
+ Op.SSTORE(1, Op.TLOAD(0xFF))
+ REENTRANT_CALL
+ Op.SSTORE(2, Op.TLOAD(0xFF)) # test value updated during
# reentrant call
),
# reenter
if_false=Op.TSTORE(0xFF, 0x101),
),
"expected_storage": {0: 0x01, 1: 0x100, 2: 0x101},
}
MANIPULATE_IN_REENTRANT_CALL = {
"description": (
"Reentrant calls can manipulate the same transient storage: "
"TSTORE(x, y), CALL(self, ...), TSTORE(x, z), TLOAD(x) returns z."
""
"Based on [ethereum/tests/.../06_tstoreInReentrancyCallFiller.yml]"
"(https://github.com/ethereum/tests/blob/"
"9b00b68593f5869eb51a6659e1cc983e875e616b/src/"
"EIPTestsFiller/StateTests/stEIP1153-transientStorage/"
"06_tstoreInReentrancyCallFiller.yml).",
),
"bytecode": Conditional(
condition=SETUP_CONDITION,
# setup
if_true=(
Op.TSTORE(0xFF, 0x100)
+ Op.SSTORE(1, Op.TLOAD(0xFF))
+ REENTRANT_CALL
+ Op.SSTORE(3, Op.TLOAD(0xFF)) # test value updated during
# reentrant call
),
# reenter
if_false=Op.TSTORE(0xFF, 0x101) + Op.SSTORE(2, Op.TLOAD(0xFF)),
),
"expected_storage": {0: 0x01, 1: 0x100, 2: 0x101, 3: 0x101},
}
TSTORE_IN_CALL_THEN_TLOAD_RETURN_IN_STATICCALL = {
"description": (
"A reentrant call followed by a reentrant subcall can "
"call tload correctly: "
"TSTORE(x, y), CALL(self, ...), STATICCALL(self, ...), "
"TLOAD(x), RETURN returns y."
"Based on [ethereum/tests/.../"
"10_revertUndoesStoreAfterReturnFiller.yml]"
"(https://github.com/ethereum/tests/blob/"
"9b00b68593f5869eb51a6659e1cc983e875e616b/src/"
"EIPTestsFiller/StateTests/stEIP1153-transientStorage/"
"10_revertUndoesStoreAfterReturnFiller.yml).",
),
"bytecode": Switch(
default_action=( # setup; make first reentrant sub-call
Op.TSTORE(0xFF, 0x100)
+ Op.SSTORE(2, Op.TLOAD(0xFF))
+ Op.MSTORE(0, 2)
+ Op.SSTORE(0, Op.CALL(address=Op.ADDRESS, args_size=32))
+ Op.SSTORE(4, Op.TLOAD(0xFE))
),
cases=[
# the first, reentrant call which calls tstore and a further
# reentrant staticcall
CalldataCase(
value=2,
action=(
Op.TSTORE(0xFE, 0x101)
+ Op.MSTORE(0, 3)
+ Op.SSTORE(
1, Op.STATICCALL(address=Op.ADDRESS, args_size=32, ret_size=32)
)
+ Op.SSTORE(3, Op.MLOAD(0))
),
),
# the second, reentrant call, which calls tload and return
# returns successfully
CalldataCase(
value=3,
action=Op.MSTORE(0, Op.TLOAD(0xFE)) + Op.RETURN(0, 32),
),
],
),
"expected_storage": {0: 0x01, 1: 0x01, 2: 0x100, 3: 0x101, 4: 0x101},
}
@ReentrancyTestCases.parametrize()
def test_reentrant_call(
state_test: StateTestFiller, pre: Alloc, bytecode: Bytecode, expected_storage: Dict
) -> None:
"""Test transient storage in different reentrancy contexts."""
env = Environment()
callee_address = pre.deploy_contract(bytecode)
tx = Transaction(
sender=pre.fund_eoa(),
to=callee_address,
data=Hash(1),
gas_limit=1_000_000,
)
post = {callee_address: Account(code=bytecode, storage=expected_storage)}
state_test(env=env, pre=pre, post=post, tx=tx)
| python | MIT | 88e9fb8f10ed89805aa3110d0a2cd5dcadc19689 | 2026-01-05T06:50:32.790998Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.