diff --git a/eth/_utils/datatypes.py b/eth/_utils/datatypes.py index 2ec5fdd0e7..609ebbda1c 100644 --- a/eth/_utils/datatypes.py +++ b/eth/_utils/datatypes.py @@ -88,9 +88,9 @@ def configure(cls: Type[T], continue elif not hasattr(cls, key): raise TypeError( - "The {0}.configure cannot set attributes that are not " - "already present on the base class. The attribute `{1}` was " - "not found on the base class `{2}`".format(cls.__name__, key, cls) + "The {}.configure cannot set attributes that are not " + "already present on the base class. The attribute `{}` was " + "not found on the base class `{}`".format(cls.__name__, key, cls) ) # overrides that are for sub-properties of this class @@ -110,10 +110,10 @@ def configure(cls: Type[T], if not isinstance(sub_cls, type) or not issubclass(sub_cls, Configurable): raise TypeError( - "Unable to configure property `{0}` on class `{1}`. The " + "Unable to configure property `{}` on class `{}`. The " "property being configured must be a subclass of the " "`Configurable` type. Instead got the following object " - "instance: {2}".format( + "instance: {}".format( key, repr(cls), repr(sub_cls), diff --git a/eth/_utils/empty.py b/eth/_utils/empty.py index bc4a0b2f0d..9867d04de5 100644 --- a/eth/_utils/empty.py +++ b/eth/_utils/empty.py @@ -1,4 +1,4 @@ -class Empty(object): +class Empty: pass diff --git a/eth/_utils/env.py b/eth/_utils/env.py index 264753bf6b..dd275acb6b 100644 --- a/eth/_utils/env.py +++ b/eth/_utils/env.py @@ -18,14 +18,14 @@ # No set literals because we support Python 2.6. -TRUE_VALUES = set(( +TRUE_VALUES = { True, 'True', 'true', -)) +} -class empty(object): +class empty: """ We use this sentinel object, instead of None, as None is a plausible value for a default in real Python code. @@ -49,7 +49,7 @@ def get_env_value(name: str, required: bool=False, default: Any=empty) -> str: value = os.environ[name] except KeyError: raise KeyError( - "Must set environment variable {0}".format(name) + f"Must set environment variable {name}" ) else: value = os.environ.get(name, default) diff --git a/eth/_utils/headers.py b/eth/_utils/headers.py index e08690e7f8..ee3d4a3baa 100644 --- a/eth/_utils/headers.py +++ b/eth/_utils/headers.py @@ -47,8 +47,8 @@ def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int: if gas_limit_floor < GAS_LIMIT_MINIMUM: raise ValueError( "The `gas_limit_floor` value must be greater than the " - "GAS_LIMIT_MINIMUM. Got {0}. Must be greater than " - "{1}".format(gas_limit_floor, GAS_LIMIT_MINIMUM) + "GAS_LIMIT_MINIMUM. Got {}. Must be greater than " + "{}".format(gas_limit_floor, GAS_LIMIT_MINIMUM) ) decay = parent_header.gas_limit // GAS_LIMIT_EMA_DENOMINATOR diff --git a/eth/_utils/module_loading.py b/eth/_utils/module_loading.py index 08bebb75d3..e36474afd6 100644 --- a/eth/_utils/module_loading.py +++ b/eth/_utils/module_loading.py @@ -26,7 +26,7 @@ def import_string(dotted_path: str) -> ModuleType: try: return getattr(module, class_name) except AttributeError: - msg = 'Module "%s" does not define a "%s" attribute/class' % ( + msg = 'Module "{}" does not define a "{}" attribute/class'.format( module_path, class_name) raise ImportError(msg) @@ -48,7 +48,7 @@ def split_at_longest_importable_path(dotted_path: str) -> Tuple[str, str]: operator.attrgetter(remainder)(module) except AttributeError: raise ImportError( - "Unable to derive appropriate import path for {0}".format( + "Unable to derive appropriate import path for {}".format( dotted_path, ) ) diff --git a/eth/_utils/numeric.py b/eth/_utils/numeric.py index ed21d651d2..eeadaed816 100644 --- a/eth/_utils/numeric.py +++ b/eth/_utils/numeric.py @@ -22,19 +22,19 @@ def int_to_bytes32(value: Union[int, bool]) -> Hash32: if not isinstance(value, int) or isinstance(value, bool): raise ValueError( - "Value must be an integer: Got: {0}".format( + "Value must be an integer: Got: {}".format( type(value), ) ) if value < 0: raise ValueError( - "Value cannot be negative: Got: {0}".format( + "Value cannot be negative: Got: {}".format( value, ) ) if value > UINT_256_MAX: raise ValueError( - "Value exeeds maximum UINT256 size. Got: {0}".format( + "Value exeeds maximum UINT256 size. Got: {}".format( value, ) ) @@ -112,13 +112,13 @@ def integer_squareroot(value: int) -> int: """ if not isinstance(value, int) or isinstance(value, bool): raise ValueError( - "Value must be an integer: Got: {0}".format( + "Value must be an integer: Got: {}".format( type(value), ) ) if value < 0: raise ValueError( - "Value cannot be negative: Got: {0}".format( + "Value cannot be negative: Got: {}".format( value, ) ) diff --git a/eth/_utils/rlp.py b/eth/_utils/rlp.py index 3c3ba83b83..fe3748f54e 100644 --- a/eth/_utils/rlp.py +++ b/eth/_utils/rlp.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import rlp from typing import ( Iterable, @@ -34,7 +32,7 @@ def diff_rlp_object(left: BaseBlock, sub_diff = diff_rlp_object(left_value, right_value) for sub_field_name, sub_left_value, sub_right_value in sub_diff: yield ( - "{0}.{1}".format(field_name, sub_field_name), + f"{field_name}.{sub_field_name}", sub_left_value, sub_right_value, ) @@ -83,7 +81,7 @@ def validate_rlp_equal(obj_a: BaseBlock, "Mismatch between {obj_a_name} and {obj_b_name} on {0} fields:\n - {1}".format( len(diff), "\n - ".join(tuple( - "{0}:\n (actual) : {1}\n (expected): {2}".format( + "{}:\n (actual) : {}\n (expected): {}".format( field_name.ljust(longest_field_name, ' '), actual, expected, diff --git a/eth/_utils/state.py b/eth/_utils/state.py index 46a2f41777..26e5fd2455 100644 --- a/eth/_utils/state.py +++ b/eth/_utils/state.py @@ -35,7 +35,7 @@ def diff_state( if actual_storage_value != expected_storage_value: yield ( account, - 'storage[{0}]'.format(slot), + f'storage[{slot}]', actual_storage_value, expected_storage_value, ) diff --git a/eth/_utils/transactions.py b/eth/_utils/transactions.py index 24ac4980b8..bcaf17d53e 100644 --- a/eth/_utils/transactions.py +++ b/eth/_utils/transactions.py @@ -92,7 +92,7 @@ def validate_transaction_signature(transaction: BaseTransaction) -> None: try: public_key = signature.recover_public_key_from_msg(message) except BadSignature as e: - raise ValidationError("Bad Signature: {0}".format(str(e))) + raise ValidationError("Bad Signature: {}".format(str(e))) if not signature.verify_msg(message, public_key): raise ValidationError("Invalid Signature") diff --git a/eth/chains/base.py b/eth/chains/base.py index 5b80960c53..9df111408f 100644 --- a/eth/chains/base.py +++ b/eth/chains/base.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import operator import random from typing import ( @@ -129,7 +127,7 @@ def get_vm_class_for_block_number(cls, block_number: BlockNumber) -> Type[Virtua if block_number >= start_block: return vm_class else: - raise VMNotFound("No vm available for block #{0}".format(block_number)) + raise VMNotFound(f"No vm available for block #{block_number}") @classmethod def get_vm_class(cls, header: BlockHeaderAPI) -> Type[VirtualMachineAPI]: @@ -172,7 +170,7 @@ def validate_chain( vm_class.validate_header(child, parent, check_seal=should_check_seal) except ValidationError as exc: raise ValidationError( - "%s is not a valid child of %s: %s" % ( + "{} is not a valid child of {}: {}".format( child, parent, exc, @@ -247,7 +245,7 @@ def from_genesis(cls, # the computed state from the initialized state database. raise ValidationError( "The provided genesis state root does not match the computed " - "genesis state root. Got {0}. Expected {1}".format( + "genesis state root. Got {}. Expected {}".format( state.state_root, genesis_params['state_root'], ) @@ -609,11 +607,11 @@ def validate_gaslimit(self, header: BlockHeaderAPI) -> None: low_bound, high_bound = compute_gas_limit_bounds(parent_header) if header.gas_limit < low_bound: raise ValidationError( - "The gas limit on block {0} is too low: {1}. It must be at least {2}".format( + "The gas limit on block {} is too low: {}. It must be at least {}".format( encode_hex(header.hash), header.gas_limit, low_bound)) elif header.gas_limit > high_bound: raise ValidationError( - "The gas limit on block {0} is too high: {1}. It must be at most {2}".format( + "The gas limit on block {} is too high: {}. It must be at most {}".format( encode_hex(header.hash), header.gas_limit, high_bound)) def validate_uncles(self, block: BlockAPI) -> None: @@ -639,7 +637,7 @@ def validate_uncles(self, block: BlockAPI) -> None: if duplicate_uncles: raise ValidationError( "Block contains duplicate uncles:\n" - " - {0}".format(' - '.join(duplicate_uncles)) + " - {}".format(' - '.join(duplicate_uncles)) ) recent_ancestors = tuple( @@ -657,13 +655,13 @@ def validate_uncles(self, block: BlockAPI) -> None: # ensure the uncle has not already been included. if uncle.hash in recent_uncle_hashes: raise ValidationError( - "Duplicate uncle: {0}".format(encode_hex(uncle.hash)) + "Duplicate uncle: {}".format(encode_hex(uncle.hash)) ) # ensure that the uncle is not one of the canonical chain blocks. if uncle.hash in recent_ancestor_hashes: raise ValidationError( - "Uncle {0} cannot be an ancestor of {1}".format( + "Uncle {} cannot be an ancestor of {}".format( encode_hex(uncle.hash), encode_hex(block.hash))) # ensure that the uncle was built off of one of the canonical chain @@ -671,7 +669,7 @@ def validate_uncles(self, block: BlockAPI) -> None: if uncle.parent_hash not in recent_ancestor_hashes or ( uncle.parent_hash == block.header.parent_hash): raise ValidationError( - "Uncle's parent {0} is not an ancestor of {1}".format( + "Uncle's parent {} is not an ancestor of {}".format( encode_hex(uncle.parent_hash), encode_hex(block.hash))) # Now perform VM level validation of the uncle @@ -681,7 +679,7 @@ def validate_uncles(self, block: BlockAPI) -> None: uncle_parent = self.get_block_header_by_hash(uncle.parent_hash) except HeaderNotFound: raise ValidationError( - "Uncle ancestor not found: {0}".format(uncle.parent_hash) + f"Uncle ancestor not found: {uncle.parent_hash}" ) uncle_vm_class = self.get_vm_class_for_block_number(uncle.block_number) diff --git a/eth/chains/tester/__init__.py b/eth/chains/tester/__init__.py index 7316b9a9ed..f29be459c6 100644 --- a/eth/chains/tester/__init__.py +++ b/eth/chains/tester/__init__.py @@ -34,7 +34,7 @@ from eth.vm.forks.homestead import HomesteadVM -class MaintainGasLimitMixin(object): +class MaintainGasLimitMixin: @classmethod def create_header_from_parent(cls, parent_header: BlockHeaderAPI, @@ -43,7 +43,7 @@ def create_header_from_parent(cls, Call the parent class method maintaining the same gas_limit as the previous block. """ - return super(MaintainGasLimitMixin, cls).create_header_from_parent( # type: ignore + return super().create_header_from_parent( # type: ignore parent_header, **assoc(header_params, 'gas_limit', parent_header.gas_limit) ) @@ -81,17 +81,17 @@ def _generate_vm_configuration(*fork_start_blocks: ForkStartBlocks, # Validate that there are no fork names which are not represented in the # mainnet chain. - fork_names = set( + fork_names = { fork_name for _, fork_name in fork_start_blocks if isinstance(fork_name, str) - ) + } unknown_forks = sorted(fork_names.difference( MAINNET_VMS.keys() )) if unknown_forks: - raise ValidationError("Configuration contains unknown forks: {0}".format(unknown_forks)) + raise ValidationError(f"Configuration contains unknown forks: {unknown_forks}") # Validate that *if* an explicit value was passed in for dao_start_block # that the Homestead fork rules are part of the VM configuration. @@ -103,7 +103,7 @@ def _generate_vm_configuration(*fork_start_blocks: ForkStartBlocks, ) # If no VM is set to start at block 0, default to the frontier VM - start_blocks = set(start_block for start_block, _ in fork_start_blocks) + start_blocks = {start_block for start_block, _ in fork_start_blocks} if 0 not in start_blocks: yield GENESIS_BLOCK_NUMBER, MAINNET_VMS['frontier'] diff --git a/eth/db/chain.py b/eth/db/chain.py index 083c3645f9..f6d0388727 100644 --- a/eth/db/chain.py +++ b/eth/db/chain.py @@ -87,7 +87,7 @@ def get_block_uncles(self, uncles_hash: Hash32) -> Tuple[BlockHeaderAPI, ...]: encoded_uncles = self.db[uncles_hash] except KeyError: raise HeaderNotFound( - "No uncles found for hash {0}".format(uncles_hash) + f"No uncles found for hash {uncles_hash}" ) else: return tuple(rlp.decode(encoded_uncles, sedes=rlp.sedes.CountableList(BlockHeader))) @@ -298,7 +298,7 @@ def get_transaction_by_index( try: block_header = self.get_canonical_block_header_by_number(block_number) except HeaderNotFound: - raise TransactionNotFound("Block {} is not in the canonical chain".format(block_number)) + raise TransactionNotFound(f"Block {block_number} is not in the canonical chain") transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root) encoded_index = rlp.encode(transaction_index) encoded_transaction = transaction_db[encoded_index] @@ -306,7 +306,7 @@ def get_transaction_by_index( return rlp.decode(encoded_transaction, sedes=transaction_class) else: raise TransactionNotFound( - "No transaction is at index {} of block {}".format(transaction_index, block_number)) + f"No transaction is at index {transaction_index} of block {block_number}") def get_transaction_index(self, transaction_hash: Hash32) -> Tuple[BlockNumber, int]: """ @@ -337,7 +337,7 @@ def get_receipt_by_index(self, try: block_header = self.get_canonical_block_header_by_number(block_number) except HeaderNotFound: - raise ReceiptNotFound("Block {} is not in the canonical chain".format(block_number)) + raise ReceiptNotFound(f"Block {block_number} is not in the canonical chain") receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root) receipt_key = rlp.encode(receipt_index) @@ -346,7 +346,7 @@ def get_receipt_by_index(self, return rlp.decode(receipt_data, sedes=Receipt) else: raise ReceiptNotFound( - "Receipt with index {} not found in block".format(receipt_index)) + f"Receipt with index {receipt_index} not found in block") @staticmethod def _get_block_transaction_data(db: DatabaseAPI, transaction_root: Hash32) -> Iterable[Hash32]: diff --git a/eth/db/diff.py b/eth/db/diff.py index aa84cb7389..28098f4636 100644 --- a/eth/db/diff.py +++ b/eth/db/diff.py @@ -143,11 +143,11 @@ def __repr__(self) -> str: if val is DELETED ] updated = [ - "key=%s to val=%s" % (encode_hex(key), encode_hex(cast(bytes, val))) + "key={} to val={}".format(encode_hex(key), encode_hex(cast(bytes, val))) for key, val in self._changes.items() if val is not DELETED ] - return "" % (deleted, updated) + return f"" def __len__(self) -> int: return len(self._changes) diff --git a/eth/db/header.py b/eth/db/header.py index 7e92798daf..4a9a7af059 100644 --- a/eth/db/header.py +++ b/eth/db/header.py @@ -67,7 +67,7 @@ def _get_canonical_block_hash(db: DatabaseAPI, block_number: BlockNumber) -> Has encoded_key = db[number_to_hash_key] except KeyError: raise HeaderNotFound( - "No canonical header for block number #{0}".format(block_number) + f"No canonical header for block number #{block_number}" ) else: return rlp.decode(encoded_key, sedes=rlp.sedes.binary) @@ -121,7 +121,7 @@ def _get_block_header_by_hash(db: DatabaseAPI, block_hash: Hash32) -> BlockHeade try: header_rlp = db[block_hash] except KeyError: - raise HeaderNotFound("No header with hash {0} found".format( + raise HeaderNotFound("No header with hash {} found".format( encode_hex(block_hash))) return _decode_block_header(header_rlp) @@ -133,7 +133,7 @@ def _get_score(db: DatabaseAPI, block_hash: Hash32) -> int: try: encoded_score = db[SchemaV1.make_block_hash_to_score_lookup_key(block_hash)] except KeyError: - raise HeaderNotFound("No header with hash {0} found".format( + raise HeaderNotFound("No header with hash {} found".format( encode_hex(block_hash))) return rlp.decode(encoded_score, sedes=rlp.sedes.big_endian_int) @@ -285,7 +285,7 @@ def _set_as_canonical_chain_head( header = cls._get_block_header_by_hash(db, block_hash) except HeaderNotFound: raise ValueError( - "Cannot use unknown block hash as canonical head: {}".format(block_hash) + f"Cannot use unknown block hash as canonical head: {block_hash}" ) new_canonical_headers = tuple(reversed( diff --git a/eth/db/slow_journal.py b/eth/db/slow_journal.py index ad093d1a69..b05a6bfc05 100644 --- a/eth/db/slow_journal.py +++ b/eth/db/slow_journal.py @@ -357,7 +357,7 @@ def _validate_changeset(self, changeset_id: uuid.UUID) -> None: Checks to be sure the changeset is known by the journal """ if not self.journal.has_changeset(changeset_id): - raise ValidationError("Changeset not found in journal: {0}".format( + raise ValidationError("Changeset not found in journal: {}".format( str(changeset_id) )) diff --git a/eth/rlp/blocks.py b/eth/rlp/blocks.py index eb9daf4ace..179ba9cef4 100644 --- a/eth/rlp/blocks.py +++ b/eth/rlp/blocks.py @@ -32,4 +32,4 @@ def __repr__(self) -> str: ) def __str__(self) -> str: - return "Block #{b.number}".format(b=self) + return f"Block #{self.number}" diff --git a/eth/rlp/headers.py b/eth/rlp/headers.py index bb0a01cd29..1e3074cbb4 100644 --- a/eth/rlp/headers.py +++ b/eth/rlp/headers.py @@ -151,7 +151,7 @@ def __init__(self, # type: ignore # noqa: F811 ) def __str__(self) -> str: - return ''.format( + return ''.format( self.block_number, encode_hex(self.hash)[2:10], ) diff --git a/eth/tools/_utils/normalization.py b/eth/tools/_utils/normalization.py index 58ba072d69..9327794635 100644 --- a/eth/tools/_utils/normalization.py +++ b/eth/tools/_utils/normalization.py @@ -91,7 +91,7 @@ def normalize_int(value: IntConvertible) -> int: elif is_string(value): return int(value) else: - raise TypeError("Unsupported type: Got `{0}`".format(type(value))) + raise TypeError("Unsupported type: Got `{}`".format(type(value))) def normalize_bytes(value: Union[bytes, str]) -> bytes: @@ -224,7 +224,7 @@ def state_definition_to_dict(state_definition: GeneralState) -> AccountState: assert TypeError("State definition must either be a mapping or a sequence") seen_keys = set(concat(d.keys() for d in state_dict.values())) - bad_keys = seen_keys - set(["balance", "nonce", "storage", "code"]) + bad_keys = seen_keys - {"balance", "nonce", "storage", "code"} if bad_keys: raise ValidationError( "State definition contains the following invalid account fields: {}".format( diff --git a/eth/tools/_utils/slow_code_stream.py b/eth/tools/_utils/slow_code_stream.py index bbe0d4bddc..7a7c5a5ef1 100644 --- a/eth/tools/_utils/slow_code_stream.py +++ b/eth/tools/_utils/slow_code_stream.py @@ -14,7 +14,7 @@ PUSH1, PUSH32, STOP = opcode_values.PUSH1, opcode_values.PUSH32, opcode_values.STOP -class SlowCodeStream(object): +class SlowCodeStream: """ A known working version of code stream that is kept around for testing, despite not being optimized. diff --git a/eth/tools/builder/chain/builders.py b/eth/tools/builder/chain/builders.py index e87ffdc2f7..ee9b4a34a5 100644 --- a/eth/tools/builder/chain/builders.py +++ b/eth/tools/builder/chain/builders.py @@ -448,12 +448,12 @@ def copy(chain: MiningChainAPI) -> MiningChainAPI: raise ValidationError("`at_block_number` may only be used with 'MiningChain") base_db = chain.chaindb.db if not isinstance(base_db, AtomicDB): - raise ValidationError("Unsupported database type: {0}".format(type(base_db))) + raise ValidationError("Unsupported database type: {}".format(type(base_db))) if isinstance(base_db.wrapped_db, MemoryDB): db = AtomicDB(MemoryDB(base_db.wrapped_db.kv_store.copy())) else: - raise ValidationError("Unsupported wrapped database: {0}".format(type(base_db.wrapped_db))) + raise ValidationError("Unsupported wrapped database: {}".format(type(base_db.wrapped_db))) chain_copy = type(chain)(db, chain.header) return chain_copy diff --git a/eth/tools/fixtures/fillers/_utils.py b/eth/tools/fixtures/fillers/_utils.py index 6ff55f1602..7319c0e08d 100644 --- a/eth/tools/fixtures/fillers/_utils.py +++ b/eth/tools/fixtures/fillers/_utils.py @@ -42,7 +42,7 @@ def add_transaction_to_group(group: Dict[str, Any], for key in ["gasPrice", "nonce", "secretKey", "to"]: if key in transaction and transaction[key] != group[key]: # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501 - raise ValueError("Can't add transaction as it differs in {}".format(key)) + raise ValueError(f"Can't add transaction as it differs in {key}") new_group = copy.deepcopy(group) indexes = {} @@ -50,7 +50,7 @@ def add_transaction_to_group(group: Dict[str, Any], if key in group: if key not in transaction: if len(new_group[key]) != 1: - raise ValueError("Can't add transaction as {} is ambiguous".format(key)) + raise ValueError(f"Can't add transaction as {key} is ambiguous") index = 0 else: if transaction[key] not in new_group[key]: # type: ignore # https://github.com/python/mypy/issues/5359 # noqa: 501 diff --git a/eth/tools/fixtures/generation.py b/eth/tools/fixtures/generation.py index 690074826b..2468f4e18c 100644 --- a/eth/tools/fixtures/generation.py +++ b/eth/tools/fixtures/generation.py @@ -25,7 +25,7 @@ def idfn(fixture_params: Iterable[Any]) -> str: """ Function for pytest to produce uniform names for fixtures. """ - return ":".join((str(item) for item in fixture_params)) + return ":".join(str(item) for item in fixture_params) def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str: @@ -61,8 +61,8 @@ def generate_fixture_tests(metafunc: Any, all_fixture_paths = find_fixture_files(base_fixture_path) current_file_hash = get_fixtures_file_hash(all_fixture_paths) - data_cache_key = 'pyevm/statetest/fixtures/{0}/data'.format(fixture_namespace) - file_hash_cache_key = 'pyevm/statetest/fixtures/{0}/data-hash'.format(fixture_namespace) + data_cache_key = f'pyevm/statetest/fixtures/{fixture_namespace}/data' + file_hash_cache_key = f'pyevm/statetest/fixtures/{fixture_namespace}/data-hash' cached_file_hash = metafunc.config.cache.get(file_hash_cache_key, None) cached_fixture_data = metafunc.config.cache.get(data_cache_key, None) @@ -83,7 +83,7 @@ def generate_fixture_tests(metafunc: Any, if not len(all_fixtures): raise AssertionError( - "Suspiciously found zero fixtures: {0}".format(base_fixture_path) + f"Suspiciously found zero fixtures: {base_fixture_path}" ) filtered_fixtures = filter_fn(preprocess_fn(all_fixtures)) diff --git a/eth/tools/fixtures/helpers.py b/eth/tools/fixtures/helpers.py index 524c8b2bb6..681b37636d 100644 --- a/eth/tools/fixtures/helpers.py +++ b/eth/tools/fixtures/helpers.py @@ -73,7 +73,7 @@ def verify_state(expected_state: AccountState, state: StateAPI) -> None: for account, field, actual_value, expected_value in diff: if field == 'balance': error_messages.append( - "{0}({1}) | Actual: {2} | Expected: {3} | Delta: {4}".format( + "{}({}) | Actual: {} | Expected: {} | Delta: {}".format( to_normalized_address(account), 'balance', actual_value, @@ -83,7 +83,7 @@ def verify_state(expected_state: AccountState, state: StateAPI) -> None: ) else: error_messages.append( - "{0}({1}) | Actual: {2} | Expected: {3}".format( + "{}({}) | Actual: {} | Expected: {}".format( to_normalized_address(account), field, actual_value, @@ -91,8 +91,8 @@ def verify_state(expected_state: AccountState, state: StateAPI) -> None: ) ) raise AssertionError( - "State DB did not match expected state on {0} values:\n" - "{1}".format( + "State DB did not match expected state on {} values:\n" + "{}".format( len(error_messages), "\n - ".join(error_messages), ) @@ -162,7 +162,7 @@ def chain_vm_configuration(fixture: Dict[str, Any]) -> Iterable[Tuple[int, Type[ (5, ConstantinopleVM), ) else: - raise ValueError("Network {0} does not match any known VM rules".format(network)) + raise ValueError(f"Network {network} does not match any known VM rules") def genesis_params_from_fixture(fixture: Dict[str, Any]) -> Dict[str, Any]: diff --git a/eth/validation.py b/eth/validation.py index b48690249e..36323ba2da 100644 --- a/eth/validation.py +++ b/eth/validation.py @@ -101,7 +101,7 @@ def validate_gte(value: int, minimum: int, title: str="Value") -> None: def validate_gt(value: int, minimum: int, title: str="Value") -> None: if value <= minimum: raise ValidationError( - "{title} {0} is not greater than {1}".format(value, minimum, title=title) + f"{title} {value} is not greater than {minimum}" ) validate_is_integer(value, title=title) @@ -121,7 +121,7 @@ def validate_lte(value: int, maximum: int, title: str="Value") -> None: def validate_lt(value: int, maximum: int, title: str="Value") -> None: if value >= maximum: raise ValidationError( - "{title} {0} is not less than {1}".format(value, maximum, title=title) + f"{title} {value} is not less than {maximum}" ) validate_is_integer(value, title=title) @@ -129,14 +129,14 @@ def validate_lt(value: int, maximum: int, title: str="Value") -> None: def validate_canonical_address(value: Address, title: str="Value") -> None: if not isinstance(value, bytes) or not len(value) == 20: raise ValidationError( - "{title} {0} is not a valid canonical address".format(value, title=title) + f"{title} {value} is not a valid canonical address" ) def validate_multiple_of(value: int, multiple_of: int, title: str="Value") -> None: if not value % multiple_of == 0: raise ValidationError( - "{title} {0} is not a multiple of {1}".format(value, multiple_of, title=title) + f"{title} {value} is not a multiple of {multiple_of}" ) @@ -247,7 +247,7 @@ def validate_unique(values: Iterable[Any], title: str="Value") -> None: ) raise ValidationError( "{title} does not contain unique items. Duplicates: {0}".format( - ', '.join((str(value) for value in duplicates)), + ', '.join(str(value) for value in duplicates), title=title, ) ) @@ -276,15 +276,15 @@ def validate_vm_configuration(vm_configuration: Tuple[Tuple[int, Type[VirtualMac def validate_gas_limit(gas_limit: int, parent_gas_limit: int) -> None: if gas_limit < GAS_LIMIT_MINIMUM: - raise ValidationError("Gas limit {0} is below minimum {1}".format( + raise ValidationError("Gas limit {} is below minimum {}".format( gas_limit, GAS_LIMIT_MINIMUM)) if gas_limit > GAS_LIMIT_MAXIMUM: - raise ValidationError("Gas limit {0} is above maximum {1}".format( + raise ValidationError("Gas limit {} is above maximum {}".format( gas_limit, GAS_LIMIT_MAXIMUM)) diff = gas_limit - parent_gas_limit if diff > (parent_gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR): raise ValidationError( - "Gas limit {0} difference to parent {1} is too big {2}".format( + "Gas limit {} difference to parent {} is too big {}".format( gas_limit, parent_gas_limit, diff)) @@ -305,8 +305,8 @@ def validate_header_params_for_configuration(header_params: Dict[str, Any]) -> N extra_fields = set(header_params.keys()).difference(ALLOWED_HEADER_FIELDS) if extra_fields: raise ValidationError( - "The `configure_header` method may only be used with the fields ({0}). " - "The provided fields ({1}) are not supported".format( + "The `configure_header` method may only be used with the fields ({}). " + "The provided fields ({}) are not supported".format( ", ".join(tuple(sorted(ALLOWED_HEADER_FIELDS))), ", ".join(tuple(sorted(extra_fields))), ) diff --git a/eth/vm/base.py b/eth/vm/base.py index 740e6b23e0..e5a80d19f6 100644 --- a/eth/vm/base.py +++ b/eth/vm/base.py @@ -150,7 +150,7 @@ def build_state(cls, # @property def logger(self) -> logging.Logger: - return logging.getLogger('eth.vm.base.VM.{0}'.format(self.__class__.__name__)) + return logging.getLogger(f'eth.vm.base.VM.{self.__class__.__name__}') # # Execution @@ -413,8 +413,8 @@ def pack_block(self, block: BlockAPI, *args: Any, **kwargs: Any) -> BlockAPI: if unknown_fields: raise AttributeError( - "Unable to set the field(s) {0} on the `BlockHeader` class. " - "Received the following unexpected fields: {1}.".format( + "Unable to set the field(s) {} on the `BlockHeader` class. " + "Received the following unexpected fields: {}.".format( ", ".join(known_fields), ", ".join(unknown_fields), ) @@ -530,7 +530,7 @@ def validate_receipt(cls, receipt: ReceiptAPI) -> None: continue elif log.address not in receipt.bloom_filter: raise ValidationError( - "The address from the log entry at position {0} is not " + "The address from the log entry at position {} is not " "present in the provided bloom filter.".format(log_idx) ) already_checked.add(log.address) @@ -541,8 +541,8 @@ def validate_receipt(cls, receipt: ReceiptAPI) -> None: continue elif uint32.serialize(topic) not in receipt.bloom_filter: raise ValidationError( - "The topic at position {0} from the log entry at " - "position {1} is not present in the provided bloom " + "The topic at position {} from the log entry at " + "position {} is not present in the provided bloom " "filter.".format(topic_idx, log_idx) ) already_checked.add(topic) @@ -553,7 +553,7 @@ def validate_block(self, block: BlockAPI) -> None: """ if not isinstance(block, self.get_block_class()): raise ValidationError( - "This vm ({0!r}) is not equipped to validate a block of type {1!r}".format( + "This vm ({!r}) is not equipped to validate a block of type {!r}".format( self, block, ) @@ -568,19 +568,19 @@ def validate_block(self, block: BlockAPI) -> None: tx_root_hash, _ = make_trie_root_and_nodes(block.transactions) if tx_root_hash != block.header.transaction_root: raise ValidationError( - "Block's transaction_root ({0}) does not match expected value: {1}".format( + "Block's transaction_root ({}) does not match expected value: {}".format( block.header.transaction_root, tx_root_hash)) if len(block.uncles) > MAX_UNCLES: raise ValidationError( - "Blocks may have a maximum of {0} uncles. Found " - "{1}.".format(MAX_UNCLES, len(block.uncles)) + "Blocks may have a maximum of {} uncles. Found " + "{}.".format(MAX_UNCLES, len(block.uncles)) ) if not self.chaindb.exists(block.header.state_root): raise ValidationError( "`state_root` was not found in the db.\n" - "- state_root: {0}".format( + "- state_root: {}".format( block.header.state_root, ) ) @@ -588,9 +588,9 @@ def validate_block(self, block: BlockAPI) -> None: if local_uncle_hash != block.header.uncles_hash: raise ValidationError( "`uncles_hash` and block `uncles` do not match.\n" - " - num_uncles : {0}\n" - " - block uncle_hash : {1}\n" - " - header uncle_hash: {2}".format( + " - num_uncles : {}\n" + " - block uncle_hash : {}\n" + " - header uncle_hash: {}".format( len(block.uncles), local_uncle_hash, block.header.uncles_hash, @@ -659,20 +659,20 @@ def validate_uncle(cls, block: BlockAPI, uncle: BlockAPI, uncle_parent: BlockAPI """ if uncle.block_number >= block.number: raise ValidationError( - "Uncle number ({0}) is higher than block number ({1})".format( + "Uncle number ({}) is higher than block number ({})".format( uncle.block_number, block.number)) if uncle.block_number != uncle_parent.block_number + 1: raise ValidationError( - "Uncle number ({0}) is not one above ancestor's number ({1})".format( + "Uncle number ({}) is not one above ancestor's number ({})".format( uncle.block_number, uncle_parent.block_number)) if uncle.timestamp < uncle_parent.timestamp: raise ValidationError( - "Uncle timestamp ({0}) is before ancestor's timestamp ({1})".format( + "Uncle timestamp ({}) is before ancestor's timestamp ({})".format( uncle.timestamp, uncle_parent.timestamp)) if uncle.gas_used > uncle.gas_limit: raise ValidationError( - "Uncle's gas usage ({0}) is above the limit ({1})".format( + "Uncle's gas usage ({}) is above the limit ({})".format( uncle.gas_used, uncle.gas_limit)) # diff --git a/eth/vm/forks/byzantium/__init__.py b/eth/vm/forks/byzantium/__init__.py index 0efd09a6bf..4e4275bcb4 100644 --- a/eth/vm/forks/byzantium/__init__.py +++ b/eth/vm/forks/byzantium/__init__.py @@ -79,8 +79,8 @@ def validate_receipt(cls, receipt: ReceiptAPI) -> None: super().validate_receipt(receipt) if receipt.state_root not in EIP658_STATUS_CODES: raise ValidationError( - "The receipt's `state_root` must be one of [{0}, {1}]. Got: " - "{2}".format( + "The receipt's `state_root` must be one of [{}, {}]. Got: " + "{}".format( encode_hex(EIP658_TRANSACTION_STATUS_CODE_SUCCESS), encode_hex(EIP658_TRANSACTION_STATUS_CODE_FAILURE), encode_hex(receipt.state_root), diff --git a/eth/vm/forks/frontier/computation.py b/eth/vm/forks/frontier/computation.py index ee9e63e66e..5841fa80b9 100644 --- a/eth/vm/forks/frontier/computation.py +++ b/eth/vm/forks/frontier/computation.py @@ -56,7 +56,7 @@ def apply_message(self) -> ComputationAPI: if sender_balance < self.msg.value: raise InsufficientFunds( - "Insufficient funds: {0} < {1}".format(sender_balance, self.msg.value) + f"Insufficient funds: {sender_balance} < {self.msg.value}" ) self.state.delta_balance(self.msg.sender, -1 * self.msg.value) diff --git a/eth/vm/forks/frontier/headers.py b/eth/vm/forks/frontier/headers.py index a80718aead..30355a26c0 100644 --- a/eth/vm/forks/frontier/headers.py +++ b/eth/vm/forks/frontier/headers.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - from typing import ( Any, TYPE_CHECKING, diff --git a/eth/vm/forks/frontier/state.py b/eth/vm/forks/frontier/state.py index ec2b985b75..d80e19ed5c 100644 --- a/eth/vm/forks/frontier/state.py +++ b/eth/vm/forks/frontier/state.py @@ -116,7 +116,7 @@ def build_computation(self, # with an existing contract address. computation = self.vm_state.get_computation(message, transaction_context) computation.error = ContractCreationCollision( - "Address collision while creating contract: {0}".format( + "Address collision while creating contract: {}".format( encode_hex(message.storage_address), ) ) diff --git a/eth/vm/forks/istanbul/constants.py b/eth/vm/forks/istanbul/constants.py index 4cdfee8cfa..9df0c11ed8 100644 --- a/eth/vm/forks/istanbul/constants.py +++ b/eth/vm/forks/istanbul/constants.py @@ -1,4 +1,3 @@ - # # New gas costs for some opcodes # diff --git a/eth/vm/forks/spurious_dragon/computation.py b/eth/vm/forks/spurious_dragon/computation.py index 525e64f925..11f88c71b2 100644 --- a/eth/vm/forks/spurious_dragon/computation.py +++ b/eth/vm/forks/spurious_dragon/computation.py @@ -40,8 +40,8 @@ def apply_create_message(self) -> ComputationAPI: if contract_code and len(contract_code) >= EIP170_CODE_SIZE_LIMIT: computation.error = OutOfGas( - "Contract code size exceeds EIP170 limit of {0}. Got code of " - "size: {1}".format( + "Contract code size exceeds EIP170 limit of {}. Got code of " + "size: {}".format( EIP170_CODE_SIZE_LIMIT, len(contract_code), ) diff --git a/eth/vm/gas_meter.py b/eth/vm/gas_meter.py index 72fb44d10e..bb05c48183 100644 --- a/eth/vm/gas_meter.py +++ b/eth/vm/gas_meter.py @@ -57,7 +57,7 @@ def consume_gas(self, amount: int, reason: str) -> None: raise ValidationError("Gas consumption amount must be positive") if amount > self.gas_remaining: - raise OutOfGas("Out of gas: Needed {0} - Remaining {1} - Reason: {2}".format( + raise OutOfGas("Out of gas: Needed {} - Remaining {} - Reason: {}".format( amount, self.gas_remaining, reason, diff --git a/eth/vm/interrupt.py b/eth/vm/interrupt.py index c239eedc40..d0ca09a8e0 100644 --- a/eth/vm/interrupt.py +++ b/eth/vm/interrupt.py @@ -31,7 +31,7 @@ def address_hash(self) -> Hash32: return self.requested_key def __repr__(self) -> str: - return "MissingAccountTrieNode: {}".format(self) + return f"MissingAccountTrieNode: {self}" def __str__(self) -> str: superclass_str = EVMMissingData.__str__(self) @@ -77,7 +77,7 @@ def account_address(self) -> Address: return self.args[3] def __repr__(self) -> str: - return "MissingStorageTrieNode: {}".format(self) + return f"MissingStorageTrieNode: {self}" def __str__(self) -> str: superclass_str = EVMMissingData.__str__(self) @@ -108,7 +108,7 @@ def missing_code_hash(self) -> Hash32: return self.args[0] def __repr__(self) -> str: - return "MissingBytecode: {}".format(self) + return f"MissingBytecode: {self}" def __str__(self) -> str: superclass_str = EVMMissingData.__str__(self) diff --git a/eth/vm/logic/call.py b/eth/vm/logic/call.py index ebec7ec120..50dd050eb3 100644 --- a/eth/vm/logic/call.py +++ b/eth/vm/logic/call.py @@ -97,7 +97,7 @@ def __call__(self, computation: ComputationAPI) -> None: if insufficient_funds or stack_too_deep: computation.return_data = b'' if insufficient_funds: - err_message = "Insufficient Funds: have: {0} | need: {1}".format( + err_message = "Insufficient Funds: have: {} | need: {}".format( sender_balance, value, ) @@ -345,7 +345,7 @@ def compute_eip150_msg_gas(*, if computation.get_gas_remaining() < extra_gas: # It feels wrong to raise an OutOfGas exception outside of GasMeter, # but I don't see an easy way around it. - raise OutOfGas("Out of gas: Needed {0} - Remaining {1} - Reason: {2}".format( + raise OutOfGas("Out of gas: Needed {} - Remaining {} - Reason: {}".format( extra_gas, computation.get_gas_remaining(), mnemonic, diff --git a/eth/vm/logic/context.py b/eth/vm/logic/context.py index d6c66eb4c7..1241eb1643 100644 --- a/eth/vm/logic/context.py +++ b/eth/vm/logic/context.py @@ -188,7 +188,7 @@ def returndatacopy(computation: BaseComputation) -> None: if returndata_start_position + size > len(computation.return_data): raise OutOfBoundsRead( "Return data length is not sufficient to satisfy request. Asked " - "for data from index {0} to {1}. Return data is {2} bytes in " + "for data from index {} to {}. Return data is {} bytes in " "length.".format( returndata_start_position, returndata_start_position + size, diff --git a/eth/vm/logic/invalid.py b/eth/vm/logic/invalid.py index 48ac553562..1b622c28ca 100644 --- a/eth/vm/logic/invalid.py +++ b/eth/vm/logic/invalid.py @@ -12,7 +12,7 @@ def __init__(self, value: int) -> None: super().__init__() def __call__(self, computation: ComputationAPI) -> None: - raise InvalidInstruction("Invalid opcode 0x{0:x} @ {1}".format( + raise InvalidInstruction("Invalid opcode 0x{:x} @ {}".format( self.value, computation.code.pc - 1, )) diff --git a/eth/vm/logic/logging.py b/eth/vm/logic/logging.py index e765838101..cfd881d437 100644 --- a/eth/vm/logic/logging.py +++ b/eth/vm/logic/logging.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import functools from typing import Tuple from eth import constants diff --git a/eth/vm/logic/storage.py b/eth/vm/logic/storage.py index 9688a7f341..6866bd0694 100644 --- a/eth/vm/logic/storage.py +++ b/eth/vm/logic/storage.py @@ -35,7 +35,7 @@ def sstore(computation: BaseComputation) -> None: else: gas_cost = constants.GAS_SRESET - computation.consume_gas(gas_cost, reason="SSTORE: {0}[{1}] -> {2} ({3})".format( + computation.consume_gas(gas_cost, reason="SSTORE: {}[{}] -> {} ({})".format( encode_hex(computation.msg.storage_address), slot, value, @@ -113,7 +113,7 @@ def net_sstore(gas_schedule: NetSStoreGasSchedule, computation: BaseComputation) computation.consume_gas( gas_cost, - reason="SSTORE: {0}[{1}] -> {2} (current: {3} / original: {4})".format( + reason="SSTORE: {}[{}] -> {} (current: {} / original: {})".format( encode_hex(computation.msg.storage_address), slot, value, diff --git a/eth/vm/opcode.py b/eth/vm/opcode.py index a1b6c5442d..c900a7baed 100644 --- a/eth/vm/opcode.py +++ b/eth/vm/opcode.py @@ -28,13 +28,13 @@ class Opcode(Configurable, OpcodeAPI): def __init__(self) -> None: if self.mnemonic is None: - raise TypeError("Opcode class {0} missing opcode mnemonic".format(type(self))) + raise TypeError("Opcode class {} missing opcode mnemonic".format(type(self))) if self.gas_cost is None: - raise TypeError("Opcode class {0} missing opcode gas_cost".format(type(self))) + raise TypeError("Opcode class {} missing opcode gas_cost".format(type(self))) @property def logger(self) -> ExtendedDebugLogger: - return get_extended_debug_logger('eth.vm.logic.{0}'.format(self.mnemonic)) + return get_extended_debug_logger(f'eth.vm.logic.{self.mnemonic}') @classmethod def as_opcode(cls: Type[T], @@ -64,7 +64,7 @@ def wrapped_logic_fn(computation: ComputationAPI) -> Any: 'mnemonic': mnemonic, 'gas_cost': gas_cost, } - opcode_cls = type("opcode:{0}".format(mnemonic), (cls,), props) + opcode_cls = type(f"opcode:{mnemonic}", (cls,), props) return opcode_cls() def __copy__(self) -> 'Opcode': diff --git a/eth/vm/stack.py b/eth/vm/stack.py index 233160b714..51c9f5c78a 100644 --- a/eth/vm/stack.py +++ b/eth/vm/stack.py @@ -258,7 +258,7 @@ def swap(self, position: int) -> None: try: self.values[-1], self.values[idx] = self.values[idx], self.values[-1] except IndexError: - raise InsufficientStack("Insufficient stack items for SWAP{0}".format(position)) + raise InsufficientStack(f"Insufficient stack items for SWAP{position}") def dup(self, position: int) -> None: """ @@ -271,4 +271,4 @@ def dup(self, position: int) -> None: try: self._append(self.values[peek_index]) except IndexError: - raise InsufficientStack("Insufficient stack items for DUP{0}".format(position)) + raise InsufficientStack(f"Insufficient stack items for DUP{position}") diff --git a/eth/vm/state.py b/eth/vm/state.py index 9001379fa5..6bbaf93693 100644 --- a/eth/vm/state.py +++ b/eth/vm/state.py @@ -76,7 +76,7 @@ def __init__( # @property def logger(self) -> ExtendedDebugLogger: - return get_extended_debug_logger('eth.vm.state.{0}'.format(self.__class__.__name__)) + return get_extended_debug_logger(f'eth.vm.state.{self.__class__.__name__}') # # Block Object Properties (in opcodes) @@ -127,7 +127,7 @@ def get_account_db_class(cls) -> Type[AccountDatabaseAPI]: state class uses. """ if cls.account_db_class is None: - raise AttributeError("No account_db_class set for {0}".format(cls.__name__)) + raise AttributeError(f"No account_db_class set for {cls.__name__}") return cls.account_db_class @property