diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000000..9b59df876f3 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# change max line length from 80 to 100 +a3b64605a548a7a707d7b05bded506d7bef384e6 \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index fb7252534a9..0eda54be548 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,7 +10,7 @@ "internal-terms": false // Disable the `internal-terms` dictionary }, "[python]": { - "editor.rulers": [80], + "editor.rulers": [100], "editor.formatOnSave": true, "editor.defaultFormatter": "ms-python.black-formatter", "editor.codeActionsOnSave": { @@ -33,5 +33,9 @@ // "pytest-framework.ini", "pytest.ini" // "-vv" + ], + "black-formatter.args": [ + "--line-length", + "99" ] } \ No newline at end of file diff --git a/docs/dev/coding_style.md b/docs/dev/coding_style.md new file mode 100644 index 00000000000..9c2f3b38a67 --- /dev/null +++ b/docs/dev/coding_style.md @@ -0,0 +1,19 @@ +# Coding Style + +## Formatting and Line Length + +The Python code in execution-spec-tests is black formatted with a maximum line length of 100. Using VS Code with `editor.formatOnSave` is a big help to ensure files conform to the repo's coding style, see [VS Code Setup](../getting_started/setup_vs_code.md) to configure this and other useful settings. + +### Ignoring Bulk Change Commits + +The max line length was changed from 80 to 100 in Q2 2023. To ignore this bulk change commit in git blame output, use the `.git-blame-ignore-revs` file, for example: + +```console +git blame --ignore-revs-file .git-blame-ignore-revs docs/gen_filler_pages.py +``` + +To use the revs file persistently with `git blame`, run + +```console +git config blame.ignoreRevsFile .git-blame-ignore-revs +``` diff --git a/docs/dev/index.md b/docs/dev/index.md index 4ed85ebd02c..f0c6e2179e1 100644 --- a/docs/dev/index.md +++ b/docs/dev/index.md @@ -2,4 +2,5 @@ This documentation is aimed at maintainers of `execution-spec-tests` but may be helpful during test case/filler development: -- [generating documentation](./docs.md). \ No newline at end of file +- [generating documentation](./docs.md). +- [coding style](./coding_style.md). \ No newline at end of file diff --git a/docs/gen_filler_pages.py b/docs/gen_filler_pages.py index 8827888a258..a498bb62b68 100644 --- a/docs/gen_filler_pages.py +++ b/docs/gen_filler_pages.py @@ -49,9 +49,7 @@ def get_script_relative_path(): # noqa: D103 "disable filler doc generation" ) else: - logger.warning( - f"{script_name}: skipping automatic generation of " "filler doc" - ) + logger.warning(f"{script_name}: skipping automatic generation of " "filler doc") logger.info( f"{script_name}: set env var {enabled_env_var_name} " "to 'true' and re-run `mkdocs serve` or `mkdocs build` to " @@ -92,9 +90,7 @@ def apply_name_filters(input_string: str): ] for pattern, replacement in regexes: - input_string = re.sub( - pattern, replacement, input_string, flags=re.IGNORECASE - ) + input_string = re.sub(pattern, replacement, input_string, flags=re.IGNORECASE) return input_string @@ -117,9 +113,7 @@ def copy_file(source_file, destination_file): if "__pycache__" in root: continue - markdown_files = [ - filename for filename in files if filename.endswith(".md") - ] + markdown_files = [filename for filename in files if filename.endswith(".md")] python_files = [filename for filename in files if filename.endswith(".py")] root_filtered = apply_name_filters(root) @@ -134,15 +128,11 @@ def copy_file(source_file, destination_file): # from the __init__.py. mkdocs seems to struggle when both # an index.md and a readme.md are present. output_file_path = output_directory / "test_cases.md" - nav_path = ( - "Test Case Reference" / relative_filler_path / "Test Cases" - ) + nav_path = "Test Case Reference" / relative_filler_path / "Test Cases" else: output_file_path = output_directory / file file_no_ext = os.path.splitext(file)[0] - nav_path = ( - "Test Case Reference" / relative_filler_path / file_no_ext - ) + nav_path = "Test Case Reference" / relative_filler_path / file_no_ext copy_file(source_file, output_file_path) nav_tuple = tuple(apply_name_filters(part) for part in nav_path.parts) nav[nav_tuple] = output_file_path @@ -159,9 +149,7 @@ def copy_file(source_file, destination_file): else: file_no_ext = os.path.splitext(file)[0] output_file_path = output_directory / f"{file_no_ext}.md" - nav_path = ( - "Test Case Reference" / relative_filler_path / file_no_ext - ) + nav_path = "Test Case Reference" / relative_filler_path / file_no_ext package_name = os.path.join(root, file_no_ext).replace(os.sep, ".") pytest_test_path = os.path.join(root, file) diff --git a/docs/navigation.md b/docs/navigation.md index acff2c19043..a565b69953b 100644 --- a/docs/navigation.md +++ b/docs/navigation.md @@ -18,6 +18,7 @@ * [Getting Help](getting_help/index.md) * [Developer Doc](dev/index.md) * [Documentation](dev/docs.md) + * [Coding Style](dev/coding_style.md) * [Library Reference](library/index.md) * [EVM Transition Tool Package](library/evm_transition_tool.md) * [EVM Block Builder Package](library/evm_block_builder.md) diff --git a/pyproject.toml b/pyproject.toml index 2d6912ad541..d3c96929e51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [tool.isort] profile = "black" multi_line_output = 3 -line_length = 79 +line_length = 99 [tool.black] -line-length = 79 +line-length = 99 diff --git a/setup.cfg b/setup.cfg index c6ff554f84b..017b317c3d9 100644 --- a/setup.cfg +++ b/setup.cfg @@ -99,6 +99,7 @@ extend-ignore = E203, D107, D200, D203, D205, # Ignore D415: First line should end with a period, question mark, or exclamation point # Ignore D416: Section name should end with a colon # Ignore N806: Variable names with all caps (ALL_CAPS) +max-line-length = 99 per-file-ignore = tests/evm_transition_tool/test_evaluate.py:E501 diff --git a/src/ethereum_test_forks/base_fork.py b/src/ethereum_test_forks/base_fork.py index f14425edfc4..9bd870ac970 100644 --- a/src/ethereum_test_forks/base_fork.py +++ b/src/ethereum_test_forks/base_fork.py @@ -32,9 +32,7 @@ class BaseFork(ABC, metaclass=BaseForkMeta): @classmethod @abstractmethod - def header_base_fee_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_base_fee_required(cls, block_number: int, timestamp: int) -> bool: """ Returns true if the header must contain base fee """ @@ -42,9 +40,7 @@ def header_base_fee_required( @classmethod @abstractmethod - def header_prev_randao_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_prev_randao_required(cls, block_number: int, timestamp: int) -> bool: """ Returns true if the header must contain Prev Randao value """ @@ -52,9 +48,7 @@ def header_prev_randao_required( @classmethod @abstractmethod - def header_zero_difficulty_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_zero_difficulty_required(cls, block_number: int, timestamp: int) -> bool: """ Returns true if the header must have difficulty zero """ @@ -62,9 +56,7 @@ def header_zero_difficulty_required( @classmethod @abstractmethod - def header_withdrawals_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_withdrawals_required(cls, block_number: int, timestamp: int) -> bool: """ Returns true if the header must contain withdrawals """ @@ -72,9 +64,7 @@ def header_withdrawals_required( @classmethod @abstractmethod - def header_excess_data_gas_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_excess_data_gas_required(cls, block_number: int, timestamp: int) -> bool: """ Returns true if the header must contain excess data gas """ diff --git a/src/ethereum_test_forks/forks/forks.py b/src/ethereum_test_forks/forks/forks.py index 5eb9f540010..09bc2b311c8 100644 --- a/src/ethereum_test_forks/forks/forks.py +++ b/src/ethereum_test_forks/forks/forks.py @@ -11,45 +11,35 @@ class Frontier(BaseFork): """ @classmethod - def header_base_fee_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_base_fee_required(cls, block_number: int, timestamp: int) -> bool: """ At genesis, header must not contain base fee """ return False @classmethod - def header_prev_randao_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_prev_randao_required(cls, block_number: int, timestamp: int) -> bool: """ At genesis, header must not contain Prev Randao value """ return False @classmethod - def header_zero_difficulty_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_zero_difficulty_required(cls, block_number: int, timestamp: int) -> bool: """ At genesis, header must not have difficulty zero """ return False @classmethod - def header_withdrawals_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_withdrawals_required(cls, block_number: int, timestamp: int) -> bool: """ At genesis, header must not contain withdrawals """ return False @classmethod - def header_excess_data_gas_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_excess_data_gas_required(cls, block_number: int, timestamp: int) -> bool: """ At genesis, header must not contain excess data gas """ @@ -139,9 +129,7 @@ class London(Berlin): """ @classmethod - def header_base_fee_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_base_fee_required(cls, block_number: int, timestamp: int) -> bool: """ Base Fee is required starting from London. """ @@ -171,18 +159,14 @@ class Merge(London): """ @classmethod - def header_prev_randao_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_prev_randao_required(cls, block_number: int, timestamp: int) -> bool: """ Prev Randao is required starting from Merge. """ return True @classmethod - def header_zero_difficulty_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_zero_difficulty_required(cls, block_number: int, timestamp: int) -> bool: """ Zero difficulty is required starting from Merge. """ @@ -202,9 +186,7 @@ class Shanghai(Merge): """ @classmethod - def header_withdrawals_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_withdrawals_required(cls, block_number: int, timestamp: int) -> bool: """ Withdrawals are required starting from Shanghai. """ @@ -225,9 +207,7 @@ def is_deployed(cls): return False @classmethod - def header_excess_data_gas_required( - cls, block_number: int, timestamp: int - ) -> bool: + def header_excess_data_gas_required(cls, block_number: int, timestamp: int) -> bool: """ Excess data gas is required starting from Cancun. """ diff --git a/src/ethereum_test_forks/helpers.py b/src/ethereum_test_forks/helpers.py index 303d7e2f4e2..6705bc95535 100644 --- a/src/ethereum_test_forks/helpers.py +++ b/src/ethereum_test_forks/helpers.py @@ -67,9 +67,7 @@ def get_transition_forks() -> List[Fork]: fork = transition.__dict__[fork_name] if not isinstance(fork, type): continue - if issubclass(fork, TransitionBaseClass) and issubclass( - fork, BaseFork - ): + if issubclass(fork, TransitionBaseClass) and issubclass(fork, BaseFork): transition_forks.append(fork) return transition_forks diff --git a/src/ethereum_test_forks/tests/test_forks.py b/src/ethereum_test_forks/tests/test_forks.py index 24511d6fe34..b4384b3b045 100644 --- a/src/ethereum_test_forks/tests/test_forks.py +++ b/src/ethereum_test_forks/tests/test_forks.py @@ -40,10 +40,7 @@ def test_transition_forks(): def test_forks_from(): # noqa: D103 assert forks_from(Merge) == [Merge, LAST_DEPLOYED] assert forks_from(Merge, deployed_only=True) == [Merge, LAST_DEPLOYED] - assert ( - forks_from(Merge, deployed_only=False) - == [Merge, LAST_DEPLOYED] + DEVELOPMENT_FORKS - ) + assert forks_from(Merge, deployed_only=False) == [Merge, LAST_DEPLOYED] + DEVELOPMENT_FORKS def test_forks(): @@ -70,22 +67,10 @@ def test_forks(): assert Merge.header_base_fee_required(0, 0) is True # Transition forks too - assert ( - cast(Fork, BerlinToLondonAt5).header_base_fee_required(4, 0) is False - ) + assert cast(Fork, BerlinToLondonAt5).header_base_fee_required(4, 0) is False assert cast(Fork, BerlinToLondonAt5).header_base_fee_required(5, 0) is True - assert ( - cast(Fork, MergeToShanghaiAtTime15k).header_withdrawals_required( - 0, 14_999 - ) - is False - ) - assert ( - cast(Fork, MergeToShanghaiAtTime15k).header_withdrawals_required( - 0, 15_000 - ) - is True - ) + assert cast(Fork, MergeToShanghaiAtTime15k).header_withdrawals_required(0, 14_999) is False + assert cast(Fork, MergeToShanghaiAtTime15k).header_withdrawals_required(0, 15_000) is True assert is_fork(Berlin, Berlin) is True assert is_fork(London, Berlin) is True diff --git a/src/ethereum_test_forks/transition_base_fork.py b/src/ethereum_test_forks/transition_base_fork.py index e17c36ca53a..ed6b3356a5c 100644 --- a/src/ethereum_test_forks/transition_base_fork.py +++ b/src/ethereum_test_forks/transition_base_fork.py @@ -43,9 +43,7 @@ def name(cls) -> str: return transition_name NewTransitionClass.transitions_to = lambda: to_fork # type: ignore - NewTransitionClass.transitions_from = ( # type: ignore - lambda: cls.__bases__[0] - ) + NewTransitionClass.transitions_from = lambda: cls.__bases__[0] # type: ignore return NewTransitionClass diff --git a/src/ethereum_test_tools/__init__.py b/src/ethereum_test_tools/__init__.py index 096b11d917e..c9d18b9013c 100644 --- a/src/ethereum_test_tools/__init__.py +++ b/src/ethereum_test_tools/__init__.py @@ -30,13 +30,7 @@ ) from .filling.fill import fill_test from .reference_spec import ReferenceSpec, ReferenceSpecTypes -from .spec import ( - BaseTest, - BlockchainTest, - BlockchainTestFiller, - StateTest, - StateTestFiller, -) +from .spec import BaseTest, BlockchainTest, BlockchainTestFiller, StateTest, StateTestFiller from .vm import Opcode, Opcodes __all__ = ( diff --git a/src/ethereum_test_tools/code/generators.py b/src/ethereum_test_tools/code/generators.py index fcb0df680d5..8184079cdf3 100644 --- a/src/ethereum_test_tools/code/generators.py +++ b/src/ethereum_test_tools/code/generators.py @@ -101,15 +101,11 @@ def __init__( if len(pre_padding_bytes) > initcode_length: raise Exception("Invalid specified length for initcode") - padding_bytes = bytes( - [padding_byte] * (initcode_length - len(pre_padding_bytes)) - ) + padding_bytes = bytes([padding_byte] * (initcode_length - len(pre_padding_bytes))) else: padding_bytes = bytes() - self.deployment_gas = GAS_PER_DEPLOYED_CODE_BYTE * len( - deploy_code_bytes - ) + self.deployment_gas = GAS_PER_DEPLOYED_CODE_BYTE * len(deploy_code_bytes) super().__init__(bytecode=pre_padding_bytes + padding_bytes, name=name) diff --git a/src/ethereum_test_tools/code/yul.py b/src/ethereum_test_tools/code/yul.py index 050225c848f..77a8b08075e 100644 --- a/src/ethereum_test_tools/code/yul.py +++ b/src/ethereum_test_tools/code/yul.py @@ -42,12 +42,8 @@ def assemble(self) -> bytes: if result.returncode != 0: stderr_lines = result.stderr.decode().split("\n") - stderr_message = "\n".join( - line.strip() for line in stderr_lines - ) - raise Exception( - f"failed to compile yul source:\n{stderr_message[7:]}" - ) + stderr_message = "\n".join(line.strip() for line in stderr_lines) + raise Exception(f"failed to compile yul source:\n{stderr_message[7:]}") lines = result.stdout.decode().split("\n") diff --git a/src/ethereum_test_tools/common/__init__.py b/src/ethereum_test_tools/common/__init__.py index c965796b4d8..8331924f29b 100644 --- a/src/ethereum_test_tools/common/__init__.py +++ b/src/ethereum_test_tools/common/__init__.py @@ -1,13 +1,7 @@ """ Common definitions and types. """ -from .constants import ( - AddrAA, - AddrBB, - EmptyTrieRoot, - TestAddress, - TestPrivateKey, -) +from .constants import AddrAA, AddrBB, EmptyTrieRoot, TestAddress, TestPrivateKey from .helpers import ( add_kzg_version, ceiling_division, diff --git a/src/ethereum_test_tools/common/constants.py b/src/ethereum_test_tools/common/constants.py index 4a0ac39d831..c05a67b608b 100644 --- a/src/ethereum_test_tools/common/constants.py +++ b/src/ethereum_test_tools/common/constants.py @@ -2,12 +2,10 @@ Common values used in Ethereum tests. """ -TestPrivateKey = ( - "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8" -) +TestPrivateKey = "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8" TestAddress = "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" AddrAA = "0x00000000000000000000000000000000000000aa" AddrBB = "0x00000000000000000000000000000000000000bb" -EmptyTrieRoot = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" # noqa: E501 +EmptyTrieRoot = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" diff --git a/src/ethereum_test_tools/common/helpers.py b/src/ethereum_test_tools/common/helpers.py index 5e2bd120bbb..f1791941b0c 100644 --- a/src/ethereum_test_tools/common/helpers.py +++ b/src/ethereum_test_tools/common/helpers.py @@ -39,9 +39,7 @@ def compute_create_address(address: str | int, nonce: int) -> str: return "0x" + hash[-20:].hex() -def compute_create2_address( - address: str | int, salt: int, initcode: bytes -) -> str: +def compute_create2_address(address: str | int, salt: int, initcode: bytes) -> str: """ Compute address of the resulting contract created using the `CREATE2` opcode. @@ -82,9 +80,7 @@ def copy_opcode_cost(length: int) -> int: empty memory, based on the costs specified in the yellow paper: https://ethereum.github.io/yellowpaper/paper.pdf """ - return ( - 3 + (ceiling_division(length, 32) * 3) + cost_memory_bytes(length, 0) - ) + return 3 + (ceiling_division(length, 32) * 3) + cost_memory_bytes(length, 0) def eip_2028_transaction_data_cost(data: bytes | str) -> int: @@ -136,9 +132,7 @@ def to_hash(input: int | str) -> str: return "0x" + to_hash_bytes(input).hex() -def add_kzg_version( - b_hashes: List[bytes | int | str], kzg_version: int -) -> List[bytes]: +def add_kzg_version(b_hashes: List[bytes | int | str], kzg_version: int) -> List[bytes]: """ Adds the Kzg Version to each blob hash. """ @@ -147,13 +141,9 @@ def add_kzg_version( for hash in b_hashes: if isinstance(hash, int) or isinstance(hash, str): - kzg_versioned_hashes.append( - kzg_version_hex + to_hash_bytes(hash)[1:] - ) + kzg_versioned_hashes.append(kzg_version_hex + to_hash_bytes(hash)[1:]) elif isinstance(hash, bytes): kzg_versioned_hashes.append(kzg_version_hex + hash[1:]) else: - raise TypeError( - "Blob hash must be either an integer, string or bytes" - ) + raise TypeError("Blob hash must be either an integer, string or bytes") return kzg_versioned_hashes diff --git a/src/ethereum_test_tools/common/types.py b/src/ethereum_test_tools/common/types.py index 77a1e0273ec..af6ddd5fb74 100644 --- a/src/ethereum_test_tools/common/types.py +++ b/src/ethereum_test_tools/common/types.py @@ -4,18 +4,7 @@ import json from copy import copy, deepcopy from dataclasses import dataclass, field -from typing import ( - Any, - ClassVar, - Dict, - List, - Mapping, - Optional, - Sequence, - Tuple, - Type, - TypeAlias, -) +from typing import Any, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Type, TypeAlias from ethereum_test_forks import Fork from evm_block_builder import BlockBuilder @@ -114,9 +103,7 @@ class Storage: data: Dict[int, int] - StorageDictType: ClassVar[TypeAlias] = Dict[ - str | int | bytes, str | int | bytes - ] + StorageDictType: ClassVar[TypeAlias] = Dict[str | int | bytes, str | int | bytes] """ Dictionary type to be used when defining an input to initialize a storage. """ @@ -197,9 +184,7 @@ def __init__(self, key: int, *args): def __str__(self): """Print exception string""" - return "key {0} not found in storage".format( - Storage.key_value_to_string(self.key) - ) + return "key {0} not found in storage".format(Storage.key_value_to_string(self.key)) class KeyValueMismatch(Exception): """ @@ -220,8 +205,7 @@ def __init__(self, key: int, want: int, got: int, *args): def __str__(self): """Print exception string""" return ( - "incorrect value for key {0}: want {1} (dec:{2})," - + " got {3} (dec:{4})" + "incorrect value for key {0}: want {1} (dec:{2})," + " got {3} (dec:{4})" ).format( Storage.key_value_to_string(self.key), Storage.key_value_to_string(self.want), @@ -287,9 +271,7 @@ def __getitem__(self, key: str | int) -> int: def __setitem__(self, key: str | int, value: str | int): # noqa: SC200 """Sets an item in the storage""" - self.data[Storage.parse_key_value(key)] = Storage.parse_key_value( - value - ) + self.data[Storage.parse_key_value(key)] = Storage.parse_key_value(value) def __delitem__(self, key: str | int): """Deletes an item from the storage""" @@ -305,9 +287,7 @@ def to_dict(self) -> Mapping[str, str]: key_repr = Storage.key_value_to_string(key) val_repr = Storage.key_value_to_string(self.data[key]) if key_repr in res and val_repr != res[key_repr]: - raise Storage.AmbiguousKeyValue( - key_repr, res[key_repr], key, val_repr - ) + raise Storage.AmbiguousKeyValue(key_repr, res[key_repr], key, val_repr) res[key_repr] = val_repr return res @@ -339,9 +319,7 @@ def must_contain(self, other: "Storage"): if other[key] != 0: raise Storage.MissingKey(key) elif self.data[key] != other.data[key]: - raise Storage.KeyValueMismatch( - key, self.data[key], other.data[key] - ) + raise Storage.KeyValueMismatch(key, self.data[key], other.data[key]) def must_be_equal(self, other: "Storage"): """ @@ -350,9 +328,7 @@ def must_be_equal(self, other: "Storage"): # Test keys contained in both storage objects for key in self.data.keys() & other.data.keys(): if self.data[key] != other.data[key]: - raise Storage.KeyValueMismatch( - key, self.data[key], other.data[key] - ) + raise Storage.KeyValueMismatch(key, self.data[key], other.data[key]) # Test keys contained in either one of the storage objects for key in self.data.keys() ^ other.data.keys(): @@ -368,9 +344,7 @@ def storage_padding(storage: Dict) -> Dict: """ Adds even padding to each storage element. """ - return { - key_value_padding(k): key_value_padding(v) for k, v in storage.items() - } + return {key_value_padding(k): key_value_padding(v) for k, v in storage.items()} @dataclass(kw_only=True) @@ -414,9 +388,7 @@ class NonceMismatch(Exception): want: int | None got: int | None - def __init__( - self, address: str, want: int | None, got: int | None, *args - ): + def __init__(self, address: str, want: int | None, got: int | None, *args): super().__init__(args) self.address = address self.want = want @@ -439,9 +411,7 @@ class BalanceMismatch(Exception): want: int | None got: int | None - def __init__( - self, address: str, want: int | None, got: int | None, *args - ): + def __init__(self, address: str, want: int | None, got: int | None, *args): super().__init__(args) self.address = address self.want = want @@ -464,9 +434,7 @@ class CodeMismatch(Exception): want: str | None got: str | None - def __init__( - self, address: str, want: str | None, got: str | None, *args - ): + def __init__(self, address: str, want: str | None, got: str | None, *args): super().__init__(args) self.address = address self.want = want @@ -519,15 +487,9 @@ def check_alloc(self: "Account", address: str, alloc: dict): if self.storage is not None: expected_storage = ( - self.storage - if isinstance(self.storage, Storage) - else Storage(self.storage) - ) - actual_storage = ( - Storage(alloc["storage"]) - if "storage" in alloc - else Storage({}) + self.storage if isinstance(self.storage, Storage) else Storage(self.storage) ) + actual_storage = Storage(alloc["storage"]) if "storage" in alloc else Storage({}) expected_storage.must_be_equal(actual_storage) @classmethod @@ -614,7 +576,7 @@ def from_parent_header(parent: "FixtureHeader") -> "Environment": block_hashes={ parent.number: parent.hash if parent.hash is not None - else "0x0000000000000000000000000000000000000000000000000000000000000000" # noqa: E501 + else "0x0000000000000000000000000000000000000000000000000000000000000000" }, ) @@ -624,7 +586,8 @@ def parent_hash(self) -> str: `block_hashes`. """ if len(self.block_hashes) == 0: - return "0x0000000000000000000000000000000000000000000000000000000000000000" # noqa: E501 + return "0x0000000000000000000000000000000000000000000000000000000000000000" + last_index = max(self.block_hashes.keys()) return self.block_hashes[last_index] @@ -643,7 +606,7 @@ def apply_new_parent(self, new_parent: "FixtureHeader") -> "Environment": env.block_hashes[new_parent.number] = ( new_parent.hash if new_parent.hash is not None - else "0x0000000000000000000000000000000000000000000000000000000000000000" # noqa: E501 + else "0x0000000000000000000000000000000000000000000000000000000000000000" ) return env @@ -735,9 +698,7 @@ class InvalidFeePayment(Exception): def __str__(self): """Print exception string""" - return ( - "only one type of fee payment field can be used in a single tx" - ) + return "only one type of fee payment field can be used in a single tx" class InvalidSignaturePrivateKey(Exception): """ @@ -887,7 +848,7 @@ def from_dict(source: Dict[str, Any]) -> "FixtureHeader": """ ommers_hash = source.get("sha3Uncles") if ommers_hash is None: - ommers_hash = "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" # noqa: E501 + ommers_hash = "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" return FixtureHeader( parent_hash=source["parentHash"], ommers_hash=ommers_hash, @@ -927,9 +888,7 @@ def to_geth_dict(self) -> Mapping[str, Any]: "gasLimit": hex(self.gas_limit), "gasUsed": hex(self.gas_used), "timestamp": hex(self.timestamp), - "extraData": self.extra_data - if len(self.extra_data) != 0 - else "0x", # noqa: E501 + "extraData": self.extra_data if len(self.extra_data) != 0 else "0x", "mixHash": self.mix_digest, "nonce": self.nonce, } @@ -1006,14 +965,10 @@ def set_environment(self, env: Environment) -> Environment: environment_default = Environment() new_env.difficulty = self.difficulty new_env.coinbase = ( - self.coinbase - if self.coinbase is not None - else environment_default.coinbase + self.coinbase if self.coinbase is not None else environment_default.coinbase ) new_env.gas_limit = ( - self.gas_limit - if self.gas_limit is not None - else environment_default.gas_limit + self.gas_limit if self.gas_limit is not None else environment_default.gas_limit ) if not isinstance(self.base_fee, Removable): new_env.base_fee = self.base_fee @@ -1121,9 +1076,7 @@ def default(self, obj): elif isinstance(obj, Account): account = { "nonce": hex_or_none(obj.nonce, hex(ACCOUNT_DEFAULTS.nonce)), - "balance": hex_or_none( - obj.balance, hex(ACCOUNT_DEFAULTS.balance) - ), + "balance": hex_or_none(obj.balance, hex(ACCOUNT_DEFAULTS.balance)), "code": code_or_none(obj.code, "0x"), "storage": storage_padding(to_json_or_none(obj.storage, {})), } @@ -1139,15 +1092,12 @@ def default(self, obj): "chainId": hex(obj.chain_id), "nonce": hex(obj.nonce), "gasPrice": hex_or_none(obj.gas_price), - "maxPriorityFeePerGas": hex_or_none( - obj.max_priority_fee_per_gas - ), + "maxPriorityFeePerGas": hex_or_none(obj.max_priority_fee_per_gas), "maxFeePerGas": hex_or_none(obj.max_fee_per_gas), "gas": hex(obj.gas_limit), "value": hex(obj.value), "input": code_to_hex(obj.data), - "to": "0x" - + int.to_bytes(obj.to, length=20, byteorder="big").hex() + "to": "0x" + int.to_bytes(obj.to, length=20, byteorder="big").hex() if obj.to is int else obj.to, "accessList": obj.access_list, @@ -1163,14 +1113,10 @@ def default(self, obj): hashes.append(h) elif type(h) is bytes: if len(h) != 32: - raise TypeError( - "improper byte size for blob_versioned_hashes" - ) + raise TypeError("improper byte size for blob_versioned_hashes") hashes.append("0x" + h.hex()) else: - raise TypeError( - "improper type for blob_versioned_hashes" - ) + raise TypeError("improper type for blob_versioned_hashes") tx["blobVersionedHashes"] = hashes if obj.secret_key is None: @@ -1205,9 +1151,7 @@ def default(self, obj): "parentGasUsed": str_or_none(obj.parent_gas_used), "parentGasLimit": str_or_none(obj.parent_gas_limit), "parentTimestamp": str_or_none(obj.parent_timestamp), - "blockHashes": { - str(k): v for (k, v) in obj.block_hashes.items() - }, + "blockHashes": {str(k): v for (k, v) in obj.block_hashes.items()}, "ommers": [], "withdrawals": to_json_or_none(obj.withdrawals), "parentUncleHash": obj.parent_ommers_hash, @@ -1231,9 +1175,7 @@ def default(self, obj): "gasLimit": hex(obj.gas_limit), "gasUsed": hex(obj.gas_used), "timestamp": hex(obj.timestamp), - "extraData": obj.extra_data - if len(obj.extra_data) != 0 - else "0x", # noqa: E501 + "extraData": obj.extra_data if len(obj.extra_data) != 0 else "0x", "mixHash": obj.mix_digest, "nonce": obj.nonce, } @@ -1285,23 +1227,18 @@ def default(self, obj): elif isinstance(obj, FixtureBlock): b = {"rlp": obj.rlp} if obj.block_header is not None: - b["blockHeader"] = json.loads( - json.dumps(obj.block_header, cls=JSONEncoder) - ) + b["blockHeader"] = json.loads(json.dumps(obj.block_header, cls=JSONEncoder)) if obj.expected_exception is not None: b["expectException"] = obj.expected_exception if obj.block_number is not None: b["blocknumber"] = str(obj.block_number) if obj.txs is not None: - b["transactions"] = [ - FixtureTransaction(tx=tx) for tx in obj.txs - ] + b["transactions"] = [FixtureTransaction(tx=tx) for tx in obj.txs] if obj.ommers is not None: b["uncleHeaders"] = obj.ommers if obj.withdrawals is not None: b["withdrawals"] = [ - even_padding(to_json(wd), excluded=["address"]) - for wd in obj.withdrawals + even_padding(to_json(wd), excluded=["address"]) for wd in obj.withdrawals ] return b elif isinstance(obj, Fixture): @@ -1311,18 +1248,13 @@ def default(self, obj): f = { "_info": obj.info, - "blocks": [ - json.loads(json.dumps(b, cls=JSONEncoder)) - for b in obj.blocks - ], + "blocks": [json.loads(json.dumps(b, cls=JSONEncoder)) for b in obj.blocks], "genesisBlockHeader": self.default(obj.genesis), "genesisRLP": obj.genesis_rlp, "lastblockhash": obj.head, "network": obj.fork, "pre": json.loads(json.dumps(obj.pre_state, cls=JSONEncoder)), - "postState": json.loads( - json.dumps(obj.post_state, cls=JSONEncoder) - ), + "postState": json.loads(json.dumps(obj.post_state, cls=JSONEncoder)), "sealEngine": obj.seal_engine, } if f["postState"] is None: diff --git a/src/ethereum_test_tools/filling/fill.py b/src/ethereum_test_tools/filling/fill.py index 19632c59641..8ce6e6ed496 100644 --- a/src/ethereum_test_tools/filling/fill.py +++ b/src/ethereum_test_tools/filling/fill.py @@ -43,9 +43,7 @@ def fill_test( genesis=genesis, genesis_rlp=genesis_rlp, head=head, - fork="+".join([fork_name] + [str(eip) for eip in eips]) - if eips is not None - else fork_name, + fork="+".join([fork_name] + [str(eip) for eip in eips]) if eips is not None else fork_name, pre_state=copy(test_spec.pre), post_state=alloc_to_accounts(alloc), seal_engine=engine, diff --git a/src/ethereum_test_tools/reference_spec/git_reference_spec.py b/src/ethereum_test_tools/reference_spec/git_reference_spec.py index 6617ed176e0..228b318a482 100644 --- a/src/ethereum_test_tools/reference_spec/git_reference_spec.py +++ b/src/ethereum_test_tools/reference_spec/git_reference_spec.py @@ -9,11 +9,7 @@ import requests -from .reference_spec import ( - NoLatestKnownVersion, - ParseModuleError, - ReferenceSpec, -) +from .reference_spec import NoLatestKnownVersion, ParseModuleError, ReferenceSpec def _decode_base64_content(encoded_data: str) -> str: diff --git a/src/ethereum_test_tools/spec/__init__.py b/src/ethereum_test_tools/spec/__init__.py index 6fb8ea4cbc4..15bffd767f6 100644 --- a/src/ethereum_test_tools/spec/__init__.py +++ b/src/ethereum_test_tools/spec/__init__.py @@ -2,11 +2,7 @@ Test spec definitions and utilities. """ from .base_test import BaseTest, TestSpec, verify_post_alloc -from .blockchain_test import ( - BlockchainTest, - BlockchainTestFiller, - BlockchainTestSpec, -) +from .blockchain_test import BlockchainTest, BlockchainTestFiller, BlockchainTestSpec from .state_test import StateTest, StateTestFiller, StateTestSpec __all__ = ( diff --git a/src/ethereum_test_tools/spec/base_test.py b/src/ethereum_test_tools/spec/base_test.py index b4529f289ae..368243c5c1c 100644 --- a/src/ethereum_test_tools/spec/base_test.py +++ b/src/ethereum_test_tools/spec/base_test.py @@ -2,16 +2,7 @@ Generic Ethereum test base class """ from abc import abstractmethod -from typing import ( - Any, - Callable, - Dict, - Generator, - List, - Mapping, - Optional, - Tuple, -) +from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple from ethereum_test_forks import Fork from evm_block_builder import BlockBuilder @@ -51,9 +42,7 @@ def verify_transactions(txs: List[Transaction] | None, result) -> List[int]: for i, tx in enumerate(txs): error = rejected_txs[i] if i in rejected_txs else None if tx.error and not error: - raise Exception( - f"tx expected to fail succeeded: pos={i}, nonce={tx.nonce}" - ) + raise Exception(f"tx expected to fail succeeded: pos={i}, nonce={tx.nonce}") elif not tx.error and error: raise Exception(f"tx unexpectedly failed: {error}") @@ -62,9 +51,7 @@ def verify_transactions(txs: List[Transaction] | None, result) -> List[int]: return list(rejected_txs.keys()) -def verify_post_alloc( - expected_post: Mapping[str, Account], got_alloc: Mapping[str, Any] -): +def verify_post_alloc(expected_post: Mapping[str, Account], got_alloc: Mapping[str, Any]): """ Verify that an allocation matches the expected post in the test. Raises exception on unexpected values. diff --git a/src/ethereum_test_tools/spec/blockchain_test.py b/src/ethereum_test_tools/spec/blockchain_test.py index a0517be65d9..43c947afaf5 100644 --- a/src/ethereum_test_tools/spec/blockchain_test.py +++ b/src/ethereum_test_tools/spec/blockchain_test.py @@ -4,17 +4,7 @@ from dataclasses import dataclass from pprint import pprint -from typing import ( - Any, - Callable, - Dict, - Generator, - List, - Mapping, - Optional, - Tuple, - Type, -) +from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Type from ethereum_test_forks import Fork from evm_block_builder import BlockBuilder @@ -66,8 +56,8 @@ def make_genesis( env = self.genesis_environment.set_fork_requirements(fork) genesis = FixtureHeader( - parent_hash="0x0000000000000000000000000000000000000000000000000000000000000000", # noqa: E501 - ommers_hash="0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", # noqa: E501 + parent_hash="0x0000000000000000000000000000000000000000000000000000000000000000", + ommers_hash="0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", coinbase="0x0000000000000000000000000000000000000000", state_root=t8n.calc_state_root( to_json(self.pre), @@ -82,7 +72,7 @@ def make_genesis( gas_used=0, timestamp=0, extra_data="0x00", - mix_digest="0x0000000000000000000000000000000000000000000000000000000000000000", # noqa: E501 + mix_digest="0x0000000000000000000000000000000000000000000000000000000000000000", nonce="0x0000000000000000", base_fee=env.base_fee, excess_data_gas=env.excess_data_gas, @@ -178,15 +168,12 @@ def make_block( "parentHash": env.parent_hash(), "miner": env.coinbase, "transactionsRoot": result.get("txRoot"), - "difficulty": str_or_none( - result.get("currentDifficulty"), "0" - ), + "difficulty": str_or_none(result.get("currentDifficulty"), "0"), "number": str(env.number), "gasLimit": str(env.gas_limit), "timestamp": str(env.timestamp), "extraData": block.extra_data - if block.extra_data is not None - and len(block.extra_data) != 0 + if block.extra_data is not None and len(block.extra_data) != 0 else "0x", "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", # noqa: E501 "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", # noqa: E501 @@ -267,7 +254,7 @@ def make_blocks( head = ( genesis.hash if genesis.hash is not None - else "0x0000000000000000000000000000000000000000000000000000000000000000" # noqa: E501 + else "0x0000000000000000000000000000000000000000000000000000000000000000" ) for block in self.blocks: fixture_block, env, alloc, head = self.make_block( diff --git a/src/ethereum_test_tools/spec/debugging.py b/src/ethereum_test_tools/spec/debugging.py index bb40f2d3aa0..57534ab8cfa 100644 --- a/src/ethereum_test_tools/spec/debugging.py +++ b/src/ethereum_test_tools/spec/debugging.py @@ -10,10 +10,7 @@ def print_traces(traces: List[List[List[Dict]]] | None): Print the traces from the transition tool for debugging. """ if traces is None: - print( - "Traces not collected. Use `--traces` to see detailed" - + " execution information." - ) + print("Traces not collected. Use `--traces` to see detailed" + " execution information.") return print("Printing traces for debugging purposes:") pp = pprint.PrettyPrinter(indent=2) diff --git a/src/ethereum_test_tools/spec/state_test.py b/src/ethereum_test_tools/spec/state_test.py index 094a30186f1..bf751dd98a8 100644 --- a/src/ethereum_test_tools/spec/state_test.py +++ b/src/ethereum_test_tools/spec/state_test.py @@ -2,17 +2,7 @@ State test filler. """ from dataclasses import dataclass -from typing import ( - Any, - Callable, - Dict, - Generator, - List, - Mapping, - Optional, - Tuple, - Type, -) +from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Type from ethereum_test_forks import Fork from evm_block_builder import BlockBuilder @@ -64,8 +54,8 @@ def make_genesis( env = self.env.set_fork_requirements(fork) genesis = FixtureHeader( - parent_hash="0x0000000000000000000000000000000000000000000000000000000000000000", # noqa: E501 - ommers_hash="0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", # noqa: E501 + parent_hash="0x0000000000000000000000000000000000000000000000000000000000000000", + ommers_hash="0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", coinbase="0x0000000000000000000000000000000000000000", state_root=t8n.calc_state_root( to_json(self.pre), @@ -80,7 +70,7 @@ def make_genesis( gas_used=0, timestamp=0, extra_data="0x00", - mix_digest="0x0000000000000000000000000000000000000000000000000000000000000000", # noqa: E501 + mix_digest="0x0000000000000000000000000000000000000000000000000000000000000000", nonce="0x0000000000000000", base_fee=env.base_fee, excess_data_gas=env.excess_data_gas, @@ -145,15 +135,13 @@ def make_blocks( "parentHash": genesis.hash, "miner": env.coinbase, "transactionsRoot": result.get("txRoot"), - "difficulty": str_or_none( - env.difficulty, result.get("currentDifficulty") - ), + "difficulty": str_or_none(env.difficulty, result.get("currentDifficulty")), "number": str(env.number), "gasLimit": str(env.gas_limit), "timestamp": str(env.timestamp), "extraData": "0x00", - "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", # noqa: E501 - "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", # noqa: E501 + "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "nonce": "0x0000000000000000", "baseFeePerGas": result.get("currentBaseFee"), "excessDataGas": result.get("currentExcessDataGas"), diff --git a/src/ethereum_test_tools/tests/test_code.py b/src/ethereum_test_tools/tests/test_code.py index 7b7cdc650d3..0597057b51f 100644 --- a/src/ethereum_test_tools/tests/test_code.py +++ b/src/ethereum_test_tools/tests/test_code.py @@ -16,15 +16,11 @@ def test_code(): assert code_to_bytes("0x01") == bytes.fromhex("01") assert code_to_bytes("01") == bytes.fromhex("01") - assert ( - Code(bytecode=code_to_bytes("0x01")) + "0x02" - ).assemble() == bytes.fromhex("0102") - assert ( - "0x01" + Code(bytecode=code_to_bytes("0x02")) - ).assemble() == bytes.fromhex("0102") - assert ( - "0x01" + Code(bytecode=code_to_bytes("0x02")) + "0x03" - ).assemble() == bytes.fromhex("010203") + assert (Code(bytecode=code_to_bytes("0x01")) + "0x02").assemble() == bytes.fromhex("0102") + assert ("0x01" + Code(bytecode=code_to_bytes("0x02"))).assemble() == bytes.fromhex("0102") + assert ("0x01" + Code(bytecode=code_to_bytes("0x02")) + "0x03").assemble() == bytes.fromhex( + "010203" + ) def test_yul(): @@ -87,11 +83,7 @@ def test_yul(): == bytes.fromhex("60026001556004600355") ) - long_code = ( - "{\n" - + "\n".join(["sstore({0}, {0})".format(i) for i in range(5000)]) - + "\n}" - ) + long_code = "{\n" + "\n".join(["sstore({0}, {0})".format(i) for i in range(5000)]) + "\n}" expected_bytecode = bytes() for i in range(5000): diff --git a/src/ethereum_test_tools/tests/test_filler.py b/src/ethereum_test_tools/tests/test_filler.py index ceefe73c0a7..9bf3b752538 100644 --- a/src/ethereum_test_tools/tests/test_filler.py +++ b/src/ethereum_test_tools/tests/test_filler.py @@ -13,14 +13,7 @@ from evm_transition_tool import EvmTransitionTool from ..code import Yul -from ..common import ( - Account, - Block, - Environment, - JSONEncoder, - TestAddress, - Transaction, -) +from ..common import Account, Block, Environment, JSONEncoder, TestAddress, Transaction from ..filling import fill_test from ..spec import BlockchainTest, StateTest @@ -31,9 +24,7 @@ def remove_info(fixture_json: Dict[str, Any]): del fixture_json[t]["_info"] -@pytest.mark.parametrize( - "fork,hash", [(Berlin, "0x193e550de"), (London, "0xb053deac0")] -) +@pytest.mark.parametrize("fork,hash", [(Berlin, "0x193e550de"), (London, "0xb053deac0")]) def test_make_genesis(fork: Fork, hash: str): env = Environment() @@ -59,9 +50,9 @@ def test_make_genesis(fork: Fork, hash: str): b11r = EvmBlockBuilder() t8n = EvmTransitionTool() - _, genesis = StateTest( - env=env, pre=pre, post={}, txs=[], tag="some_state_test" - ).make_genesis(b11r, t8n, fork) + _, genesis = StateTest(env=env, pre=pre, post={}, txs=[], tag="some_state_test").make_genesis( + b11r, t8n, fork + ) assert genesis.hash is not None assert genesis.hash.startswith(hash) @@ -86,12 +77,8 @@ def test_fill_state_test(fork: Fork, expected_json_file: str): ) pre = { - "0x1000000000000000000000000000000000000000": Account( - code="0x4660015500" - ), - "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account( - balance=1000000000000000000000 - ), + "0x1000000000000000000000000000000000000000": Account(code="0x4660015500"), + "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account(balance=1000000000000000000000), } tx = Transaction( @@ -110,9 +97,7 @@ def test_fill_state_test(fork: Fork, expected_json_file: str): ), } - state_test = StateTest( - env=env, pre=pre, post=post, txs=[tx], tag="my_chain_id_test" - ) + state_test = StateTest(env=env, pre=pre, post=post, txs=[tx], tag="my_chain_id_test") b11r = EvmBlockBuilder() t8n = EvmTransitionTool() @@ -147,9 +132,7 @@ def test_fill_london_blockchain_test_valid_txs(): Test `ethereum_test.filler.fill_fixtures` with `BlockchainTest`. """ pre = { - "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account( - balance=0x1000000000000000000 - ), + "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account(balance=0x1000000000000000000), "0xd02d72E067e77158444ef2020Ff2d325f929B363": Account( balance=0x1000000000000000000, nonce=1 ), @@ -435,9 +418,7 @@ def test_fill_london_blockchain_test_invalid_txs(): Test `ethereum_test.filler.fill_fixtures` with `BlockchainTest`. """ pre = { - "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account( - balance=0x1000000000000000000 - ), + "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account(balance=0x1000000000000000000), "0xd02d72E067e77158444ef2020Ff2d325f929B363": Account( balance=0x1000000000000000000, nonce=1 ), diff --git a/src/ethereum_test_tools/tests/test_helpers.py b/src/ethereum_test_tools/tests/test_helpers.py index 2bd3f6166ff..43b0646d15d 100644 --- a/src/ethereum_test_tools/tests/test_helpers.py +++ b/src/ethereum_test_tools/tests/test_helpers.py @@ -4,11 +4,7 @@ import pytest -from ..common import ( - compute_create2_address, - compute_create_address, - to_address, -) +from ..common import compute_create2_address, compute_create_address, to_address def test_to_address(): @@ -20,10 +16,7 @@ def test_to_address(): assert to_address(1) == "0x0000000000000000000000000000000000000001" assert to_address("10") == "0x000000000000000000000000000000000000000a" assert to_address("0x10") == "0x0000000000000000000000000000000000000010" - assert ( - to_address(2 ** (20 * 8) - 1) - == "0xffffffffffffffffffffffffffffffffffffffff" - ) + assert to_address(2 ** (20 * 8) - 1) == "0xffffffffffffffffffffffffffffffffffffffff" @pytest.mark.parametrize( @@ -59,15 +52,12 @@ def test_to_address(): "0x06012c8cf97bead5deae237070f9587f8e7a266d", id="large-nonce-0x-str-address", marks=pytest.mark.xfail( - reason="Nonce too large to convert with hard-coded to_bytes " - "length of 1" + reason="Nonce too large to convert with hard-coded to_bytes " "length of 1" ), ), ], ) -def test_compute_create_address( - address: str | int, nonce: int, expected_contract_address: str -): +def test_compute_create_address(address: str | int, nonce: int, expected_contract_address: str): """ Test `ethereum_test.helpers.compute_create_address` with some famous contracts: diff --git a/src/ethereum_test_tools/tests/test_types.py b/src/ethereum_test_tools/tests/test_types.py index 3c277435fa8..d9130f2ee2a 100644 --- a/src/ethereum_test_tools/tests/test_types.py +++ b/src/ethereum_test_tools/tests/test_types.py @@ -6,13 +6,7 @@ import pytest -from ..common import ( - Account, - Storage, - even_padding, - key_value_padding, - storage_padding, -) +from ..common import Account, Storage, even_padding, key_value_padding, storage_padding def test_storage(): @@ -246,9 +240,7 @@ def test_storage(): ), ], ) -def test_account_check_alloc( - account: Account, alloc: Dict[Any, Any], should_pass: bool -): +def test_account_check_alloc(account: Account, alloc: Dict[Any, Any], should_pass: bool): if should_pass: account.check_alloc("test", alloc) else: diff --git a/src/ethereum_test_tools/vm/opcode.py b/src/ethereum_test_tools/vm/opcode.py index 456c17cebe1..cce0185f7d4 100644 --- a/src/ethereum_test_tools/vm/opcode.py +++ b/src/ethereum_test_tools/vm/opcode.py @@ -50,7 +50,7 @@ def __new__( popped_stack_items: int = 0, pushed_stack_items: int = 0, min_stack_height: int = 0, - data_portion_length: int = 0 + data_portion_length: int = 0, ): """ Creates a new opcode instance. @@ -104,9 +104,7 @@ def __call__(self, *args_t: Union[int, bytes, "Opcode"]) -> bytes: # For opcodes with a data portion, the first argument is the data # and the rest of the arguments form the stack. if len(args) == 0: - raise ValueError( - "Opcode with data portion requires at least one argument" - ) + raise ValueError("Opcode with data portion requires at least one argument") data = args.pop(0) if isinstance(data, bytes): data_portion = data @@ -118,9 +116,7 @@ def __call__(self, *args_t: Union[int, bytes, "Opcode"]) -> bytes: signed=signed, ) else: - raise TypeError( - "Opcode data portion must be either an int or a bytes" - ) + raise TypeError("Opcode data portion must be either an int or a bytes") # The rest of the arguments conform the stack. while len(args) > 0: @@ -132,9 +128,7 @@ def __call__(self, *args_t: Union[int, bytes, "Opcode"]) -> bytes: signed = data < 0 data_size = _get_int_size(data) if data_size > 32: - raise ValueError( - "Opcode stack data must be less than 32 bytes" - ) + raise ValueError("Opcode stack data must be less than 32 bytes") elif data_size == 0: # Pushing 0 is done with the PUSH1 opcode for compatibility # reasons. @@ -148,9 +142,7 @@ def __call__(self, *args_t: Union[int, bytes, "Opcode"]) -> bytes: ) else: - raise TypeError( - "Opcode stack data must be either an int or a bytes" - ) + raise TypeError("Opcode stack data must be either an int or a bytes") return pre_opcode_bytecode + self + data_portion diff --git a/src/evm_block_builder/__init__.py b/src/evm_block_builder/__init__.py index ea42e392dae..a53bad42d7f 100644 --- a/src/evm_block_builder/__init__.py +++ b/src/evm_block_builder/__init__.py @@ -125,9 +125,7 @@ def version(self) -> str: ) if result.returncode != 0: - raise Exception( - "failed to evaluate: " + result.stderr.decode() - ) + raise Exception("failed to evaluate: " + result.stderr.decode()) self.cached_version = result.stdout.decode().strip() diff --git a/src/evm_block_builder/tests/test_build.py b/src/evm_block_builder/tests/test_build.py index 3d993755620..5e052077b6e 100644 --- a/src/evm_block_builder/tests/test_build.py +++ b/src/evm_block_builder/tests/test_build.py @@ -6,9 +6,7 @@ from evm_block_builder import BlockBuilder, EvmBlockBuilder -FIXTURES_ROOT = Path( - os.path.join("src", "evm_block_builder", "tests", "fixtures") -) +FIXTURES_ROOT = Path(os.path.join("src", "evm_block_builder", "tests", "fixtures")) @pytest.mark.parametrize("b11r", [EvmBlockBuilder()]) diff --git a/src/evm_transition_tool/__init__.py b/src/evm_transition_tool/__init__.py index f2a63b95b1d..239413228ea 100644 --- a/src/evm_transition_tool/__init__.py +++ b/src/evm_transition_tool/__init__.py @@ -104,7 +104,7 @@ def calc_withdrawals_root(self, withdrawals: Any, fork: Fork) -> str: """ if type(withdrawals) is list and len(withdrawals) == 0: # Optimize returning the empty root immediately - return "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" # noqa: E501 + return "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" env: Dict[str, Any] = { "currentCoinbase": "0x0000000000000000000000000000000000000000", @@ -128,8 +128,7 @@ def calc_withdrawals_root(self, withdrawals: Any, fork: Fork) -> str: withdrawals_root = result.get("withdrawalsRoot") if withdrawals_root is None: raise Exception( - "Unable to calculate withdrawals root: " - + "no value returned from transition tool" + "Unable to calculate withdrawals root: no value returned from transition tool" ) if type(withdrawals_root) is not str: raise Exception( @@ -170,10 +169,7 @@ def __init__( try: result = subprocess.run(args, capture_output=True, text=True) except subprocess.CalledProcessError as e: - raise Exception( - "evm process unexpectedly returned a non-zero status code: " - f"{e}." - ) + raise Exception("evm process unexpectedly returned a non-zero status code: " f"{e}.") except Exception as e: raise Exception(f"Unexpected exception calling evm tool: {e}.") self.help_string = result.stdout @@ -246,9 +242,7 @@ def evaluate( for i, r in enumerate(receipts): h = r["transactionHash"] trace_file_name = f"trace-{i}-{h}.jsonl" - with open( - os.path.join(temp_dir.name, trace_file_name), "r" - ) as trace_file: + with open(os.path.join(temp_dir.name, trace_file_name), "r") as trace_file: tx_traces: List[Dict] = [] for trace_line in trace_file.readlines(): tx_traces.append(json.loads(trace_line)) @@ -270,9 +264,7 @@ def version(self) -> str: ) if result.returncode != 0: - raise Exception( - "failed to evaluate: " + result.stderr.decode() - ) + raise Exception("failed to evaluate: " + result.stderr.decode()) self.cached_version = result.stdout.decode().strip() diff --git a/src/evm_transition_tool/tests/test_evaluate.py b/src/evm_transition_tool/tests/test_evaluate.py index 85454f7a9d7..84ef3845a0e 100644 --- a/src/evm_transition_tool/tests/test_evaluate.py +++ b/src/evm_transition_tool/tests/test_evaluate.py @@ -8,9 +8,7 @@ from ethereum_test_forks import Berlin, Fork, Istanbul, London from evm_transition_tool import EvmTransitionTool, TransitionTool -FIXTURES_ROOT = Path( - os.path.join("src", "evm_transition_tool", "tests", "fixtures") -) +FIXTURES_ROOT = Path(os.path.join("src", "evm_transition_tool", "tests", "fixtures")) @pytest.mark.parametrize("t8n", [EvmTransitionTool()]) diff --git a/src/logger.py b/src/logger.py index ca1dacd46f6..09c1c1cef93 100644 --- a/src/logger.py +++ b/src/logger.py @@ -15,9 +15,7 @@ def setup_logger(name): Set up a logger with the provided name using the 'logger.cfg' file. """ config = configparser.ConfigParser() - config.read( - os.path.join(os.path.dirname(os.path.abspath(__file__)), "logger.cfg") - ) + config.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), "logger.cfg")) logging.config.fileConfig(config, disable_existing_loggers=False) logger = logging.getLogger(name) diff --git a/src/pytest_plugins/forks/forks.py b/src/pytest_plugins/forks/forks.py index dc3d49430ef..006b1302a5a 100644 --- a/src/pytest_plugins/forks/forks.py +++ b/src/pytest_plugins/forks/forks.py @@ -19,9 +19,7 @@ def pytest_addoption(parser): """ Adds command-line options to pytest. """ - fork_group = parser.getgroup( - "Forks", "Specify the fork range to generate fixtures for" - ) + fork_group = parser.getgroup("Forks", "Specify the fork range to generate fixtures for") fork_group.addoption( "--forks", action="store_true", @@ -117,10 +115,7 @@ def pytest_configure(config): pytest.exit("Invalid command-line options.", returncode=1) if single_fork and (forks_from or forks_until): - print( - "Error: --fork cannot be used in combination with --forks-from or " - "--forks-until" - ) + print("Error: --fork cannot be used in combination with --forks-from or " "--forks-until") pytest.exit("Invalid command-line options.", returncode=1) if single_fork: @@ -149,10 +144,7 @@ def pytest_configure(config): pytest.exit("Invalid command-line options.", returncode=1) config.fork_range = config.fork_names[ - config.fork_names.index(forks_from) : config.fork_names.index( - forks_until - ) - + 1 + config.fork_names.index(forks_from) : config.fork_names.index(forks_until) + 1 ] if not config.fork_range: @@ -160,9 +152,7 @@ def pytest_configure(config): f"Error: --forks-from {forks_from} --forks-until {forks_until} " "creates an empty fork range." ) - pytest.exit( - "Command-line options produce empty fork range.", returncode=1 - ) + pytest.exit("Command-line options produce empty fork range.", returncode=1) # with --collect-only, we don't have access to these config options if config.option.collectonly: @@ -172,9 +162,7 @@ def pytest_configure(config): trace=config.getoption("evm_collect_traces"), ) unsupported_forks = [ - fork - for fork in config.fork_range - if not t8n.is_fork_supported(config.fork_map[fork]) + fork for fork in config.fork_range if not t8n.is_fork_supported(config.fork_map[fork]) ] if unsupported_forks: print( @@ -195,18 +183,12 @@ def pytest_report_header(config, start_path): warning = "\033[93m" reset = "\033[39;49m" header = [ - ( - bold - + f"Executing tests for: {', '.join(config.fork_range)} " - + reset - ), + (bold + f"Executing tests for: {', '.join(config.fork_range)} " + reset), ] if config.getoption("forks_until") is None: header += [ ( - bold - + warning - + "Only executing tests with stable/deployed forks: " + bold + warning + "Only executing tests with stable/deployed forks: " "Specify an upcoming fork via --until=fork to " "add forks under development." + reset ) @@ -228,17 +210,11 @@ def pytest_generate_tests(metafunc): """ valid_at_transition_to = [ marker.args[0] - for marker in metafunc.definition.iter_markers( - name="valid_at_transition_to" - ) - ] - valid_from = [ - marker.args[0] - for marker in metafunc.definition.iter_markers(name="valid_from") + for marker in metafunc.definition.iter_markers(name="valid_at_transition_to") ] + valid_from = [marker.args[0] for marker in metafunc.definition.iter_markers(name="valid_from")] valid_until = [ - marker.args[0] - for marker in metafunc.definition.iter_markers(name="valid_until") + marker.args[0] for marker in metafunc.definition.iter_markers(name="valid_until") ] if valid_at_transition_to and (valid_from or valid_until): pytest.fail( @@ -283,9 +259,9 @@ def pytest_generate_tests(metafunc): test_fork_range = set( metafunc.config.fork_names[ - metafunc.config.fork_names.index( - valid_from[0] - ) : metafunc.config.fork_names.index(valid_until[0]) + metafunc.config.fork_names.index(valid_from[0]) : metafunc.config.fork_names.index( + valid_until[0] + ) + 1 ] ) @@ -299,14 +275,10 @@ def pytest_generate_tests(metafunc): f"@pytest.mark.valid_until ({valid_until[0]})." ) - intersection_range = list( - set(metafunc.config.fork_range) & test_fork_range - ) + intersection_range = list(set(metafunc.config.fork_range) & test_fork_range) intersection_range.sort(key=metafunc.config.fork_range.index) - intersection_range = [ - metafunc.config.fork_map[fork] for fork in intersection_range - ] + intersection_range = [metafunc.config.fork_map[fork] for fork in intersection_range] # TODO: skip: test is not valid for any forks in the configured range # (from, until). diff --git a/src/pytest_plugins/forks/tests/test_forks.py b/src/pytest_plugins/forks/tests/test_forks.py index ce16fde21de..d68ae0795fd 100644 --- a/src/pytest_plugins/forks/tests/test_forks.py +++ b/src/pytest_plugins/forks/tests/test_forks.py @@ -4,12 +4,7 @@ import pytest -from ethereum_test_forks import ( - ArrowGlacier, - forks_from_until, - get_deployed_forks, - get_forks, -) +from ethereum_test_forks import ArrowGlacier, forks_from_until, get_deployed_forks, get_forks pytest_plugin_args = ( "-p", @@ -50,9 +45,7 @@ def test_all_forks(state_test): all_forks = get_deployed_forks() forks_under_test = forks_from_until(all_forks[0], all_forks[-1]) for fork in forks_under_test: - assert f":test_all_forks[fork={fork}]" in "\n".join( - result.stdout.lines - ) + assert f":test_all_forks[fork={fork}]" in "\n".join(result.stdout.lines) result.assert_outcomes( passed=len(forks_under_test), failed=0, @@ -86,9 +79,7 @@ def test_all_forks(state_test): all_forks = get_deployed_forks() forks_under_test = forks_from_until(fork_map[fork], all_forks[-1]) for fork_under_test in forks_under_test: - assert f":test_all_forks[fork={fork_under_test}]" in "\n".join( - result.stdout.lines - ) + assert f":test_all_forks[fork={fork_under_test}]" in "\n".join(result.stdout.lines) result.assert_outcomes( passed=len(forks_under_test), failed=0, @@ -97,9 +88,7 @@ def test_all_forks(state_test): ) -def test_from_london_until_shanghai_option_no_validity_marker( - pytester, fork_map -): +def test_from_london_until_shanghai_option_no_validity_marker(pytester, fork_map): """ Test test parametrization with: - --from London command-line option, @@ -117,15 +106,11 @@ def test_all_forks(state_test): result = pytester.runpytest( *pytest_plugin_args, "-v", "--from", "London", "--until", "Shanghai" ) - forks_under_test = forks_from_until( - fork_map["London"], fork_map["Shanghai"] - ) + forks_under_test = forks_from_until(fork_map["London"], fork_map["Shanghai"]) if ArrowGlacier in forks_under_test: forks_under_test.remove(ArrowGlacier) for fork_under_test in forks_under_test: - assert f":test_all_forks[fork={fork_under_test}]" in "\n".join( - result.stdout.lines - ) + assert f":test_all_forks[fork={fork_under_test}]" in "\n".join(result.stdout.lines) result.assert_outcomes( passed=len(forks_under_test), failed=0, diff --git a/src/pytest_plugins/spec_version_checker/spec_version_checker.py b/src/pytest_plugins/spec_version_checker/spec_version_checker.py index 2c952aa5fe0..05a95510033 100644 --- a/src/pytest_plugins/spec_version_checker/spec_version_checker.py +++ b/src/pytest_plugins/spec_version_checker/spec_version_checker.py @@ -48,8 +48,7 @@ class UnableToCheckReferenceSpec(Warning): def __init__(self, filler_module: str, error: Exception): super().__init__( - f"Reference spec could not be determined for " - f"{filler_module}: {error}." + f"Reference spec could not be determined for " f"{filler_module}: {error}." ) diff --git a/src/pytest_plugins/test_filler/test_filler.py b/src/pytest_plugins/test_filler/test_filler.py index b972bd9064f..e6872c01612 100644 --- a/src/pytest_plugins/test_filler/test_filler.py +++ b/src/pytest_plugins/test_filler/test_filler.py @@ -31,9 +31,7 @@ def pytest_addoption(parser): """ Adds command-line options to pytest. """ - evm_group = parser.getgroup( - "evm", "Arguments defining evm executable behavior" - ) + evm_group = parser.getgroup("evm", "Arguments defining evm executable behavior") evm_group.addoption( "--evm-bin", action="store", @@ -46,13 +44,10 @@ def pytest_addoption(parser): action="store_true", dest="evm_collect_traces", default=None, - help="Collect traces of the execution information from the " - + "transition tool", + help="Collect traces of the execution information from the " + "transition tool", ) - test_group = parser.getgroup( - "tests", "Arguments defining filler location and output" - ) + test_group = parser.getgroup("tests", "Arguments defining filler location and output") test_group.addoption( "--filler-path", action="store", @@ -219,9 +214,7 @@ def fixture_collector(request): Returns the configured fixture collector instance used for all tests in one test module. """ - fixture_collector = FixtureCollector( - output_dir=request.config.getoption("output") - ) + fixture_collector = FixtureCollector(output_dir=request.config.getoption("output")) yield fixture_collector fixture_collector.dump_fixtures() @@ -256,9 +249,7 @@ def eips(): SPEC_TYPES: List[Type[BaseTest]] = [StateTest, BlockchainTest] -SPEC_TYPES_PARAMETERS: List[str] = [ - s.pytest_parameter_name() for s in SPEC_TYPES -] +SPEC_TYPES_PARAMETERS: List[str] = [s.pytest_parameter_name() for s in SPEC_TYPES] @pytest.fixture(scope="function") @@ -359,13 +350,9 @@ class InvalidFiller(Exception): def __init__(self, message): super().__init__(message) - if ( - "state_test" in item.fixturenames - and "blockchain_test" in item.fixturenames - ): + if "state_test" in item.fixturenames and "blockchain_test" in item.fixturenames: raise InvalidFiller( - "A filler should only implement either a state test or " - "a blockchain test; not both." + "A filler should only implement either a state test or " "a blockchain test; not both." ) # Check that the test defines either test type as parameter. diff --git a/tests/eips/eip4844/test_blob_txs.py b/tests/eips/eip4844/test_blob_txs.py index 6ebbed6f909..702c91eee43 100644 --- a/tests/eips/eip4844/test_blob_txs.py +++ b/tests/eips/eip4844/test_blob_txs.py @@ -58,9 +58,7 @@ def fake_exponential(factor: int, numerator: int, denominator: int) -> int: numerator_accumulator = factor * denominator while numerator_accumulator > 0: output += numerator_accumulator - numerator_accumulator = (numerator_accumulator * numerator) // ( - denominator * i - ) + numerator_accumulator = (numerator_accumulator * numerator) // (denominator * i) i += 1 return output // denominator @@ -201,9 +199,7 @@ def total_account_minimum_balance( # noqa: D103 for tx_blob_count in [len(x) for x in blob_hashes_per_tx]: data_cost = data_gasprice * DATA_GAS_PER_BLOB * tx_blob_count total_cost += ( - (tx_gas * (block_fee_per_gas + tx_max_priority_fee_per_gas)) - + tx_value - + data_cost + (tx_gas * (block_fee_per_gas + tx_max_priority_fee_per_gas)) + tx_value + data_cost ) return total_cost @@ -304,9 +300,7 @@ def pre( # noqa: D103 blocks. """ return { - TestAddress: Account( - balance=total_account_minimum_balance + account_balance_modifier - ), + TestAddress: Account(balance=total_account_minimum_balance + account_balance_modifier), } @@ -349,8 +343,7 @@ def all_valid_blob_combinations() -> List[Tuple[int, ...]]: for seq in itertools.combinations_with_replacement( range(1, MAX_BLOBS_PER_BLOCK + 1), i ) # We iterate through all possible combinations - if sum(seq) - <= MAX_BLOBS_PER_BLOCK # And we only keep the ones that are valid + if sum(seq) <= MAX_BLOBS_PER_BLOCK # And we only keep the ones that are valid ] # We also add the reversed version of each combination, only if it's not # already in the list. E.g. (2, 1, 1) is added from (1, 1, 2) but not @@ -372,8 +365,7 @@ def invalid_blob_combinations() -> List[Tuple[int, ...]]: for seq in itertools.combinations_with_replacement( range(1, MAX_BLOBS_PER_BLOCK + 2), i ) # We iterate through all possible combinations - if sum(seq) - == MAX_BLOBS_PER_BLOCK + 1 # And we only keep the ones that match the + if sum(seq) == MAX_BLOBS_PER_BLOCK + 1 # And we only keep the ones that match the # expected invalid blob count ] # We also add the reversed version of each combination, only if it's not @@ -499,12 +491,8 @@ def test_invalid_block_blob_count( @pytest.mark.parametrize("tx_max_priority_fee_per_gas", [0, 8]) @pytest.mark.parametrize("tx_value", [0, 1]) -@pytest.mark.parametrize( - "account_balance_modifier", [-1], ids=["exact_balance_minus_1"] -) -@pytest.mark.parametrize( - "tx_error", ["insufficient_account_balance"], ids=[""] -) +@pytest.mark.parametrize("account_balance_modifier", [-1], ids=["exact_balance_minus_1"]) +@pytest.mark.parametrize("tx_error", ["insufficient_account_balance"], ids=[""]) @pytest.mark.valid_from("Cancun") def test_insufficient_balance_blob_tx( blockchain_test: BlockchainTestFiller, @@ -528,12 +516,8 @@ def test_insufficient_balance_blob_tx( "blobs_per_tx", all_valid_blob_combinations(), ) -@pytest.mark.parametrize( - "account_balance_modifier", [-1], ids=["exact_balance_minus_1"] -) -@pytest.mark.parametrize( - "tx_error", ["insufficient_account_balance"], ids=[""] -) +@pytest.mark.parametrize("account_balance_modifier", [-1], ids=["exact_balance_minus_1"]) +@pytest.mark.parametrize("tx_error", ["insufficient_account_balance"], ids=[""]) @pytest.mark.valid_from("Cancun") def test_insufficient_balance_blob_tx_combinations( blockchain_test: BlockchainTestFiller, @@ -588,14 +572,8 @@ def test_invalid_tx_blob_count( [ [[to_hash_bytes(1)]], [[to_hash_bytes(x) for x in range(2)]], - [ - add_kzg_version([to_hash_bytes(1)], BLOB_COMMITMENT_VERSION_KZG) - + [to_hash_bytes(2)] - ], - [ - [to_hash_bytes(1)] - + add_kzg_version([to_hash_bytes(2)], BLOB_COMMITMENT_VERSION_KZG) - ], + [add_kzg_version([to_hash_bytes(1)], BLOB_COMMITMENT_VERSION_KZG) + [to_hash_bytes(2)]], + [[to_hash_bytes(1)] + add_kzg_version([to_hash_bytes(2)], BLOB_COMMITMENT_VERSION_KZG)], [ add_kzg_version([to_hash_bytes(1)], BLOB_COMMITMENT_VERSION_KZG), [to_hash_bytes(2)], @@ -606,8 +584,7 @@ def test_invalid_tx_blob_count( ], [ add_kzg_version([to_hash_bytes(1)], BLOB_COMMITMENT_VERSION_KZG), - [to_hash_bytes(2)] - + add_kzg_version([to_hash_bytes(3)], BLOB_COMMITMENT_VERSION_KZG), + [to_hash_bytes(2)] + add_kzg_version([to_hash_bytes(3)], BLOB_COMMITMENT_VERSION_KZG), ], [ add_kzg_version([to_hash_bytes(1)], BLOB_COMMITMENT_VERSION_KZG), diff --git a/tests/eips/eip4844/test_blobhash_opcode.py b/tests/eips/eip4844/test_blobhash_opcode.py index 2b326a97bda..67a69164fea 100644 --- a/tests/eips/eip4844/test_blobhash_opcode.py +++ b/tests/eips/eip4844/test_blobhash_opcode.py @@ -114,9 +114,7 @@ def test_blobhash_gas_cost( gas_price=10 if tx_type < 2 else None, access_list=[] if tx_type >= 2 else None, max_priority_fee_per_gas=10 if tx_type >= 2 else None, - blob_versioned_hashes=random_blob_hashes[ - 0:TARGET_BLOB_PER_BLOCK - ] + blob_versioned_hashes=random_blob_hashes[0:TARGET_BLOB_PER_BLOCK] if tx_type >= 3 else None, ) @@ -156,9 +154,7 @@ def test_blobhash_scenarios( the valid range `[0, 2**256-1]`. """ TOTAL_BLOCKS = 5 - b_hashes_list = BlobhashScenario.create_blob_hashes_list( - length=TOTAL_BLOCKS - ) + b_hashes_list = BlobhashScenario.create_blob_hashes_list(length=TOTAL_BLOCKS) blobhash_calls = BlobhashScenario.generate_blobhash_bytecode(scenario) for i in range(TOTAL_BLOCKS): address = to_address(0x100 + i * 0x100) @@ -178,10 +174,7 @@ def test_blobhash_scenarios( ) ) post[address] = Account( - storage={ - index: b_hashes_list[i][index] - for index in range(MAX_BLOB_PER_BLOCK) - } + storage={index: b_hashes_list[i][index] for index in range(MAX_BLOB_PER_BLOCK)} ) blockchain_test( pre=pre, @@ -237,9 +230,7 @@ def test_blobhash_invalid_blob_index( ) post[address] = Account( storage={ - index: ( - 0 if index < 0 or index >= blob_per_block else blobs[index] - ) + 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_BLOB_PER_BLOCK)), @@ -266,9 +257,7 @@ def test_blobhash_multiple_txs_in_block( 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( - "single_valid" - ) + blobhash_bytecode = BlobhashScenario.generate_blobhash_bytecode("single_valid") pre = { **pre, **{ @@ -298,9 +287,7 @@ def test_blobhash_multiple_txs_in_block( ] post = { to_address(address): Account( - storage={ - i: random_blob_hashes[i] for i in range(MAX_BLOB_PER_BLOCK) - } + storage={i: random_blob_hashes[i] for i in range(MAX_BLOB_PER_BLOCK)} ) if address in (0x200, 0x400) else Account(storage={i: 0 for i in range(MAX_BLOB_PER_BLOCK)}) diff --git a/tests/eips/eip4844/test_blobhash_opcode_contexts.py b/tests/eips/eip4844/test_blobhash_opcode_contexts.py index 9eb0735d38b..80491a6cd2f 100644 --- a/tests/eips/eip4844/test_blobhash_opcode_contexts.py +++ b/tests/eips/eip4844/test_blobhash_opcode_contexts.py @@ -84,9 +84,7 @@ def create_opcode_context(pre, tx, post): to=BlobhashContext.address("blobhash_sstore"), ), { - BlobhashContext.address("blobhash_sstore"): Account( - storage={} - ), + BlobhashContext.address("blobhash_sstore"): Account(storage={}), }, ), ), @@ -94,9 +92,7 @@ def create_opcode_context(pre, tx, post): "on_CALL", create_opcode_context( { - BlobhashContext.address("call"): Account( - code=BlobhashContext.code("call") - ), + BlobhashContext.address("call"): Account(code=BlobhashContext.code("call")), BlobhashContext.address("blobhash_sstore"): Account( code=BlobhashContext.code("blobhash_sstore") ), @@ -131,10 +127,7 @@ def create_opcode_context(pre, tx, post): { BlobhashContext.address("delegatecall"): Account( storage={ - k: v - for (k, v) in zip( - range(len(simple_blob_hashes)), simple_blob_hashes - ) + k: v for (k, v) in zip(range(len(simple_blob_hashes)), simple_blob_hashes) } ), }, @@ -158,10 +151,7 @@ def create_opcode_context(pre, tx, post): { BlobhashContext.address("staticcall"): Account( storage={ - k: v - for (k, v) in zip( - range(len(simple_blob_hashes)), simple_blob_hashes - ) + k: v for (k, v) in zip(range(len(simple_blob_hashes)), simple_blob_hashes) } ), }, @@ -185,10 +175,7 @@ def create_opcode_context(pre, tx, post): { BlobhashContext.address("callcode"): Account( storage={ - k: v - for (k, v) in zip( - range(len(simple_blob_hashes)), simple_blob_hashes - ) + k: v for (k, v) in zip(range(len(simple_blob_hashes)), simple_blob_hashes) } ), }, @@ -203,14 +190,9 @@ def create_opcode_context(pre, tx, post): to=None, ), { - BlobhashContext.created_contract( - "tx_created_contract" - ): Account( + BlobhashContext.created_contract("tx_created_contract"): Account( storage={ - k: v - for (k, v) in zip( - range(len(simple_blob_hashes)), simple_blob_hashes - ) + k: v for (k, v) in zip(range(len(simple_blob_hashes)), simple_blob_hashes) } ), }, @@ -220,9 +202,7 @@ def create_opcode_context(pre, tx, post): "on_CREATE", create_opcode_context( { - BlobhashContext.address("create"): Account( - code=BlobhashContext.code("create") - ), + BlobhashContext.address("create"): Account(code=BlobhashContext.code("create")), }, tx_type_3.with_fields( data=BlobhashContext.code("initcode"), @@ -231,10 +211,7 @@ def create_opcode_context(pre, tx, post): { BlobhashContext.created_contract("create"): Account( storage={ - k: v - for (k, v) in zip( - range(len(simple_blob_hashes)), simple_blob_hashes - ) + k: v for (k, v) in zip(range(len(simple_blob_hashes)), simple_blob_hashes) } ), }, @@ -244,9 +221,7 @@ def create_opcode_context(pre, tx, post): "on_CREATE2", create_opcode_context( { - BlobhashContext.address("create2"): Account( - code=BlobhashContext.code("create2") - ), + BlobhashContext.address("create2"): Account(code=BlobhashContext.code("create2")), }, tx_type_3.with_fields( data=BlobhashContext.code("initcode"), @@ -255,10 +230,7 @@ def create_opcode_context(pre, tx, post): { BlobhashContext.created_contract("create2"): Account( storage={ - k: v - for (k, v) in zip( - range(len(simple_blob_hashes)), simple_blob_hashes - ) + k: v for (k, v) in zip(range(len(simple_blob_hashes)), simple_blob_hashes) } ), }, @@ -282,9 +254,7 @@ def create_opcode_context(pre, tx, post): access_list=[], ), { - BlobhashContext.address("blobhash_sstore"): Account( - storage={0: 0} - ), + BlobhashContext.address("blobhash_sstore"): Account(storage={0: 0}), }, ), ), @@ -305,9 +275,7 @@ def create_opcode_context(pre, tx, post): access_list=[], ), { - BlobhashContext.address("blobhash_sstore"): Account( - storage={0: 0} - ), + BlobhashContext.address("blobhash_sstore"): Account(storage={0: 0}), }, ), ), @@ -328,9 +296,7 @@ def create_opcode_context(pre, tx, post): access_list=[], ), { - BlobhashContext.address("blobhash_sstore"): Account( - storage={0: 0} - ), + BlobhashContext.address("blobhash_sstore"): Account(storage={0: 0}), }, ), ), @@ -346,9 +312,7 @@ def context(request): return request.param[1] -def test_blobhash_opcode_contexts( - context, blockchain_test: BlockchainTestFiller -): +def test_blobhash_opcode_contexts(context, blockchain_test: BlockchainTestFiller): """ Tests that the BLOBHASH opcode functions correctly when called in different contexts including: diff --git a/tests/eips/eip4844/test_excess_data_gas.py b/tests/eips/eip4844/test_excess_data_gas.py index 71f69767325..10324c615ca 100644 --- a/tests/eips/eip4844/test_excess_data_gas.py +++ b/tests/eips/eip4844/test_excess_data_gas.py @@ -64,9 +64,7 @@ def fake_exponential(factor: int, numerator: int, denominator: int) -> int: numerator_accumulator = factor * denominator while numerator_accumulator > 0: output += numerator_accumulator - numerator_accumulator = (numerator_accumulator * numerator) // ( - denominator * i - ) + numerator_accumulator = (numerator_accumulator * numerator) // (denominator * i) i += 1 return output // denominator @@ -118,11 +116,7 @@ def calc_excess_data_gas(parent_excess_data_gas: int, new_blobs: int) -> int: if parent_excess_data_gas + consumed_data_gas < TARGET_DATA_GAS_PER_BLOCK: return 0 else: - return ( - parent_excess_data_gas - + consumed_data_gas - - TARGET_DATA_GAS_PER_BLOCK - ) + return parent_excess_data_gas + consumed_data_gas - TARGET_DATA_GAS_PER_BLOCK @pytest.fixture @@ -166,9 +160,7 @@ def header_excess_data_gas( # noqa: D103 header_excess_data_gas_delta: Optional[int], ) -> Optional[int]: if header_excess_blobs_delta is not None: - return parent_excess_data_gas + ( - header_excess_blobs_delta * DATA_GAS_PER_BLOB - ) + return parent_excess_data_gas + (header_excess_blobs_delta * DATA_GAS_PER_BLOB) if header_excess_data_gas_delta is not None: return parent_excess_data_gas + header_excess_data_gas_delta return None @@ -225,9 +217,7 @@ def tx_value() -> int: # noqa: D103 @pytest.fixture -def tx_exact_cost( # noqa: D103 - tx_value: int, tx_max_fee: int, tx_data_cost: int -) -> int: +def tx_exact_cost(tx_value: int, tx_max_fee: int, tx_data_cost: int) -> int: # noqa: D103 tx_gas = 21000 return (tx_gas * tx_max_fee) + tx_value + tx_data_cost @@ -245,9 +235,7 @@ def destination_account() -> str: # noqa: D103 @pytest.fixture -def post( # noqa: D103 - destination_account: str, tx_value: int -) -> Mapping[str, Account]: +def post(destination_account: str, tx_value: int) -> Mapping[str, Account]: # noqa: D103 return { destination_account: Account(balance=tx_value), } @@ -307,9 +295,7 @@ def blocks( # noqa: D103 @pytest.mark.parametrize("new_blobs", range(0, MAX_BLOBS_PER_BLOCK + 1)) -@pytest.mark.parametrize( - "parent_excess_blobs", range(0, TARGET_BLOBS_PER_BLOCK + 1) -) +@pytest.mark.parametrize("parent_excess_blobs", range(0, TARGET_BLOBS_PER_BLOCK + 1)) def test_correct_excess_data_gas_calculation( blockchain_test: BlockchainTestFiller, env: Environment, @@ -482,11 +468,7 @@ def test_invalid_excess_data_gas_above_target_change( @pytest.mark.parametrize("header_excess_blobs_delta", [0]) @pytest.mark.parametrize( "new_blobs", - [ - b - for b in range(0, MAX_BLOBS_PER_BLOCK + 1) - if b != TARGET_BLOBS_PER_BLOCK - ], + [b for b in range(0, MAX_BLOBS_PER_BLOCK + 1) if b != TARGET_BLOBS_PER_BLOCK], ) def test_invalid_static_excess_data_gas( blockchain_test: BlockchainTestFiller, @@ -520,9 +502,7 @@ def test_invalid_static_excess_data_gas( ) -@pytest.mark.parametrize( - "header_excess_blobs_delta", range(1, MAX_BLOBS_PER_BLOCK) -) +@pytest.mark.parametrize("header_excess_blobs_delta", range(1, MAX_BLOBS_PER_BLOCK)) @pytest.mark.parametrize("new_blobs", range(0, TARGET_BLOBS_PER_BLOCK + 1)) @pytest.mark.parametrize("parent_excess_blobs", [0]) # Start at 0 def test_invalid_excess_data_gas_target_blobs_increase_from_zero( @@ -558,9 +538,7 @@ def test_invalid_excess_data_gas_target_blobs_increase_from_zero( @pytest.mark.parametrize("header_excess_blobs_delta", [0]) -@pytest.mark.parametrize( - "new_blobs", range(TARGET_BLOBS_PER_BLOCK + 1, MAX_BLOBS_PER_BLOCK + 1) -) +@pytest.mark.parametrize("new_blobs", range(TARGET_BLOBS_PER_BLOCK + 1, MAX_BLOBS_PER_BLOCK + 1)) @pytest.mark.parametrize("parent_excess_blobs", [0]) # Start at 0 def test_invalid_static_excess_data_gas_from_zero_on_blobs_above_target( blockchain_test: BlockchainTestFiller, @@ -604,8 +582,7 @@ def test_invalid_static_excess_data_gas_from_zero_on_blobs_above_target( # header_excess_blobs_delta range(-TARGET_BLOBS_PER_BLOCK, TARGET_BLOBS_PER_BLOCK + 1), ) - if c[1] - != c[0] - TARGET_BLOBS_PER_BLOCK # Only get incorrect combinations + if c[1] != c[0] - TARGET_BLOBS_PER_BLOCK # Only get incorrect combinations ], ) def test_invalid_excess_data_gas_change( @@ -642,10 +619,7 @@ def test_invalid_excess_data_gas_change( @pytest.mark.parametrize( "header_excess_data_gas", - [ - (2**64 + (x * DATA_GAS_PER_BLOB)) - for x in range(-TARGET_BLOBS_PER_BLOCK, 0) - ], + [(2**64 + (x * DATA_GAS_PER_BLOB)) for x in range(-TARGET_BLOBS_PER_BLOCK, 0)], ) @pytest.mark.parametrize("new_blobs", range(TARGET_BLOBS_PER_BLOCK)) @pytest.mark.parametrize("parent_excess_blobs", range(TARGET_BLOBS_PER_BLOCK)) diff --git a/tests/eips/eip4844/test_excess_data_gas_fork_transition.py b/tests/eips/eip4844/test_excess_data_gas_fork_transition.py index e19e49b4e18..7e66e9aa1cd 100644 --- a/tests/eips/eip4844/test_excess_data_gas_fork_transition.py +++ b/tests/eips/eip4844/test_excess_data_gas_fork_transition.py @@ -45,9 +45,7 @@ def fake_exponential(factor: int, numerator: int, denominator: int) -> int: numerator_accumulator = factor * denominator while numerator_accumulator > 0: output += numerator_accumulator - numerator_accumulator = (numerator_accumulator * numerator) // ( - denominator * i - ) + numerator_accumulator = (numerator_accumulator * numerator) // (denominator * i) i += 1 return output // denominator @@ -105,11 +103,7 @@ def calc_excess_data_gas(parent_excess_data_gas: int, new_blobs: int) -> int: if parent_excess_data_gas + consumed_data_gas < TARGET_DATA_GAS_PER_BLOCK: return 0 else: - return ( - parent_excess_data_gas - + consumed_data_gas - - TARGET_DATA_GAS_PER_BLOCK - ) + return parent_excess_data_gas + consumed_data_gas - TARGET_DATA_GAS_PER_BLOCK @pytest.fixture @@ -176,10 +170,7 @@ def post_fork_blocks( max_fee_per_data_gas=100, access_list=[], blob_versioned_hashes=add_kzg_version( - [ - to_hash_bytes(x) - for x in range(blob_count_per_block) - ], + [to_hash_bytes(x) for x in range(blob_count_per_block)], BLOB_COMMITMENT_VERSION_KZG, ), ) @@ -268,9 +259,7 @@ def test_invalid_post_fork_block_without_excess_data_gas( "post_fork_block_count,blob_count_per_block", [ ( - BLOBS_TO_DATA_GAS_COST_INCREASE - // (MAX_BLOBS_PER_BLOCK - TARGET_BLOBS_PER_BLOCK) - + 2, + BLOBS_TO_DATA_GAS_COST_INCREASE // (MAX_BLOBS_PER_BLOCK - TARGET_BLOBS_PER_BLOCK) + 2, MAX_BLOBS_PER_BLOCK, ), (10, 0), diff --git a/tests/eips/eip4844/test_point_evaluation_precompile.py b/tests/eips/eip4844/test_point_evaluation_precompile.py index cb744781bca..4a03bcd9961 100644 --- a/tests/eips/eip4844/test_point_evaluation_precompile.py +++ b/tests/eips/eip4844/test_point_evaluation_precompile.py @@ -30,9 +30,7 @@ POINT_EVALUATION_PRECOMPILE_GAS = 50_000 BLOB_COMMITMENT_VERSION_KZG = b"\x01" -BLS_MODULUS = ( - 0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001 -) +BLS_MODULUS = 0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001 BLS_MODULUS_BYTES = BLS_MODULUS.to_bytes(32, "big") FIELD_ELEMENTS_PER_BLOB = 4096 FIELD_ELEMENTS_PER_BLOB_BYTES = FIELD_ELEMENTS_PER_BLOB.to_bytes(32, "big") @@ -57,9 +55,7 @@ def kzg_to_versioned_hash( 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" - ) + blob_commitment_version_kzg = blob_commitment_version_kzg.to_bytes(1, "big") return blob_commitment_version_kzg + sha256(kzg_commitment).digest()[1:] @@ -254,9 +250,7 @@ def post( @pytest.mark.parametrize( "z,y,kzg_commitment,kzg_proof,versioned_hash", [ - pytest.param( - BLS_MODULUS - 1, 0, INF_POINT, INF_POINT, auto, id="in_bounds_z" - ), + pytest.param(BLS_MODULUS - 1, 0, INF_POINT, INF_POINT, auto, id="in_bounds_z"), ], ) @pytest.mark.parametrize("success", [True]) @@ -412,13 +406,9 @@ def all_external_vectors() -> List: test_cases = [] for test_file in get_point_evaluation_test_files_in_directory( - os.path.join( - current_python_script_directory(), "point_evaluation_vectors" - ) + os.path.join(current_python_script_directory(), "point_evaluation_vectors") ): - file_loaded_tests = load_kzg_point_evaluation_test_vectors_from_file( - test_file - ) + file_loaded_tests = load_kzg_point_evaluation_test_vectors_from_file(test_file) assert len(file_loaded_tests) > 0 test_cases += file_loaded_tests @@ -528,9 +518,7 @@ def test_point_evaluation_precompile_gas_tx_to( } # Gas is appended the intrinsic gas cost of the transaction - intrinsic_gas_cost = 21_000 + eip_2028_transaction_data_cost( - precompile_input - ) + intrinsic_gas_cost = 21_000 + eip_2028_transaction_data_cost(precompile_input) # Consumed gas will only be the precompile gas if the proof is correct and # the call gas is sufficient. @@ -620,9 +608,7 @@ def tx_generator() -> Iterator[Transaction]: PRE_FORK_BLOCK_RANGE = range(999, FORK_TIMESTAMP, 1_000) # Blocks before fork - blocks = [ - Block(timestamp=t, txs=[next(iter_tx)]) for t in PRE_FORK_BLOCK_RANGE - ] + blocks = [Block(timestamp=t, txs=[next(iter_tx)]) for t in PRE_FORK_BLOCK_RANGE] # Block after fork blocks += [Block(timestamp=FORK_TIMESTAMP, txs=[next(iter_tx)])] diff --git a/tests/eips/eip4844/test_point_evaluation_precompile_gas.py b/tests/eips/eip4844/test_point_evaluation_precompile_gas.py index 13308f6a7f7..8931b393d37 100644 --- a/tests/eips/eip4844/test_point_evaluation_precompile_gas.py +++ b/tests/eips/eip4844/test_point_evaluation_precompile_gas.py @@ -40,9 +40,7 @@ def kzg_to_versioned_hash( 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" - ) + blob_commitment_version_kzg = blob_commitment_version_kzg.to_bytes(1, "big") return blob_commitment_version_kzg + sha256(kzg_commitment).digest()[1:] diff --git a/tests/eips/eip4844/util_blobhash.py b/tests/eips/eip4844/util_blobhash.py index de89b43cc6e..2f78f900191 100644 --- a/tests/eips/eip4844/util_blobhash.py +++ b/tests/eips/eip4844/util_blobhash.py @@ -296,9 +296,7 @@ def generate_blobhash_bytecode(cls, scenario_name: str) -> bytes: Returns BLOBHASH bytecode for the given scenario. """ scenarios = { - "single_valid": b"".join( - cls.blobhash_sstore(i) for i in range(MAX_BLOB_PER_BLOCK) - ), + "single_valid": b"".join(cls.blobhash_sstore(i) for i in range(MAX_BLOB_PER_BLOCK)), "repeated_valid": b"".join( b"".join(cls.blobhash_sstore(i) for _ in range(10)) for i in range(MAX_BLOB_PER_BLOCK) @@ -310,14 +308,11 @@ def generate_blobhash_bytecode(cls, scenario_name: str) -> bytes: for i in range(MAX_BLOB_PER_BLOCK) ), "varied_valid": b"".join( - cls.blobhash_sstore(i) - + cls.blobhash_sstore(i + 1) - + cls.blobhash_sstore(i) + cls.blobhash_sstore(i) + cls.blobhash_sstore(i + 1) + cls.blobhash_sstore(i) for i in range(MAX_BLOB_PER_BLOCK - 1) ), "invalid_calls": b"".join( - cls.blobhash_sstore(i) - for i in range(-5, MAX_BLOB_PER_BLOCK + 5) + cls.blobhash_sstore(i) for i in range(-5, MAX_BLOB_PER_BLOCK + 5) ), } scenario = scenarios.get(scenario_name) diff --git a/tests/eips/test_eip3651.py b/tests/eips/test_eip3651.py index ca15a1cf7d5..da85cbb2d49 100644 --- a/tests/eips/test_eip3651.py +++ b/tests/eips/test_eip3651.py @@ -94,9 +94,7 @@ def test_warm_coinbase_call_out_of_gas( pre = { TestAddress: Account(balance=1000000000000000000000), caller_address: Account(code=caller_code), - to_address(contract_under_test_address): Account( - code=contract_under_test_code - ), + to_address(contract_under_test_address): Account(code=contract_under_test_code), } tx = Transaction( diff --git a/tests/eips/test_eip3855.py b/tests/eips/test_eip3855.py index cbd2625d839..67eb410a9e8 100644 --- a/tests/eips/test_eip3855.py +++ b/tests/eips/test_eip3855.py @@ -174,14 +174,7 @@ def test_push0_before_jumpdest( """ Jump to a JUMPDEST next to a PUSH0, must succeed. """ - code = ( - Op.PUSH1(4) - + Op.JUMP - + Op.PUSH0 - + Op.JUMPDEST - + Op.SSTORE(Op.PUSH0, 1) - + Op.STOP - ) + code = Op.PUSH1(4) + Op.JUMP + Op.PUSH0 + Op.JUMPDEST + Op.SSTORE(Op.PUSH0, 1) + Op.STOP pre[addr_1] = Account(code=code) post[addr_1] = Account(storage={0x00: 0x01}) diff --git a/tests/eips/test_eip3860.py b/tests/eips/test_eip3860.py index 1679481b674..ed4c8260eee 100644 --- a/tests/eips/test_eip3860.py +++ b/tests/eips/test_eip3860.py @@ -69,9 +69,7 @@ def calculate_create2_word_cost(length: int) -> int: return KECCAK_WORD_COST * ceiling_division(length, 32) -def calculate_create_tx_intrinsic_cost( - initcode: Initcode, eip_3860_active: bool -) -> int: +def calculate_create_tx_intrinsic_cost(initcode: Initcode, eip_3860_active: bool) -> int: """ Calculates the intrinsic gas cost of a transaction that contains initcode and creates a contract @@ -79,9 +77,7 @@ def calculate_create_tx_intrinsic_cost( cost = ( BASE_TRANSACTION_GAS # G_transaction + CREATE_CONTRACT_BASE_GAS # G_transaction_create - + eip_2028_transaction_data_cost( - initcode.assemble() - ) # Transaction calldata cost + + eip_2028_transaction_data_cost(initcode.assemble()) # Transaction calldata cost ) if eip_3860_active: cost += calculate_initcode_word_cost(len(initcode.assemble())) @@ -96,9 +92,7 @@ def calculate_create_tx_execution_cost( Calculates the total execution gas cost of a transaction that contains initcode and creates a contract """ - cost = calculate_create_tx_intrinsic_cost( - initcode=initcode, eip_3860_active=eip_3860_active - ) + cost = calculate_create_tx_intrinsic_cost(initcode=initcode, eip_3860_active=eip_3860_active) cost += initcode.deployment_gas cost += initcode.execution_gas return cost @@ -202,9 +196,7 @@ def get_initcode_name(val): ], ids=get_initcode_name, ) -def test_contract_creating_tx( - blockchain_test: BlockchainTestFiller, initcode: Initcode -): +def test_contract_creating_tx(blockchain_test: BlockchainTestFiller, initcode: Initcode): """ Test cases using a contract creating transaction @@ -406,19 +398,12 @@ def post( Test that contract creation fails unless enough execution gas is provided. """ - if ( - gas_test_case == "exact_intrinsic_gas" - and exact_intrinsic_gas == exact_execution_gas - ): + if gas_test_case == "exact_intrinsic_gas" and exact_intrinsic_gas == exact_execution_gas: # Special scenario where the execution of the initcode and # gas cost to deploy are zero - return { - created_contract_address: Account(code=initcode.deploy_code) - } + return {created_contract_address: Account(code=initcode.deploy_code)} elif gas_test_case == "exact_execution_gas": - return { - created_contract_address: Account(code=initcode.deploy_code) - } + return {created_contract_address: Account(code=initcode.deploy_code)} return {created_contract_address: Account.NONEXISTENT} def test_gas_usage( @@ -517,9 +502,7 @@ def create_code(self, opcode: Op, initcode: Initcode): # noqa: D102 ) @pytest.fixture - def created_contract_address( # noqa: D102 - self, initcode: Initcode, opcode: Op - ): + def created_contract_address(self, initcode: Initcode, opcode: Op): # noqa: D102 if opcode == Op.CREATE: return compute_create_address( address=0x100, @@ -615,16 +598,12 @@ def test_create_opcode_initcode( if opcode == Op.CREATE2: # CREATE2 hashing cost should only be deducted if the initcode # does not exceed the max length - expected_gas_usage += calculate_create2_word_cost( - len(initcode.assemble()) - ) + expected_gas_usage += calculate_create2_word_cost(len(initcode.assemble())) if eip_3860_active: # Initcode word cost is only deducted if the length check # succeeds - expected_gas_usage += calculate_initcode_word_cost( - len(initcode.assemble()) - ) + expected_gas_usage += calculate_initcode_word_cost(len(initcode.assemble())) # Call returns 1 as valid initcode length s[0]==1 && s[1]==1 post[to_address(0x200)] = Account( diff --git a/tests/example/test_acl_example.py b/tests/example/test_acl_example.py index 05768ec555e..a41448b9da3 100644 --- a/tests/example/test_acl_example.py +++ b/tests/example/test_acl_example.py @@ -42,11 +42,11 @@ def test_access_list(state_test: StateTestFiller, fork: Fork): AccessList( address="0x0000000000000000000000000000000000000000", storage_keys=[ - "0x0000000000000000000000000000000000000000000000000000000000000000", # noqa: E501 + "0x0000000000000000000000000000000000000000000000000000000000000000", ], ) ], - secret_key="0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", # noqa: E501 + secret_key="0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", protected=True, ) @@ -57,9 +57,7 @@ def test_access_list(state_test: StateTestFiller, fork: Fork): nonce=1, ), "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba": Account( - balance=0x1BC16D674EC80000 - if is_fork(fork, London) - else 0x1BC16D674ECB26CE, + balance=0x1BC16D674EC80000 if is_fork(fork, London) else 0x1BC16D674ECB26CE, ), "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account( balance=0x2CD931, diff --git a/tests/security/test_selfdestruct_balance_bug.py b/tests/security/test_selfdestruct_balance_bug.py index 748d63f9f68..ed2158b6665 100644 --- a/tests/security/test_selfdestruct_balance_bug.py +++ b/tests/security/test_selfdestruct_balance_bug.py @@ -64,9 +64,9 @@ def test_tx_selfdestruct_balance_bug(blockchain_test: BlockchainTestFiller): """ ) - cc_code = Op.SSTORE( - 0xCA1101, Op.CALL(100000, 0xAA, 0, 0, 0, 0, 0) - ) + Op.CALL(100000, 0xAA, 1, 0, 0, 0, 0) + cc_code = Op.SSTORE(0xCA1101, Op.CALL(100000, 0xAA, 0, 0, 0, 0, 0)) + Op.CALL( + 100000, 0xAA, 1, 0, 0, 0, 0 + ) balance_code = Op.SSTORE(0xBA1AA, Op.BALANCE(0xAA)) diff --git a/tests/vm/test_chain_id.py b/tests/vm/test_chain_id.py index 62a42d082da..f3ce1446c3c 100644 --- a/tests/vm/test_chain_id.py +++ b/tests/vm/test_chain_id.py @@ -44,9 +44,7 @@ def test_chain_id(state_test: StateTestFiller): ) post = { - to_address(0x100): Account( - code="0x4660015500", storage={"0x01": "0x01"} - ), + to_address(0x100): Account(code="0x4660015500", storage={"0x01": "0x01"}), } state_test(env=env, pre=pre, post=post, txs=[tx]) diff --git a/tests/vm/test_dup.py b/tests/vm/test_dup.py index 4f73a4f18c7..2e2229450e5 100644 --- a/tests/vm/test_dup.py +++ b/tests/vm/test_dup.py @@ -18,11 +18,7 @@ def test_dup(state_test: StateTestFiller): Original test by: Ori Pomerantz qbzzt1@gmail.com """ env = Environment() - pre = { - "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account( - balance=1000000000000000000000 - ) - } + pre = {"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": Account(balance=1000000000000000000000)} txs = [] post = {} diff --git a/tests/withdrawals/test_withdrawals.py b/tests/withdrawals/test_withdrawals.py index 702de46f252..3118b0a0113 100644 --- a/tests/withdrawals/test_withdrawals.py +++ b/tests/withdrawals/test_withdrawals.py @@ -29,9 +29,7 @@ ONE_GWEI = 10**9 -def set_withdrawal_index( - withdrawals: List[Withdrawal], start_index: int = 0 -) -> None: +def set_withdrawal_index(withdrawals: List[Withdrawal], start_index: int = 0) -> None: """ Automatically set the index of each withdrawal in a list in sequential order. @@ -79,17 +77,11 @@ def withdrawal(self, tx: Transaction): # noqa: D102 ) @pytest.fixture - def blocks( # noqa: D102 - self, tx: Transaction, withdrawal: Withdrawal, test_case - ): + def blocks(self, tx: Transaction, withdrawal: Withdrawal, test_case): # noqa: D102 if test_case == "tx_in_withdrawals_block": return [ Block( - txs=[ - tx.with_error( - "intrinsic gas too low: have 0, want 21000" - ) - ], + txs=[tx.with_error("intrinsic gas too low: have 0, want 21000")], withdrawals=[ withdrawal, ], @@ -587,9 +579,7 @@ class ZeroAmountTestCases(Enum): # noqa: D101 TWO_ZERO = "two_withdrawals_no_value" THREE_ONE_WITH_VALUE = "three_withdrawals_one_with_value" FOUR_ONE_WITH_MAX = "four_withdrawals_one_with_value_one_with_max" - FOUR_ONE_WITH_MAX_REVERSED = ( - "four_withdrawals_one_with_value_one_with_max_reversed_order" - ) + FOUR_ONE_WITH_MAX_REVERSED = "four_withdrawals_one_with_value_one_with_max_reversed_order" @pytest.mark.parametrize(