diff --git a/docs/api/api.abc.rst b/docs/api/api.abc.rst index 9be76d34a3..0d878e2ca3 100644 --- a/docs/api/api.abc.rst +++ b/docs/api/api.abc.rst @@ -164,13 +164,6 @@ ComputationAPI :members: -MessageComputationAPI ---------------------- - -.. autoclass:: eth.abc.MessageComputationAPI - :members: - - AccountStorageDatabaseAPI ------------------------- diff --git a/docs/api/vm/api.vm.computation.rst b/docs/api/vm/api.vm.computation.rst index 7287f13eaf..62314439e2 100644 --- a/docs/api/vm/api.vm.computation.rst +++ b/docs/api/vm/api.vm.computation.rst @@ -6,9 +6,3 @@ BaseComputation .. autoclass:: eth.vm.computation.BaseComputation :members: - -MessageComputation ------------------- - -.. autoclass:: eth.vm.computation.MessageComputation - :members: diff --git a/docs/api/vm/api.vm.forks.rst b/docs/api/vm/api.vm.forks.rst index 80835264be..2255350b93 100644 --- a/docs/api/vm/api.vm.forks.rst +++ b/docs/api/vm/api.vm.forks.rst @@ -3,7 +3,7 @@ Forks Frontier ---------- +-------- FrontierVM ~~~~~~~~~~ @@ -17,10 +17,10 @@ FrontierState .. autoclass:: eth.vm.forks.frontier.state.FrontierState :members: -FrontierMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~ +FrontierComputation +~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.frontier.computation.FrontierMessageComputation +.. autoclass:: eth.vm.forks.frontier.computation.FrontierComputation :members: @@ -39,10 +39,10 @@ HomesteadState .. autoclass:: eth.vm.forks.homestead.state.HomesteadState :members: -HomesteadMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +HomesteadComputation +~~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.homestead.computation.HomesteadMessageComputation +.. autoclass:: eth.vm.forks.homestead.computation.HomesteadComputation :members: @@ -61,10 +61,10 @@ TangerineWhistleState .. autoclass:: eth.vm.forks.tangerine_whistle.state.TangerineWhistleState :members: -TangerineWhistleMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +TangerineWhistleComputation +~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.tangerine_whistle.computation.TangerineWhistleMessageComputation +.. autoclass:: eth.vm.forks.tangerine_whistle.computation.TangerineWhistleComputation :members: @@ -72,7 +72,7 @@ SpuriousDragon -------------- SpuriousDragonVM -~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~ .. autoclass:: eth.vm.forks.spurious_dragon.SpuriousDragonVM :members: @@ -83,10 +83,10 @@ SpuriousDragonState .. autoclass:: eth.vm.forks.spurious_dragon.state.SpuriousDragonState :members: -SpuriousDragonMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +SpuriousDragonComputation +~~~~~~~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.spurious_dragon.computation.SpuriousDragonMessageComputation +.. autoclass:: eth.vm.forks.spurious_dragon.computation.SpuriousDragonComputation :members: @@ -105,10 +105,10 @@ ByzantiumState .. autoclass:: eth.vm.forks.byzantium.state.ByzantiumState :members: -ByzantiumMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +ByzantiumComputation +~~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.byzantium.computation.ByzantiumMessageComputation +.. autoclass:: eth.vm.forks.byzantium.computation.ByzantiumComputation :members: @@ -127,10 +127,10 @@ ConstantinopleState .. autoclass:: eth.vm.forks.constantinople.state.ConstantinopleState :members: -ConstantinopleMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +ConstantinopleComputation +~~~~~~~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.constantinople.computation.ConstantinopleMessageComputation +.. autoclass:: eth.vm.forks.constantinople.computation.ConstantinopleComputation :members: @@ -149,32 +149,32 @@ PetersburgState .. autoclass:: eth.vm.forks.petersburg.state.PetersburgState :members: -PetersburgMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +PetersburgComputation +~~~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.petersburg.computation.PetersburgMessageComputation +.. autoclass:: eth.vm.forks.petersburg.computation.PetersburgComputation :members: Istanbul ----------- +-------- IstanbulVM -~~~~~~~~~~~~ +~~~~~~~~~~ .. autoclass:: eth.vm.forks.istanbul.IstanbulVM :members: IstanbulState -~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~ .. autoclass:: eth.vm.forks.istanbul.state.IstanbulState :members: -IstanbulMessageComputation -~~~~~~~~~~~~~~~~~~~~~~~~~~ +IstanbulComputation +~~~~~~~~~~~~~~~~~~~ -.. autoclass:: eth.vm.forks.istanbul.computation.IstanbulMessageComputation +.. autoclass:: eth.vm.forks.istanbul.computation.IstanbulComputation :members: @@ -182,7 +182,7 @@ Muir Glacier ------------ Submodules -~~~~~~~~~~~ +~~~~~~~~~~ eth.vm.forks.muir\_glacier.blocks module ======================================== @@ -243,7 +243,7 @@ Module contents Berlin -------- +------ Submodules ~~~~~~~~~~ @@ -489,7 +489,7 @@ Submodules ~~~~~~~~~~ eth.vm.forks.gray\_glacier.blocks module -========================================= +======================================== .. automodule:: eth.vm.forks.gray_glacier.blocks :members: @@ -497,7 +497,7 @@ eth.vm.forks.gray\_glacier.blocks module :show-inheritance: eth.vm.forks.gray\_glacier.computation module -============================================== +============================================= .. automodule:: eth.vm.forks.gray_glacier.computation :members: @@ -505,7 +505,7 @@ eth.vm.forks.gray\_glacier.computation module :show-inheritance: eth.vm.forks.gray\_glacier.headers module -========================================== +========================================= .. automodule:: eth.vm.forks.gray_glacier.headers :members: @@ -513,7 +513,7 @@ eth.vm.forks.gray\_glacier.headers module :show-inheritance: eth.vm.forks.gray\_glacier.state module -======================================== +======================================= .. automodule:: eth.vm.forks.gray_glacier.state :members: @@ -521,7 +521,7 @@ eth.vm.forks.gray\_glacier.state module :show-inheritance: eth.vm.forks.gray\_glacier.transactions module -=============================================== +============================================== .. automodule:: eth.vm.forks.gray_glacier.transactions :members: diff --git a/eth/_utils/address.py b/eth/_utils/address.py index 54f6943c57..66a5a3925d 100644 --- a/eth/_utils/address.py +++ b/eth/_utils/address.py @@ -1,8 +1,11 @@ +from eth_hash.auto import ( + keccak, +) +from eth_typing import ( + Address, +) import rlp -from eth_hash.auto import keccak -from eth_typing import Address - from eth._utils.numeric import ( int_to_bytes32, ) diff --git a/eth/_utils/blake2/coders.py b/eth/_utils/blake2/coders.py index 02a9520314..9c40168587 100644 --- a/eth/_utils/blake2/coders.py +++ b/eth/_utils/blake2/coders.py @@ -1,13 +1,13 @@ from typing import ( - cast, Iterable, Tuple, + cast, ) from eth_utils import ( + ValidationError, to_int, to_tuple, - ValidationError, ) from .compression import ( diff --git a/eth/_utils/bn128.py b/eth/_utils/bn128.py index a1a31a4092..d117dd7588 100644 --- a/eth/_utils/bn128.py +++ b/eth/_utils/bn128.py @@ -1,17 +1,18 @@ +from typing import ( + Tuple, +) + +from eth_utils import ( + ValidationError, +) from py_ecc import ( optimized_bn128 as bn128, ) from py_ecc.optimized_bn128 import ( - FQP, FQ2, + FQP, ) -from eth_utils import ( - ValidationError, -) - -from typing import Tuple - def validate_point(x: int, y: int) -> Tuple[bn128.FQ, bn128.FQ, bn128.FQ]: FQ = bn128.FQ diff --git a/eth/_utils/datatypes.py b/eth/_utils/datatypes.py index 8dd7b84d09..87894c134d 100644 --- a/eth/_utils/datatypes.py +++ b/eth/_utils/datatypes.py @@ -1,17 +1,25 @@ -from eth_utils.toolz import ( - assoc, - groupby, +from typing import ( + Any, + Dict, + Iterator, + List, + Tuple, + Type, + TypeVar, ) from eth_utils import ( to_dict, to_set, ) +from eth_utils.toolz import ( + assoc, + groupby, +) - -from typing import Any, Dict, Tuple, Type, TypeVar, Iterator, List - -from eth.abc import ConfigurableAPI +from eth.abc import ( + ConfigurableAPI, +) def _is_local_prop(prop: str) -> bool: diff --git a/eth/_utils/env.py b/eth/_utils/env.py index 8e049b7a27..9ad130829b 100644 --- a/eth/_utils/env.py +++ b/eth/_utils/env.py @@ -4,7 +4,6 @@ """ import os - from typing import ( Any, Callable, @@ -16,7 +15,6 @@ Union, ) - # No set literals because we support Python 2.6. TRUE_VALUES = { True, diff --git a/eth/_utils/generator.py b/eth/_utils/generator.py index 5f1b52276f..0cb26fbe96 100644 --- a/eth/_utils/generator.py +++ b/eth/_utils/generator.py @@ -7,7 +7,6 @@ TypeVar, ) - TItem = TypeVar('TItem') diff --git a/eth/_utils/headers.py b/eth/_utils/headers.py index a91dec309b..0252b6a990 100644 --- a/eth/_utils/headers.py +++ b/eth/_utils/headers.py @@ -9,17 +9,19 @@ Address, ) -from eth.abc import BlockHeaderAPI +from eth.abc import ( + BlockHeaderAPI, +) from eth.constants import ( BLANK_ROOT_HASH, - GENESIS_BLOCK_NUMBER, - GENESIS_PARENT_HASH, - GAS_LIMIT_EMA_DENOMINATOR, GAS_LIMIT_ADJUSTMENT_FACTOR, + GAS_LIMIT_EMA_DENOMINATOR, GAS_LIMIT_MAXIMUM, GAS_LIMIT_MINIMUM, - GAS_LIMIT_USAGE_ADJUSTMENT_NUMERATOR, GAS_LIMIT_USAGE_ADJUSTMENT_DENOMINATOR, + GAS_LIMIT_USAGE_ADJUSTMENT_NUMERATOR, + GENESIS_BLOCK_NUMBER, + GENESIS_PARENT_HASH, ZERO_ADDRESS, ) from eth.typing import ( diff --git a/eth/_utils/module_loading.py b/eth/_utils/module_loading.py index d824a3db84..1bae37d5ab 100644 --- a/eth/_utils/module_loading.py +++ b/eth/_utils/module_loading.py @@ -1,6 +1,7 @@ +from importlib import ( + import_module, +) import operator -from importlib import import_module - from types import ( ModuleType, ) diff --git a/eth/_utils/numeric.py b/eth/_utils/numeric.py index 80819b9217..e6a25a11ed 100644 --- a/eth/_utils/numeric.py +++ b/eth/_utils/numeric.py @@ -5,17 +5,17 @@ Union, ) -from eth_utils.toolz import ( - curry, -) from eth_typing import ( Hash32, ) +from eth_utils.toolz import ( + curry, +) from eth.constants import ( UINT_255_MAX, - UINT_256_MAX, UINT_256_CEILING, + UINT_256_MAX, ) diff --git a/eth/_utils/padding.py b/eth/_utils/padding.py index 977963ef8e..30b21c39d0 100644 --- a/eth/_utils/padding.py +++ b/eth/_utils/padding.py @@ -2,7 +2,6 @@ curry, ) - ZERO_BYTE = b'\x00' diff --git a/eth/_utils/rlp.py b/eth/_utils/rlp.py index f737dd83b9..9c8edde72e 100644 --- a/eth/_utils/rlp.py +++ b/eth/_utils/rlp.py @@ -1,18 +1,17 @@ -import rlp from typing import ( Iterable, Optional, Tuple, ) -from eth_utils.toolz import ( - curry, -) - from eth_utils import ( - to_tuple, ValidationError, + to_tuple, ) +from eth_utils.toolz import ( + curry, +) +import rlp from eth.rlp.blocks import ( BaseBlock, diff --git a/eth/_utils/spoof.py b/eth/_utils/spoof.py index 9689b59ed5..97bd957770 100644 --- a/eth/_utils/spoof.py +++ b/eth/_utils/spoof.py @@ -8,16 +8,15 @@ merge, ) -from eth.constants import ( - DEFAULT_SPOOF_Y_PARITY, - DEFAULT_SPOOF_R, - DEFAULT_SPOOF_S, -) - from eth.abc import ( SignedTransactionAPI, UnsignedTransactionAPI, ) +from eth.constants import ( + DEFAULT_SPOOF_R, + DEFAULT_SPOOF_S, + DEFAULT_SPOOF_Y_PARITY, +) SPOOF_ATTRIBUTES_DEFAULTS = { 'y_parity': DEFAULT_SPOOF_Y_PARITY, diff --git a/eth/_utils/state.py b/eth/_utils/state.py index 26e5fd2455..71b906c16e 100644 --- a/eth/_utils/state.py +++ b/eth/_utils/state.py @@ -6,7 +6,9 @@ AccountDiff, AccountState, ) -from eth.vm.state import BaseState +from eth.vm.state import ( + BaseState, +) @to_tuple diff --git a/eth/_utils/transactions.py b/eth/_utils/transactions.py index 3b8ee67706..db683e0d09 100644 --- a/eth/_utils/transactions.py +++ b/eth/_utils/transactions.py @@ -1,18 +1,23 @@ -from typing import NamedTuple - -import rlp +from typing import ( + NamedTuple, +) -from eth_keys import keys -from eth_keys import datatypes +from eth_keys import ( + datatypes, + keys, +) from eth_keys.exceptions import ( BadSignature, ) - from eth_utils import ( - int_to_big_endian, ValidationError, + int_to_big_endian, ) +import rlp +from eth._utils.numeric import ( + is_even, +) from eth.abc import ( SignedTransactionAPI, UnsignedTransactionAPI, @@ -20,16 +25,13 @@ from eth.constants import ( CREATE_CONTRACT_ADDRESS, ) +from eth.rlp.transactions import ( + BaseTransaction, +) from eth.typing import ( - Address, VRS, + Address, ) -from eth._utils.numeric import ( - is_even, -) - -from eth.rlp.transactions import BaseTransaction - EIP155_CHAIN_ID_OFFSET = 35 # Add this offset to y_parity to get "v" for legacy transactions, from Frontier diff --git a/eth/_utils/version.py b/eth/_utils/version.py index 1077df56f7..254c589f7c 100644 --- a/eth/_utils/version.py +++ b/eth/_utils/version.py @@ -1,6 +1,8 @@ import sys -from eth import __version__ +from eth import ( + __version__, +) def construct_evm_runtime_identifier() -> str: diff --git a/eth/_warnings.py b/eth/_warnings.py index 366d25aa75..4f7b2688f3 100644 --- a/eth/_warnings.py +++ b/eth/_warnings.py @@ -1,5 +1,9 @@ -from contextlib import contextmanager -from typing import Iterator +from contextlib import ( + contextmanager, +) +from typing import ( + Iterator, +) import warnings diff --git a/eth/abc.py b/eth/abc.py index cca3901c3d..c53ea61995 100644 --- a/eth/abc.py +++ b/eth/abc.py @@ -1,6 +1,6 @@ from abc import ( ABC, - abstractmethod + abstractmethod, ) from typing import ( Any, @@ -9,6 +9,7 @@ ContextManager, Dict, FrozenSet, + Hashable, Iterable, Iterator, List, @@ -20,36 +21,38 @@ Type, TypeVar, Union, - Hashable, ) -from eth_bloom import BloomFilter - +from eth_bloom import ( + BloomFilter, +) +from eth_keys.datatypes import ( + PrivateKey, +) from eth_typing import ( Address, BlockNumber, Hash32, ) - -from eth_utils import ExtendedDebugLogger - -from eth_keys.datatypes import PrivateKey +from eth_utils import ( + ExtendedDebugLogger, +) from eth.constants import ( BLANK_ROOT_HASH, ) - -from eth.exceptions import VMError +from eth.exceptions import ( + VMError, +) from eth.typing import ( + AccountState, BytesOrView, ChainGaps, - JournalDBCheckpoint, - AccountState, HeaderParams, + JournalDBCheckpoint, VMConfiguration, ) - T = TypeVar('T') # A decoded RLP object of unknown interpretation, with a maximum "depth" of 1. @@ -347,7 +350,7 @@ def get_intrinsic_gas(self) -> int: ... @abstractmethod - def gas_used_by(self, computation: 'MessageComputationAPI') -> int: + def gas_used_by(self, computation: 'ComputationAPI') -> int: """ Return the gas used by the given computation. In Frontier, for example, this is sum of the intrinsic cost and the gas used @@ -1440,7 +1443,7 @@ class OpcodeAPI(ABC): mnemonic: str @abstractmethod - def __call__(self, computation: 'MessageComputationAPI') -> None: + def __call__(self, computation: 'ComputationAPI') -> None: """ Execute the logic of the opcode. """ @@ -1449,7 +1452,7 @@ def __call__(self, computation: 'MessageComputationAPI') -> None: @classmethod @abstractmethod def as_opcode(cls: Type[T], - logic_fn: Callable[['MessageComputationAPI'], None], + logic_fn: Callable[['ComputationAPI'], None], mnemonic: str, gas_cost: int) -> T: """ @@ -1872,15 +1875,34 @@ class ComputationAPI( logger: ExtendedDebugLogger state: "StateAPI" + msg: MessageAPI + transaction_context: TransactionContextAPI code: CodeStreamAPI - return_data: bytes + children: List["ComputationAPI"] + return_data: bytes = b'' + accounts_to_delete: Dict[Address, Address] + + _memory: MemoryAPI + _stack: StackAPI + _gas_meter: GasMeterAPI + _error: VMError + _output: bytes = b'' + _log_entries: List[Tuple[int, Address, Tuple[int, ...], bytes]] # VM configuration opcodes: Dict[int, OpcodeAPI] _precompiles: Dict[Address, Callable[["ComputationAPI"], "ComputationAPI"]] @abstractmethod - def __init__(self, state: "StateAPI") -> None: + def __init__( + self, + state: "StateAPI", + message: MessageAPI, + transaction_context: TransactionContextAPI, + ) -> None: + """ + Instantiate the computation. + """ ... @abstractmethod @@ -1890,6 +1912,16 @@ def _configure_gas_meter(self) -> GasMeterAPI: """ ... + # -- convenience -- # + @property + @abstractmethod + def is_origin_computation(self) -> bool: + """ + Return ``True`` if this computation is the outermost computation at + ``depth == 0``. + """ + ... + # -- error handling -- # @property @abstractmethod @@ -2100,41 +2132,6 @@ def get_opcode_fn(self, opcode: int) -> OpcodeAPI: """ ... - -class MessageComputationAPI( - ComputationAPI, - ContextManager['MessageComputationAPI'], -): - """ - The base abstract class for all execution *message* computations. - """ - - msg: MessageAPI - transaction_context: TransactionContextAPI - - @abstractmethod - def __init__( - self, - state: "StateAPI", - message: MessageAPI, - transaction_context: TransactionContextAPI, - ) -> None: - """ - Instantiate the message computation. - """ - ... - - # -- convenience -- # - @property - @abstractmethod - def is_origin_computation(self) -> bool: - """ - Return ``True`` if this message computation is the outermost computation at - ``depth == 0``. Since EOF computations cannot exist without a message, this - is solely an inherent property of message computations. - """ - ... - # -- runtime operations -- # @abstractmethod def prepare_child_message(self, @@ -2145,34 +2142,34 @@ def prepare_child_message(self, code: bytes, **kwargs: Any) -> MessageAPI: """ - Helper method for creating a child message computation. + Helper method for creating a child computation. """ ... @abstractmethod - def apply_child_message_computation( + def apply_child_computation( self, child_msg: MessageAPI, - ) -> "MessageComputationAPI": + ) -> "ComputationAPI": """ - Apply the vm message ``child_msg`` as a child message computation. + Apply the vm message ``child_msg`` as a child computation. """ ... @abstractmethod - def generate_child_message_computation( + def generate_child_computation( self, child_msg: MessageAPI, - ) -> "MessageComputationAPI": + ) -> "ComputationAPI": """ - Generate a child message computation from the given ``child_msg``. + Generate a child computation from the given ``child_msg``. """ ... @abstractmethod - def add_child_message_computation( + def add_child_computation( self, - child_message_computation: "MessageComputationAPI", + child_computation: "ComputationAPI", ) -> None: """ Add the given ``child_computation``. @@ -2235,7 +2232,7 @@ def apply_message( state: "StateAPI", message: MessageAPI, transaction_context: TransactionContextAPI, - ) -> "MessageComputationAPI": + ) -> "ComputationAPI": """ Execute a VM message. This is where the VM-specific call logic exists. """ @@ -2244,10 +2241,11 @@ def apply_message( @classmethod @abstractmethod def apply_create_message( - cls, - state: 'StateAPI', - message: MessageAPI, - transaction_context: TransactionContextAPI) -> 'MessageComputationAPI': + cls, + state: "StateAPI", + message: MessageAPI, + transaction_context: TransactionContextAPI, + ) -> "ComputationAPI": """ Execute a VM message to create a new contract. This is where the VM-specific create logic exists. @@ -2261,7 +2259,7 @@ def apply_computation( state: 'StateAPI', message: MessageAPI, transaction_context: TransactionContextAPI, - ) -> 'MessageComputationAPI': + ) -> "ComputationAPI": """ Execute the logic within the message: Either run the precompile, or step through each opcode. Generally, the only VM-specific logic is for @@ -2669,9 +2667,9 @@ def __init__(self, vm_state: 'StateAPI') -> None: ... @abstractmethod - def __call__(self, transaction: SignedTransactionAPI) -> 'MessageComputationAPI': + def __call__(self, transaction: SignedTransactionAPI) -> "ComputationAPI": """ - Execute the ``transaction`` and return a :class:`eth.abc.MessageComputationAPI`. + Execute the ``transaction`` and return a :class:`eth.abc.ComputationAPI`. """ ... @@ -2693,7 +2691,7 @@ def build_evm_message(self, transaction: SignedTransactionAPI) -> MessageAPI: @abstractmethod def build_computation(self, message: MessageAPI, - transaction: SignedTransactionAPI) -> 'MessageComputationAPI': + transaction: SignedTransactionAPI) -> "ComputationAPI": """ Apply the ``message`` to the VM and use the given ``transaction`` to retrieve the context from. @@ -2704,7 +2702,7 @@ def build_computation(self, @abstractmethod def finalize_computation(self, transaction: SignedTransactionAPI, - computation: 'MessageComputationAPI') -> 'MessageComputationAPI': + computation: "ComputationAPI") -> "ComputationAPI": """ Finalize the ``transaction``. """ @@ -2734,7 +2732,7 @@ class StateAPI(ConfigurableAPI): Each :class:`~eth.abc.StateAPI` class must be configured with: - - ``message_computation_class``: The :class:`~eth.abc.MessageComputationAPI` class for + - ``computation_class``: The :class:`~eth.abc.ComputationAPI` class for vm execution. - ``transaction_context_class``: The :class:`~eth.abc.TransactionContextAPI` class for vm execution. @@ -2744,7 +2742,7 @@ class for vm execution. # execution_context: ExecutionContextAPI - message_computation_class: Type[MessageComputationAPI] + computation_class: Type[ComputationAPI] transaction_context_class: Type[TransactionContextAPI] account_db_class: Type[AccountDatabaseAPI] transaction_executor_class: Type[TransactionExecutorAPI] = None @@ -3103,7 +3101,7 @@ def get_ancestor_hash(self, block_number: BlockNumber) -> Hash32: @abstractmethod def get_computation(self, message: MessageAPI, - transaction_context: TransactionContextAPI) -> MessageComputationAPI: + transaction_context: TransactionContextAPI) -> ComputationAPI: """ Return a computation instance for the given `message` and `transaction_context` """ @@ -3128,7 +3126,7 @@ def get_transaction_context_class(cls) -> Type[TransactionContextAPI]: def apply_transaction( self, transaction: SignedTransactionAPI, - ) -> MessageComputationAPI: + ) -> ComputationAPI: """ Apply transaction to the vm state @@ -3148,7 +3146,7 @@ def get_transaction_executor(self) -> TransactionExecutorAPI: def costless_execute_transaction( self, transaction: SignedTransactionAPI, - ) -> MessageComputationAPI: + ) -> ComputationAPI: """ Execute the given ``transaction`` with a gas price of ``0``. """ @@ -3318,7 +3316,7 @@ def transaction_applied_hook( transactions: Sequence[SignedTransactionAPI], base_header: BlockHeaderAPI, partial_header: BlockHeaderAPI, - computation: MessageComputationAPI, + computation: ComputationAPI, receipt: ReceiptAPI) -> None: """ A hook for a subclass to use as a way to note that a transaction was applied. @@ -3334,7 +3332,7 @@ def transaction_applied_hook( def apply_transaction(self, header: BlockHeaderAPI, transaction: SignedTransactionAPI - ) -> Tuple[ReceiptAPI, MessageComputationAPI]: + ) -> Tuple[ReceiptAPI, ComputationAPI]: """ Apply the transaction to the current block. This is a wrapper around :func:`~eth.vm.state.State.apply_transaction` with some extra orchestration logic. @@ -3365,7 +3363,7 @@ def execute_bytecode(self, value: int, data: bytes, code: bytes, - code_address: Address = None) -> MessageComputationAPI: + code_address: Address = None) -> ComputationAPI: """ Execute raw bytecode in the context of the current state of the virtual machine. Note that this skips over some of the logic @@ -3377,8 +3375,8 @@ def execute_bytecode(self, - others... For other potential surprises, check the implementation differences - between :meth:`MessageComputationAPI.apply_computation` and - :meth:`MessageComputationAPI.apply_message`. (depending on the VM fork) + between :meth:`ComputationAPI.apply_computation` and + :meth:`ComputationAPI.apply_message`. (depending on the VM fork) """ ... @@ -3387,7 +3385,7 @@ def apply_all_transactions( self, transactions: Sequence[SignedTransactionAPI], base_header: BlockHeaderAPI - ) -> Tuple[BlockHeaderAPI, Tuple[ReceiptAPI, ...], Tuple[MessageComputationAPI, ...]]: + ) -> Tuple[BlockHeaderAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: """ Determine the results of applying all transactions to the base header. This does *not* update the current block or header of the VM. @@ -3411,7 +3409,7 @@ def apply_all_withdrawals(self, withdrawals: Sequence[WithdrawalAPI]) -> None: def make_receipt(self, base_header: BlockHeaderAPI, transaction: SignedTransactionAPI, - computation: MessageComputationAPI, + computation: ComputationAPI, state: StateAPI) -> ReceiptAPI: """ Generate the receipt resulting from applying the transaction. @@ -4045,7 +4043,7 @@ def build_block_with_transactions_and_withdrawals( transactions: Tuple[SignedTransactionAPI, ...], parent_header: BlockHeaderAPI = None, withdrawals: Tuple[WithdrawalAPI, ...] = None, - ) -> Tuple[BlockAPI, Tuple[ReceiptAPI, ...], Tuple[MessageComputationAPI, ...]]: + ) -> Tuple[BlockAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: """ Generate a block with the provided transactions. This does *not* import that block into your chain. If you want this new block in your chain, @@ -4271,7 +4269,7 @@ def mine_all( *args: Any, parent_header: BlockHeaderAPI = None, **kwargs: Any, - ) -> Tuple[BlockImportResult, Tuple[ReceiptAPI, ...], Tuple[MessageComputationAPI, ...]]: + ) -> Tuple[BlockImportResult, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: """ Build a block with the given transactions, and mine it. @@ -4285,7 +4283,7 @@ def mine_all( @abstractmethod def apply_transaction(self, transaction: SignedTransactionAPI - ) -> Tuple[BlockAPI, ReceiptAPI, MessageComputationAPI]: + ) -> Tuple[BlockAPI, ReceiptAPI, ComputationAPI]: """ Apply the transaction to the current tip block. diff --git a/eth/chains/base.py b/eth/chains/base.py index 67e9e88d14..214aa5d8d0 100644 --- a/eth/chains/base.py +++ b/eth/chains/base.py @@ -1,3 +1,4 @@ +import logging import operator import random from typing import ( @@ -10,8 +11,6 @@ Type, ) -import logging - from eth_typing import ( Address, BlockNumber, @@ -25,32 +24,35 @@ sliding_window, ) -from eth._utils.db import ( - apply_state_dict, -) from eth._utils.datatypes import ( Configurable, ) +from eth._utils.db import ( + apply_state_dict, +) from eth._utils.rlp import ( validate_imported_block_unchanged, ) +from eth._warnings import ( + catch_and_ignore_import_warning, +) from eth.abc import ( - BlockAPI, - BlockAndMetaWitness, - MiningChainAPI, AtomicDatabaseAPI, + BlockAndMetaWitness, + BlockAPI, BlockHeaderAPI, BlockImportResult, BlockPersistResult, ChainAPI, ChainDatabaseAPI, + ComputationAPI, ConsensusContextAPI, - VirtualMachineAPI, + MiningChainAPI, ReceiptAPI, - MessageComputationAPI, - StateAPI, SignedTransactionAPI, + StateAPI, UnsignedTransactionAPI, + VirtualMachineAPI, WithdrawalAPI, ) from eth.consensus import ( @@ -60,14 +62,12 @@ EMPTY_UNCLE_HASH, MAX_UNCLE_DEPTH, ) - from eth.db.chain import ( ChainDB, ) from eth.db.header import ( HeaderDB, ) - from eth.estimators import ( get_gas_estimator, ) @@ -76,30 +76,28 @@ TransactionNotFound, VMNotFound, ) - from eth.rlp.headers import ( BlockHeader, ) - from eth.typing import ( AccountState, HeaderParams, StaticMethod, ) - from eth.validation import ( validate_block_number, validate_uint256, - validate_word, validate_vm_configuration, + validate_word, +) +from eth.vm.chain_context import ( + ChainContext, ) -from eth.vm.chain_context import ChainContext -from eth._warnings import catch_and_ignore_import_warning with catch_and_ignore_import_warning(): from eth_utils import ( - to_set, ValidationError, + to_set, ) from eth_utils.toolz import ( assoc, @@ -352,7 +350,7 @@ def build_block_with_transactions_and_withdrawals( transactions: Sequence[SignedTransactionAPI], parent_header: BlockHeaderAPI = None, withdrawals: Sequence[WithdrawalAPI] = None, - ) -> Tuple[BlockAPI, Tuple[ReceiptAPI, ...], Tuple[MessageComputationAPI, ...]]: + ) -> Tuple[BlockAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: base_header = self.ensure_header(parent_header) vm = self.get_vm(base_header) @@ -645,7 +643,7 @@ def __init__(self, base_db: AtomicDatabaseAPI, header: BlockHeaderAPI = None) -> def apply_transaction( self, transaction: SignedTransactionAPI, - ) -> Tuple[BlockAPI, ReceiptAPI, MessageComputationAPI]: + ) -> Tuple[BlockAPI, ReceiptAPI, ComputationAPI]: vm = self.get_vm(self.header) base_block = vm.get_block() @@ -696,7 +694,7 @@ def mine_all( parent_header: BlockHeaderAPI = None, withdrawals: Sequence[WithdrawalAPI] = None, **kwargs: Any, - ) -> Tuple[BlockImportResult, Tuple[ReceiptAPI, ...], Tuple[MessageComputationAPI, ...]]: + ) -> Tuple[BlockImportResult, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: if parent_header is None: base_header = self.header diff --git a/eth/chains/goerli/constants.py b/eth/chains/goerli/constants.py index 807096a9bb..f91a96e5c7 100644 --- a/eth/chains/goerli/constants.py +++ b/eth/chains/goerli/constants.py @@ -1,5 +1,6 @@ -from eth_typing import BlockNumber - +from eth_typing import ( + BlockNumber, +) GOERLI_CHAIN_ID = 5 diff --git a/eth/chains/header.py b/eth/chains/header.py index de8a5c416f..95a3985f82 100644 --- a/eth/chains/header.py +++ b/eth/chains/header.py @@ -1,7 +1,7 @@ from typing import ( - cast, Tuple, Type, + cast, ) from eth_typing import ( @@ -9,6 +9,9 @@ Hash32, ) +from eth._utils.datatypes import ( + Configurable, +) from eth.abc import ( AtomicDatabaseAPI, BlockHeaderAPI, @@ -21,9 +24,6 @@ from eth.db.header import ( HeaderDB, ) -from eth._utils.datatypes import ( - Configurable, -) class HeaderChain(Configurable, HeaderChainAPI): diff --git a/eth/chains/mainnet/constants.py b/eth/chains/mainnet/constants.py index 4a42c06c8e..a75d3c9b34 100644 --- a/eth/chains/mainnet/constants.py +++ b/eth/chains/mainnet/constants.py @@ -1,5 +1,6 @@ -from eth_typing import BlockNumber - +from eth_typing import ( + BlockNumber, +) # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md MAINNET_CHAIN_ID = 1 diff --git a/eth/chains/ropsten/constants.py b/eth/chains/ropsten/constants.py index 9fe0bbe456..67498c066c 100644 --- a/eth/chains/ropsten/constants.py +++ b/eth/chains/ropsten/constants.py @@ -1,5 +1,6 @@ -from eth_typing import BlockNumber - +from eth_typing import ( + BlockNumber, +) # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md ROPSTEN_CHAIN_ID = 3 diff --git a/eth/consensus/clique/_utils.py b/eth/consensus/clique/_utils.py index 4473401187..368bdf75f2 100644 --- a/eth/consensus/clique/_utils.py +++ b/eth/consensus/clique/_utils.py @@ -2,19 +2,25 @@ Iterable, ) -from eth_keys import keys -from eth_keys.datatypes import PrivateKey +from eth_keys import ( + keys, +) +from eth_keys.datatypes import ( + PrivateKey, +) from eth_typing import ( Address, Hash32, ) from eth_utils import ( + ValidationError, encode_hex, to_tuple, - ValidationError, ) -from eth._utils.headers import eth_now +from eth._utils.headers import ( + eth_now, +) from eth.abc import ( BlockHeaderAPI, ) diff --git a/eth/consensus/clique/clique.py b/eth/consensus/clique/clique.py index 5c6e640386..bee4c16acd 100644 --- a/eth/consensus/clique/clique.py +++ b/eth/consensus/clique/clique.py @@ -4,26 +4,25 @@ Sequence, ) -from eth.abc import ( - AtomicDatabaseAPI, - BlockHeaderAPI, - VirtualMachineAPI, - VirtualMachineModifierAPI, -) -from eth.db.chain import ChainDB - from eth_typing import ( Address, ) from eth_utils import ( + ValidationError, encode_hex, to_tuple, - ValidationError, ) from eth.abc import ( + AtomicDatabaseAPI, + BlockHeaderAPI, ConsensusAPI, ConsensusContextAPI, + VirtualMachineAPI, + VirtualMachineModifierAPI, +) +from eth.db.chain import ( + ChainDB, ) from eth.typing import ( HeaderParams, @@ -31,17 +30,19 @@ VMFork, ) +from ._utils import ( + get_block_signer, + is_in_turn, + validate_header_integrity, +) from .constants import ( EPOCH_LENGTH, ) from .datatypes import ( Snapshot, ) -from .snapshot_manager import SnapshotManager -from ._utils import ( - get_block_signer, - is_in_turn, - validate_header_integrity, +from .snapshot_manager import ( + SnapshotManager, ) diff --git a/eth/consensus/clique/constants.py b/eth/consensus/clique/constants.py index 474bde958c..44d7f1a886 100644 --- a/eth/consensus/clique/constants.py +++ b/eth/consensus/clique/constants.py @@ -1,4 +1,6 @@ -from eth_utils import decode_hex +from eth_utils import ( + decode_hex, +) ALLOWED_CLIQUE_DIFFICULTIES = {1, 2} diff --git a/eth/consensus/clique/datatypes.py b/eth/consensus/clique/datatypes.py index 554d1e0c03..d3b3955def 100644 --- a/eth/consensus/clique/datatypes.py +++ b/eth/consensus/clique/datatypes.py @@ -1,5 +1,5 @@ from enum import ( - Enum + Enum, ) from typing import ( Dict, @@ -11,7 +11,7 @@ from eth_typing import ( Address, - Hash32 + Hash32, ) from eth_utils import ( ValidationError, @@ -19,7 +19,7 @@ from .constants import ( NONCE_AUTH, - NONCE_DROP + NONCE_DROP, ) diff --git a/eth/consensus/clique/encoding.py b/eth/consensus/clique/encoding.py index a67faaf6ef..c8cb2bfb8d 100644 --- a/eth/consensus/clique/encoding.py +++ b/eth/consensus/clique/encoding.py @@ -1,4 +1,3 @@ -import rlp from typing import ( Tuple, ) @@ -6,16 +5,17 @@ from eth_typing import ( Address, ) +import rlp -from eth.rlp.sedes import ( - uint256, -) from eth.consensus.clique.datatypes import ( Snapshot, Tally, Vote, VoteAction, ) +from eth.rlp.sedes import ( + uint256, +) ADDRESS_TALLY_SEDES = rlp.sedes.List((rlp.sedes.binary, rlp.sedes.binary)) VOTE_SEDES = rlp.sedes.List( diff --git a/eth/consensus/clique/exceptions.py b/eth/consensus/clique/exceptions.py index 843a65cdee..fcd90a8e18 100644 --- a/eth/consensus/clique/exceptions.py +++ b/eth/consensus/clique/exceptions.py @@ -1,4 +1,6 @@ -from eth.exceptions import PyEVMError +from eth.exceptions import ( + PyEVMError, +) class SnapshotNotFound(PyEVMError): diff --git a/eth/consensus/clique/snapshot_manager.py b/eth/consensus/clique/snapshot_manager.py index cb66d83a4e..434fd572a2 100644 --- a/eth/consensus/clique/snapshot_manager.py +++ b/eth/consensus/clique/snapshot_manager.py @@ -1,12 +1,5 @@ -import lru -from typing import Iterable - -from eth.abc import ( - BlockHeaderAPI, - ChainDatabaseAPI, -) -from eth.exceptions import ( - HeaderNotFound, +from typing import ( + Iterable, ) from eth_typing import ( @@ -14,17 +7,24 @@ Hash32, ) from eth_utils import ( + ValidationError, encode_hex, get_extended_debug_logger, - ValidationError, ) +import lru -from .encoding import ( - decode_snapshot, - encode_snapshot, +from eth.abc import ( + BlockHeaderAPI, + ChainDatabaseAPI, ) -from .exceptions import ( - SnapshotNotFound, +from eth.exceptions import ( + HeaderNotFound, +) + +from ._utils import ( + get_block_signer, + get_signers_at_checkpoint, + is_checkpoint, ) from .constants import ( IN_MEMORY_SNAPSHOTS, @@ -38,11 +38,12 @@ Vote, VoteAction, ) - -from ._utils import ( - get_signers_at_checkpoint, - get_block_signer, - is_checkpoint, +from .encoding import ( + decode_snapshot, + encode_snapshot, +) +from .exceptions import ( + SnapshotNotFound, ) diff --git a/eth/consensus/noproof.py b/eth/consensus/noproof.py index 06fb9e3870..40a174a984 100644 --- a/eth/consensus/noproof.py +++ b/eth/consensus/noproof.py @@ -1,6 +1,7 @@ from typing import ( Iterable, ) + from eth.abc import ( AtomicDatabaseAPI, BlockHeaderAPI, diff --git a/eth/consensus/pos.py b/eth/consensus/pos.py index 12b1fcd3ad..c38183fdf5 100644 --- a/eth/consensus/pos.py +++ b/eth/consensus/pos.py @@ -1,6 +1,7 @@ from typing import ( Iterable, ) + from eth.abc import ( AtomicDatabaseAPI, BlockHeaderAPI, diff --git a/eth/consensus/pow.py b/eth/consensus/pow.py index bf5228f6f0..7b636a65f8 100644 --- a/eth/consensus/pow.py +++ b/eth/consensus/pow.py @@ -1,29 +1,29 @@ -from collections import OrderedDict +from collections import ( + OrderedDict, +) from typing import ( Iterable, Tuple, ) +from eth_hash.auto import ( + keccak, +) from eth_typing import ( Address, Hash32, ) - from eth_utils import ( - big_endian_to_int, ValidationError, + big_endian_to_int, encode_hex, ) - -from eth_hash.auto import keccak - from pyethash import ( EPOCH_LENGTH, hashimoto_light, mkcache_bytes, ) - from eth.abc import ( AtomicDatabaseAPI, BlockHeaderAPI, @@ -34,7 +34,6 @@ validate_lte, ) - # Type annotation here is to ensure we don't accidentally use strings instead of bytes. cache_by_epoch: 'OrderedDict[int, bytearray]' = OrderedDict() CACHE_MAX_ITEMS = 10 diff --git a/eth/constants.py b/eth/constants.py index 762a46353d..f5262943c2 100644 --- a/eth/constants.py +++ b/eth/constants.py @@ -1,16 +1,22 @@ +from typing import ( + List, + Optional, +) + from eth_typing import ( Address, BlockNumber, Hash32, ) -from typing import ( - List, - Optional, + +from eth._warnings import ( + catch_and_ignore_import_warning, ) -from eth._warnings import catch_and_ignore_import_warning with catch_and_ignore_import_warning(): - from eth_utils import denoms + from eth_utils import ( + denoms, + ) ANY = 'any' diff --git a/eth/db/accesslog.py b/eth/db/accesslog.py index c4f0d84caf..074c50fe6c 100644 --- a/eth/db/accesslog.py +++ b/eth/db/accesslog.py @@ -1,22 +1,24 @@ -from contextlib import contextmanager +from contextlib import ( + contextmanager, +) import logging from typing import ( - Iterator, FrozenSet, + Iterator, Set, ) from eth.abc import ( - AtomicWriteBatchAPI, AtomicDatabaseAPI, + AtomicWriteBatchAPI, DatabaseAPI, ) -from eth.db.backends.base import ( - BaseDB, -) from eth.db.atomic import ( BaseAtomicDB, ) +from eth.db.backends.base import ( + BaseDB, +) class KeyAccessLoggerDB(BaseDB): diff --git a/eth/db/account.py b/eth/db/account.py index 5ada5c89be..084bb1ea0e 100644 --- a/eth/db/account.py +++ b/eth/db/account.py @@ -1,26 +1,29 @@ -from lru import LRU from typing import ( - cast, Dict, Iterable, Set, Tuple, + cast, ) -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_typing import ( Address, - Hash32 + Hash32, ) - from eth_utils import ( + ValidationError, encode_hex, get_extended_debug_logger, int_to_big_endian, to_checksum_address, to_dict, to_tuple, - ValidationError, +) +from lru import ( + LRU, ) import rlp from trie import ( @@ -43,6 +46,9 @@ KeyAccessLoggerAtomicDB, KeyAccessLoggerDB, ) +from eth.db.backends.memory import ( + MemoryDB, +) from eth.db.batch import ( BatchDB, ) @@ -55,9 +61,6 @@ from eth.db.journal import ( JournalDB, ) -from eth.db.backends.memory import ( - MemoryDB, -) from eth.db.storage import ( AccountStorageDB, ) @@ -65,23 +68,25 @@ AccountQueryTracker, MetaWitness, ) -from eth.typing import ( - JournalDBCheckpoint, -) -from eth.vm.interrupt import ( - MissingAccountTrieNode, - MissingBytecode, -) from eth.rlp.accounts import ( Account, ) +from eth.typing import ( + JournalDBCheckpoint, +) from eth.validation import ( + validate_canonical_address, validate_is_bytes, validate_uint256, - validate_canonical_address, +) +from eth.vm.interrupt import ( + MissingAccountTrieNode, + MissingBytecode, ) -from .hash_trie import HashTrie +from .hash_trie import ( + HashTrie, +) IS_PRESENT_VALUE = b'' diff --git a/eth/db/atomic.py b/eth/db/atomic.py index 4bfe8de9f0..70df739afa 100644 --- a/eth/db/atomic.py +++ b/eth/db/atomic.py @@ -1,4 +1,6 @@ -from contextlib import contextmanager +from contextlib import ( + contextmanager, +) import logging from typing import ( Iterator, @@ -12,14 +14,18 @@ AtomicWriteBatchAPI, DatabaseAPI, ) - +from eth.db.backends.base import ( + BaseAtomicDB, + BaseDB, +) +from eth.db.backends.memory import ( + MemoryDB, +) from eth.db.diff import ( DBDiff, DBDiffTracker, DiffMissingError, ) -from eth.db.backends.base import BaseAtomicDB, BaseDB -from eth.db.backends.memory import MemoryDB class AtomicDB(BaseAtomicDB): diff --git a/eth/db/backends/level.py b/eth/db/backends/level.py index fb5763fed9..0ac6eef425 100644 --- a/eth/db/backends/level.py +++ b/eth/db/backends/level.py @@ -1,13 +1,22 @@ -from contextlib import contextmanager +from contextlib import ( + contextmanager, +) import logging -from pathlib import Path +from pathlib import ( + Path, +) from typing import ( - Iterator, TYPE_CHECKING, + Iterator, ) -from eth_utils import ValidationError +from eth_utils import ( + ValidationError, +) +from eth._warnings import ( + catch_and_ignore_import_warning, +) from eth.abc import ( AtomicWriteBatchAPI, DatabaseAPI, @@ -16,13 +25,12 @@ DBDiffTracker, DiffMissingError, ) + from .base import ( BaseAtomicDB, BaseDB, ) -from eth._warnings import catch_and_ignore_import_warning - if TYPE_CHECKING: with catch_and_ignore_import_warning(): import plyvel # noqa: F401 diff --git a/eth/db/batch.py b/eth/db/batch.py index a9835812e8..aee439caf3 100644 --- a/eth/db/batch.py +++ b/eth/db/batch.py @@ -4,13 +4,17 @@ ValidationError, ) -from eth.abc import DatabaseAPI +from eth.abc import ( + DatabaseAPI, +) +from eth.db.backends.base import ( + BaseDB, +) from eth.db.diff import ( DBDiff, DBDiffTracker, DiffMissingError, ) -from eth.db.backends.base import BaseDB class BatchDB(BaseDB): diff --git a/eth/db/cache.py b/eth/db/cache.py index a4dba2ae36..e9967dbfb8 100644 --- a/eth/db/cache.py +++ b/eth/db/cache.py @@ -1,7 +1,13 @@ -from lru import LRU +from lru import ( + LRU, +) -from eth.abc import DatabaseAPI -from eth.db.backends.base import BaseDB +from eth.abc import ( + DatabaseAPI, +) +from eth.db.backends.base import ( + BaseDB, +) class CacheDB(BaseDB): diff --git a/eth/db/chain.py b/eth/db/chain.py index 6db784b90b..a1aca85505 100644 --- a/eth/db/chain.py +++ b/eth/db/chain.py @@ -1,6 +1,5 @@ import functools import itertools - from typing import ( Dict, Iterable, @@ -10,28 +9,29 @@ cast, ) -from eth.vm.forks.shanghai.withdrawals import ( - Withdrawal, +from eth_hash.auto import ( + keccak, ) from eth_typing import ( BlockNumber, - Hash32 + Hash32, ) from eth_utils import ( encode_hex, ) - -from eth_hash.auto import keccak from trie.exceptions import ( MissingTrieNode, ) +from eth._warnings import ( + catch_and_ignore_import_warning, +) from eth.abc import ( + AtomicDatabaseAPI, BlockAPI, BlockHeaderAPI, ChainDatabaseAPI, DatabaseAPI, - AtomicDatabaseAPI, ReceiptAPI, ReceiptDecoderAPI, SignedTransactionAPI, @@ -43,37 +43,52 @@ GENESIS_PARENT_HASH, ) from eth.db.chain_gaps import ( - fill_gap, + GENESIS_CHAIN_GAPS, GapChange, GapInfo, - GENESIS_CHAIN_GAPS, + fill_gap, is_block_number_in_gap, reopen_gap, ) -from eth.db.trie import make_trie_root_and_nodes +from eth.db.header import ( + HeaderDB, +) +from eth.db.schema import ( + SchemaV1, +) +from eth.db.trie import ( + make_trie_root_and_nodes, +) from eth.exceptions import ( HeaderNotFound, ReceiptNotFound, TransactionNotFound, ) -from eth.db.header import HeaderDB -from eth.db.schema import SchemaV1 -from eth.rlp.sedes import chain_gaps -from eth.typing import ChainGaps +from eth.rlp.sedes import ( + chain_gaps, +) +from eth.typing import ( + ChainGaps, +) from eth.validation import ( validate_word, ) -from eth.vm.header import HeaderSedes -from eth._warnings import catch_and_ignore_import_warning +from eth.vm.forks.shanghai.withdrawals import ( + Withdrawal, +) +from eth.vm.header import ( + HeaderSedes, +) + with catch_and_ignore_import_warning(): + from eth_utils import ( + ValidationError, + to_tuple, + ) import rlp from trie import ( HexaryTrie, ) - from eth_utils import ( - to_tuple, - ValidationError, - ) class BlockDataKey(rlp.Serializable): diff --git a/eth/db/chain_gaps.py b/eth/db/chain_gaps.py index 4ab125d11c..93c0423048 100644 --- a/eth/db/chain_gaps.py +++ b/eth/db/chain_gaps.py @@ -1,14 +1,24 @@ import enum -from typing import Iterable, Tuple +from typing import ( + Iterable, + Tuple, +) -from eth_typing import BlockNumber +from eth_typing import ( + BlockNumber, +) from eth_utils import ( ValidationError, to_tuple, ) -from eth.exceptions import GapTrackingCorrupted -from eth.typing import BlockRange, ChainGaps +from eth.exceptions import ( + GapTrackingCorrupted, +) +from eth.typing import ( + BlockRange, + ChainGaps, +) class GapChange(enum.Enum): diff --git a/eth/db/diff.py b/eth/db/diff.py index d94553f62a..060437789c 100644 --- a/eth/db/diff.py +++ b/eth/db/diff.py @@ -3,12 +3,12 @@ MutableMapping, ) from typing import ( - cast, + TYPE_CHECKING, Dict, Iterable, - Union, Tuple, - TYPE_CHECKING, + Union, + cast, ) from eth_utils import ( @@ -16,8 +16,12 @@ to_tuple, ) -from eth.abc import DatabaseAPI -from eth.vm.interrupt import EVMMissingData +from eth.abc import ( + DatabaseAPI, +) +from eth.vm.interrupt import ( + EVMMissingData, +) if TYPE_CHECKING: ABC_Mutable_Mapping = MutableMapping[bytes, Union[bytes, 'MissingReason']] diff --git a/eth/db/hash_trie.py b/eth/db/hash_trie.py index 7b94c79530..6f218d56e0 100644 --- a/eth/db/hash_trie.py +++ b/eth/db/hash_trie.py @@ -1,11 +1,15 @@ import contextlib from typing import ( - cast, Iterator, + cast, ) -from eth_hash.auto import keccak -from trie import HexaryTrie +from eth_hash.auto import ( + keccak, +) +from trie import ( + HexaryTrie, +) from eth.db.keymap import ( KeyMapDB, diff --git a/eth/db/header.py b/eth/db/header.py index 862dba1a75..e9c72cc26e 100644 --- a/eth/db/header.py +++ b/eth/db/header.py @@ -1,29 +1,26 @@ import functools from typing import ( - cast, Iterable, Sequence, Tuple, + cast, ) -import rlp - -from eth_utils.toolz import ( - concat, - first, - sliding_window, +from eth_typing import ( + BlockNumber, + Hash32, ) - from eth_utils import ( + ValidationError, encode_hex, to_tuple, - ValidationError, ) - -from eth_typing import ( - Hash32, - BlockNumber, +from eth_utils.toolz import ( + concat, + first, + sliding_window, ) +import rlp from eth.abc import ( AtomicDatabaseAPI, @@ -35,27 +32,35 @@ GENESIS_PARENT_HASH, ) from eth.db.chain_gaps import ( - GapChange, - GapInfo, GAP_WRITES, GENESIS_CHAIN_GAPS, + GapChange, + GapInfo, fill_gap, reopen_gap, ) +from eth.db.schema import ( + SchemaV1, +) from eth.exceptions import ( CanonicalHeadNotFound, CheckpointsMustBeCanonical, HeaderNotFound, ParentNotFound, ) -from eth.db.schema import SchemaV1 -from eth.rlp.sedes import chain_gaps -from eth.typing import ChainGaps +from eth.rlp.sedes import ( + chain_gaps, +) +from eth.typing import ( + ChainGaps, +) from eth.validation import ( validate_block_number, validate_word, ) -from eth.vm.header import HeaderSedes +from eth.vm.header import ( + HeaderSedes, +) class HeaderDB(HeaderDatabaseAPI): diff --git a/eth/db/journal.py b/eth/db/journal.py index 033c079170..5b0e33a8db 100644 --- a/eth/db/journal.py +++ b/eth/db/journal.py @@ -2,21 +2,37 @@ from itertools import ( count, ) -from typing import Callable, cast, Dict, List, Set, Union +from typing import ( + Callable, + Dict, + List, + Set, + Union, + cast, +) +from eth_utils import ( + ValidationError, +) from eth_utils.toolz import ( first, nth, ) -from eth_utils import ( - ValidationError, -) -from eth.abc import DatabaseAPI -from eth.typing import JournalDBCheckpoint +from eth.abc import ( + DatabaseAPI, +) +from eth.typing import ( + JournalDBCheckpoint, +) -from .backends.base import BaseDB -from .diff import DBDiff, DBDiffTracker +from .backends.base import ( + BaseDB, +) +from .diff import ( + DBDiff, + DBDiffTracker, +) class DeletedEntry: diff --git a/eth/db/keymap.py b/eth/db/keymap.py index e65d1bcd2a..9481522dfd 100644 --- a/eth/db/keymap.py +++ b/eth/db/keymap.py @@ -1,13 +1,16 @@ from abc import ( abstractmethod, ) - from typing import ( Any, ) -from eth.abc import DatabaseAPI -from eth.db.backends.base import BaseDB +from eth.abc import ( + DatabaseAPI, +) +from eth.db.backends.base import ( + BaseDB, +) class KeyMapDB(BaseDB): diff --git a/eth/db/schema.py b/eth/db/schema.py index 760d763b4a..6abdeb1fa8 100644 --- a/eth/db/schema.py +++ b/eth/db/schema.py @@ -3,7 +3,9 @@ Hash32, ) -from eth.abc import SchemaAPI +from eth.abc import ( + SchemaAPI, +) class SchemaV1(SchemaAPI): diff --git a/eth/db/slow_journal.py b/eth/db/slow_journal.py index 4101dea216..5585e92d4a 100644 --- a/eth/db/slow_journal.py +++ b/eth/db/slow_journal.py @@ -1,19 +1,31 @@ import collections -from typing import cast, Dict, Set, Union +from typing import ( + Dict, + Set, + Union, + cast, +) import uuid +from eth_utils import ( + ValidationError, +) from eth_utils.toolz import ( first, merge, nth, ) -from eth_utils import ( - ValidationError, -) -from eth.abc import DatabaseAPI -from eth.db.backends.base import BaseDB -from eth.db.diff import DBDiff, DBDiffTracker +from eth.abc import ( + DatabaseAPI, +) +from eth.db.backends.base import ( + BaseDB, +) +from eth.db.diff import ( + DBDiff, + DBDiffTracker, +) class DeletedEntry: diff --git a/eth/db/storage.py b/eth/db/storage.py index e3c87bb9ce..ade294a723 100644 --- a/eth/db/storage.py +++ b/eth/db/storage.py @@ -5,7 +5,9 @@ Set, ) -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_typing import ( Address, Hash32, @@ -50,12 +52,12 @@ from eth.db.journal import ( JournalDB, ) -from eth.vm.interrupt import ( - MissingStorageTrieNode, -) from eth.typing import ( JournalDBCheckpoint, ) +from eth.vm.interrupt import ( + MissingStorageTrieNode, +) class PendingWrites(NamedTuple): diff --git a/eth/db/trie.py b/eth/db/trie.py index f529a5b848..e637094930 100644 --- a/eth/db/trie.py +++ b/eth/db/trie.py @@ -1,13 +1,19 @@ import functools -from typing import Dict, Sequence, Tuple, Union +from typing import ( + Dict, + Sequence, + Tuple, + Union, +) +from eth_typing import ( + Hash32, +) import rlp from trie import ( HexaryTrie, ) -from eth_typing import Hash32 - from eth.abc import ( ReceiptAPI, SignedTransactionAPI, diff --git a/eth/estimators/gas.py b/eth/estimators/gas.py index b2b0481e71..2a27d2e962 100644 --- a/eth/estimators/gas.py +++ b/eth/estimators/gas.py @@ -1,14 +1,22 @@ -from typing import cast, Optional - -from eth_utils.toolz import curry +from typing import ( + Optional, + cast, +) -from eth.exceptions import VMError +from eth_utils.toolz import ( + curry, +) from eth.abc import ( SignedTransactionAPI, StateAPI, ) -from eth.vm.spoof import SpoofTransaction +from eth.exceptions import ( + VMError, +) +from eth.vm.spoof import ( + SpoofTransaction, +) def _get_computation_error(state: StateAPI, transaction: SignedTransactionAPI) -> Optional[VMError]: diff --git a/eth/exceptions.py b/eth/exceptions.py index 10b7e51870..ca207c85ca 100644 --- a/eth/exceptions.py +++ b/eth/exceptions.py @@ -1,4 +1,6 @@ -from eth_typing import Hash32 +from eth_typing import ( + Hash32, +) class PyEVMError(Exception): diff --git a/eth/precompiles/blake2.py b/eth/precompiles/blake2.py index ac6a16cd7e..47985c5bb3 100644 --- a/eth/precompiles/blake2.py +++ b/eth/precompiles/blake2.py @@ -2,23 +2,29 @@ ValidationError, ) -from eth._utils.blake2.coders import extract_blake2b_parameters +from eth._utils.blake2.coders import ( + extract_blake2b_parameters, +) +from eth.abc import ( + ComputationAPI, +) from eth.exceptions import ( VMError, ) -from eth.vm.computation import ( - MessageComputation, -) try: - from blake2b import compress as blake2b_compress + from blake2b import ( + compress as blake2b_compress, + ) except ImportError: - from eth._utils.blake2.compression import blake2b_compress + from eth._utils.blake2.compression import ( + blake2b_compress, + ) GAS_COST_PER_ROUND = 1 -def blake2b_fcompress(computation: MessageComputation) -> MessageComputation: +def blake2b_fcompress(computation: ComputationAPI) -> ComputationAPI: try: parameters = extract_blake2b_parameters(computation.msg.data_as_bytes) except ValidationError as exc: diff --git a/eth/precompiles/ecadd.py b/eth/precompiles/ecadd.py index eecf18813c..ad9451e4a0 100644 --- a/eth/precompiles/ecadd.py +++ b/eth/precompiles/ecadd.py @@ -1,7 +1,5 @@ -from typing import Tuple - -from py_ecc import ( - optimized_bn128 as bn128, +from typing import ( + Tuple, ) from eth_utils import ( @@ -12,11 +10,12 @@ from eth_utils.toolz import ( curry, ) +from py_ecc import ( + optimized_bn128 as bn128, +) -from eth import constants - -from eth.exceptions import ( - VMError, +from eth import ( + constants, ) from eth._utils.bn128 import ( validate_point, @@ -25,16 +24,18 @@ pad32, pad32r, ) - -from eth.vm.computation import ( - MessageComputation, +from eth.abc import ( + ComputationAPI, +) +from eth.exceptions import ( + VMError, ) @curry def ecadd( - computation: MessageComputation, - gas_cost: int = constants.GAS_ECADD) -> MessageComputation: + computation: ComputationAPI, + gas_cost: int = constants.GAS_ECADD) -> ComputationAPI: computation.consume_gas(gas_cost, reason='ECADD Precompile') diff --git a/eth/precompiles/ecmul.py b/eth/precompiles/ecmul.py index 506815dfec..bcff2eb3d2 100644 --- a/eth/precompiles/ecmul.py +++ b/eth/precompiles/ecmul.py @@ -1,22 +1,21 @@ -from typing import Tuple - -from py_ecc import ( - optimized_bn128 as bn128, +from typing import ( + Tuple, ) from eth_utils import ( + ValidationError, big_endian_to_int, int_to_big_endian, - ValidationError, ) from eth_utils.toolz import ( curry, ) +from py_ecc import ( + optimized_bn128 as bn128, +) -from eth import constants - -from eth.exceptions import ( - VMError, +from eth import ( + constants, ) from eth._utils.bn128 import ( validate_point, @@ -25,16 +24,18 @@ pad32, pad32r, ) - -from eth.vm.computation import ( - MessageComputation, +from eth.abc import ( + ComputationAPI, +) +from eth.exceptions import ( + VMError, ) @curry def ecmul( - computation: MessageComputation, - gas_cost: int = constants.GAS_ECMUL) -> MessageComputation: + computation: ComputationAPI, + gas_cost: int = constants.GAS_ECMUL) -> ComputationAPI: computation.consume_gas(gas_cost, reason='ECMUL Precompile') diff --git a/eth/precompiles/ecpairing.py b/eth/precompiles/ecpairing.py index 971c86694d..703a1210be 100644 --- a/eth/precompiles/ecpairing.py +++ b/eth/precompiles/ecpairing.py @@ -1,8 +1,10 @@ -from typing import Tuple +from typing import ( + Tuple, +) from eth_utils import ( - big_endian_to_int, ValidationError, + big_endian_to_int, ) from eth_utils.toolz import ( curry, @@ -12,28 +14,25 @@ optimized_bn128 as bn128, ) -from eth import constants - -from eth.exceptions import ( - VMError, +from eth import ( + constants, ) - -from eth.typing import ( - BytesOrView, -) - from eth._utils.bn128 import ( - validate_point, FQP_point_to_FQ2_point, + validate_point, ) from eth._utils.padding import ( pad32, ) - -from eth.vm.computation import ( - MessageComputation, +from eth.abc import ( + ComputationAPI, +) +from eth.exceptions import ( + VMError, +) +from eth.typing import ( + BytesOrView, ) - ZERO = bn128.Z2 EXPONENT = bn128.FQ12.one() @@ -41,9 +40,9 @@ @curry def ecpairing( - computation: MessageComputation, + computation: ComputationAPI, gas_cost_base: int = constants.GAS_ECPAIRING_BASE, - gas_cost_per_point: int = constants.GAS_ECPAIRING_PER_POINT) -> MessageComputation: + gas_cost_per_point: int = constants.GAS_ECPAIRING_PER_POINT) -> ComputationAPI: if len(computation.msg.data) % 192: # data length must be an exact multiple of 192 diff --git a/eth/precompiles/ecrecover.py b/eth/precompiles/ecrecover.py index 2a1b0e83bd..1f5b4073ab 100644 --- a/eth/precompiles/ecrecover.py +++ b/eth/precompiles/ecrecover.py @@ -1,31 +1,32 @@ -from eth_keys import keys +from eth_keys import ( + keys, +) from eth_keys.exceptions import ( BadSignature, ) - from eth_utils import ( - big_endian_to_int, ValidationError, + big_endian_to_int, ) -from eth import constants - +from eth import ( + constants, +) from eth._utils.padding import ( pad32, pad32r, ) - +from eth.abc import ( + ComputationAPI, +) from eth.validation import ( - validate_lt_secpk1n, validate_gte, + validate_lt_secpk1n, validate_lte, ) -from eth.vm.computation import ( - MessageComputation, -) -def ecrecover(computation: MessageComputation) -> MessageComputation: +def ecrecover(computation: ComputationAPI) -> ComputationAPI: computation.consume_gas(constants.GAS_ECRECOVER, reason="ECRecover Precompile") data = computation.msg.data_as_bytes raw_message_hash = data[:32] diff --git a/eth/precompiles/identity.py b/eth/precompiles/identity.py index 22b76cbe05..949714c69f 100644 --- a/eth/precompiles/identity.py +++ b/eth/precompiles/identity.py @@ -1,14 +1,15 @@ -from eth import constants +from eth import ( + constants, +) from eth._utils.numeric import ( ceil32, ) - -from eth.vm.computation import ( - MessageComputation, +from eth.abc import ( + ComputationAPI, ) -def identity(computation: MessageComputation) -> MessageComputation: +def identity(computation: ComputationAPI) -> ComputationAPI: word_count = ceil32(len(computation.msg.data)) // 32 gas_fee = constants.GAS_IDENTITY + word_count * constants.GAS_IDENTITYWORD diff --git a/eth/precompiles/modexp.py b/eth/precompiles/modexp.py index 9cad85a7ff..35c8aca568 100644 --- a/eth/precompiles/modexp.py +++ b/eth/precompiles/modexp.py @@ -11,19 +11,19 @@ curry, ) -from eth import constants - +from eth import ( + constants, +) from eth._utils.numeric import ( get_highest_bit_index, ) from eth._utils.padding import ( pad32r, - zpad_right, zpad_left, + zpad_right, ) - -from eth.vm.computation import ( - MessageComputation, +from eth.abc import ( + ComputationAPI, ) @@ -127,9 +127,9 @@ def _modexp(data: bytes) -> int: @curry def modexp( - computation: MessageComputation, + computation: ComputationAPI, gas_calculator: Callable[[bytes], int] = _compute_modexp_gas_fee_eip_198 -) -> MessageComputation: +) -> ComputationAPI: """ https://github.com/ethereum/EIPs/pull/198 """ diff --git a/eth/precompiles/ripemd160.py b/eth/precompiles/ripemd160.py index 573c0d550a..0f2a9803d4 100644 --- a/eth/precompiles/ripemd160.py +++ b/eth/precompiles/ripemd160.py @@ -1,19 +1,20 @@ import hashlib -from eth import constants - +from eth import ( + constants, +) from eth._utils.numeric import ( ceil32, ) from eth._utils.padding import ( pad32, ) -from eth.vm.computation import ( - MessageComputation, +from eth.abc import ( + ComputationAPI, ) -def ripemd160(computation: MessageComputation) -> MessageComputation: +def ripemd160(computation: ComputationAPI) -> ComputationAPI: word_count = ceil32(len(computation.msg.data)) // 32 gas_fee = constants.GAS_RIPEMD160 + word_count * constants.GAS_RIPEMD160WORD diff --git a/eth/precompiles/sha256.py b/eth/precompiles/sha256.py index 73960e9440..2001a43e59 100644 --- a/eth/precompiles/sha256.py +++ b/eth/precompiles/sha256.py @@ -1,17 +1,17 @@ import hashlib -from eth import constants - +from eth import ( + constants, +) from eth._utils.numeric import ( ceil32, ) - -from eth.vm.computation import ( - MessageComputation, +from eth.abc import ( + ComputationAPI, ) -def sha256(computation: MessageComputation) -> MessageComputation: +def sha256(computation: ComputationAPI) -> ComputationAPI: word_count = ceil32(len(computation.msg.data)) // 32 gas_fee = constants.GAS_SHA256 + word_count * constants.GAS_SHA256WORD diff --git a/eth/rlp/accounts.py b/eth/rlp/accounts.py index ce4ae4658e..83e8efeeaf 100644 --- a/eth/rlp/accounts.py +++ b/eth/rlp/accounts.py @@ -1,21 +1,25 @@ +from typing import ( + Any, +) + import rlp from rlp.sedes import ( big_endian_int, ) -from eth.abc import AccountAPI +from eth.abc import ( + AccountAPI, +) from eth.constants import ( - EMPTY_SHA3, BLANK_ROOT_HASH, + EMPTY_SHA3, ) from .sedes import ( - trie_root, hash32, + trie_root, ) -from typing import Any - class Account(rlp.Serializable, AccountAPI): """ diff --git a/eth/rlp/headers.py b/eth/rlp/headers.py index 2add9f5387..fc5a8d6c47 100644 --- a/eth/rlp/headers.py +++ b/eth/rlp/headers.py @@ -4,24 +4,23 @@ overload, ) -import rlp -from rlp.sedes import ( - big_endian_int, - Binary, - binary, +from eth_hash.auto import ( + keccak, ) - from eth_typing import ( Address, BlockNumber, Hash32, ) - -from eth_hash.auto import keccak - from eth_utils import ( encode_hex, ) +import rlp +from rlp.sedes import ( + Binary, + big_endian_int, + binary, +) from eth._utils.headers import ( new_timestamp_from_parent, @@ -31,20 +30,22 @@ MiningHeaderAPI, ) from eth.constants import ( - ZERO_ADDRESS, - ZERO_HASH32, + BLANK_ROOT_HASH, EMPTY_UNCLE_HASH, GENESIS_NONCE, GENESIS_PARENT_HASH, - BLANK_ROOT_HASH, + ZERO_ADDRESS, + ZERO_HASH32, +) +from eth.typing import ( + HeaderParams, ) -from eth.typing import HeaderParams from .sedes import ( address, hash32, - uint256, trie_root, + uint256, ) diff --git a/eth/rlp/logs.py b/eth/rlp/logs.py index ea4f0db58f..649075aa6e 100644 --- a/eth/rlp/logs.py +++ b/eth/rlp/logs.py @@ -1,15 +1,16 @@ -from rlp.sedes import ( - CountableList, - binary, -) - from typing import ( Tuple, ) import rlp +from rlp.sedes import ( + CountableList, + binary, +) -from eth.abc import LogAPI +from eth.abc import ( + LogAPI, +) from .sedes import ( address, diff --git a/eth/rlp/receipts.py b/eth/rlp/receipts.py index 44af73f852..dcd1fd593a 100644 --- a/eth/rlp/receipts.py +++ b/eth/rlp/receipts.py @@ -1,11 +1,15 @@ import itertools -from typing import Iterable +from typing import ( + Iterable, +) -from eth_bloom import BloomFilter +from eth_bloom import ( + BloomFilter, +) import rlp from rlp.sedes import ( - big_endian_int, CountableList, + big_endian_int, binary, ) @@ -14,7 +18,9 @@ ReceiptBuilderAPI, ) -from .logs import Log +from .logs import ( + Log, +) from .sedes import ( uint256, ) diff --git a/eth/rlp/sedes.py b/eth/rlp/sedes.py index 333bfd039a..1aac26bd3d 100644 --- a/eth/rlp/sedes.py +++ b/eth/rlp/sedes.py @@ -4,7 +4,6 @@ Binary, ) - address = Binary.fixed_length(20, allow_empty=True) hash32 = Binary.fixed_length(32) uint32 = BigEndianInt(32) diff --git a/eth/rlp/transactions.py b/eth/rlp/transactions.py index 14f6780a19..d2540fd0e7 100644 --- a/eth/rlp/transactions.py +++ b/eth/rlp/transactions.py @@ -5,26 +5,28 @@ cast, ) -from cached_property import cached_property -import rlp -from rlp.sedes import ( - big_endian_int, - binary, +from cached_property import ( + cached_property, +) +from eth_hash.auto import ( + keccak, ) - from eth_typing import ( Address, Hash32, ) - -from eth_hash.auto import keccak from eth_utils import ( ValidationError, ) +import rlp +from rlp.sedes import ( + big_endian_int, + binary, +) from eth.abc import ( BaseTransactionAPI, - MessageComputationAPI, + ComputationAPI, LegacyTransactionFieldsAPI, SignedTransactionAPI, TransactionBuilderAPI, @@ -32,7 +34,9 @@ UnsignedTransactionAPI, ) -from .sedes import address +from .sedes import ( + address, +) class BaseTransactionMethods(BaseTransactionAPI): @@ -44,7 +48,7 @@ def validate(self) -> None: def intrinsic_gas(self) -> int: return self.get_intrinsic_gas() - def gas_used_by(self, computation: MessageComputationAPI) -> int: + def gas_used_by(self, computation: ComputationAPI) -> int: return self.get_intrinsic_gas() + computation.get_gas_used() @property diff --git a/eth/tools/_utils/deprecation.py b/eth/tools/_utils/deprecation.py index 44710a20e0..49960c7a4d 100644 --- a/eth/tools/_utils/deprecation.py +++ b/eth/tools/_utils/deprecation.py @@ -1,12 +1,11 @@ import functools -import warnings from typing import ( Any, Callable, TypeVar, cast, ) - +import warnings TFunc = TypeVar("TFunc", bound=Callable[..., Any]) diff --git a/eth/tools/_utils/git.py b/eth/tools/_utils/git.py index d45eb91340..a2e3a2a2c8 100644 --- a/eth/tools/_utils/git.py +++ b/eth/tools/_utils/git.py @@ -1,6 +1,8 @@ import subprocess -from eth_utils import to_text +from eth_utils import ( + to_text, +) def get_version_from_git() -> str: diff --git a/eth/tools/_utils/hashing.py b/eth/tools/_utils/hashing.py index 1dcacdb20b..8744e1a852 100644 --- a/eth/tools/_utils/hashing.py +++ b/eth/tools/_utils/hashing.py @@ -4,13 +4,17 @@ cast, ) -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_typing import ( Hash32, ) import rlp -from eth.rlp.logs import Log +from eth.rlp.logs import ( + Log, +) def hash_log_entries(log_entries: Iterable[Tuple[bytes, Tuple[int, ...], bytes]]) -> Hash32: diff --git a/eth/tools/_utils/mappings.py b/eth/tools/_utils/mappings.py index 1a0483e25f..de449a3762 100644 --- a/eth/tools/_utils/mappings.py +++ b/eth/tools/_utils/mappings.py @@ -1,13 +1,16 @@ -from collections.abc import Mapping +from collections.abc import ( + Mapping, +) import itertools - from typing import ( Any, Dict, Sequence, ) -from eth_utils.toolz import merge_with +from eth_utils.toolz import ( + merge_with, +) def merge_if_dicts(values: Sequence[Dict[Any, Any]]) -> Any: diff --git a/eth/tools/_utils/normalization.py b/eth/tools/_utils/normalization.py index 27351a3437..04a8762b6e 100644 --- a/eth/tools/_utils/normalization.py +++ b/eth/tools/_utils/normalization.py @@ -4,7 +4,6 @@ Any, AnyStr, Callable, - cast, Dict, Iterable, List, @@ -12,28 +11,15 @@ Sequence, Tuple, Union, + cast, ) -from mypy_extensions import ( - TypedDict, -) - -from eth_utils.toolz import ( - assoc_in, - compose, - concat, - curry, - identity, - merge, -) -from eth_utils.toolz import curried - from eth_typing import ( Address, HexStr, ) - from eth_utils.curried import ( + ValidationError, apply_formatter_if, apply_formatter_to_array, apply_formatters_to_dict, @@ -49,18 +35,27 @@ to_bytes, to_canonical_address, to_dict, - ValidationError, +) +from eth_utils.toolz import ( + assoc_in, + compose, + concat, + curried, + curry, + identity, + merge, +) +from mypy_extensions import ( + TypedDict, ) from eth.constants import ( CREATE_CONTRACT_ADDRESS, ) - from eth.tools._utils.mappings import ( deep_merge, is_cleanly_mergable, ) - from eth.typing import ( AccountState, GeneralState, diff --git a/eth/tools/_utils/slow_code_stream.py b/eth/tools/_utils/slow_code_stream.py index 4547efdfd7..d459f6278c 100644 --- a/eth/tools/_utils/slow_code_stream.py +++ b/eth/tools/_utils/slow_code_stream.py @@ -3,13 +3,15 @@ import logging from typing import ( Iterator, - Set + Set, ) from eth.validation import ( validate_is_bytes, ) -from eth.vm import opcode_values +from eth.vm import ( + opcode_values, +) PUSH1, PUSH32, STOP = opcode_values.PUSH1, opcode_values.PUSH32, opcode_values.STOP diff --git a/eth/tools/_utils/vyper.py b/eth/tools/_utils/vyper.py index b1717e32fd..17e816fcb3 100644 --- a/eth/tools/_utils/vyper.py +++ b/eth/tools/_utils/vyper.py @@ -1,5 +1,4 @@ import functools - from typing import ( Any, Callable, @@ -10,10 +9,12 @@ try: from vyper.compile_lll import ( - compile_to_assembly, assembly_to_evm, + compile_to_assembly, + ) + from vyper.parser.parser_utils import ( + LLLnode, ) - from vyper.parser.parser_utils import LLLnode except ImportError: vyper_available = False else: diff --git a/eth/tools/builder/chain/builders.py b/eth/tools/builder/chain/builders.py index c3fa727a1f..f7540395b4 100644 --- a/eth/tools/builder/chain/builders.py +++ b/eth/tools/builder/chain/builders.py @@ -1,7 +1,6 @@ import functools import time from typing import ( - cast, Any, Callable, Dict, @@ -9,12 +8,7 @@ Tuple, Type, Union, -) - -from eth_utils.toolz import ( - curry, - merge, - pipe, + cast, ) from eth_typing import ( @@ -22,14 +16,20 @@ BlockNumber, Hash32, ) - from eth_utils import ( + ValidationError, to_dict, to_tuple, - ValidationError, +) +from eth_utils.toolz import ( + curry, + merge, + pipe, ) -from eth import constants +from eth import ( + constants, +) from eth.abc import ( AtomicDatabaseAPI, BlockAPI, @@ -37,47 +37,55 @@ MiningChainAPI, VirtualMachineAPI, ) -from eth.consensus.applier import ConsensusApplier -from eth.consensus.noproof import NoProofConsensus -from eth.db.atomic import AtomicDB +from eth.consensus.applier import ( + ConsensusApplier, +) +from eth.consensus.noproof import ( + NoProofConsensus, +) +from eth.db.atomic import ( + AtomicDB, +) from eth.db.backends.memory import ( MemoryDB, ) from eth.rlp.headers import ( HeaderParams, ) -from eth.tools.mining import POWMiningMixin from eth.tools._utils.mappings import ( deep_merge, ) from eth.tools._utils.normalization import ( normalize_state, ) +from eth.tools.mining import ( + POWMiningMixin, +) from eth.typing import ( AccountState, GeneralState, - VMFork, VMConfiguration, + VMFork, ) from eth.validation import ( validate_vm_configuration, ) from eth.vm.forks import ( - FrontierVM, - HomesteadVM, - TangerineWhistleVM, - SpuriousDragonVM, + ArrowGlacierVM, + BerlinVM, ByzantiumVM, ConstantinopleVM, - PetersburgVM, + FrontierVM, + GrayGlacierVM, + HomesteadVM, IstanbulVM, - MuirGlacierVM, - BerlinVM, LondonVM, - ArrowGlacierVM, - GrayGlacierVM, + MuirGlacierVM, ParisVM, + PetersburgVM, ShanghaiVM, + SpuriousDragonVM, + TangerineWhistleVM, ) diff --git a/eth/tools/db/atomic.py b/eth/tools/db/atomic.py index 7b3a2c5fc9..5ae0775ab3 100644 --- a/eth/tools/db/atomic.py +++ b/eth/tools/db/atomic.py @@ -1,8 +1,12 @@ import pytest -from eth_utils import ValidationError +from eth_utils import ( + ValidationError, +) -from eth.abc import AtomicDatabaseAPI +from eth.abc import ( + AtomicDatabaseAPI, +) class AtomicDatabaseBatchAPITestSuite: diff --git a/eth/tools/db/base.py b/eth/tools/db/base.py index f0d5011196..6cdc46ba64 100644 --- a/eth/tools/db/base.py +++ b/eth/tools/db/base.py @@ -1,6 +1,8 @@ import pytest -from eth.abc import DatabaseAPI +from eth.abc import ( + DatabaseAPI, +) class DatabaseAPITestSuite: diff --git a/eth/tools/factories/keys.py b/eth/tools/factories/keys.py index 4721cdb6ce..dd05fe605c 100644 --- a/eth/tools/factories/keys.py +++ b/eth/tools/factories/keys.py @@ -1,14 +1,17 @@ import secrets -try: - import factory -except ImportError: - raise ImportError("The p2p.tools.factories module requires the `factory_boy` library.") +from eth_keys import ( + keys, +) from eth_utils import ( int_to_big_endian, ) -from eth_keys import keys +try: + import factory +except ImportError: + raise ImportError( + "The p2p.tools.factories module requires the `factory_boy` library.") def _mk_private_key_bytes() -> bytes: diff --git a/eth/tools/factories/transaction.py b/eth/tools/factories/transaction.py index 86651f6962..d5bdf0e3d0 100644 --- a/eth/tools/factories/transaction.py +++ b/eth/tools/factories/transaction.py @@ -1,4 +1,6 @@ -from eth_utils.toolz import curry +from eth_utils.toolz import ( + curry, +) from eth.vm.spoof import ( SpoofTransaction, diff --git a/eth/tools/fixtures/_utils.py b/eth/tools/fixtures/_utils.py index fe9e85e107..1410559775 100644 --- a/eth/tools/fixtures/_utils.py +++ b/eth/tools/fixtures/_utils.py @@ -1,14 +1,15 @@ import fnmatch import functools import os - from typing import ( Any, Callable, Iterable, ) -from eth_utils import to_tuple +from eth_utils import ( + to_tuple, +) @to_tuple diff --git a/eth/tools/fixtures/fillers/_utils.py b/eth/tools/fixtures/fillers/_utils.py index 7319c0e08d..1adb7ddbda 100644 --- a/eth/tools/fixtures/fillers/_utils.py +++ b/eth/tools/fixtures/fillers/_utils.py @@ -8,7 +8,9 @@ Type, ) -from eth_keys import keys +from eth_keys import ( + keys, +) from eth_typing import ( Address, ) @@ -22,8 +24,12 @@ from eth._utils.padding import ( pad32, ) -from eth.constants import BLANK_ROOT_HASH -from eth.db.atomic import AtomicDB +from eth.constants import ( + BLANK_ROOT_HASH, +) +from eth.db.atomic import ( + AtomicDB, +) from eth.typing import ( AccountState, TransactionDict, diff --git a/eth/tools/fixtures/fillers/common.py b/eth/tools/fixtures/fillers/common.py index 6581c54873..edd023c91f 100644 --- a/eth/tools/fixtures/fillers/common.py +++ b/eth/tools/fixtures/fillers/common.py @@ -10,35 +10,35 @@ Callable, Dict, ) + +from eth_utils import ( + apply_formatters_to_dict, + decode_hex, + to_canonical_address, +) from eth_utils.toolz import ( assoc, assoc_in, curry, merge, ) -from eth_utils import ( - apply_formatters_to_dict, - decode_hex, - to_canonical_address, -) -from eth.tools.fixtures.helpers import ( - get_test_name, +from eth.tools._utils.mappings import ( + deep_merge, ) from eth.tools._utils.normalization import ( normalize_environment, normalize_execution, + normalize_networks, normalize_state, normalize_transaction, - normalize_networks, -) -from eth.tools._utils.mappings import ( - deep_merge, ) from eth.tools._utils.vyper import ( compile_vyper_lll, ) - +from eth.tools.fixtures.helpers import ( + get_test_name, +) from eth.typing import ( GeneralState, TransactionDict, @@ -49,7 +49,6 @@ wrap_in_list, ) - # # Defaults # diff --git a/eth/tools/fixtures/fillers/formatters.py b/eth/tools/fixtures/fillers/formatters.py index d286496402..85797638f2 100644 --- a/eth/tools/fixtures/fillers/formatters.py +++ b/eth/tools/fixtures/fillers/formatters.py @@ -12,9 +12,9 @@ to_checksum_address, to_hex, ) - -from eth_utils.toolz import curried - +from eth_utils.toolz import ( + curried, +) environment_formatter = apply_formatters_to_dict({ "currentCoinbase": to_checksum_address, diff --git a/eth/tools/fixtures/fillers/main.py b/eth/tools/fixtures/fillers/main.py index 4fa9a3e6cf..0e9cac7ddd 100644 --- a/eth/tools/fixtures/fillers/main.py +++ b/eth/tools/fixtures/fillers/main.py @@ -8,18 +8,23 @@ merge, ) +from eth.tools._utils.git import ( + get_version_from_git, +) from eth.tools.fixtures.helpers import ( get_test_name, ) -from eth.tools._utils.git import get_version_from_git from .formatters import ( filled_state_test_formatter, filled_vm_test_formatter, ) -from .state import fill_state_test -from .vm import fill_vm_test - +from .state import ( + fill_state_test, +) +from .vm import ( + fill_vm_test, +) FILLED_WITH_TEMPLATE = "py-evm-{version}" diff --git a/eth/tools/fixtures/fillers/state.py b/eth/tools/fixtures/fillers/state.py index 36aa71cb54..649ce558fd 100644 --- a/eth/tools/fixtures/fillers/state.py +++ b/eth/tools/fixtures/fillers/state.py @@ -1,14 +1,18 @@ -from collections import defaultdict +from collections import ( + defaultdict, +) from typing import ( Any, Dict, List, ) -from eth_utils import encode_hex +from eth_utils import ( + encode_hex, +) -from eth.tools.fixtures.helpers import ( - get_test_name, +from eth.tools._utils.mappings import ( + deep_merge, ) from eth.tools._utils.normalization import ( normalize_environment, @@ -16,21 +20,38 @@ normalize_state, normalize_transaction_group, ) -from eth.tools._utils.mappings import deep_merge -from eth.vm.forks.byzantium.state import ByzantiumState -from eth.vm.forks.constantinople.state import ConstantinopleState -from eth.vm.forks.frontier.state import FrontierState -from eth.vm.forks.homestead.state import HomesteadState -from eth.vm.forks.istanbul.state import IstanbulState -from eth.vm.forks.petersburg.state import PetersburgState -from eth.vm.forks.spurious_dragon.state import SpuriousDragonState -from eth.vm.forks.tangerine_whistle.state import TangerineWhistleState +from eth.tools.fixtures.helpers import ( + get_test_name, +) +from eth.vm.forks.byzantium.state import ( + ByzantiumState, +) +from eth.vm.forks.constantinople.state import ( + ConstantinopleState, +) +from eth.vm.forks.frontier.state import ( + FrontierState, +) +from eth.vm.forks.homestead.state import ( + HomesteadState, +) +from eth.vm.forks.istanbul.state import ( + IstanbulState, +) +from eth.vm.forks.petersburg.state import ( + PetersburgState, +) +from eth.vm.forks.spurious_dragon.state import ( + SpuriousDragonState, +) +from eth.vm.forks.tangerine_whistle.state import ( + TangerineWhistleState, +) from ._utils import ( calc_state_root, ) - ALL_NETWORKS = [ "Frontier", "Homestead", diff --git a/eth/tools/fixtures/fillers/vm.py b/eth/tools/fixtures/fillers/vm.py index 609d906dc9..b6dec34605 100644 --- a/eth/tools/fixtures/fillers/vm.py +++ b/eth/tools/fixtures/fillers/vm.py @@ -6,8 +6,11 @@ Union, ) -from eth.tools.fixtures.helpers import ( - get_test_name, +from eth.tools._utils.hashing import ( + hash_log_entries, +) +from eth.tools._utils.mappings import ( + deep_merge, ) from eth.tools._utils.normalization import ( normalize_bytes, @@ -18,8 +21,9 @@ normalize_logs, normalize_state, ) -from eth.tools._utils.hashing import hash_log_entries -from eth.tools._utils.mappings import deep_merge +from eth.tools.fixtures.helpers import ( + get_test_name, +) def fill_vm_test( diff --git a/eth/tools/fixtures/generation.py b/eth/tools/fixtures/generation.py index fec792ac0e..5a57180f96 100644 --- a/eth/tools/fixtures/generation.py +++ b/eth/tools/fixtures/generation.py @@ -1,5 +1,4 @@ import hashlib - from typing import ( Any, Callable, diff --git a/eth/tools/fixtures/helpers.py b/eth/tools/fixtures/helpers.py index d12c84283c..5c948d253d 100644 --- a/eth/tools/fixtures/helpers.py +++ b/eth/tools/fixtures/helpers.py @@ -1,60 +1,61 @@ import os - -import rlp - from typing import ( - cast, Any, Dict, Iterable, Tuple, Type, + cast, ) +from eth_utils import ( + to_normalized_address, +) from eth_utils.toolz import ( assoc, first, ) +import rlp -from eth_utils import ( - to_normalized_address, +from eth import ( + MainnetChain, + constants, +) +from eth._utils.state import ( + diff_state, ) - -from eth import MainnetChain from eth.abc import ( BlockAPI, ChainAPI, StateAPI, VirtualMachineAPI, ) -from eth import constants -from eth.db.atomic import AtomicDB from eth.chains.mainnet import ( MainnetDAOValidatorVM, ) +from eth.db.atomic import ( + AtomicDB, +) from eth.tools.builder.chain import ( disable_pow_check, ) from eth.typing import ( AccountState, ) -from eth._utils.state import ( - diff_state, -) from eth.vm.forks import ( - PetersburgVM, - ConstantinopleVM, + BerlinVM, ByzantiumVM, - TangerineWhistleVM, + ConstantinopleVM, FrontierVM, + GrayGlacierVM, HomesteadVM as BaseHomesteadVM, - SpuriousDragonVM, IstanbulVM, - BerlinVM, LondonVM, - GrayGlacierVM, ParisVM, + PetersburgVM, ShanghaiVM, + SpuriousDragonVM, + TangerineWhistleVM, ) diff --git a/eth/tools/fixtures/loading.py b/eth/tools/fixtures/loading.py index 71bf3ac4a6..63b17ddce0 100644 --- a/eth/tools/fixtures/loading.py +++ b/eth/tools/fixtures/loading.py @@ -1,7 +1,6 @@ import functools import json import os - from typing import ( Any, Callable, @@ -10,13 +9,14 @@ Tuple, ) +from eth_utils import ( + to_tuple, +) from eth_utils.toolz import ( curry, identity, ) -from eth_utils import to_tuple - from ._utils import ( recursive_find_files, require_pytest, diff --git a/eth/tools/mining.py b/eth/tools/mining.py index c2aa7105ec..f85c3da0fe 100644 --- a/eth/tools/mining.py +++ b/eth/tools/mining.py @@ -1,6 +1,6 @@ from eth.abc import ( - BlockAPI, BlockAndMetaWitness, + BlockAPI, VirtualMachineAPI, ) from eth.consensus import ( diff --git a/eth/tools/rlp.py b/eth/tools/rlp.py index 5e81ad15da..1ad065cb14 100644 --- a/eth/tools/rlp.py +++ b/eth/tools/rlp.py @@ -1,13 +1,12 @@ from eth_utils import ( - replace_exceptions, ValidationError, + replace_exceptions, ) from eth._utils.rlp import ( validate_rlp_equal, ) - assert_imported_block_unchanged = replace_exceptions({ ValidationError: AssertionError, })(validate_rlp_equal(obj_a_name='provided block', obj_b_name='executed block')) diff --git a/eth/typing.py b/eth/typing.py index 5c575f5902..0a79b39abf 100644 --- a/eth/typing.py +++ b/eth/typing.py @@ -1,17 +1,17 @@ from typing import ( + TYPE_CHECKING, Any, Callable, Dict, Generic, Iterable, List, - Optional, NewType, + Optional, Sequence, Tuple, Type, TypeVar, - TYPE_CHECKING, Union, ) diff --git a/eth/validation.py b/eth/validation.py index f09fd5e8df..877da446fb 100644 --- a/eth/validation.py +++ b/eth/validation.py @@ -1,41 +1,40 @@ import functools - from typing import ( Any, - cast, Dict, Iterable, Sequence, Tuple, Type, Union, + cast, ) from eth_typing import ( Address, Hash32, ) - from eth_utils import ( - is_list_like, ValidationError, + is_list_like, +) +from eth_utils.toolz import ( + dicttoolz, + functoolz, + itertoolz, ) -from eth_utils.toolz import dicttoolz - -from eth_utils.toolz import functoolz - -from eth_utils.toolz import itertoolz from eth._utils.headers import ( compute_gas_limit_bounds, ) -from eth.abc import VirtualMachineAPI +from eth.abc import ( + VirtualMachineAPI, +) from eth.constants import ( SECPK1_N, - UINT_256_MAX, UINT_64_MAX, + UINT_256_MAX, ) - from eth.typing import ( BytesOrView, ) diff --git a/eth/vm/base.py b/eth/vm/base.py index cc7dfc5f1a..e7f4826bf4 100644 --- a/eth/vm/base.py +++ b/eth/vm/base.py @@ -16,8 +16,12 @@ Union, ) -from cached_property import cached_property -from eth_hash.auto import keccak +from cached_property import ( + cached_property, +) +from eth_hash.auto import ( + keccak, +) from eth_typing import ( Address, Hash32, @@ -28,14 +32,21 @@ ) import rlp +from eth._utils.datatypes import ( + Configurable, +) +from eth._utils.db import ( + get_block_header_by_hash, + get_parent_header, +) from eth.abc import ( AtomicDatabaseAPI, - BlockAPI, BlockAndMetaWitness, + BlockAPI, BlockHeaderAPI, ChainContextAPI, ChainDatabaseAPI, - MessageComputationAPI, + ComputationAPI, ConsensusAPI, ConsensusContextAPI, ExecutionContextAPI, @@ -56,7 +67,9 @@ MAX_PREV_HEADER_DEPTH, MAX_UNCLES, ) -from eth.db.trie import make_trie_root_and_nodes +from eth.db.trie import ( + make_trie_root_and_nodes, +) from eth.exceptions import ( HeaderNotFound, ) @@ -66,16 +79,9 @@ from eth.rlp.sedes import ( uint32, ) -from eth._utils.datatypes import ( - Configurable, -) -from eth._utils.db import ( - get_parent_header, - get_block_header_by_hash, -) from eth.validation import ( - validate_length_lte, validate_gas_limit, + validate_length_lte, ) from eth.vm.execution_context import ( ExecutionContext, @@ -166,7 +172,7 @@ def logger(self) -> logging.Logger: def apply_transaction(self, header: BlockHeaderAPI, transaction: SignedTransactionAPI - ) -> Tuple[ReceiptAPI, MessageComputationAPI]: + ) -> Tuple[ReceiptAPI, ComputationAPI]: self.validate_transaction_against_header(header, transaction) # Mark current state as un-revertable, since new transaction is starting... @@ -222,7 +228,7 @@ def execute_bytecode(self, data: bytes, code: bytes, code_address: Address = None, - ) -> MessageComputationAPI: + ) -> ComputationAPI: if origin is None: origin = sender @@ -244,7 +250,7 @@ def execute_bytecode(self, ) # Execute it in the VM - return self.state.message_computation_class.apply_computation( + return self.state.computation_class.apply_computation( self.state, message, transaction_context, @@ -254,7 +260,7 @@ def apply_all_transactions( self, transactions: Sequence[SignedTransactionAPI], base_header: BlockHeaderAPI - ) -> Tuple[BlockHeaderAPI, Tuple[ReceiptAPI, ...], Tuple[MessageComputationAPI, ...]]: + ) -> Tuple[BlockHeaderAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]: vm_header = self.get_header() if base_header.block_number != vm_header.block_number: raise ValidationError( diff --git a/eth/vm/chain_context.py b/eth/vm/chain_context.py index 2588b53cf2..4601129046 100644 --- a/eth/vm/chain_context.py +++ b/eth/vm/chain_context.py @@ -1,6 +1,10 @@ -from typing import Optional +from typing import ( + Optional, +) -from eth.abc import ChainContextAPI +from eth.abc import ( + ChainContextAPI, +) from eth.validation import ( validate_uint256, ) diff --git a/eth/vm/code_stream.py b/eth/vm/code_stream.py index fc90da43c6..3845a9342f 100644 --- a/eth/vm/code_stream.py +++ b/eth/vm/code_stream.py @@ -2,10 +2,12 @@ import logging from typing import ( Iterator, - Set + Set, ) -from eth.abc import CodeStreamAPI +from eth.abc import ( + CodeStreamAPI, +) from eth.validation import ( validate_is_bytes, ) diff --git a/eth/vm/computation.py b/eth/vm/computation.py new file mode 100644 index 0000000000..94a90ea586 --- /dev/null +++ b/eth/vm/computation.py @@ -0,0 +1,645 @@ +import itertools +from types import ( + TracebackType, +) +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Tuple, + Type, + Union, + cast, +) + +from cached_property import ( + cached_property, +) +from eth_typing import ( + Address, +) +from eth_utils import ( + encode_hex, + get_extended_debug_logger, +) + +from eth._utils.datatypes import ( + Configurable, +) +from eth._utils.numeric import ( + ceil32, +) +from eth.abc import ( + CodeStreamAPI, + ComputationAPI, + GasMeterAPI, + MemoryAPI, + MessageAPI, + OpcodeAPI, + StackAPI, + StateAPI, + TransactionContextAPI, +) +from eth.constants import ( + GAS_MEMORY, + GAS_MEMORY_QUADRATIC_DENOMINATOR, +) +from eth.exceptions import ( + Halt, + VMError, +) +from eth.typing import ( + BytesOrView, +) +from eth.validation import ( + validate_canonical_address, + validate_is_bytes, + validate_uint256, +) +from eth.vm.code_stream import ( + CodeStream, +) +from eth.vm.gas_meter import ( + GasMeter, +) +from eth.vm.logic.invalid import ( + InvalidOpcode, +) +from eth.vm.memory import ( + Memory, +) +from eth.vm.message import ( + Message, +) +from eth.vm.stack import ( + Stack, +) + + +def NO_RESULT(computation: ComputationAPI) -> None: + """ + This is a special method intended for usage as the "no precompile found" result. + The type signature is designed to match the other precompiles. + """ + raise Exception("This method is never intended to be executed") + + +def memory_gas_cost(size_in_bytes: int) -> int: + size_in_words = ceil32(size_in_bytes) // 32 + linear_cost = size_in_words * GAS_MEMORY + quadratic_cost = size_in_words ** 2 // GAS_MEMORY_QUADRATIC_DENOMINATOR + + total_cost = linear_cost + quadratic_cost + return total_cost + + +class BaseComputation(ComputationAPI, Configurable): + """ + The base class for all execution computations. + + .. note:: + + Each :class:`~eth.vm.computation.BaseComputation` class must be configured with: + + ``opcodes``: A mapping from the opcode integer value to the logic + function for the opcode. + + ``_precompiles``: A mapping of contract address to the precompile function + for execution of precompiled contracts. + """ + + logger = get_extended_debug_logger("eth.vm.computation.BaseComputation") + + state: StateAPI = None + msg: MessageAPI = None + transaction_context: TransactionContextAPI = None + code: CodeStreamAPI = None + children: List[ComputationAPI] = None + return_data: bytes = b'' + accounts_to_delete: Dict[Address, Address] = None + + _memory: MemoryAPI = None + _stack: StackAPI = None + _gas_meter: GasMeterAPI = None + _error: VMError = None + _output: bytes = b'' + _log_entries: List[Tuple[int, Address, Tuple[int, ...], bytes]] = None + + # VM configuration + opcodes: Dict[int, OpcodeAPI] = None + _precompiles: Dict[Address, Callable[[ComputationAPI], ComputationAPI]] = None + + def __init__( + self, + state: StateAPI, + message: MessageAPI, + transaction_context: TransactionContextAPI, + ) -> None: + self.state = state + self.msg = message + self.transaction_context = transaction_context + self.code = CodeStream(message.code) + + self._gas_meter = self._configure_gas_meter() + + self.children = [] + self.accounts_to_delete = {} + self._stack = Stack() + self._memory = Memory() + self._log_entries = [] + + def _configure_gas_meter(self) -> GasMeter: + return GasMeter(self.msg.gas) + + # -- class methods -- # + @classmethod + def apply_message( + cls, + state: StateAPI, + message: MessageAPI, + transaction_context: TransactionContextAPI, + ) -> ComputationAPI: + raise NotImplementedError("Must be implemented by subclasses") + + @classmethod + def apply_create_message( + cls, + state: StateAPI, + message: MessageAPI, + transaction_context: TransactionContextAPI, + ) -> ComputationAPI: + raise NotImplementedError("Must be implemented by subclasses") + + # -- convenience -- # + @property + def is_origin_computation(self) -> bool: + return self.msg.sender == self.transaction_context.origin + + # -- runtime operations -- # + def prepare_child_message( + self, + gas: int, + to: Address, + value: int, + data: BytesOrView, + code: bytes, + **kwargs: Any, + ) -> MessageAPI: + kwargs.setdefault('sender', self.msg.storage_address) + + child_message = Message( + gas=gas, + to=to, + value=value, + data=data, + code=code, + depth=self.msg.depth + 1, + **kwargs + ) + return child_message + + def apply_child_computation( + self, + child_msg: MessageAPI, + ) -> ComputationAPI: + child_computation = self.generate_child_computation(child_msg) + self.add_child_computation(child_computation) + return child_computation + + def generate_child_computation( + self, + child_msg: MessageAPI, + ) -> ComputationAPI: + if child_msg.is_create: + child_computation = self.apply_create_message( + self.state, + child_msg, + self.transaction_context, + ) + else: + child_computation = self.apply_message( + self.state, + child_msg, + self.transaction_context, + ) + return child_computation + + def add_child_computation( + self, + child_computation: ComputationAPI, + ) -> None: + if child_computation.is_error: + if child_computation.msg.is_create: + self.return_data = child_computation.output + elif child_computation.should_burn_gas: + self.return_data = b'' + else: + self.return_data = child_computation.output + else: + if child_computation.msg.is_create: + self.return_data = b'' + else: + self.return_data = child_computation.output + self.children.append(child_computation) + + # -- gas consumption -- # + def get_gas_refund(self) -> int: + if self.is_error: + return 0 + else: + return ( + self._gas_meter.gas_refunded + + sum(c.get_gas_refund() for c in self.children) + ) + + # -- account management -- # + def register_account_for_deletion(self, beneficiary: Address) -> None: + # SELFDESTRUCT + + validate_canonical_address( + beneficiary, + title="Self destruct beneficiary address", + ) + + if self.msg.storage_address in self.accounts_to_delete: + raise ValueError( + "Invariant. Should be impossible for an account to be " + "registered for deletion multiple times" + ) + self.accounts_to_delete[self.msg.storage_address] = beneficiary + + def get_accounts_for_deletion(self) -> Tuple[Tuple[Address, Address], ...]: + # SELFDESTRUCT + + if self.is_error: + return () + else: + return tuple( + dict( + itertools.chain( + self.accounts_to_delete.items(), + *( + child.get_accounts_for_deletion() + for child in self.children + ) + ) + ).items() + ) + + # -- EVM logging -- # + def add_log_entry( + self, + account: Address, + topics: Tuple[int, ...], + data: bytes, + ) -> None: + validate_canonical_address(account, title="Log entry address") + for topic in topics: + validate_uint256(topic, title="Log entry topic") + validate_is_bytes(data, title="Log entry data") + self._log_entries.append( + (self.transaction_context.get_next_log_counter(), account, topics, data) + ) + + def get_raw_log_entries(self) -> Tuple[ + Tuple[int, bytes, Tuple[int, ...], bytes], ... + ]: + if self.is_error: + return () + else: + return tuple( + sorted( + itertools.chain( + self._log_entries, + *(child.get_raw_log_entries() for child in self.children) + ) + ) + ) + + def get_log_entries(self) -> Tuple[Tuple[bytes, Tuple[int, ...], bytes], ...]: + return tuple(log[1:] for log in self.get_raw_log_entries()) + + # -- state transition -- # + @classmethod + def apply_computation( + cls, + state: StateAPI, + message: MessageAPI, + transaction_context: TransactionContextAPI, + ) -> ComputationAPI: + + with cls(state, message, transaction_context) as computation: + if message.is_create and computation.is_origin_computation: + # If computation is from a create transaction, consume initcode gas if + # >= Shanghai. CREATE and CREATE2 are handled in the opcode + # implementations. + cls.consume_initcode_gas_cost(computation) + + # Early exit on pre-compiles + precompile = computation.precompiles.get( + message.code_address, NO_RESULT + ) + if precompile is not NO_RESULT: + precompile(computation) + return computation + + show_debug2 = computation.logger.show_debug2 + + opcode_lookup = computation.opcodes + for opcode in computation.code: + try: + opcode_fn = opcode_lookup[opcode] + except KeyError: + opcode_fn = InvalidOpcode(opcode) + + if show_debug2: + # We dig into some internals for debug logs + base_comp = cast(BaseComputation, computation) + computation.logger.debug2( + "OPCODE: 0x%x (%s) | pc: %s | stack: %s", + opcode, + opcode_fn.mnemonic, + max(0, computation.code.program_counter - 1), + base_comp._stack, + ) + + try: + opcode_fn(computation=computation) + except Halt: + break + + return computation + + # -- error handling -- # + @property + def is_success(self) -> bool: + return self._error is None + + @property + def is_error(self) -> bool: + return not self.is_success + + @property + def error(self) -> VMError: + if self._error is not None: + return self._error + raise AttributeError("Computation does not have an error") + + @error.setter + def error(self, value: VMError) -> None: + if self._error is not None: + raise AttributeError(f"Computation already has an error set: {self._error}") + self._error = value + + def raise_if_error(self) -> None: + if self._error is not None: + raise self._error + + @property + def should_burn_gas(self) -> bool: + return self.is_error and self._error.burns_gas + + @property + def should_return_gas(self) -> bool: + return not self.should_burn_gas + + @property + def should_erase_return_data(self) -> bool: + return self.is_error and self._error.erases_return_data + + # -- memory management -- # + def extend_memory(self, start_position: int, size: int) -> None: + validate_uint256(start_position, title="Memory start position") + validate_uint256(size, title="Memory size") + + before_size = ceil32(len(self._memory)) + after_size = ceil32(start_position + size) + + before_cost = memory_gas_cost(before_size) + after_cost = memory_gas_cost(after_size) + + if self.logger.show_debug2: + self.logger.debug2( + "MEMORY: size (%s -> %s) | cost (%s -> %s)", + before_size, + after_size, + before_cost, + after_cost, + ) + + if size: + if before_cost < after_cost: + gas_fee = after_cost - before_cost + self._gas_meter.consume_gas( + gas_fee, + reason=" ".join( + ( + "Expanding memory", + str(before_size), + "->", + str(after_size), + ) + ) + ) + + self._memory.extend(start_position, size) + + def memory_write(self, start_position: int, size: int, value: bytes) -> None: + return self._memory.write(start_position, size, value) + + def memory_read(self, start_position: int, size: int) -> memoryview: + return self._memory.read(start_position, size) + + def memory_read_bytes(self, start_position: int, size: int) -> bytes: + return self._memory.read_bytes(start_position, size) + + # -- gas consumption -- # + def get_gas_meter(self) -> GasMeterAPI: + return self._gas_meter + + def consume_gas(self, amount: int, reason: str) -> None: + return self._gas_meter.consume_gas(amount, reason) + + def return_gas(self, amount: int) -> None: + return self._gas_meter.return_gas(amount) + + def refund_gas(self, amount: int) -> None: + return self._gas_meter.refund_gas(amount) + + def get_gas_used(self) -> int: + if self.should_burn_gas: + return self._gas_meter.start_gas + else: + return max( + 0, + self._gas_meter.start_gas - self._gas_meter.gas_remaining, + ) + + def get_gas_remaining(self) -> int: + if self.should_burn_gas: + return 0 + else: + return self._gas_meter.gas_remaining + + @classmethod + def consume_initcode_gas_cost(cls, computation: ComputationAPI) -> None: + # this method does not become relevant until the Shanghai hard fork + """ + Before starting the computation, consume initcode gas cost. + """ + pass + + # -- stack management -- # + def stack_swap(self, position: int) -> None: + return self._stack.swap(position) + + def stack_dup(self, position: int) -> None: + return self._stack.dup(position) + + # Stack manipulation is performance-sensitive code. + # Avoid method call overhead by proxying stack method directly to stack object + + @cached_property + def stack_pop_ints(self) -> Callable[[int], Tuple[int, ...]]: + return self._stack.pop_ints + + @cached_property + def stack_pop_bytes(self) -> Callable[[int], Tuple[bytes, ...]]: + return self._stack.pop_bytes + + @cached_property + def stack_pop_any(self) -> Callable[[int], Tuple[Union[int, bytes], ...]]: + return self._stack.pop_any + + @cached_property + def stack_pop1_int(self) -> Callable[[], int]: + return self._stack.pop1_int + + @cached_property + def stack_pop1_bytes(self) -> Callable[[], bytes]: + return self._stack.pop1_bytes + + @cached_property + def stack_pop1_any(self) -> Callable[[], Union[int, bytes]]: + return self._stack.pop1_any + + @cached_property + def stack_push_int(self) -> Callable[[int], None]: + return self._stack.push_int + + @cached_property + def stack_push_bytes(self) -> Callable[[bytes], None]: + return self._stack.push_bytes + + # -- computation result -- # + @property + def output(self) -> bytes: + if self.should_erase_return_data: + return b'' + else: + return self._output + + @output.setter + def output(self, value: bytes) -> None: + validate_is_bytes(value) + self._output = value + + # -- opcode API -- # + @property + def precompiles(self) -> Dict[Address, Callable[[ComputationAPI], Any]]: + if self._precompiles is None: + return {} + else: + return self._precompiles + + @classmethod + def get_precompiles(cls) -> Dict[Address, Callable[[ComputationAPI], Any]]: + if cls._precompiles is None: + return {} + else: + return cls._precompiles + + def get_opcode_fn(self, opcode: int) -> OpcodeAPI: + try: + return self.opcodes[opcode] + except KeyError: + return InvalidOpcode(opcode) + + # -- context manager API -- # + def __enter__(self) -> ComputationAPI: + if self.logger.show_debug2: + self.logger.debug2( + ( + "MESSAGE COMPUTATION STARTING: " + "from: %s | to: %s | value: %s | depth %s | static: %s | gas: %s" + ), + encode_hex(self.msg.sender), + encode_hex(self.msg.to), + self.msg.value, + self.msg.depth, + "y" if self.msg.is_static else "n", + self.msg.gas, + ) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> Union[None, bool]: + if exc_value and isinstance(exc_value, VMError): + if self.logger.show_debug2: + self.logger.debug2( + ( + "COMPUTATION ERROR: " + "gas: %s | from: %s | to: %s | value: %s | " + "depth: %s | static: %s | error: %s" + ), + self.msg.gas, + encode_hex(self.msg.sender), + encode_hex(self.msg.to), + self.msg.value, + self.msg.depth, + "y" if self.msg.is_static else "n", + exc_value, + ) + + self._error = exc_value + if self.should_burn_gas: + self.consume_gas( + self._gas_meter.gas_remaining, + reason=" ".join( + ( + "Zeroing gas due to VM Exception:", + str(exc_value), + ) + ), + ) + + # when we raise an exception that erases return data, erase the return data + if self.should_erase_return_data: + self.return_data = b'' + + # suppress VM exceptions + return True + + elif exc_type is None and self.logger.show_debug2: + self.logger.debug2( + ( + "COMPUTATION SUCCESS: " + "from: %s | to: %s | value: %s | depth: %s | static: %s " + "| gas-used: %s | gas-remaining: %s" + ), + encode_hex(self.msg.sender), + encode_hex(self.msg.to), + self.msg.value, + self.msg.depth, + "y" if self.msg.is_static else "n", + self.get_gas_used(), + self._gas_meter.gas_remaining, + ) + + return None diff --git a/eth/vm/computation/__init__.py b/eth/vm/computation/__init__.py deleted file mode 100644 index b42a0f5efa..0000000000 --- a/eth/vm/computation/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .message_computation import ( # noqa: F401 - BaseComputation, - MessageComputation, -) diff --git a/eth/vm/computation/base_computation.py b/eth/vm/computation/base_computation.py deleted file mode 100644 index f7ba78f128..0000000000 --- a/eth/vm/computation/base_computation.py +++ /dev/null @@ -1,354 +0,0 @@ -from types import TracebackType -from typing import ( - Any, - Callable, - Dict, - Generic, - List, - Optional, - Tuple, - Type, - TypeVar, - Union, -) - -from cached_property import cached_property - -from eth_typing import ( - Address, -) -from eth_utils import ( - get_extended_debug_logger, -) - -from eth._utils.datatypes import ( - Configurable, -) -from eth._utils.numeric import ( - ceil32, -) -from eth.abc import ( - ComputationAPI, - MemoryAPI, - StackAPI, - GasMeterAPI, - OpcodeAPI, - CodeStreamAPI, - MessageComputationAPI, - StateAPI, -) -from eth.constants import ( - GAS_MEMORY, - GAS_MEMORY_QUADRATIC_DENOMINATOR, -) -from eth.exceptions import ( - VMError, -) -from eth.validation import ( - validate_is_bytes, - validate_uint256, -) -from eth.vm.logic.invalid import ( - InvalidOpcode, -) -from eth.vm.memory import ( - Memory, -) -from eth.vm.stack import ( - Stack, -) - - -def NO_RESULT(computation: ComputationAPI) -> None: - """ - This is a special method intended for usage as the "no precompile found" result. - The type signature is designed to match the other precompiles. - """ - raise Exception("This method is never intended to be executed") - - -def memory_gas_cost(size_in_bytes: int) -> int: - size_in_words = ceil32(size_in_bytes) // 32 - linear_cost = size_in_words * GAS_MEMORY - quadratic_cost = size_in_words ** 2 // GAS_MEMORY_QUADRATIC_DENOMINATOR - - total_cost = linear_cost + quadratic_cost - return total_cost - - -C = TypeVar("C", bound="ComputationAPI") - - -class BaseComputation(ComputationAPI, Configurable, Generic[C]): - """ - The base class for all execution computations. - - .. note:: - - Each :class:`~eth.vm.computation.BaseComputation` class must be configured with: - - ``opcodes``: A mapping from the opcode integer value to the logic - function for the opcode. - - ``_precompiles``: A mapping of contract address to the precompile function - for execution of precompiled contracts. - """ - - logger = get_extended_debug_logger("eth.vm.computation.BaseComputation") - - state: StateAPI = None - code: CodeStreamAPI = None - children: List[C] = None - return_data: bytes = b'' - - _memory: MemoryAPI = None - _stack: StackAPI = None - _gas_meter: GasMeterAPI = None - _error: VMError = None - _output: bytes = b'' - - # VM configuration - opcodes: Dict[int, OpcodeAPI] = None - _precompiles: Dict[Address, Callable[[ComputationAPI], ComputationAPI]] = None - - def __init__(self, state: StateAPI) -> None: - self.state = state - self.children = [] - - self._memory = Memory() - self._stack = Stack() - - def _configure_gas_meter(self) -> GasMeterAPI: - raise NotImplementedError("Must be implemented by subclasses") - - # -- error handling -- # - @property - def is_success(self) -> bool: - return self._error is None - - @property - def is_error(self) -> bool: - return not self.is_success - - @property - def error(self) -> VMError: - if self._error is not None: - return self._error - raise AttributeError("Computation does not have an error") - - @error.setter - def error(self, value: VMError) -> None: - if self._error is not None: - raise AttributeError(f"Computation already has an error set: {self._error}") - self._error = value - - def raise_if_error(self) -> None: - if self._error is not None: - raise self._error - - @property - def should_burn_gas(self) -> bool: - return self.is_error and self._error.burns_gas - - @property - def should_return_gas(self) -> bool: - return not self.should_burn_gas - - @property - def should_erase_return_data(self) -> bool: - return self.is_error and self._error.erases_return_data - - # -- memory management -- # - def extend_memory(self, start_position: int, size: int) -> None: - validate_uint256(start_position, title="Memory start position") - validate_uint256(size, title="Memory size") - - before_size = ceil32(len(self._memory)) - after_size = ceil32(start_position + size) - - before_cost = memory_gas_cost(before_size) - after_cost = memory_gas_cost(after_size) - - if self.logger.show_debug2: - self.logger.debug2( - "MEMORY: size (%s -> %s) | cost (%s -> %s)", - before_size, - after_size, - before_cost, - after_cost, - ) - - if size: - if before_cost < after_cost: - gas_fee = after_cost - before_cost - self._gas_meter.consume_gas( - gas_fee, - reason=" ".join( - ( - "Expanding memory", - str(before_size), - "->", - str(after_size), - ) - ) - ) - - self._memory.extend(start_position, size) - - def memory_write(self, start_position: int, size: int, value: bytes) -> None: - return self._memory.write(start_position, size, value) - - def memory_read(self, start_position: int, size: int) -> memoryview: - return self._memory.read(start_position, size) - - def memory_read_bytes(self, start_position: int, size: int) -> bytes: - return self._memory.read_bytes(start_position, size) - - # -- gas consumption -- # - def get_gas_meter(self) -> GasMeterAPI: - return self._gas_meter - - def consume_gas(self, amount: int, reason: str) -> None: - return self._gas_meter.consume_gas(amount, reason) - - def return_gas(self, amount: int) -> None: - return self._gas_meter.return_gas(amount) - - def refund_gas(self, amount: int) -> None: - return self._gas_meter.refund_gas(amount) - - def get_gas_used(self) -> int: - if self.should_burn_gas: - return self._gas_meter.start_gas - else: - return max( - 0, - self._gas_meter.start_gas - self._gas_meter.gas_remaining, - ) - - def get_gas_remaining(self) -> int: - if self.should_burn_gas: - return 0 - else: - return self._gas_meter.gas_remaining - - @classmethod - def consume_initcode_gas_cost(cls, computation: MessageComputationAPI) -> None: - # this method does not become relevant until the Shanghai hard fork - """ - Before starting the computation, consume initcode gas cost. - """ - pass - - # -- stack management -- # - def stack_swap(self, position: int) -> None: - return self._stack.swap(position) - - def stack_dup(self, position: int) -> None: - return self._stack.dup(position) - - # Stack manipulation is performance-sensitive code. - # Avoid method call overhead by proxying stack method directly to stack object - - @cached_property - def stack_pop_ints(self) -> Callable[[int], Tuple[int, ...]]: - return self._stack.pop_ints - - @cached_property - def stack_pop_bytes(self) -> Callable[[int], Tuple[bytes, ...]]: - return self._stack.pop_bytes - - @cached_property - def stack_pop_any(self) -> Callable[[int], Tuple[Union[int, bytes], ...]]: - return self._stack.pop_any - - @cached_property - def stack_pop1_int(self) -> Callable[[], int]: - return self._stack.pop1_int - - @cached_property - def stack_pop1_bytes(self) -> Callable[[], bytes]: - return self._stack.pop1_bytes - - @cached_property - def stack_pop1_any(self) -> Callable[[], Union[int, bytes]]: - return self._stack.pop1_any - - @cached_property - def stack_push_int(self) -> Callable[[int], None]: - return self._stack.push_int - - @cached_property - def stack_push_bytes(self) -> Callable[[bytes], None]: - return self._stack.push_bytes - - # -- computation result -- # - @property - def output(self) -> bytes: - if self.should_erase_return_data: - return b'' - else: - return self._output - - @output.setter - def output(self, value: bytes) -> None: - validate_is_bytes(value) - self._output = value - - # -- opcode API -- # - @property - def precompiles(self) -> Dict[Address, Callable[[ComputationAPI], Any]]: - if self._precompiles is None: - return {} - else: - return self._precompiles - - @classmethod - def get_precompiles(cls) -> Dict[Address, Callable[[ComputationAPI], Any]]: - if cls._precompiles is None: - return {} - else: - return cls._precompiles - - def get_opcode_fn(self, opcode: int) -> OpcodeAPI: - try: - return self.opcodes[opcode] - except KeyError: - return InvalidOpcode(opcode) - - # -- context manager API -- # - def __enter__(self) -> ComputationAPI: - if self.logger.show_debug2: - self.logger.debug2("COMPUTATION STARTING") - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - traceback: Optional[TracebackType], - ) -> Union[None, bool]: - if exc_value and isinstance(exc_value, VMError): - # Exception handling logic for computations is done here in the base class. - # Subclass-specific logging can be done in each subclass by overriding - # `__exit__` and calling `super().__exit__(exc_type, exc_value, traceback)`. - self._error = exc_value - if self.should_burn_gas: - self.consume_gas( - self._gas_meter.gas_remaining, - reason=" ".join( - ( - "Zeroing gas due to VM Exception:", - str(exc_value), - ) - ), - ) - - # when we raise an exception that erases return data, erase the return data - if self.should_erase_return_data: - self.return_data = b'' - - # suppress VM exceptions - return True - - return None diff --git a/eth/vm/computation/message_computation.py b/eth/vm/computation/message_computation.py deleted file mode 100644 index 7fdebf33c5..0000000000 --- a/eth/vm/computation/message_computation.py +++ /dev/null @@ -1,360 +0,0 @@ -import itertools -from types import TracebackType -from typing import ( - Any, - Dict, - List, - Optional, - Tuple, - Type, - Union, - cast, -) - -from eth.vm.computation.base_computation import ( - BaseComputation, - NO_RESULT, -) -from eth_typing import ( - Address, -) -from eth_utils import ( - encode_hex, - get_extended_debug_logger, -) - -from eth.abc import ( - MessageAPI, - MessageComputationAPI, - StateAPI, - TransactionContextAPI, -) -from eth.exceptions import ( - Halt, - VMError, -) -from eth.typing import ( - BytesOrView, -) -from eth.validation import ( - validate_canonical_address, - validate_is_bytes, - validate_uint256, -) -from eth.vm.code_stream import ( - CodeStream, -) -from eth.vm.gas_meter import ( - GasMeter, -) -from eth.vm.logic.invalid import ( - InvalidOpcode, -) -from eth.vm.message import ( - Message, -) - - -class MessageComputation( - MessageComputationAPI, - BaseComputation[MessageComputationAPI], -): - """ - A class for executing message computations. - """ - - logger = get_extended_debug_logger("eth.vm.computation.MessageComputation") - - msg: MessageAPI = None - transaction_context: TransactionContextAPI = None - children: List[MessageComputationAPI] = None - accounts_to_delete: Dict[Address, Address] = None - - _log_entries: List[Tuple[int, Address, Tuple[int, ...], bytes]] = None - - def __init__( - self, - state: StateAPI, - message: MessageAPI, - transaction_context: TransactionContextAPI, - ) -> None: - BaseComputation.__init__(self, state) - - self.msg = message - self.transaction_context = transaction_context - self.code = CodeStream(message.code) - self._gas_meter = self._configure_gas_meter() - - self.accounts_to_delete = {} - self._log_entries = [] - - def _configure_gas_meter(self) -> GasMeter: - return GasMeter(self.msg.gas) - - # -- class methods -- # - @classmethod - def apply_message( - cls, - state: StateAPI, - message: MessageAPI, - transaction_context: TransactionContextAPI, - ) -> MessageComputationAPI: - raise NotImplementedError("Must be implemented by subclasses") - - @classmethod - def apply_create_message( - cls, - state: StateAPI, - message: MessageAPI, - transaction_context: TransactionContextAPI, - ) -> MessageComputationAPI: - raise NotImplementedError("Must be implemented by subclasses") - - # -- convenience -- # - @property - def is_origin_computation(self) -> bool: - return self.msg.sender == self.transaction_context.origin - - # -- runtime operations -- # - def prepare_child_message( - self, - gas: int, - to: Address, - value: int, - data: BytesOrView, - code: bytes, - **kwargs: Any, - ) -> MessageAPI: - kwargs.setdefault('sender', self.msg.storage_address) - - child_message = Message( - gas=gas, - to=to, - value=value, - data=data, - code=code, - depth=self.msg.depth + 1, - **kwargs - ) - return child_message - - def apply_child_message_computation( - self, - child_msg: MessageAPI, - ) -> MessageComputationAPI: - child_computation = self.generate_child_message_computation(child_msg) - self.add_child_message_computation(child_computation) - return child_computation - - def generate_child_message_computation( - self, - child_msg: MessageAPI, - ) -> MessageComputationAPI: - if child_msg.is_create: - child_computation = self.apply_create_message( - self.state, - child_msg, - self.transaction_context, - ) - else: - child_computation = self.apply_message( - self.state, - child_msg, - self.transaction_context, - ) - return child_computation - - def add_child_message_computation( - self, - child_message_computation: MessageComputationAPI, - ) -> None: - if child_message_computation.is_error: - if child_message_computation.msg.is_create: - self.return_data = child_message_computation.output - elif child_message_computation.should_burn_gas: - self.return_data = b'' - else: - self.return_data = child_message_computation.output - else: - if child_message_computation.msg.is_create: - self.return_data = b'' - else: - self.return_data = child_message_computation.output - self.children.append(child_message_computation) - - # -- gas consumption -- # - def get_gas_refund(self) -> int: - if self.is_error: - return 0 - else: - return ( - self._gas_meter.gas_refunded - + sum(c.get_gas_refund() for c in self.children) - ) - - # -- account management -- # - def register_account_for_deletion(self, beneficiary: Address) -> None: - # SELFDESTRUCT - - validate_canonical_address( - beneficiary, - title="Self destruct beneficiary address", - ) - - if self.msg.storage_address in self.accounts_to_delete: - raise ValueError( - "Invariant. Should be impossible for an account to be " - "registered for deletion multiple times" - ) - self.accounts_to_delete[self.msg.storage_address] = beneficiary - - def get_accounts_for_deletion(self) -> Tuple[Tuple[Address, Address], ...]: - # SELFDESTRUCT - - if self.is_error: - return () - else: - return tuple(dict(itertools.chain( - self.accounts_to_delete.items(), - *(child.get_accounts_for_deletion() for child in self.children) - )).items()) - - # -- EVM logging -- # - def add_log_entry( - self, - account: Address, - topics: Tuple[int, ...], - data: bytes, - ) -> None: - validate_canonical_address(account, title="Log entry address") - for topic in topics: - validate_uint256(topic, title="Log entry topic") - validate_is_bytes(data, title="Log entry data") - self._log_entries.append( - (self.transaction_context.get_next_log_counter(), account, topics, data)) - - def get_raw_log_entries(self) -> Tuple[ - Tuple[int, bytes, Tuple[int, ...], bytes], ... - ]: - if self.is_error: - return () - else: - return tuple(sorted(itertools.chain( - self._log_entries, - *(child.get_raw_log_entries() for child in self.children) - ))) - - def get_log_entries(self) -> Tuple[Tuple[bytes, Tuple[int, ...], bytes], ...]: - return tuple(log[1:] for log in self.get_raw_log_entries()) - - # -- state transition -- # - @classmethod - def apply_computation( - cls, - state: StateAPI, - message: MessageAPI, - transaction_context: TransactionContextAPI, - ) -> MessageComputationAPI: - - with cls(state, message, transaction_context) as computation: - if message.is_create and computation.is_origin_computation: - # If computation is from a create transaction, consume initcode gas if - # >= Shanghai. CREATE and CREATE2 are handled in the opcode - # implementations. - cls.consume_initcode_gas_cost(computation) - - # Early exit on pre-compiles - precompile = computation.precompiles.get( - message.code_address, NO_RESULT - ) - if precompile is not NO_RESULT: - precompile(computation) - return computation - - show_debug2 = computation.logger.show_debug2 - - opcode_lookup = computation.opcodes - for opcode in computation.code: - try: - opcode_fn = opcode_lookup[opcode] - except KeyError: - opcode_fn = InvalidOpcode(opcode) - - if show_debug2: - # We dig into some internals for debug logs - base_comp = cast(MessageComputation, computation) - computation.logger.debug2( - "OPCODE: 0x%x (%s) | pc: %s | stack: %s", - opcode, - opcode_fn.mnemonic, - max(0, computation.code.program_counter - 1), - base_comp._stack, - ) - - try: - opcode_fn(computation=computation) - except Halt: - break - - return computation - - # -- context manager API -- # - def __enter__(self) -> MessageComputationAPI: - super().__enter__() - if self.logger.show_debug2: - self.logger.debug2( - ( - "MESSAGE COMPUTATION: " - "from: %s | to: %s | value: %s | depth %s | static: %s | gas: %s" - ), - encode_hex(self.msg.sender), - encode_hex(self.msg.to), - self.msg.value, - self.msg.depth, - "y" if self.msg.is_static else "n", - self.msg.gas, - ) - - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - traceback: Optional[TracebackType], - ) -> Union[None, bool]: - if exc_value and isinstance(exc_value, VMError): - if self.logger.show_debug2: - self.logger.debug2( - ( - "MESSAGE COMPUTATION ERROR: " - "gas: %s | from: %s | to: %s | value: %s | " - "depth: %s | static: %s | error: %s" - ), - self.msg.gas, - encode_hex(self.msg.sender), - encode_hex(self.msg.to), - self.msg.value, - self.msg.depth, - "y" if self.msg.is_static else "n", - exc_value, - ) - return super().__exit__(exc_type, exc_value, traceback) - elif exc_type is None and self.logger.show_debug2: - super().__exit__(exc_type, exc_value, traceback) - self.logger.debug2( - ( - "MESSAGE COMPUTATION SUCCESS: " - "from: %s | to: %s | value: %s | depth: %s | static: %s " - "| gas-used: %s | gas-remaining: %s" - ), - encode_hex(self.msg.sender), - encode_hex(self.msg.to), - self.msg.value, - self.msg.depth, - "y" if self.msg.is_static else "n", - self.get_gas_used(), - self._gas_meter.gas_remaining, - ) - - return None diff --git a/eth/vm/execution_context.py b/eth/vm/execution_context.py index 85941f11ce..c68a189161 100644 --- a/eth/vm/execution_context.py +++ b/eth/vm/execution_context.py @@ -9,8 +9,12 @@ Hash32, ) -from eth.abc import ExecutionContextAPI -from eth._utils.generator import CachedIterable +from eth._utils.generator import ( + CachedIterable, +) +from eth.abc import ( + ExecutionContextAPI, +) class ExecutionContext(ExecutionContextAPI): diff --git a/eth/vm/forks/arrow_glacier/blocks.py b/eth/vm/forks/arrow_glacier/blocks.py index aaa042c9f0..e2eafe201b 100644 --- a/eth/vm/forks/arrow_glacier/blocks.py +++ b/eth/vm/forks/arrow_glacier/blocks.py @@ -1,18 +1,21 @@ -from abc import ABC -from typing import Type +from abc import ( + ABC, +) +from typing import ( + Type, +) -from eth.abc import TransactionBuilderAPI from eth_utils import ( encode_hex, ) - from rlp.sedes import ( CountableList, ) -from .transactions import ( - ArrowGlacierTransactionBuilder, +from eth.abc import ( + TransactionBuilderAPI, ) + from ..london import ( LondonBlock, ) @@ -21,6 +24,9 @@ LondonBlockHeader, LondonMiningHeader, ) +from .transactions import ( + ArrowGlacierTransactionBuilder, +) class ArrowGlacierMiningHeader(LondonMiningHeader, ABC): diff --git a/eth/vm/forks/arrow_glacier/computation.py b/eth/vm/forks/arrow_glacier/computation.py index b61816c076..8dbf54f1e3 100644 --- a/eth/vm/forks/arrow_glacier/computation.py +++ b/eth/vm/forks/arrow_glacier/computation.py @@ -1,9 +1,11 @@ -from ..london.computation import LondonMessageComputation +from ..london.computation import ( + LondonComputation, +) -class ArrowGlacierMessageComputation(LondonMessageComputation): +class ArrowGlacierComputation(LondonComputation): """ A class for all execution *message* computations in the ``ArrowGlacier`` fork. - Inherits from :class:`~eth.vm.forks.london.LondonMessageComputation` + Inherits from :class:`~eth.vm.forks.london.LondonComputation` """ pass diff --git a/eth/vm/forks/arrow_glacier/headers.py b/eth/vm/forks/arrow_glacier/headers.py index ae99201444..0f5f9de3d8 100644 --- a/eth/vm/forks/arrow_glacier/headers.py +++ b/eth/vm/forks/arrow_glacier/headers.py @@ -1,20 +1,27 @@ -from typing import Any, Callable, Optional - -from toolz import curry +from typing import ( + Any, + Callable, + Optional, +) -from eth.abc import BlockHeaderAPI -from .blocks import ( - ArrowGlacierBlockHeader, +from toolz import ( + curry, ) -from eth.vm.forks.london.headers import ( - create_london_header_from_parent, + +from eth.abc import ( + BlockHeaderAPI, ) from eth.vm.forks.byzantium.headers import ( compute_difficulty, -) -from eth.vm.forks.byzantium.headers import ( configure_header, ) +from eth.vm.forks.london.headers import ( + create_london_header_from_parent, +) + +from .blocks import ( + ArrowGlacierBlockHeader, +) compute_arrow_glacier_difficulty = compute_difficulty(10_700_000) configure_arrow_glacier_header = configure_header(difficulty_fn=compute_arrow_glacier_difficulty) diff --git a/eth/vm/forks/arrow_glacier/state.py b/eth/vm/forks/arrow_glacier/state.py index ccc820a370..e1db23033c 100644 --- a/eth/vm/forks/arrow_glacier/state.py +++ b/eth/vm/forks/arrow_glacier/state.py @@ -1,9 +1,20 @@ -from typing import Type +from typing import ( + Type, +) -from eth.abc import TransactionExecutorAPI -from .computation import ArrowGlacierMessageComputation -from ..london import LondonState -from ..london.state import LondonTransactionExecutor +from eth.abc import ( + TransactionExecutorAPI, +) + +from ..london import ( + LondonState, +) +from ..london.state import ( + LondonTransactionExecutor, +) +from .computation import ( + ArrowGlacierComputation, +) class ArrowGlacierTransactionExecutor(LondonTransactionExecutor): @@ -11,5 +22,5 @@ class ArrowGlacierTransactionExecutor(LondonTransactionExecutor): class ArrowGlacierState(LondonState): - message_computation_class = ArrowGlacierMessageComputation + computation_class = ArrowGlacierComputation transaction_executor_class: Type[TransactionExecutorAPI] = ArrowGlacierTransactionExecutor diff --git a/eth/vm/forks/arrow_glacier/transactions.py b/eth/vm/forks/arrow_glacier/transactions.py index b90b66202f..5f44eefe91 100644 --- a/eth/vm/forks/arrow_glacier/transactions.py +++ b/eth/vm/forks/arrow_glacier/transactions.py @@ -1,6 +1,10 @@ -from abc import ABC +from abc import ( + ABC, +) -from eth_keys.datatypes import PrivateKey +from eth_keys.datatypes import ( + PrivateKey, +) from eth._utils.transactions import ( create_transaction_signature, diff --git a/eth/vm/forks/berlin/blocks.py b/eth/vm/forks/berlin/blocks.py index 7e062e7a10..0e31e7b435 100644 --- a/eth/vm/forks/berlin/blocks.py +++ b/eth/vm/forks/berlin/blocks.py @@ -1,4 +1,6 @@ -from typing import Type +from typing import ( + Type, +) from rlp.sedes import ( CountableList, diff --git a/eth/vm/forks/berlin/computation.py b/eth/vm/forks/berlin/computation.py index 6046cf6146..be2a0896de 100644 --- a/eth/vm/forks/berlin/computation.py +++ b/eth/vm/forks/berlin/computation.py @@ -7,10 +7,6 @@ merge, ) -from eth.precompiles.modexp import ( - extract_lengths, - modexp, -) from eth._utils.address import ( force_bytes_to_address, ) @@ -20,17 +16,21 @@ from eth._utils.padding import ( zpad_right, ) - -from eth.vm.forks.berlin import constants - -from eth.vm.forks.muir_glacier.computation import ( - MUIR_GLACIER_PRECOMPILES +from eth.precompiles.modexp import ( + extract_lengths, + modexp, +) +from eth.vm.forks.berlin import ( + constants, ) from eth.vm.forks.muir_glacier.computation import ( - MuirGlacierMessageComputation, + MUIR_GLACIER_PRECOMPILES, + MuirGlacierComputation, ) -from .opcodes import BERLIN_OPCODES +from .opcodes import ( + BERLIN_OPCODES, +) def _calculate_multiplication_complexity(base_length: int, modulus_length: int) -> int: @@ -79,10 +79,10 @@ def _compute_modexp_gas_fee_eip_2565(data: bytes) -> int: ) -class BerlinMessageComputation(MuirGlacierMessageComputation): +class BerlinComputation(MuirGlacierComputation): """ A class for all execution *message* computations in the ``Berlin`` fork. - Inherits from :class:`~eth.vm.forks.muir_glacier.MuirGlacierMessageComputation` + Inherits from :class:`~eth.vm.forks.muir_glacier.MuirGlacierComputation` """ # Override opcodes = BERLIN_OPCODES diff --git a/eth/vm/forks/berlin/headers.py b/eth/vm/forks/berlin/headers.py index 93262f1a99..8457e9d25c 100644 --- a/eth/vm/forks/berlin/headers.py +++ b/eth/vm/forks/berlin/headers.py @@ -1,10 +1,9 @@ from eth.vm.forks.muir_glacier.headers import ( + compute_muir_glacier_difficulty, configure_header, create_header_from_parent, - compute_muir_glacier_difficulty, ) - compute_berlin_difficulty = compute_muir_glacier_difficulty create_berlin_header_from_parent = create_header_from_parent( diff --git a/eth/vm/forks/berlin/logic.py b/eth/vm/forks/berlin/logic.py index b0bbf30939..578315900d 100644 --- a/eth/vm/forks/berlin/logic.py +++ b/eth/vm/forks/berlin/logic.py @@ -1,16 +1,22 @@ from eth_typing import ( Address, ) -from eth_utils.toolz import curry +from eth_utils.toolz import ( + curry, +) -from eth import constants +from eth import ( + constants, +) from eth._utils.address import ( force_bytes_to_address, ) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, +) +from eth.vm import ( + mnemonics, ) -from eth.vm import mnemonics from eth.vm.forks.istanbul.storage import ( GAS_SCHEDULE_EIP2200, sstore_eip2200_generic, @@ -23,8 +29,8 @@ ) from eth.vm.logic.context import ( consume_extcodecopy_word_cost, - push_balance_of_address, extcodecopy_execute, + push_balance_of_address, ) from eth.vm.logic.storage import ( NetSStoreGasSchedule, @@ -36,10 +42,12 @@ selfdestruct_eip161_on_address, ) -from . import constants as berlin_constants +from . import ( + constants as berlin_constants, +) -def _mark_address_warm(computation: MessageComputationAPI, address: Address) -> bool: +def _mark_address_warm(computation: ComputationAPI, address: Address) -> bool: """ Mark the given address as warm if it was not previously. @@ -62,7 +70,7 @@ def _account_load_cost(was_cold: bool) -> int: def _consume_gas_for_account_load( - computation: MessageComputationAPI, + computation: ComputationAPI, address: Address, reason: str) -> None: was_cold = _mark_address_warm(computation, address) @@ -70,7 +78,7 @@ def _consume_gas_for_account_load( computation.consume_gas(gas_cost, reason=reason) -def _mark_storage_warm(computation: MessageComputationAPI, slot: int) -> bool: +def _mark_storage_warm(computation: ComputationAPI, slot: int) -> bool: """ :return was_cold: True if the storage slot was not previously accessed during this transaction @@ -83,13 +91,13 @@ def _mark_storage_warm(computation: MessageComputationAPI, slot: int) -> bool: return True -def balance_eip2929(computation: MessageComputationAPI) -> None: +def balance_eip2929(computation: ComputationAPI) -> None: address = force_bytes_to_address(computation.stack_pop1_bytes()) _consume_gas_for_account_load(computation, address, mnemonics.BALANCE) push_balance_of_address(address, computation) -def extcodesize_eip2929(computation: MessageComputationAPI) -> None: +def extcodesize_eip2929(computation: ComputationAPI) -> None: address = force_bytes_to_address(computation.stack_pop1_bytes()) _consume_gas_for_account_load(computation, address, mnemonics.EXTCODEHASH) @@ -97,13 +105,13 @@ def extcodesize_eip2929(computation: MessageComputationAPI) -> None: computation.stack_push_int(code_size) -def extcodecopy_eip2929(computation: MessageComputationAPI) -> None: +def extcodecopy_eip2929(computation: ComputationAPI) -> None: address, size = extcodecopy_execute(computation) consume_extcodecopy_word_cost(computation, size) _consume_gas_for_account_load(computation, address, mnemonics.EXTCODECOPY) -def extcodehash_eip2929(computation: MessageComputationAPI) -> None: +def extcodehash_eip2929(computation: ComputationAPI) -> None: """ Return the code hash for a given address. EIP: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1052.md @@ -119,7 +127,7 @@ def extcodehash_eip2929(computation: MessageComputationAPI) -> None: computation.stack_push_bytes(state.get_code_hash(address)) -def sload_eip2929(computation: MessageComputationAPI) -> None: +def sload_eip2929(computation: ComputationAPI) -> None: slot = computation.stack_pop1_int() if _mark_storage_warm(computation, slot): @@ -144,7 +152,7 @@ def sload_eip2929(computation: MessageComputationAPI) -> None: @curry def sstore_eip2929_generic( gas_schedule: NetSStoreGasSchedule, - computation: MessageComputationAPI, + computation: ComputationAPI, ) -> int: slot = sstore_eip2200_generic(gas_schedule, computation) @@ -161,7 +169,7 @@ def sstore_eip2929_generic( class LoadFeeByCacheWarmth: def get_account_load_fee( self, - computation: MessageComputationAPI, + computation: ComputationAPI, code_address: Address, ) -> int: was_cold = _mark_address_warm(computation, code_address) @@ -184,7 +192,7 @@ class StaticCallEIP2929(LoadFeeByCacheWarmth, StaticCall): pass -def selfdestruct_eip2929(computation: MessageComputationAPI) -> None: +def selfdestruct_eip2929(computation: ComputationAPI) -> None: beneficiary = force_bytes_to_address(computation.stack_pop1_bytes()) if _mark_address_warm(computation, beneficiary): @@ -201,7 +209,7 @@ class CreateEIP2929(CreateByzantium): def generate_contract_address(self, stack_data: CreateOpcodeStackData, call_data: bytes, - computation: MessageComputationAPI) -> Address: + computation: ComputationAPI) -> Address: address = super().generate_contract_address(stack_data, call_data, computation) computation.state.mark_address_warm(address) return address @@ -211,7 +219,7 @@ class Create2EIP2929(Create2): def generate_contract_address(self, stack_data: CreateOpcodeStackData, call_data: bytes, - computation: MessageComputationAPI) -> Address: + computation: ComputationAPI) -> Address: address = super().generate_contract_address(stack_data, call_data, computation) computation.state.mark_address_warm(address) return address diff --git a/eth/vm/forks/berlin/opcodes.py b/eth/vm/forks/berlin/opcodes.py index bc82b88b52..cea4c051f8 100644 --- a/eth/vm/forks/berlin/opcodes.py +++ b/eth/vm/forks/berlin/opcodes.py @@ -1,30 +1,36 @@ import copy -from typing import Dict +from typing import ( + Dict, +) -from eth_utils.toolz import merge +from eth_utils.toolz import ( + merge, +) +from eth import ( + constants, +) from eth.vm import ( mnemonics, opcode_values, ) -from eth.vm.opcode import ( - Opcode, - as_opcode, -) -from eth import constants - -from eth.vm.forks.tangerine_whistle.constants import ( - GAS_SELFDESTRUCT_EIP150, -) from eth.vm.forks.byzantium.opcodes import ( ensure_no_static, ) from eth.vm.forks.muir_glacier.opcodes import ( MUIR_GLACIER_OPCODES, ) +from eth.vm.forks.tangerine_whistle.constants import ( + GAS_SELFDESTRUCT_EIP150, +) +from eth.vm.opcode import ( + Opcode, + as_opcode, +) -from . import logic - +from . import ( + logic, +) UPDATED_OPCODES: Dict[int, Opcode] = { opcode_values.BALANCE: as_opcode( diff --git a/eth/vm/forks/berlin/receipts.py b/eth/vm/forks/berlin/receipts.py index 6c2b2b54a8..2dbb8c3e50 100644 --- a/eth/vm/forks/berlin/receipts.py +++ b/eth/vm/forks/berlin/receipts.py @@ -4,8 +4,12 @@ Type, ) -from cached_property import cached_property -from eth_bloom import BloomFilter +from cached_property import ( + cached_property, +) +from eth_bloom import ( + BloomFilter, +) from eth_utils import ( ValidationError, to_bytes, @@ -23,15 +27,18 @@ ReceiptBuilderAPI, ReceiptDecoderAPI, ) -from eth.exceptions import UnrecognizedTransactionType -from eth.rlp.receipts import Receipt +from eth.exceptions import ( + UnrecognizedTransactionType, +) +from eth.rlp.receipts import ( + Receipt, +) from .constants import ( ACCESS_LIST_TRANSACTION_TYPE, VALID_TRANSACTION_TYPES, ) - TYPED_RECEIPT_BODY_CODECS = { # Note that the body of a "type 1" receipt uses exactly the same codec as a # legacy receipt, so we can simply reuse all the logic. diff --git a/eth/vm/forks/berlin/state.py b/eth/vm/forks/berlin/state.py index cc66db771b..9f50216ce5 100644 --- a/eth/vm/forks/berlin/state.py +++ b/eth/vm/forks/berlin/state.py @@ -1,26 +1,30 @@ -from typing import Type +from typing import ( + Type, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, MessageAPI, SignedTransactionAPI, TransactionExecutorAPI, ) from eth.vm.forks.muir_glacier.state import ( - MuirGlacierState + MuirGlacierState, ) from eth.vm.forks.spurious_dragon.state import ( SpuriousDragonTransactionExecutor, ) -from .computation import BerlinMessageComputation +from .computation import ( + BerlinComputation, +) class BerlinTransactionExecutor(SpuriousDragonTransactionExecutor): def build_computation( self, message: MessageAPI, - transaction: SignedTransactionAPI) -> MessageComputationAPI: + transaction: SignedTransactionAPI) -> ComputationAPI: self.vm_state.mark_address_warm(transaction.sender) @@ -36,5 +40,5 @@ def build_computation( class BerlinState(MuirGlacierState): - message_computation_class = BerlinMessageComputation + computation_class = BerlinComputation transaction_executor_class: Type[TransactionExecutorAPI] = BerlinTransactionExecutor diff --git a/eth/vm/forks/berlin/transactions.py b/eth/vm/forks/berlin/transactions.py index 83cd1e040a..b68c7fe803 100644 --- a/eth/vm/forks/berlin/transactions.py +++ b/eth/vm/forks/berlin/transactions.py @@ -4,13 +4,19 @@ Sequence, Tuple, Type, - cast, Union, + cast, ) -from cached_property import cached_property -from eth_keys.datatypes import PrivateKey -from eth_hash.auto import keccak +from cached_property import ( + cached_property, +) +from eth_hash.auto import ( + keccak, +) +from eth_keys.datatypes import ( + PrivateKey, +) from eth_typing import ( Address, Hash32, @@ -29,6 +35,12 @@ binary, ) +from eth._utils.transactions import ( + calculate_intrinsic_gas, + create_transaction_signature, + extract_transaction_sender, + validate_transaction_signature, +) from eth.abc import ( DecodedZeroOrOneLayerRLP, ReceiptAPI, @@ -37,12 +49,24 @@ TransactionDecoderAPI, UnsignedTransactionAPI, ) -from eth.constants import CREATE_CONTRACT_ADDRESS -from eth.exceptions import UnrecognizedTransactionType -from eth.rlp.logs import Log -from eth.rlp.receipts import Receipt -from eth.rlp.sedes import address -from eth.rlp.transactions import SignedTransactionMethods +from eth.constants import ( + CREATE_CONTRACT_ADDRESS, +) +from eth.exceptions import ( + UnrecognizedTransactionType, +) +from eth.rlp.logs import ( + Log, +) +from eth.rlp.receipts import ( + Receipt, +) +from eth.rlp.sedes import ( + address, +) +from eth.rlp.transactions import ( + SignedTransactionMethods, +) from eth.validation import ( validate_canonical_address, validate_is_bytes, @@ -57,13 +81,6 @@ MuirGlacierUnsignedTransaction, ) -from eth._utils.transactions import ( - calculate_intrinsic_gas, - create_transaction_signature, - extract_transaction_sender, - validate_transaction_signature, -) - from .constants import ( ACCESS_LIST_ADDRESS_COST_EIP_2930, ACCESS_LIST_STORAGE_KEY_COST_EIP_2930, diff --git a/eth/vm/forks/byzantium/__init__.py b/eth/vm/forks/byzantium/__init__.py index 235e16ad8b..7246f50337 100644 --- a/eth/vm/forks/byzantium/__init__.py +++ b/eth/vm/forks/byzantium/__init__.py @@ -16,7 +16,7 @@ from eth.abc import ( BlockAPI, BlockHeaderAPI, - MessageComputationAPI, + ComputationAPI, ReceiptAPI, SignedTransactionAPI, StateAPI, @@ -104,7 +104,7 @@ def make_receipt( cls, base_header: BlockHeaderAPI, transaction: SignedTransactionAPI, - computation: MessageComputationAPI, + computation: ComputationAPI, state: StateAPI) -> ReceiptAPI: gas_used = base_header.gas_used + cls.finalize_gas_used(transaction, computation) diff --git a/eth/vm/forks/byzantium/blocks.py b/eth/vm/forks/byzantium/blocks.py index 3ce0d707f3..20a523e8a8 100644 --- a/eth/vm/forks/byzantium/blocks.py +++ b/eth/vm/forks/byzantium/blocks.py @@ -1,6 +1,7 @@ from rlp.sedes import ( CountableList, ) + from eth.rlp.headers import ( BlockHeader, ) diff --git a/eth/vm/forks/byzantium/computation.py b/eth/vm/forks/byzantium/computation.py index 30becc1e5d..9e0e532204 100644 --- a/eth/vm/forks/byzantium/computation.py +++ b/eth/vm/forks/byzantium/computation.py @@ -2,14 +2,22 @@ merge, ) -from eth import precompiles +from eth import ( + precompiles, +) from eth._utils.address import ( force_bytes_to_address, ) -from eth.vm.forks.frontier.computation import FRONTIER_PRECOMPILES -from eth.vm.forks.spurious_dragon.computation import SpuriousDragonMessageComputation +from eth.vm.forks.frontier.computation import ( + FRONTIER_PRECOMPILES, +) +from eth.vm.forks.spurious_dragon.computation import ( + SpuriousDragonComputation, +) -from .opcodes import BYZANTIUM_OPCODES +from .opcodes import ( + BYZANTIUM_OPCODES, +) BYZANTIUM_PRECOMPILES = merge( FRONTIER_PRECOMPILES, @@ -22,11 +30,11 @@ ) -class ByzantiumMessageComputation(SpuriousDragonMessageComputation): +class ByzantiumComputation(SpuriousDragonComputation): """ A class for all execution *message* computations in the ``Byzantium`` fork. Inherits from - :class:`~eth.vm.forks.spurious_dragon.computation.SpuriousDragonMessageComputation` + :class:`~eth.vm.forks.spurious_dragon.computation.SpuriousDragonComputation` """ # Override opcodes = BYZANTIUM_OPCODES diff --git a/eth/vm/forks/byzantium/constants.py b/eth/vm/forks/byzantium/constants.py index 9c4d445d18..9bea1d0549 100644 --- a/eth/vm/forks/byzantium/constants.py +++ b/eth/vm/forks/byzantium/constants.py @@ -1,4 +1,6 @@ -from eth_utils import denoms +from eth_utils import ( + denoms, +) # # Difficulty diff --git a/eth/vm/forks/byzantium/headers.py b/eth/vm/forks/byzantium/headers.py index 6cacd0e440..a6be477229 100644 --- a/eth/vm/forks/byzantium/headers.py +++ b/eth/vm/forks/byzantium/headers.py @@ -2,26 +2,27 @@ Any, Callable, ) + from eth_utils.toolz import ( curry, ) +from eth._utils.db import ( + get_parent_header, +) +from eth._utils.headers import ( + new_timestamp_from_parent, +) from eth.abc import ( BlockHeaderAPI, VirtualMachineAPI, ) from eth.constants import ( - EMPTY_UNCLE_HASH, + BOMB_EXPONENTIAL_FREE_PERIODS, + BOMB_EXPONENTIAL_PERIOD, DIFFICULTY_ADJUSTMENT_DENOMINATOR, DIFFICULTY_MINIMUM, - BOMB_EXPONENTIAL_PERIOD, - BOMB_EXPONENTIAL_FREE_PERIODS, -) -from eth._utils.db import ( - get_parent_header, -) -from eth._utils.headers import ( - new_timestamp_from_parent, + EMPTY_UNCLE_HASH, ) from eth.validation import ( validate_gt, @@ -32,7 +33,7 @@ ) from .constants import ( - BYZANTIUM_DIFFICULTY_ADJUSTMENT_CUTOFF + BYZANTIUM_DIFFICULTY_ADJUSTMENT_CUTOFF, ) diff --git a/eth/vm/forks/byzantium/opcodes.py b/eth/vm/forks/byzantium/opcodes.py index 3e614f195f..15309db689 100644 --- a/eth/vm/forks/byzantium/opcodes.py +++ b/eth/vm/forks/byzantium/opcodes.py @@ -1,26 +1,35 @@ import copy import functools -from typing import Dict - -from eth_utils.toolz import merge - from typing import ( Any, Callable, + Dict, ) -from eth import constants +from eth_utils.toolz import ( + merge, +) -from eth.abc import OpcodeAPI +from eth import ( + constants, +) +from eth.abc import ( + ComputationAPI, + OpcodeAPI, +) from eth.exceptions import ( WriteProtection, ) -from eth.vm import mnemonics -from eth.vm import opcode_values -from eth.vm.computation import MessageComputation +from eth.vm import ( + mnemonics, + opcode_values, +) +from eth.vm.forks.spurious_dragon.opcodes import ( + SPURIOUS_DRAGON_OPCODES, +) from eth.vm.forks.tangerine_whistle.constants import ( GAS_CALL_EIP150, - GAS_SELFDESTRUCT_EIP150 + GAS_SELFDESTRUCT_EIP150, ) from eth.vm.logic import ( call, @@ -29,14 +38,14 @@ storage, system, ) -from eth.vm.opcode import as_opcode - -from eth.vm.forks.spurious_dragon.opcodes import SPURIOUS_DRAGON_OPCODES +from eth.vm.opcode import ( + as_opcode, +) def ensure_no_static(opcode_fn: Callable[..., Any]) -> Callable[..., Any]: @functools.wraps(opcode_fn) - def inner(computation: MessageComputation) -> Callable[..., Any]: + def inner(computation: ComputationAPI) -> Callable[..., Any]: if computation.msg.is_static: raise WriteProtection("Cannot modify state while inside of a STATICCALL context") return opcode_fn(computation) diff --git a/eth/vm/forks/byzantium/state.py b/eth/vm/forks/byzantium/state.py index 0ff9c3164f..a47500e91a 100644 --- a/eth/vm/forks/byzantium/state.py +++ b/eth/vm/forks/byzantium/state.py @@ -1,7 +1,11 @@ -from eth.vm.forks.spurious_dragon.state import SpuriousDragonState +from eth.vm.forks.spurious_dragon.state import ( + SpuriousDragonState, +) -from .computation import ByzantiumMessageComputation +from .computation import ( + ByzantiumComputation, +) class ByzantiumState(SpuriousDragonState): - message_computation_class = ByzantiumMessageComputation + computation_class = ByzantiumComputation diff --git a/eth/vm/forks/byzantium/transactions.py b/eth/vm/forks/byzantium/transactions.py index 4f40e07ee4..91d51de838 100644 --- a/eth/vm/forks/byzantium/transactions.py +++ b/eth/vm/forks/byzantium/transactions.py @@ -1,10 +1,13 @@ -from eth_keys.datatypes import PrivateKey -from eth_typing import Address +from eth_keys.datatypes import ( + PrivateKey, +) +from eth_typing import ( + Address, +) from eth._utils.transactions import ( create_transaction_signature, ) - from eth.vm.forks.spurious_dragon.transactions import ( SpuriousDragonTransaction, SpuriousDragonUnsignedTransaction, diff --git a/eth/vm/forks/constantinople/blocks.py b/eth/vm/forks/constantinople/blocks.py index 8bd7480596..f8021ee767 100644 --- a/eth/vm/forks/constantinople/blocks.py +++ b/eth/vm/forks/constantinople/blocks.py @@ -1,6 +1,7 @@ from rlp.sedes import ( CountableList, ) + from eth.rlp.headers import ( BlockHeader, ) diff --git a/eth/vm/forks/constantinople/computation.py b/eth/vm/forks/constantinople/computation.py index 2fbf5dd107..81667c87a2 100644 --- a/eth/vm/forks/constantinople/computation.py +++ b/eth/vm/forks/constantinople/computation.py @@ -1,24 +1,24 @@ from eth.vm.forks.byzantium.computation import ( - BYZANTIUM_PRECOMPILES -) -from eth.vm.forks.byzantium.computation import ( - ByzantiumMessageComputation + BYZANTIUM_PRECOMPILES, + ByzantiumComputation, ) from eth.vm.gas_meter import ( - allow_negative_refund_strategy, GasMeter, + allow_negative_refund_strategy, ) -from .opcodes import CONSTANTINOPLE_OPCODES +from .opcodes import ( + CONSTANTINOPLE_OPCODES, +) CONSTANTINOPLE_PRECOMPILES = BYZANTIUM_PRECOMPILES -class ConstantinopleMessageComputation(ByzantiumMessageComputation): +class ConstantinopleComputation(ByzantiumComputation): """ A class for all execution *message* computations in the ``Constantinople`` fork. Inherits from - :class:`~eth.vm.forks.byzantium.computation.ByzantiumMessageComputation` + :class:`~eth.vm.forks.byzantium.computation.ByzantiumComputation` """ # Override opcodes = CONSTANTINOPLE_OPCODES diff --git a/eth/vm/forks/constantinople/constants.py b/eth/vm/forks/constantinople/constants.py index 3c9424f8bb..b85c0bb931 100644 --- a/eth/vm/forks/constantinople/constants.py +++ b/eth/vm/forks/constantinople/constants.py @@ -1,5 +1,6 @@ -from eth_utils import denoms - +from eth_utils import ( + denoms, +) GAS_EXTCODEHASH_EIP1052 = 400 GAS_SSTORE_EIP1283_NOOP = 200 diff --git a/eth/vm/forks/constantinople/headers.py b/eth/vm/forks/constantinople/headers.py index 4a75b016bc..d477659dce 100644 --- a/eth/vm/forks/constantinople/headers.py +++ b/eth/vm/forks/constantinople/headers.py @@ -1,10 +1,9 @@ from eth.vm.forks.byzantium.headers import ( + compute_difficulty, configure_header, create_header_from_parent, - compute_difficulty, ) - compute_constantinople_difficulty = compute_difficulty(5000000) create_constantinople_header_from_parent = create_header_from_parent( diff --git a/eth/vm/forks/constantinople/opcodes.py b/eth/vm/forks/constantinople/opcodes.py index 658b5ca4c4..9655a80e03 100644 --- a/eth/vm/forks/constantinople/opcodes.py +++ b/eth/vm/forks/constantinople/opcodes.py @@ -1,10 +1,11 @@ import copy + from eth_utils.toolz import ( - merge + merge, ) from eth import ( - constants + constants, ) from eth.vm import ( mnemonics, @@ -12,10 +13,10 @@ ) from eth.vm.forks.byzantium.opcodes import ( BYZANTIUM_OPCODES, - ensure_no_static + ensure_no_static, ) from eth.vm.forks.constantinople.constants import ( - GAS_EXTCODEHASH_EIP1052 + GAS_EXTCODEHASH_EIP1052, ) from eth.vm.forks.constantinople.storage import ( sstore_eip1283, @@ -26,10 +27,9 @@ system, ) from eth.vm.opcode import ( - as_opcode + as_opcode, ) - UPDATED_OPCODES = { opcode_values.SHL: as_opcode( logic_fn=arithmetic.shl, diff --git a/eth/vm/forks/constantinople/state.py b/eth/vm/forks/constantinople/state.py index ca41f928d5..e4c7956fb1 100644 --- a/eth/vm/forks/constantinople/state.py +++ b/eth/vm/forks/constantinople/state.py @@ -1,9 +1,11 @@ from eth.vm.forks.byzantium.state import ( - ByzantiumState + ByzantiumState, ) -from .computation import ConstantinopleMessageComputation +from .computation import ( + ConstantinopleComputation, +) class ConstantinopleState(ByzantiumState): - message_computation_class = ConstantinopleMessageComputation + computation_class = ConstantinopleComputation diff --git a/eth/vm/forks/constantinople/storage.py b/eth/vm/forks/constantinople/storage.py index 829444940e..ecc7ae47e7 100644 --- a/eth/vm/forks/constantinople/storage.py +++ b/eth/vm/forks/constantinople/storage.py @@ -1,8 +1,10 @@ -from functools import partial +from functools import ( + partial, +) from eth.vm.logic.storage import ( - net_sstore, NetSStoreGasSchedule, + net_sstore, ) GAS_SCHEDULE_EIP1283 = NetSStoreGasSchedule( diff --git a/eth/vm/forks/constantinople/transactions.py b/eth/vm/forks/constantinople/transactions.py index daed44e4b0..093b357b7b 100644 --- a/eth/vm/forks/constantinople/transactions.py +++ b/eth/vm/forks/constantinople/transactions.py @@ -1,14 +1,17 @@ -from eth_keys.datatypes import PrivateKey -from eth_typing import Address - -from eth.vm.forks.byzantium.transactions import ( - ByzantiumTransaction, - ByzantiumUnsignedTransaction, +from eth_keys.datatypes import ( + PrivateKey, +) +from eth_typing import ( + Address, ) from eth._utils.transactions import ( create_transaction_signature, ) +from eth.vm.forks.byzantium.transactions import ( + ByzantiumTransaction, + ByzantiumUnsignedTransaction, +) class ConstantinopleTransaction(ByzantiumTransaction): diff --git a/eth/vm/forks/frontier/__init__.py b/eth/vm/forks/frontier/__init__.py index 174f939160..0f2441b9b2 100644 --- a/eth/vm/forks/frontier/__init__.py +++ b/eth/vm/forks/frontier/__init__.py @@ -12,7 +12,7 @@ ReceiptAPI, StateAPI, SignedTransactionAPI, - MessageComputationAPI, + ComputationAPI, ) from eth.constants import ( BLOCK_REWARD, @@ -35,7 +35,7 @@ from .validation import validate_frontier_transaction_against_header -def make_frontier_receipt(computation: MessageComputationAPI, +def make_frontier_receipt(computation: ComputationAPI, new_cumulative_gas_used: int) -> ReceiptAPI: # Reusable for other forks # This skips setting the state root (set to 0 instead). The logic for making a state root @@ -101,7 +101,7 @@ def calculate_net_gas_refund(cls, consumed_gas: int, gross_refund: int) -> int: @classmethod def finalize_gas_used(cls, transaction: SignedTransactionAPI, - computation: MessageComputationAPI) -> int: + computation: ComputationAPI) -> int: gas_remaining = computation.get_gas_remaining() consumed_gas = transaction.gas - gas_remaining @@ -116,7 +116,7 @@ def make_receipt( cls, base_header: BlockHeaderAPI, transaction: SignedTransactionAPI, - computation: MessageComputationAPI, + computation: ComputationAPI, state: StateAPI) -> ReceiptAPI: gas_used = base_header.gas_used + cls.finalize_gas_used(transaction, computation) diff --git a/eth/vm/forks/frontier/blocks.py b/eth/vm/forks/frontier/blocks.py index 75ce44bc40..7145771f03 100644 --- a/eth/vm/forks/frontier/blocks.py +++ b/eth/vm/forks/frontier/blocks.py @@ -4,19 +4,16 @@ Type, ) -from rlp.sedes import ( - CountableList, -) - from eth_bloom import ( BloomFilter, ) - from eth_typing import ( BlockNumber, Hash32, ) - +from rlp.sedes import ( + CountableList, +) from trie.exceptions import ( MissingTrieNode, ) diff --git a/eth/vm/forks/frontier/computation.py b/eth/vm/forks/frontier/computation.py index 693ece056e..c1b2ecb56c 100644 --- a/eth/vm/forks/frontier/computation.py +++ b/eth/vm/forks/frontier/computation.py @@ -1,35 +1,38 @@ -from eth import precompiles - -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_utils import ( encode_hex, ) -from eth.constants import ( - GAS_CODEDEPOSIT, - STACK_DEPTH_LIMIT, +from eth import ( + precompiles, ) - from eth._utils.address import ( force_bytes_to_address, ) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, MessageAPI, StateAPI, TransactionContextAPI, ) +from eth.constants import ( + GAS_CODEDEPOSIT, + STACK_DEPTH_LIMIT, +) from eth.exceptions import ( - OutOfGas, InsufficientFunds, + OutOfGas, StackDepthLimit, ) from eth.vm.computation import ( - MessageComputation, + BaseComputation, ) -from .opcodes import FRONTIER_OPCODES - +from .opcodes import ( + FRONTIER_OPCODES, +) FRONTIER_PRECOMPILES = { force_bytes_to_address(b'\x01'): precompiles.ecrecover, @@ -39,10 +42,10 @@ } -class FrontierMessageComputation(MessageComputation): +class FrontierComputation(BaseComputation): """ A class for all execution message computations in the ``Frontier`` fork. - Inherits from :class:`~eth.vm.computation.MessageComputation` + Inherits from :class:`~eth.vm.computation.BaseComputation` """ # Override opcodes = FRONTIER_OPCODES @@ -54,7 +57,7 @@ def apply_message( state: StateAPI, message: MessageAPI, transaction_context: TransactionContextAPI, - ) -> MessageComputationAPI: + ) -> ComputationAPI: snapshot = state.snapshot() @@ -99,7 +102,7 @@ def apply_create_message( cls, state: StateAPI, message: MessageAPI, - transaction_context: TransactionContextAPI) -> MessageComputationAPI: + transaction_context: TransactionContextAPI) -> ComputationAPI: computation = cls.apply_message(state, message, transaction_context) diff --git a/eth/vm/forks/frontier/headers.py b/eth/vm/forks/frontier/headers.py index f7fce87301..d71bd60d87 100644 --- a/eth/vm/forks/frontier/headers.py +++ b/eth/vm/forks/frontier/headers.py @@ -1,21 +1,8 @@ from typing import ( - Any, TYPE_CHECKING, + Any, ) -from eth.abc import BlockHeaderAPI -from eth.validation import ( - validate_gt, - validate_header_params_for_configuration, -) - -from eth.constants import ( - GENESIS_GAS_LIMIT, - DIFFICULTY_ADJUSTMENT_DENOMINATOR, - DIFFICULTY_MINIMUM, - BOMB_EXPONENTIAL_PERIOD, - BOMB_EXPONENTIAL_FREE_PERIODS, -) from eth._utils.db import ( get_parent_header, ) @@ -24,14 +11,30 @@ fill_header_params_from_parent, new_timestamp_from_parent, ) -from eth.rlp.headers import BlockHeader +from eth.abc import ( + BlockHeaderAPI, +) +from eth.constants import ( + BOMB_EXPONENTIAL_FREE_PERIODS, + BOMB_EXPONENTIAL_PERIOD, + DIFFICULTY_ADJUSTMENT_DENOMINATOR, + DIFFICULTY_MINIMUM, + GENESIS_GAS_LIMIT, +) +from eth.rlp.headers import ( + BlockHeader, +) +from eth.validation import ( + validate_gt, + validate_header_params_for_configuration, +) from .constants import ( - FRONTIER_DIFFICULTY_ADJUSTMENT_CUTOFF + FRONTIER_DIFFICULTY_ADJUSTMENT_CUTOFF, ) if TYPE_CHECKING: - from eth.vm.forks.frontier import FrontierVM # noqa: F401 + from eth.vm.forks.frontier import FrontierVM # noqa: F401 def compute_frontier_difficulty(parent_header: BlockHeaderAPI, timestamp: int) -> int: diff --git a/eth/vm/forks/frontier/opcodes.py b/eth/vm/forks/frontier/opcodes.py index c265338250..1b5f2158d9 100644 --- a/eth/vm/forks/frontier/opcodes.py +++ b/eth/vm/forks/frontier/opcodes.py @@ -1,10 +1,17 @@ -from typing import Dict - -from eth import constants +from typing import ( + Dict, +) -from eth.abc import OpcodeAPI -from eth.vm import mnemonics -from eth.vm import opcode_values +from eth import ( + constants, +) +from eth.abc import ( + OpcodeAPI, +) +from eth.vm import ( + mnemonics, + opcode_values, +) from eth.vm.logic import ( arithmetic, block, @@ -25,7 +32,6 @@ as_opcode, ) - FRONTIER_OPCODES: Dict[int, OpcodeAPI] = { # # Arithmetic diff --git a/eth/vm/forks/frontier/state.py b/eth/vm/forks/frontier/state.py index ee8da8b623..3567a549ac 100644 --- a/eth/vm/forks/frontier/state.py +++ b/eth/vm/forks/frontier/state.py @@ -1,30 +1,34 @@ -from typing import Type +from typing import ( + Type, +) -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_utils import ( encode_hex, ) +from eth._utils.address import ( + generate_contract_address, +) from eth.abc import ( AccountDatabaseAPI, - MessageComputationAPI, - SignedTransactionAPI, + ComputationAPI, MessageAPI, + SignedTransactionAPI, TransactionContextAPI, TransactionExecutorAPI, ) -from eth.constants import CREATE_CONTRACT_ADDRESS +from eth.constants import ( + CREATE_CONTRACT_ADDRESS, +) from eth.db.account import ( AccountDB, ) from eth.exceptions import ( ContractCreationCollision, ) - -from eth._utils.address import ( - generate_contract_address, -) - from eth.vm.message import ( Message, ) @@ -33,16 +37,19 @@ BaseTransactionExecutor, ) - -from .computation import FrontierMessageComputation +from .computation import ( + FrontierComputation, +) from .constants import ( - REFUND_SELFDESTRUCT, MAX_REFUND_QUOTIENT, + REFUND_SELFDESTRUCT, ) from .transaction_context import ( - FrontierTransactionContext + FrontierTransactionContext, +) +from .validation import ( + validate_frontier_transaction, ) -from .validation import validate_frontier_transaction class FrontierTransactionExecutor(BaseTransactionExecutor): @@ -111,7 +118,7 @@ def build_evm_message(self, transaction: SignedTransactionAPI) -> MessageAPI: def build_computation(self, message: MessageAPI, - transaction: SignedTransactionAPI) -> MessageComputationAPI: + transaction: SignedTransactionAPI) -> ComputationAPI: transaction_context = self.vm_state.get_transaction_context(transaction) if message.is_create: is_collision = self.vm_state.has_code_or_nonce( @@ -131,13 +138,13 @@ def build_computation(self, encode_hex(message.storage_address), ) else: - computation = self.vm_state.message_computation_class.apply_create_message( + computation = self.vm_state.computation_class.apply_create_message( self.vm_state, message, transaction_context, ) else: - computation = self.vm_state.message_computation_class.apply_message( + computation = self.vm_state.computation_class.apply_message( self.vm_state, message, transaction_context, @@ -147,7 +154,7 @@ def build_computation(self, @classmethod def calculate_gas_refund(cls, - computation: MessageComputationAPI, + computation: ComputationAPI, gas_used: int) -> int: # Self Destruct Refunds num_deletions = len(computation.get_accounts_for_deletion()) @@ -162,8 +169,8 @@ def calculate_gas_refund(cls, def finalize_computation( self, transaction: SignedTransactionAPI, - computation: MessageComputationAPI - ) -> MessageComputationAPI: + computation: ComputationAPI + ) -> ComputationAPI: transaction_context = self.vm_state.get_transaction_context(transaction) gas_remaining = computation.get_gas_remaining() @@ -204,12 +211,12 @@ def finalize_computation( class FrontierState(BaseState): - message_computation_class: Type[MessageComputationAPI] = FrontierMessageComputation + computation_class: Type[ComputationAPI] = FrontierComputation transaction_context_class: Type[TransactionContextAPI] = FrontierTransactionContext account_db_class: Type[AccountDatabaseAPI] = AccountDB transaction_executor_class: Type[TransactionExecutorAPI] = FrontierTransactionExecutor - def apply_transaction(self, transaction: SignedTransactionAPI) -> MessageComputationAPI: + def apply_transaction(self, transaction: SignedTransactionAPI) -> ComputationAPI: executor = self.get_transaction_executor() return executor(transaction) diff --git a/eth/vm/forks/frontier/transaction_context.py b/eth/vm/forks/frontier/transaction_context.py index 4f63c6fc9a..fc5520a59d 100644 --- a/eth/vm/forks/frontier/transaction_context.py +++ b/eth/vm/forks/frontier/transaction_context.py @@ -1,4 +1,6 @@ -from eth.vm.transaction_context import BaseTransactionContext +from eth.vm.transaction_context import ( + BaseTransactionContext, +) class FrontierTransactionContext(BaseTransactionContext): diff --git a/eth/vm/forks/frontier/transactions.py b/eth/vm/forks/frontier/transactions.py index d6e0d4bf34..49557aeb3a 100644 --- a/eth/vm/forks/frontier/transactions.py +++ b/eth/vm/forks/frontier/transactions.py @@ -1,14 +1,26 @@ -from functools import partial +from functools import ( + partial, +) from typing import ( Tuple, ) -from eth_keys.datatypes import PrivateKey +from eth_keys.datatypes import ( + PrivateKey, +) from eth_typing import ( Address, ) import rlp +from eth._utils.transactions import ( + V_OFFSET, + IntrinsicGasSchedule, + calculate_intrinsic_gas, + create_transaction_signature, + extract_transaction_sender, + validate_transaction_signature, +) from eth.abc import ( ReceiptAPI, SignedTransactionAPI, @@ -16,36 +28,29 @@ from eth.constants import ( CREATE_CONTRACT_ADDRESS, GAS_TX, - GAS_TXDATAZERO, GAS_TXDATANONZERO, + GAS_TXDATAZERO, ) -from eth.validation import ( - validate_uint256, - validate_is_integer, - validate_is_bytes, - validate_lt_secpk1n, - validate_lte, - validate_gte, - validate_canonical_address, +from eth.rlp.logs import ( + Log, +) +from eth.rlp.receipts import ( + Receipt, ) - -from eth.rlp.logs import Log -from eth.rlp.receipts import Receipt from eth.rlp.transactions import ( BaseTransaction, BaseUnsignedTransaction, ) - -from eth._utils.transactions import ( - V_OFFSET, - create_transaction_signature, - extract_transaction_sender, - validate_transaction_signature, - IntrinsicGasSchedule, - calculate_intrinsic_gas, +from eth.validation import ( + validate_canonical_address, + validate_gte, + validate_is_bytes, + validate_is_integer, + validate_lt_secpk1n, + validate_lte, + validate_uint256, ) - FRONTIER_TX_GAS_SCHEDULE = IntrinsicGasSchedule( gas_tx=GAS_TX, gas_txcreate=0, diff --git a/eth/vm/forks/gray_glacier/blocks.py b/eth/vm/forks/gray_glacier/blocks.py index 58f0a43273..be1609648d 100644 --- a/eth/vm/forks/gray_glacier/blocks.py +++ b/eth/vm/forks/gray_glacier/blocks.py @@ -1,18 +1,21 @@ -from abc import ABC -from typing import Type +from abc import ( + ABC, +) +from typing import ( + Type, +) -from eth.abc import TransactionBuilderAPI from eth_utils import ( encode_hex, ) - from rlp.sedes import ( CountableList, ) -from .transactions import ( - GrayGlacierTransactionBuilder, +from eth.abc import ( + TransactionBuilderAPI, ) + from ..arrow_glacier import ( ArrowGlacierBlock, ) @@ -20,7 +23,12 @@ ArrowGlacierBlockHeader, ArrowGlacierMiningHeader, ) -from ..london.blocks import LondonBackwardsHeader +from ..london.blocks import ( + LondonBackwardsHeader, +) +from .transactions import ( + GrayGlacierTransactionBuilder, +) class GrayGlacierMiningHeader(ArrowGlacierMiningHeader, ABC): diff --git a/eth/vm/forks/gray_glacier/computation.py b/eth/vm/forks/gray_glacier/computation.py index 378434304d..9a2f54bf20 100644 --- a/eth/vm/forks/gray_glacier/computation.py +++ b/eth/vm/forks/gray_glacier/computation.py @@ -1,9 +1,11 @@ -from ..arrow_glacier.computation import ArrowGlacierMessageComputation +from ..arrow_glacier.computation import ( + ArrowGlacierComputation, +) -class GrayGlacierMessageComputation(ArrowGlacierMessageComputation): +class GrayGlacierComputation(ArrowGlacierComputation): """ A class for all execution *message* computations in the ``GrayGlacier`` fork. - Inherits from :class:`~eth.vm.forks.arrow_glacier.ArrowGlacierMessageComputation` + Inherits from :class:`~eth.vm.forks.arrow_glacier.ArrowGlacierComputation` """ pass diff --git a/eth/vm/forks/gray_glacier/headers.py b/eth/vm/forks/gray_glacier/headers.py index 2896f0c75e..b24fa412eb 100644 --- a/eth/vm/forks/gray_glacier/headers.py +++ b/eth/vm/forks/gray_glacier/headers.py @@ -1,10 +1,13 @@ -from typing import Any, Callable, Optional - -from toolz import curry +from typing import ( + Any, + Callable, + Optional, +) -from .blocks import ( - GrayGlacierBlockHeader, +from toolz import ( + curry, ) + from eth.abc import ( BlockHeaderAPI, ) @@ -13,11 +16,13 @@ ) from eth.vm.forks.byzantium.headers import ( compute_difficulty, -) -from eth.vm.forks.byzantium.headers import ( configure_header, ) +from .blocks import ( + GrayGlacierBlockHeader, +) + compute_gray_glacier_difficulty = compute_difficulty(11_400_000) configure_gray_glacier_header = configure_header(difficulty_fn=compute_gray_glacier_difficulty) diff --git a/eth/vm/forks/gray_glacier/state.py b/eth/vm/forks/gray_glacier/state.py index 629ccd65e4..0e9e3ea627 100644 --- a/eth/vm/forks/gray_glacier/state.py +++ b/eth/vm/forks/gray_glacier/state.py @@ -1,9 +1,20 @@ -from typing import Type +from typing import ( + Type, +) -from eth.abc import TransactionExecutorAPI -from .computation import GrayGlacierMessageComputation -from ..arrow_glacier import ArrowGlacierState -from ..arrow_glacier.state import ArrowGlacierTransactionExecutor +from eth.abc import ( + TransactionExecutorAPI, +) + +from ..arrow_glacier import ( + ArrowGlacierState, +) +from ..arrow_glacier.state import ( + ArrowGlacierTransactionExecutor, +) +from .computation import ( + GrayGlacierComputation, +) class GrayGlacierTransactionExecutor(ArrowGlacierTransactionExecutor): @@ -11,5 +22,5 @@ class GrayGlacierTransactionExecutor(ArrowGlacierTransactionExecutor): class GrayGlacierState(ArrowGlacierState): - message_computation_class = GrayGlacierMessageComputation + computation_class = GrayGlacierComputation transaction_executor_class: Type[TransactionExecutorAPI] = GrayGlacierTransactionExecutor diff --git a/eth/vm/forks/gray_glacier/transactions.py b/eth/vm/forks/gray_glacier/transactions.py index 008be551f6..ab4d758695 100644 --- a/eth/vm/forks/gray_glacier/transactions.py +++ b/eth/vm/forks/gray_glacier/transactions.py @@ -1,6 +1,10 @@ -from abc import ABC +from abc import ( + ABC, +) -from eth_keys.datatypes import PrivateKey +from eth_keys.datatypes import ( + PrivateKey, +) from eth._utils.transactions import ( create_transaction_signature, diff --git a/eth/vm/forks/homestead/blocks.py b/eth/vm/forks/homestead/blocks.py index 5555f26e3f..53aa27b706 100644 --- a/eth/vm/forks/homestead/blocks.py +++ b/eth/vm/forks/homestead/blocks.py @@ -1,12 +1,14 @@ from rlp.sedes import ( CountableList, ) + from eth.rlp.headers import ( BlockHeader, ) from eth.vm.forks.frontier.blocks import ( FrontierBlock, ) + from .transactions import ( HomesteadTransaction, ) diff --git a/eth/vm/forks/homestead/computation.py b/eth/vm/forks/homestead/computation.py index e2926cecb4..09cc49d7e5 100644 --- a/eth/vm/forks/homestead/computation.py +++ b/eth/vm/forks/homestead/computation.py @@ -1,30 +1,35 @@ -from eth_hash.auto import keccak - -from eth import constants -from eth.exceptions import ( - OutOfGas, +from eth_hash.auto import ( + keccak, ) from eth_utils import ( encode_hex, ) +from eth import ( + constants, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, MessageAPI, StateAPI, TransactionContextAPI, ) +from eth.exceptions import ( + OutOfGas, +) from eth.vm.forks.frontier.computation import ( - FrontierMessageComputation, + FrontierComputation, ) -from .opcodes import HOMESTEAD_OPCODES +from .opcodes import ( + HOMESTEAD_OPCODES, +) -class HomesteadMessageComputation(FrontierMessageComputation): +class HomesteadComputation(FrontierComputation): """ A class for all execution *message* computations in the ``Frontier`` fork. - Inherits from :class:`~eth.vm.forks.frontier.computation.FrontierMessageComputation` + Inherits from :class:`~eth.vm.forks.frontier.computation.FrontierComputation` """ # Override opcodes = HOMESTEAD_OPCODES @@ -34,7 +39,7 @@ def apply_create_message( cls, state: StateAPI, message: MessageAPI, - transaction_context: TransactionContextAPI) -> MessageComputationAPI: + transaction_context: TransactionContextAPI) -> ComputationAPI: snapshot = state.snapshot() computation = cls.apply_message(state, message, transaction_context) diff --git a/eth/vm/forks/homestead/headers.py b/eth/vm/forks/homestead/headers.py index 2008b68d2d..9868e41217 100644 --- a/eth/vm/forks/homestead/headers.py +++ b/eth/vm/forks/homestead/headers.py @@ -1,6 +1,6 @@ from typing import ( - Any, TYPE_CHECKING, + Any, ) from eth_typing import ( @@ -10,16 +10,20 @@ decode_hex, ) -from eth.abc import BlockHeaderAPI +from eth._utils.db import ( + get_parent_header, +) +from eth.abc import ( + BlockHeaderAPI, +) from eth.constants import ( + BOMB_EXPONENTIAL_FREE_PERIODS, + BOMB_EXPONENTIAL_PERIOD, DIFFICULTY_ADJUSTMENT_DENOMINATOR, DIFFICULTY_MINIMUM, - BOMB_EXPONENTIAL_PERIOD, - BOMB_EXPONENTIAL_FREE_PERIODS, ) -from eth.rlp.headers import BlockHeader -from eth._utils.db import ( - get_parent_header, +from eth.rlp.headers import ( + BlockHeader, ) from eth.validation import ( validate_gt, @@ -30,11 +34,11 @@ ) from .constants import ( - HOMESTEAD_DIFFICULTY_ADJUSTMENT_CUTOFF + HOMESTEAD_DIFFICULTY_ADJUSTMENT_CUTOFF, ) if TYPE_CHECKING: - from eth.vm.forks.homestead import HomesteadVM # noqa: F401 + from eth.vm.forks.homestead import HomesteadVM # noqa: F401 def compute_homestead_difficulty(parent_header: BlockHeaderAPI, timestamp: int) -> int: diff --git a/eth/vm/forks/homestead/opcodes.py b/eth/vm/forks/homestead/opcodes.py index a3104dcf25..9e3a58ad81 100644 --- a/eth/vm/forks/homestead/opcodes.py +++ b/eth/vm/forks/homestead/opcodes.py @@ -1,19 +1,29 @@ import copy -from typing import Dict +from typing import ( + Dict, +) -from eth_utils.toolz import merge +from eth_utils.toolz import ( + merge, +) -from eth import constants -from eth.abc import OpcodeAPI -from eth.vm import mnemonics -from eth.vm import opcode_values +from eth import ( + constants, +) +from eth.abc import ( + OpcodeAPI, +) +from eth.vm import ( + mnemonics, + opcode_values, +) +from eth.vm.forks.frontier.opcodes import ( + FRONTIER_OPCODES, +) from eth.vm.logic import ( call, ) -from eth.vm.forks.frontier.opcodes import FRONTIER_OPCODES - - NEW_OPCODES = { opcode_values.DELEGATECALL: call.DelegateCall.configure( __name__='opcode:DELEGATECALL', diff --git a/eth/vm/forks/homestead/state.py b/eth/vm/forks/homestead/state.py index c994ee74c3..4284496c66 100644 --- a/eth/vm/forks/homestead/state.py +++ b/eth/vm/forks/homestead/state.py @@ -1,7 +1,9 @@ -from typing import Type +from typing import ( + Type, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, SignedTransactionAPI, ) from eth.vm.forks.frontier.state import ( @@ -9,12 +11,16 @@ FrontierTransactionExecutor, ) -from .computation import HomesteadMessageComputation -from .validation import validate_homestead_transaction +from .computation import ( + HomesteadComputation, +) +from .validation import ( + validate_homestead_transaction, +) class HomesteadState(FrontierState): - message_computation_class: Type[MessageComputationAPI] = HomesteadMessageComputation + computation_class: Type[ComputationAPI] = HomesteadComputation def validate_transaction(self, transaction: SignedTransactionAPI) -> None: validate_homestead_transaction(self, transaction) diff --git a/eth/vm/forks/homestead/transactions.py b/eth/vm/forks/homestead/transactions.py index f9ba670d17..0cdc3eb6be 100644 --- a/eth/vm/forks/homestead/transactions.py +++ b/eth/vm/forks/homestead/transactions.py @@ -1,26 +1,29 @@ -from functools import partial +from functools import ( + partial, +) +from eth_keys.datatypes import ( + PrivateKey, +) +from eth_typing import ( + Address, +) import rlp -from eth_keys.datatypes import PrivateKey - -from eth_typing import Address - -from eth.constants import GAS_TXCREATE - +from eth._utils.transactions import ( + calculate_intrinsic_gas, + create_transaction_signature, +) +from eth.constants import ( + GAS_TXCREATE, +) from eth.validation import ( validate_lt_secpk1n2, ) - from eth.vm.forks.frontier.transactions import ( + FRONTIER_TX_GAS_SCHEDULE, FrontierTransaction, FrontierUnsignedTransaction, - FRONTIER_TX_GAS_SCHEDULE, -) - -from eth._utils.transactions import ( - create_transaction_signature, - calculate_intrinsic_gas, ) HOMESTEAD_TX_GAS_SCHEDULE = FRONTIER_TX_GAS_SCHEDULE._replace( diff --git a/eth/vm/forks/homestead/validation.py b/eth/vm/forks/homestead/validation.py index b02ecf5031..dca1158893 100644 --- a/eth/vm/forks/homestead/validation.py +++ b/eth/vm/forks/homestead/validation.py @@ -2,14 +2,13 @@ ValidationError, ) -from eth.constants import ( - SECPK1_N, -) - from eth.abc import ( SignedTransactionAPI, StateAPI, ) +from eth.constants import ( + SECPK1_N, +) from eth.vm.forks.frontier.validation import ( validate_frontier_transaction, ) diff --git a/eth/vm/forks/istanbul/blocks.py b/eth/vm/forks/istanbul/blocks.py index 414ee1ac1d..9a6e89b64a 100644 --- a/eth/vm/forks/istanbul/blocks.py +++ b/eth/vm/forks/istanbul/blocks.py @@ -1,6 +1,7 @@ from rlp.sedes import ( CountableList, ) + from eth.rlp.headers import ( BlockHeader, ) diff --git a/eth/vm/forks/istanbul/computation.py b/eth/vm/forks/istanbul/computation.py index d548a113d8..020a7a1e2f 100644 --- a/eth/vm/forks/istanbul/computation.py +++ b/eth/vm/forks/istanbul/computation.py @@ -2,19 +2,19 @@ merge, ) -from eth import precompiles +from eth import ( + precompiles, +) from eth._utils.address import ( force_bytes_to_address, ) from eth.vm.forks.petersburg.computation import ( - PETERSBURG_PRECOMPILES -) -from eth.vm.forks.petersburg.computation import ( - PetersburgMessageComputation, + PETERSBURG_PRECOMPILES, + PetersburgComputation, ) from eth.vm.gas_meter import ( - allow_negative_refund_strategy, GasMeter, + allow_negative_refund_strategy, ) from .constants import ( @@ -23,7 +23,9 @@ GAS_ECPAIRING_BASE, GAS_ECPAIRING_PER_POINT, ) -from .opcodes import ISTANBUL_OPCODES +from .opcodes import ( + ISTANBUL_OPCODES, +) ISTANBUL_PRECOMPILES = merge( PETERSBURG_PRECOMPILES, @@ -39,11 +41,11 @@ ) -class IstanbulMessageComputation(PetersburgMessageComputation): +class IstanbulComputation(PetersburgComputation): """ A class for all execution *message* computations in the ``Istanbul`` fork. Inherits from - :class:`~eth.vm.forks.constantinople.petersburg.PetersburgMessageComputation` + :class:`~eth.vm.forks.constantinople.petersburg.PetersburgComputation` """ # Override opcodes = ISTANBUL_OPCODES diff --git a/eth/vm/forks/istanbul/headers.py b/eth/vm/forks/istanbul/headers.py index 78d206ad8d..ba3066a583 100644 --- a/eth/vm/forks/istanbul/headers.py +++ b/eth/vm/forks/istanbul/headers.py @@ -1,10 +1,9 @@ from eth.vm.forks.petersburg.headers import ( + compute_petersburg_difficulty, configure_header, create_header_from_parent, - compute_petersburg_difficulty, ) - compute_istanbul_difficulty = compute_petersburg_difficulty create_istanbul_header_from_parent = create_header_from_parent( diff --git a/eth/vm/forks/istanbul/opcodes.py b/eth/vm/forks/istanbul/opcodes.py index b0f7e9d754..2a0a11eb6b 100644 --- a/eth/vm/forks/istanbul/opcodes.py +++ b/eth/vm/forks/istanbul/opcodes.py @@ -1,33 +1,39 @@ import copy -from eth_utils.toolz import merge +from eth_utils.toolz import ( + merge, +) -from eth import constants +from eth import ( + constants, +) from eth.vm import ( mnemonics, opcode_values, ) from eth.vm.forks.byzantium.opcodes import ( - ensure_no_static -) -from eth.vm.forks.petersburg.opcodes import ( - PETERSBURG_OPCODES, + ensure_no_static, ) from eth.vm.forks.istanbul.constants import ( GAS_BALANCE_EIP1884, - GAS_SLOAD_EIP1884, GAS_EXTCODEHASH_EIP1884, + GAS_SLOAD_EIP1884, +) +from eth.vm.forks.petersburg.opcodes import ( + PETERSBURG_OPCODES, ) from eth.vm.logic import ( context, storage, ) -from eth.vm.opcode import as_opcode +from eth.vm.opcode import ( + as_opcode, +) + from .storage import ( sstore_eip2200, ) - UPDATED_OPCODES = { # New opcodes opcode_values.CHAINID: as_opcode( diff --git a/eth/vm/forks/istanbul/state.py b/eth/vm/forks/istanbul/state.py index 92969a76ae..448a7834d5 100644 --- a/eth/vm/forks/istanbul/state.py +++ b/eth/vm/forks/istanbul/state.py @@ -1,9 +1,11 @@ from eth.vm.forks.petersburg.state import ( - PetersburgState + PetersburgState, ) -from .computation import IstanbulMessageComputation +from .computation import ( + IstanbulComputation, +) class IstanbulState(PetersburgState): - message_computation_class = IstanbulMessageComputation + computation_class = IstanbulComputation diff --git a/eth/vm/forks/istanbul/storage.py b/eth/vm/forks/istanbul/storage.py index 773ba9da77..d8f38509b2 100644 --- a/eth/vm/forks/istanbul/storage.py +++ b/eth/vm/forks/istanbul/storage.py @@ -1,12 +1,18 @@ -from eth_utils.toolz import curry +from eth_utils.toolz import ( + curry, +) -from eth.exceptions import OutOfGas -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) +from eth.exceptions import ( + OutOfGas, +) from eth.vm.forks.constantinople.storage import ( GAS_SCHEDULE_EIP1283, ) from eth.vm.forks.istanbul import ( - constants + constants, ) from eth.vm.logic.storage import ( NetSStoreGasSchedule, @@ -21,7 +27,7 @@ @curry def sstore_eip2200_generic( gas_schedule: NetSStoreGasSchedule, - computation: MessageComputation, + computation: ComputationAPI, ) -> int: gas_remaining = computation.get_gas_remaining() if gas_remaining <= 2300: diff --git a/eth/vm/forks/istanbul/transactions.py b/eth/vm/forks/istanbul/transactions.py index 2e0e6b7041..76da9a04b1 100644 --- a/eth/vm/forks/istanbul/transactions.py +++ b/eth/vm/forks/istanbul/transactions.py @@ -1,20 +1,25 @@ -from functools import partial - -from eth_keys.datatypes import PrivateKey -from eth_typing import Address +from functools import ( + partial, +) -from eth.vm.forks.petersburg.transactions import ( - PetersburgTransaction, - PetersburgUnsignedTransaction, +from eth_keys.datatypes import ( + PrivateKey, +) +from eth_typing import ( + Address, ) from eth._utils.transactions import ( - create_transaction_signature, calculate_intrinsic_gas, + create_transaction_signature, ) from eth.vm.forks.homestead.transactions import ( HOMESTEAD_TX_GAS_SCHEDULE, ) +from eth.vm.forks.petersburg.transactions import ( + PetersburgTransaction, + PetersburgUnsignedTransaction, +) from .constants import ( GAS_TXDATANONZERO_EIP2028, diff --git a/eth/vm/forks/london/blocks.py b/eth/vm/forks/london/blocks.py index 9526887fd0..a4926df6c4 100644 --- a/eth/vm/forks/london/blocks.py +++ b/eth/vm/forks/london/blocks.py @@ -5,13 +5,15 @@ cast, ) -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_typing import ( BlockNumber, ) from eth_typing.evm import ( Address, - Hash32 + Hash32, ) from eth_utils import ( encode_hex, @@ -21,7 +23,7 @@ Binary, CountableList, big_endian_int, - binary + binary, ) from eth._utils.headers import ( @@ -35,12 +37,12 @@ TransactionBuilderAPI, ) from eth.constants import ( - ZERO_ADDRESS, - ZERO_HASH32, + BLANK_ROOT_HASH, EMPTY_UNCLE_HASH, GENESIS_NONCE, GENESIS_PARENT_HASH, - BLANK_ROOT_HASH, + ZERO_ADDRESS, + ZERO_HASH32, ) from eth.rlp.headers import ( BlockHeader, diff --git a/eth/vm/forks/london/computation.py b/eth/vm/forks/london/computation.py index 7e56152073..0bd2785fa1 100644 --- a/eth/vm/forks/london/computation.py +++ b/eth/vm/forks/london/computation.py @@ -1,16 +1,22 @@ -from eth.exceptions import ReservedBytesInCode +from eth.exceptions import ( + ReservedBytesInCode, +) from eth.vm.forks.berlin.computation import ( - BerlinMessageComputation, + BerlinComputation, ) -from .opcodes import LONDON_OPCODES -from ..london.constants import EIP3541_RESERVED_STARTING_BYTE +from ..london.constants import ( + EIP3541_RESERVED_STARTING_BYTE, +) +from .opcodes import ( + LONDON_OPCODES, +) -class LondonMessageComputation(BerlinMessageComputation): +class LondonComputation(BerlinComputation): """ A class for all execution *message* computations in the ``London`` fork. - Inherits from :class:`~eth.vm.forks.berlin.BerlinMessageComputation` + Inherits from :class:`~eth.vm.forks.berlin.BerlinComputation` """ opcodes = LONDON_OPCODES diff --git a/eth/vm/forks/london/headers.py b/eth/vm/forks/london/headers.py index 06c5352868..afe2eb683c 100644 --- a/eth/vm/forks/london/headers.py +++ b/eth/vm/forks/london/headers.py @@ -8,7 +8,9 @@ from eth_utils import ( ValidationError, ) -from toolz.functoolz import curry +from toolz.functoolz import ( + curry, +) from eth._utils.headers import ( compute_gas_limit, @@ -19,8 +21,12 @@ BlockHeaderAPI, BlockHeaderSedesAPI, ) -from eth.constants import GENESIS_GAS_LIMIT -from eth.rlp.headers import BlockHeader +from eth.constants import ( + GENESIS_GAS_LIMIT, +) +from eth.rlp.headers import ( + BlockHeader, +) from eth.vm.forks.berlin.headers import ( configure_header, ) @@ -28,8 +34,9 @@ compute_difficulty, ) - -from .blocks import LondonBlockHeader +from .blocks import ( + LondonBlockHeader, +) from .constants import ( BASE_FEE_MAX_CHANGE_DENOMINATOR, ELASTICITY_MULTIPLIER, diff --git a/eth/vm/forks/london/opcodes.py b/eth/vm/forks/london/opcodes.py index 2b1d738044..a3b25f2952 100644 --- a/eth/vm/forks/london/opcodes.py +++ b/eth/vm/forks/london/opcodes.py @@ -1,29 +1,36 @@ import copy -from typing import Dict +from typing import ( + Dict, +) -from eth_utils.toolz import merge +from eth_utils.toolz import ( + merge, +) -from eth.vm.logic import ( - block, +from eth import ( + constants, ) from eth.vm import ( mnemonics, opcode_values, ) -from eth.vm.opcode import ( - Opcode, - as_opcode, -) -from eth import constants - from eth.vm.forks.berlin.opcodes import ( BERLIN_OPCODES, ) from eth.vm.forks.byzantium.opcodes import ( ensure_no_static, ) +from eth.vm.logic import ( + block, +) +from eth.vm.opcode import ( + Opcode, + as_opcode, +) -from . import storage +from . import ( + storage, +) UPDATED_OPCODES: Dict[int, Opcode] = { opcode_values.BASEFEE: as_opcode( diff --git a/eth/vm/forks/london/receipts.py b/eth/vm/forks/london/receipts.py index 105ec9489a..2a7d8ab7b1 100644 --- a/eth/vm/forks/london/receipts.py +++ b/eth/vm/forks/london/receipts.py @@ -6,15 +6,17 @@ from eth.rlp.receipts import ( Receipt, ) +from eth.vm.forks.berlin.constants import ( + ACCESS_LIST_TRANSACTION_TYPE, +) from eth.vm.forks.berlin.receipts import ( BerlinReceiptBuilder, TypedReceipt as BerlinTypedReceipt, ) -from eth.vm.forks.berlin.constants import ( - ACCESS_LIST_TRANSACTION_TYPE, -) -from .constants import DYNAMIC_FEE_TRANSACTION_TYPE +from .constants import ( + DYNAMIC_FEE_TRANSACTION_TYPE, +) class LondonTypedReceipt(BerlinTypedReceipt): diff --git a/eth/vm/forks/london/state.py b/eth/vm/forks/london/state.py index 39ea04d7a0..91e833169e 100644 --- a/eth/vm/forks/london/state.py +++ b/eth/vm/forks/london/state.py @@ -1,12 +1,19 @@ -from typing import Type +from typing import ( + Type, +) -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_utils import ( encode_hex, ) +from eth._utils.address import ( + generate_contract_address, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, MessageAPI, SignedTransactionAPI, StateAPI, @@ -16,20 +23,23 @@ from eth.constants import ( CREATE_CONTRACT_ADDRESS, ) -from eth.vm.message import ( - Message, -) from eth.vm.forks.berlin.state import ( BerlinState, BerlinTransactionExecutor, ) -from eth._utils.address import ( - generate_contract_address, +from eth.vm.message import ( + Message, ) -from .computation import LondonMessageComputation -from .validation import validate_london_normalized_transaction -from .constants import EIP3529_MAX_REFUND_QUOTIENT +from .computation import ( + LondonComputation, +) +from .constants import ( + EIP3529_MAX_REFUND_QUOTIENT, +) +from .validation import ( + validate_london_normalized_transaction, +) class LondonTransactionExecutor(BerlinTransactionExecutor): @@ -86,7 +96,7 @@ def build_evm_message(self, transaction: SignedTransactionAPI) -> MessageAPI: @classmethod def calculate_gas_refund(cls, - computation: MessageComputationAPI, + computation: ComputationAPI, gas_used: int) -> int: # Self destruct refunds were added in Frontier # London removes them in EIP-3529 @@ -96,7 +106,7 @@ def calculate_gas_refund(cls, class LondonState(BerlinState): - message_computation_class = LondonMessageComputation + computation_class = LondonComputation transaction_executor_class: Type[TransactionExecutorAPI] = LondonTransactionExecutor def get_tip(self, transaction: SignedTransactionAPI) -> int: diff --git a/eth/vm/forks/london/storage.py b/eth/vm/forks/london/storage.py index a72f663a0c..96e84732b1 100644 --- a/eth/vm/forks/london/storage.py +++ b/eth/vm/forks/london/storage.py @@ -1,12 +1,15 @@ -from eth_utils.toolz import partial +from eth_utils.toolz import ( + partial, +) -from eth.vm.forks.berlin import constants as berlin_constants +from eth.vm.forks.berlin import ( + constants as berlin_constants, +) from eth.vm.forks.berlin.logic import ( GAS_SCHEDULE_EIP2929, sstore_eip2929_generic, ) - SSTORE_CLEARS_SCHEDULE_EIP_3529 = ( GAS_SCHEDULE_EIP2929.sstore_reset_gas + berlin_constants.ACCESS_LIST_STORAGE_KEY_COST_EIP_2930 diff --git a/eth/vm/forks/london/transactions.py b/eth/vm/forks/london/transactions.py index 74cf58d50b..8550748623 100644 --- a/eth/vm/forks/london/transactions.py +++ b/eth/vm/forks/london/transactions.py @@ -1,4 +1,3 @@ -from cached_property import cached_property from typing import ( Dict, Sequence, @@ -7,7 +6,12 @@ Union, ) -from eth_keys.datatypes import PrivateKey +from cached_property import ( + cached_property, +) +from eth_keys.datatypes import ( + PrivateKey, +) from eth_typing import ( Address, Hash32, @@ -33,11 +37,21 @@ SignedTransactionAPI, TransactionDecoderAPI, ) -from eth.constants import CREATE_CONTRACT_ADDRESS -from eth.rlp.logs import Log -from eth.rlp.receipts import Receipt -from eth.rlp.transactions import SignedTransactionMethods -from eth.rlp.sedes import address +from eth.constants import ( + CREATE_CONTRACT_ADDRESS, +) +from eth.rlp.logs import ( + Log, +) +from eth.rlp.receipts import ( + Receipt, +) +from eth.rlp.sedes import ( + address, +) +from eth.rlp.transactions import ( + SignedTransactionMethods, +) from eth.validation import ( validate_canonical_address, validate_is_bytes, @@ -61,8 +75,12 @@ ISTANBUL_TX_GAS_SCHEDULE, ) -from .constants import DYNAMIC_FEE_TRANSACTION_TYPE -from .receipts import LondonReceiptBuilder +from .constants import ( + DYNAMIC_FEE_TRANSACTION_TYPE, +) +from .receipts import ( + LondonReceiptBuilder, +) class LondonLegacyTransaction(BerlinLegacyTransaction): diff --git a/eth/vm/forks/london/validation.py b/eth/vm/forks/london/validation.py index 4b4c0e09d2..c41c45159d 100644 --- a/eth/vm/forks/london/validation.py +++ b/eth/vm/forks/london/validation.py @@ -1,8 +1,10 @@ -from eth_utils.exceptions import ValidationError +from eth_utils.exceptions import ( + ValidationError, +) from eth.abc import ( SignedTransactionAPI, - StateAPI + StateAPI, ) from eth.vm.forks.homestead.validation import ( validate_homestead_transaction, diff --git a/eth/vm/forks/muir_glacier/blocks.py b/eth/vm/forks/muir_glacier/blocks.py index c53915065a..4591c444c9 100644 --- a/eth/vm/forks/muir_glacier/blocks.py +++ b/eth/vm/forks/muir_glacier/blocks.py @@ -1,6 +1,7 @@ from rlp.sedes import ( CountableList, ) + from eth.rlp.headers import ( BlockHeader, ) diff --git a/eth/vm/forks/muir_glacier/computation.py b/eth/vm/forks/muir_glacier/computation.py index 50d0a863af..d5472c8b49 100644 --- a/eth/vm/forks/muir_glacier/computation.py +++ b/eth/vm/forks/muir_glacier/computation.py @@ -1,20 +1,20 @@ from eth.vm.forks.istanbul.computation import ( - ISTANBUL_PRECOMPILES -) -from eth.vm.forks.istanbul.computation import ( - IstanbulMessageComputation, + ISTANBUL_PRECOMPILES, + IstanbulComputation, ) -from .opcodes import MUIR_GLACIER_OPCODES +from .opcodes import ( + MUIR_GLACIER_OPCODES, +) MUIR_GLACIER_PRECOMPILES = ISTANBUL_PRECOMPILES -class MuirGlacierMessageComputation(IstanbulMessageComputation): +class MuirGlacierComputation(IstanbulComputation): """ A class for all execution *message* computations in the ``MuirGlacier`` fork. Inherits from - :class:`~eth.vm.forks.constantinople.istanbul.IstanbulMessageComputation` + :class:`~eth.vm.forks.constantinople.istanbul.IstanbulComputation` """ # Override opcodes = MUIR_GLACIER_OPCODES diff --git a/eth/vm/forks/muir_glacier/headers.py b/eth/vm/forks/muir_glacier/headers.py index 906342ea41..9eaf43a4df 100644 --- a/eth/vm/forks/muir_glacier/headers.py +++ b/eth/vm/forks/muir_glacier/headers.py @@ -1,11 +1,10 @@ -from eth.vm.forks.petersburg.headers import ( - compute_difficulty, -) from eth.vm.forks.istanbul.headers import ( configure_header, create_header_from_parent, ) - +from eth.vm.forks.petersburg.headers import ( + compute_difficulty, +) compute_muir_glacier_difficulty = compute_difficulty(9000000) diff --git a/eth/vm/forks/muir_glacier/opcodes.py b/eth/vm/forks/muir_glacier/opcodes.py index b0c1df773b..e1bcbec419 100644 --- a/eth/vm/forks/muir_glacier/opcodes.py +++ b/eth/vm/forks/muir_glacier/opcodes.py @@ -1,7 +1,7 @@ import copy + from eth.vm.forks.istanbul.opcodes import ( ISTANBUL_OPCODES, ) - MUIR_GLACIER_OPCODES = copy.deepcopy(ISTANBUL_OPCODES) diff --git a/eth/vm/forks/muir_glacier/state.py b/eth/vm/forks/muir_glacier/state.py index de97ee944a..c33e10dee2 100644 --- a/eth/vm/forks/muir_glacier/state.py +++ b/eth/vm/forks/muir_glacier/state.py @@ -1,9 +1,11 @@ from eth.vm.forks.istanbul.state import ( - IstanbulState + IstanbulState, ) -from .computation import MuirGlacierMessageComputation +from .computation import ( + MuirGlacierComputation, +) class MuirGlacierState(IstanbulState): - message_computation_class = MuirGlacierMessageComputation + computation_class = MuirGlacierComputation diff --git a/eth/vm/forks/muir_glacier/transactions.py b/eth/vm/forks/muir_glacier/transactions.py index ad3ed40c36..309f8e5a24 100644 --- a/eth/vm/forks/muir_glacier/transactions.py +++ b/eth/vm/forks/muir_glacier/transactions.py @@ -1,14 +1,17 @@ -from eth_keys.datatypes import PrivateKey -from eth_typing import Address - -from eth.vm.forks.istanbul.transactions import ( - IstanbulTransaction, - IstanbulUnsignedTransaction, +from eth_keys.datatypes import ( + PrivateKey, +) +from eth_typing import ( + Address, ) from eth._utils.transactions import ( create_transaction_signature, ) +from eth.vm.forks.istanbul.transactions import ( + IstanbulTransaction, + IstanbulUnsignedTransaction, +) class MuirGlacierTransaction(IstanbulTransaction): diff --git a/eth/vm/forks/paris/blocks.py b/eth/vm/forks/paris/blocks.py index 023ba5025b..f8ed63830c 100644 --- a/eth/vm/forks/paris/blocks.py +++ b/eth/vm/forks/paris/blocks.py @@ -1,27 +1,32 @@ -from abc import ABC -from typing import Type - -from eth.abc import TransactionBuilderAPI +from abc import ( + ABC, +) +from typing import ( + Type, +) from eth_utils import ( encode_hex, ) - from rlp.sedes import ( CountableList, ) -from .transactions import ( - ParisTransactionBuilder, +from eth.abc import ( + TransactionBuilderAPI, ) from eth.vm.forks.gray_glacier.blocks import ( GrayGlacierBlock, GrayGlacierBlockHeader, GrayGlacierMiningHeader, ) + from ..london.blocks import ( LondonBackwardsHeader, ) +from .transactions import ( + ParisTransactionBuilder, +) class ParisMiningHeader(GrayGlacierMiningHeader, ABC): diff --git a/eth/vm/forks/paris/computation.py b/eth/vm/forks/paris/computation.py index e308f5416c..b8cd2736a8 100644 --- a/eth/vm/forks/paris/computation.py +++ b/eth/vm/forks/paris/computation.py @@ -1,10 +1,15 @@ -from .opcodes import PARIS_OPCODES -from eth.vm.forks.gray_glacier.computation import GrayGlacierMessageComputation +from eth.vm.forks.gray_glacier.computation import ( + GrayGlacierComputation, +) +from .opcodes import ( + PARIS_OPCODES, +) -class ParisMessageComputation(GrayGlacierMessageComputation): + +class ParisComputation(GrayGlacierComputation): """ A class for all execution *message* computations in the ``Paris`` hard fork - Inherits from :class:`~eth.vm.forks.gray_glacier.GrayGlacierMessageComputation` + Inherits from :class:`~eth.vm.forks.gray_glacier.GrayGlacierComputation` """ opcodes = PARIS_OPCODES diff --git a/eth/vm/forks/paris/headers.py b/eth/vm/forks/paris/headers.py index c9c8054f5c..b2cf7f4782 100644 --- a/eth/vm/forks/paris/headers.py +++ b/eth/vm/forks/paris/headers.py @@ -1,22 +1,34 @@ -from typing import Any, Optional +from typing import ( + Any, + Optional, +) -from toolz import curry +from eth_utils import ( + ValidationError, +) +from toolz import ( + curry, +) -from eth.abc import BlockHeaderAPI +from eth.abc import ( + BlockHeaderAPI, +) from eth.constants import ( POST_MERGE_DIFFICULTY, POST_MERGE_MIX_HASH, POST_MERGE_NONCE, ) +from eth.vm.forks.byzantium.headers import ( + configure_header, +) from eth.vm.forks.gray_glacier.headers import ( compute_gray_glacier_difficulty, create_gray_glacier_header_from_parent, ) -from eth.vm.forks.byzantium.headers import ( - configure_header, + +from .blocks import ( + ParisBlockHeader, ) -from eth_utils import ValidationError -from .blocks import ParisBlockHeader def _validate_and_return_paris_header_param( diff --git a/eth/vm/forks/paris/opcodes.py b/eth/vm/forks/paris/opcodes.py index a382909544..9a7595f008 100644 --- a/eth/vm/forks/paris/opcodes.py +++ b/eth/vm/forks/paris/opcodes.py @@ -1,19 +1,31 @@ import copy -from typing import Dict +from typing import ( + Dict, +) -from eth.vm.opcode import as_opcode -from eth_utils.toolz import merge +from eth_utils.toolz import ( + merge, +) -from eth import constants -from eth.abc import OpcodeAPI -from eth.vm import mnemonics -from eth.vm import opcode_values +from eth import ( + constants, +) +from eth.abc import ( + OpcodeAPI, +) +from eth.vm import ( + mnemonics, + opcode_values, +) +from eth.vm.forks.london.opcodes import ( + LONDON_OPCODES, +) from eth.vm.logic import ( block, ) - -from eth.vm.forks.london.opcodes import LONDON_OPCODES - +from eth.vm.opcode import ( + as_opcode, +) NEW_OPCODES = { # EIP-4399: supplant DIFFICULTY with PREVRANDAO diff --git a/eth/vm/forks/paris/state.py b/eth/vm/forks/paris/state.py index 321480ce26..08a2f6ff43 100644 --- a/eth/vm/forks/paris/state.py +++ b/eth/vm/forks/paris/state.py @@ -1,13 +1,25 @@ -from typing import Type +from typing import ( + Type, +) + +from eth_typing import ( + Hash32, +) from eth.abc import ( StateAPI, TransactionExecutorAPI, ) -from eth_typing import Hash32 -from .computation import ParisMessageComputation -from ..gray_glacier import GrayGlacierState -from ..gray_glacier.state import GrayGlacierTransactionExecutor + +from ..gray_glacier import ( + GrayGlacierState, +) +from ..gray_glacier.state import ( + GrayGlacierTransactionExecutor, +) +from .computation import ( + ParisComputation, +) class ParisTransactionExecutor(GrayGlacierTransactionExecutor): @@ -15,7 +27,7 @@ class ParisTransactionExecutor(GrayGlacierTransactionExecutor): class ParisState(GrayGlacierState): - message_computation_class = ParisMessageComputation + computation_class = ParisComputation transaction_executor_class: Type[TransactionExecutorAPI] = ParisTransactionExecutor @property diff --git a/eth/vm/forks/paris/transactions.py b/eth/vm/forks/paris/transactions.py index ace279910a..1f44b00ab5 100644 --- a/eth/vm/forks/paris/transactions.py +++ b/eth/vm/forks/paris/transactions.py @@ -1,6 +1,10 @@ -from abc import ABC +from abc import ( + ABC, +) -from eth_keys.datatypes import PrivateKey +from eth_keys.datatypes import ( + PrivateKey, +) from eth._utils.transactions import ( create_transaction_signature, diff --git a/eth/vm/forks/petersburg/blocks.py b/eth/vm/forks/petersburg/blocks.py index 4c244af159..da27af7bd6 100644 --- a/eth/vm/forks/petersburg/blocks.py +++ b/eth/vm/forks/petersburg/blocks.py @@ -1,6 +1,7 @@ from rlp.sedes import ( CountableList, ) + from eth.rlp.headers import ( BlockHeader, ) diff --git a/eth/vm/forks/petersburg/computation.py b/eth/vm/forks/petersburg/computation.py index 6d08ce25c4..44096b83a9 100644 --- a/eth/vm/forks/petersburg/computation.py +++ b/eth/vm/forks/petersburg/computation.py @@ -1,20 +1,20 @@ from eth.vm.forks.byzantium.computation import ( - BYZANTIUM_PRECOMPILES -) -from eth.vm.forks.byzantium.computation import ( - ByzantiumMessageComputation + BYZANTIUM_PRECOMPILES, + ByzantiumComputation, ) -from .opcodes import PETERSBURG_OPCODES +from .opcodes import ( + PETERSBURG_OPCODES, +) PETERSBURG_PRECOMPILES = BYZANTIUM_PRECOMPILES -class PetersburgMessageComputation(ByzantiumMessageComputation): +class PetersburgComputation(ByzantiumComputation): """ A class for all execution *message* computations in the ``Petersburg`` fork. Inherits from - :class:`~eth.vm.forks.byzantium.computation.ByzantiumMessageComputation` + :class:`~eth.vm.forks.byzantium.computation.ByzantiumComputation` """ # Override opcodes = PETERSBURG_OPCODES diff --git a/eth/vm/forks/petersburg/constants.py b/eth/vm/forks/petersburg/constants.py index 0ba9138d13..bdfe5e9a19 100644 --- a/eth/vm/forks/petersburg/constants.py +++ b/eth/vm/forks/petersburg/constants.py @@ -1,5 +1,6 @@ -from eth_utils import denoms - +from eth_utils import ( + denoms, +) GAS_EXTCODEHASH_EIP1052 = 400 diff --git a/eth/vm/forks/petersburg/headers.py b/eth/vm/forks/petersburg/headers.py index d641b2bd0f..93df416568 100644 --- a/eth/vm/forks/petersburg/headers.py +++ b/eth/vm/forks/petersburg/headers.py @@ -1,10 +1,9 @@ from eth.vm.forks.byzantium.headers import ( + compute_difficulty, configure_header, create_header_from_parent, - compute_difficulty, ) - compute_petersburg_difficulty = compute_difficulty(5000000) create_petersburg_header_from_parent = create_header_from_parent( diff --git a/eth/vm/forks/petersburg/opcodes.py b/eth/vm/forks/petersburg/opcodes.py index dc26b9a62a..a5281ad0d4 100644 --- a/eth/vm/forks/petersburg/opcodes.py +++ b/eth/vm/forks/petersburg/opcodes.py @@ -1,14 +1,18 @@ import copy -from typing import Dict +from typing import ( + Dict, +) from eth_utils.toolz import ( - merge + merge, ) from eth import ( - constants + constants, +) +from eth.abc import ( + OpcodeAPI, ) -from eth.abc import OpcodeAPI from eth.vm import ( mnemonics, opcode_values, @@ -17,7 +21,7 @@ BYZANTIUM_OPCODES, ) from eth.vm.forks.petersburg.constants import ( - GAS_EXTCODEHASH_EIP1052 + GAS_EXTCODEHASH_EIP1052, ) from eth.vm.logic import ( arithmetic, @@ -25,10 +29,9 @@ system, ) from eth.vm.opcode import ( - as_opcode + as_opcode, ) - UPDATED_OPCODES = { opcode_values.SHL: as_opcode( logic_fn=arithmetic.shl, diff --git a/eth/vm/forks/petersburg/state.py b/eth/vm/forks/petersburg/state.py index 60b23d12fb..3114e2e7f9 100644 --- a/eth/vm/forks/petersburg/state.py +++ b/eth/vm/forks/petersburg/state.py @@ -1,9 +1,11 @@ from eth.vm.forks.byzantium.state import ( - ByzantiumState + ByzantiumState, ) -from .computation import PetersburgMessageComputation +from .computation import ( + PetersburgComputation, +) class PetersburgState(ByzantiumState): - message_computation_class = PetersburgMessageComputation + computation_class = PetersburgComputation diff --git a/eth/vm/forks/petersburg/transactions.py b/eth/vm/forks/petersburg/transactions.py index ba299bb764..bf723d6f1f 100644 --- a/eth/vm/forks/petersburg/transactions.py +++ b/eth/vm/forks/petersburg/transactions.py @@ -1,14 +1,17 @@ -from eth_keys.datatypes import PrivateKey -from eth_typing import Address - -from eth.vm.forks.byzantium.transactions import ( - ByzantiumTransaction, - ByzantiumUnsignedTransaction, +from eth_keys.datatypes import ( + PrivateKey, +) +from eth_typing import ( + Address, ) from eth._utils.transactions import ( create_transaction_signature, ) +from eth.vm.forks.byzantium.transactions import ( + ByzantiumTransaction, + ByzantiumUnsignedTransaction, +) class PetersburgTransaction(ByzantiumTransaction): diff --git a/eth/vm/forks/shanghai/blocks.py b/eth/vm/forks/shanghai/blocks.py index 30df5e4ebe..0cf0ad6e60 100644 --- a/eth/vm/forks/shanghai/blocks.py +++ b/eth/vm/forks/shanghai/blocks.py @@ -1,47 +1,89 @@ -from abc import ABC -from typing import List, Sequence, Tuple, Type, cast +from abc import ( + ABC, +) +from typing import ( + List, + Sequence, + Tuple, + Type, + cast, +) +from eth_bloom import ( + BloomFilter, +) +from eth_typing import ( + Address, + BlockNumber, + Hash32, +) +from eth_utils import ( + encode_hex, + keccak, +) import rlp -from eth.exceptions import BlockNotFound, HeaderNotFound -from eth.rlp.blocks import BaseBlock -from eth.rlp.headers import BlockHeader -from eth.rlp.sedes import address, hash32, trie_root, uint256 -from eth_bloom import BloomFilter -from eth_typing import Address, BlockNumber, Hash32 - -from eth._utils.headers import new_timestamp_from_parent +from rlp.sedes import ( + Binary, + CountableList, + big_endian_int, + binary, +) +from trie.exceptions import ( + MissingTrieNode, +) + +from eth._utils.headers import ( + new_timestamp_from_parent, +) from eth.abc import ( - BlockHeaderAPI, BlockHeaderSedesAPI, ChainDatabaseAPI, MiningHeaderAPI, - ReceiptAPI, ReceiptBuilderAPI, SignedTransactionAPI, TransactionBuilderAPI, + BlockHeaderAPI, + BlockHeaderSedesAPI, + ChainDatabaseAPI, + MiningHeaderAPI, + ReceiptAPI, + ReceiptBuilderAPI, + SignedTransactionAPI, + TransactionBuilderAPI, WithdrawalAPI, ) from eth.constants import ( - ZERO_ADDRESS, - ZERO_HASH32, + BLANK_ROOT_HASH, EMPTY_UNCLE_HASH, GENESIS_NONCE, GENESIS_PARENT_HASH, - BLANK_ROOT_HASH, + ZERO_ADDRESS, + ZERO_HASH32, ) - -from eth_utils import ( - encode_hex, keccak, +from eth.exceptions import ( + BlockNotFound, + HeaderNotFound, ) - -from rlp.sedes import ( - Binary, CountableList, big_endian_int, binary, +from eth.rlp.blocks import ( + BaseBlock, +) +from eth.rlp.headers import ( + BlockHeader, +) +from eth.rlp.sedes import ( + address, + hash32, + trie_root, + uint256, ) -from trie.exceptions import MissingTrieNode +from ..london.blocks import ( + LondonBlockHeader, +) +from ..london.receipts import ( + LondonReceiptBuilder, +) from .transactions import ( ShanghaiTransactionBuilder, ) -from .withdrawals import Withdrawal -from ..london.blocks import ( - LondonBlockHeader, +from .withdrawals import ( + Withdrawal, ) - UNMINED_SHANGHAI_HEADER_FIELDS = [ ('parent_hash', hash32), ('uncles_hash', hash32), @@ -182,6 +224,8 @@ class ShanghaiBlock(BaseBlock): # re-defined from `BaseBlock`, as `FrontierBlock` was, to include withdrawals transaction_builder: Type[TransactionBuilderAPI] = ShanghaiTransactionBuilder + # London was the last fork where the receipt builder was updated + receipt_builder: Type[ReceiptBuilderAPI] = LondonReceiptBuilder fields = [ ('header', ShanghaiBlockHeader), ('transactions', CountableList(transaction_builder)), diff --git a/eth/vm/forks/shanghai/computation.py b/eth/vm/forks/shanghai/computation.py index afd00e9183..3458ea5580 100644 --- a/eth/vm/forks/shanghai/computation.py +++ b/eth/vm/forks/shanghai/computation.py @@ -1,22 +1,29 @@ -from eth._utils.numeric import ceil32 +from eth._utils.numeric import ( + ceil32, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, MessageAPI, StateAPI, TransactionContextAPI, ) +from eth.exceptions import ( + OutOfGas, +) +from eth.vm.forks.paris.computation import ( + ParisComputation, +) + from .constants import ( INITCODE_WORD_COST, MAX_INITCODE_SIZE, ) -from .opcodes import SHANGHAI_OPCODES -from eth.exceptions import ( - OutOfGas, +from .opcodes import ( + SHANGHAI_OPCODES, ) -from eth.vm.forks.paris.computation import ParisMessageComputation -class ShanghaiMessageComputation(ParisMessageComputation): +class ShanghaiComputation(ParisComputation): """ A class for all execution *message* computations in the ``Shanghai`` hard fork """ @@ -45,7 +52,7 @@ def validate_create_message(cls, message: MessageAPI) -> None: ) @classmethod - def consume_initcode_gas_cost(cls, computation: MessageComputationAPI) -> None: + def consume_initcode_gas_cost(cls, computation: ComputationAPI) -> None: # EIP-3860: initcode gas cost initcode_length = len(computation.msg.code) diff --git a/eth/vm/forks/shanghai/constants.py b/eth/vm/forks/shanghai/constants.py index 41bb499491..916f807540 100644 --- a/eth/vm/forks/shanghai/constants.py +++ b/eth/vm/forks/shanghai/constants.py @@ -1,4 +1,6 @@ -from eth.vm.forks.spurious_dragon.constants import EIP170_CODE_SIZE_LIMIT +from eth.vm.forks.spurious_dragon.constants import ( + EIP170_CODE_SIZE_LIMIT, +) # https://eips.ethereum.org/EIPS/eip-3860 INITCODE_WORD_COST = 2 diff --git a/eth/vm/forks/shanghai/headers.py b/eth/vm/forks/shanghai/headers.py index d4234143c4..6c03fc76d1 100644 --- a/eth/vm/forks/shanghai/headers.py +++ b/eth/vm/forks/shanghai/headers.py @@ -1,15 +1,25 @@ -from typing import Any, Optional +from typing import ( + Any, + Optional, +) -from toolz import curry +from toolz import ( + curry, +) -from eth.abc import BlockHeaderAPI -from eth.vm.forks.paris.headers import ( - create_paris_header_from_parent, +from eth.abc import ( + BlockHeaderAPI, ) from eth.vm.forks.byzantium.headers import ( configure_header, ) -from .blocks import ShanghaiBlockHeader +from eth.vm.forks.paris.headers import ( + create_paris_header_from_parent, +) + +from .blocks import ( + ShanghaiBlockHeader, +) @curry diff --git a/eth/vm/forks/shanghai/logic.py b/eth/vm/forks/shanghai/logic.py index 8dcab5edea..a627baa637 100644 --- a/eth/vm/forks/shanghai/logic.py +++ b/eth/vm/forks/shanghai/logic.py @@ -1,17 +1,18 @@ -from .constants import ( - INITCODE_WORD_COST, -) from eth._utils.numeric import ( ceil32, ) from eth.vm.forks.berlin.logic import ( - CreateEIP2929, Create2EIP2929, + CreateEIP2929, ) from eth.vm.logic.system import ( CreateOpcodeStackData, ) +from .constants import ( + INITCODE_WORD_COST, +) + class CreateEIP3860(CreateEIP2929): def get_gas_cost(self, data: CreateOpcodeStackData) -> int: diff --git a/eth/vm/forks/shanghai/opcodes.py b/eth/vm/forks/shanghai/opcodes.py index e6209c0912..bc757f7abf 100644 --- a/eth/vm/forks/shanghai/opcodes.py +++ b/eth/vm/forks/shanghai/opcodes.py @@ -1,24 +1,39 @@ import copy -from typing import Dict +from typing import ( + Dict, +) -from .logic import ( - CreateEIP3860, - Create2EIP3860, +from eth_utils.toolz import ( + merge, ) -from eth.tools._utils.deprecation import deprecate_method -from eth.vm.opcode import as_opcode -from eth_utils.toolz import merge -from eth import constants -from eth.abc import OpcodeAPI -from eth.vm import mnemonics -from eth.vm import opcode_values +from eth import ( + constants, +) +from eth.abc import ( + OpcodeAPI, +) +from eth.tools._utils.deprecation import ( + deprecate_method, +) +from eth.vm import ( + mnemonics, + opcode_values, +) +from eth.vm.forks.paris.opcodes import ( + PARIS_OPCODES, +) from eth.vm.logic import ( stack, ) +from eth.vm.opcode import ( + as_opcode, +) -from eth.vm.forks.paris.opcodes import PARIS_OPCODES - +from .logic import ( + Create2EIP3860, + CreateEIP3860, +) UPDATED_OPCODES: Dict[int, OpcodeAPI] = { opcode_values.CREATE: CreateEIP3860.configure( diff --git a/eth/vm/forks/shanghai/state.py b/eth/vm/forks/shanghai/state.py index 5dbd97eda2..7f59abb82b 100644 --- a/eth/vm/forks/shanghai/state.py +++ b/eth/vm/forks/shanghai/state.py @@ -1,12 +1,21 @@ -from typing import Type +from typing import ( + Type, +) from eth.abc import ( TransactionExecutorAPI, WithdrawalAPI, ) -from .computation import ShanghaiMessageComputation -from ..paris import ParisState -from ..paris.state import ParisTransactionExecutor + +from ..paris import ( + ParisState, +) +from ..paris.state import ( + ParisTransactionExecutor, +) +from .computation import ( + ShanghaiComputation, +) class ShanghaiTransactionExecutor(ParisTransactionExecutor): @@ -14,7 +23,7 @@ class ShanghaiTransactionExecutor(ParisTransactionExecutor): class ShanghaiState(ParisState): - message_computation_class = ShanghaiMessageComputation + computation_class = ShanghaiComputation transaction_executor_class: Type[TransactionExecutorAPI] = ShanghaiTransactionExecutor # noqa: E501 def apply_withdrawal(self, withdrawal: WithdrawalAPI) -> None: diff --git a/eth/vm/forks/shanghai/transactions.py b/eth/vm/forks/shanghai/transactions.py index 79e48ff9b3..bc320aeae7 100644 --- a/eth/vm/forks/shanghai/transactions.py +++ b/eth/vm/forks/shanghai/transactions.py @@ -1,6 +1,10 @@ -from abc import ABC +from abc import ( + ABC, +) -from eth_keys.datatypes import PrivateKey +from eth_keys.datatypes import ( + PrivateKey, +) from eth._utils.transactions import ( create_transaction_signature, diff --git a/eth/vm/forks/shanghai/withdrawals.py b/eth/vm/forks/shanghai/withdrawals.py index 4161af8b8b..b0dedac734 100644 --- a/eth/vm/forks/shanghai/withdrawals.py +++ b/eth/vm/forks/shanghai/withdrawals.py @@ -1,20 +1,32 @@ -from cached_property import cached_property -from typing import cast +from typing import ( + cast, +) -from eth.abc import WithdrawalAPI -from eth.validation import ( - validate_canonical_address, - validate_uint64, +from cached_property import ( + cached_property, ) from eth_typing import ( Address, Hash32, ) - +from eth_utils import ( + keccak, +) import rlp -from eth.rlp.sedes import address -from eth_utils import keccak -from rlp.sedes import big_endian_int +from rlp.sedes import ( + big_endian_int, +) + +from eth.abc import ( + WithdrawalAPI, +) +from eth.rlp.sedes import ( + address, +) +from eth.validation import ( + validate_canonical_address, + validate_uint64, +) class Withdrawal(rlp.Serializable): diff --git a/eth/vm/forks/spurious_dragon/_utils.py b/eth/vm/forks/spurious_dragon/_utils.py index a55bce7f66..66e6f69ec1 100644 --- a/eth/vm/forks/spurious_dragon/_utils.py +++ b/eth/vm/forks/spurious_dragon/_utils.py @@ -1,24 +1,30 @@ -from typing import Iterable - -from eth_typing import Address - -from eth_utils import to_set +from typing import ( + Iterable, +) -from eth import constants +from eth_typing import ( + Address, +) +from eth_utils import ( + to_set, +) +from eth import ( + constants, +) from eth._utils.address import ( force_bytes_to_address, ) - -from eth.vm.computation import MessageComputation - +from eth.abc import ( + ComputationAPI, +) THREE = force_bytes_to_address(b'\x03') @to_set def collect_touched_accounts( - computation: MessageComputation, + computation: ComputationAPI, ancestor_had_error: bool = False ) -> Iterable[Address]: """ diff --git a/eth/vm/forks/spurious_dragon/blocks.py b/eth/vm/forks/spurious_dragon/blocks.py index fe9371d1e5..d11d95bc94 100644 --- a/eth/vm/forks/spurious_dragon/blocks.py +++ b/eth/vm/forks/spurious_dragon/blocks.py @@ -1,12 +1,14 @@ from rlp.sedes import ( CountableList, ) + from eth.rlp.headers import ( BlockHeader, ) from eth.vm.forks.homestead.blocks import ( HomesteadBlock, ) + from .transactions import ( SpuriousDragonTransaction, ) diff --git a/eth/vm/forks/spurious_dragon/computation.py b/eth/vm/forks/spurious_dragon/computation.py index a9848a611a..5fdd0addd6 100644 --- a/eth/vm/forks/spurious_dragon/computation.py +++ b/eth/vm/forks/spurious_dragon/computation.py @@ -1,12 +1,15 @@ -from eth_hash.auto import keccak - +from eth_hash.auto import ( + keccak, +) from eth_utils import ( encode_hex, ) -from eth import constants +from eth import ( + constants, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, MessageAPI, StateAPI, TransactionContextAPI, @@ -16,18 +19,22 @@ VMError, ) from eth.vm.forks.homestead.computation import ( - HomesteadMessageComputation, + HomesteadComputation, ) -from ..spurious_dragon.constants import EIP170_CODE_SIZE_LIMIT -from .opcodes import SPURIOUS_DRAGON_OPCODES +from ..spurious_dragon.constants import ( + EIP170_CODE_SIZE_LIMIT, +) +from .opcodes import ( + SPURIOUS_DRAGON_OPCODES, +) -class SpuriousDragonMessageComputation(HomesteadMessageComputation): +class SpuriousDragonComputation(HomesteadComputation): """ A class for all execution *message* computations in the ``SpuriousDragon`` fork. Inherits from - :class:`~eth.vm.forks.homestead.computation.HomesteadMessageComputation` + :class:`~eth.vm.forks.homestead.computation.HomesteadComputation` """ # Override opcodes = SPURIOUS_DRAGON_OPCODES @@ -37,7 +44,7 @@ def apply_create_message( cls, state: StateAPI, message: MessageAPI, - transaction_context: TransactionContextAPI) -> MessageComputationAPI: + transaction_context: TransactionContextAPI) -> ComputationAPI: snapshot = state.snapshot() diff --git a/eth/vm/forks/spurious_dragon/opcodes.py b/eth/vm/forks/spurious_dragon/opcodes.py index eed5820eda..0ce713a539 100644 --- a/eth/vm/forks/spurious_dragon/opcodes.py +++ b/eth/vm/forks/spurious_dragon/opcodes.py @@ -1,29 +1,40 @@ import copy -from typing import Dict +from typing import ( + Dict, +) -from eth_utils.toolz import merge +from eth_utils.toolz import ( + merge, +) -from eth.abc import OpcodeAPI +from eth.abc import ( + OpcodeAPI, +) +from eth.vm import ( + mnemonics, + opcode_values, +) from eth.vm.forks.tangerine_whistle.constants import ( + GAS_CALL_EIP150, GAS_SELFDESTRUCT_EIP150, - GAS_CALL_EIP150 ) -from eth.vm import mnemonics -from eth.vm import opcode_values -from eth.vm.forks.tangerine_whistle.opcodes import TANGERINE_WHISTLE_OPCODES +from eth.vm.forks.tangerine_whistle.opcodes import ( + TANGERINE_WHISTLE_OPCODES, +) from eth.vm.logic import ( arithmetic, - system, call, + system, +) +from eth.vm.opcode import ( + as_opcode, ) -from eth.vm.opcode import as_opcode from .constants import ( GAS_EXP_EIP160, - GAS_EXPBYTE_EIP160 + GAS_EXPBYTE_EIP160, ) - UPDATED_OPCODES = { opcode_values.EXP: as_opcode( logic_fn=arithmetic.exp(gas_per_byte=GAS_EXPBYTE_EIP160), diff --git a/eth/vm/forks/spurious_dragon/state.py b/eth/vm/forks/spurious_dragon/state.py index 67e0e98096..ae02650920 100644 --- a/eth/vm/forks/spurious_dragon/state.py +++ b/eth/vm/forks/spurious_dragon/state.py @@ -1,11 +1,13 @@ -from typing import Type +from typing import ( + Type, +) from eth_utils import ( encode_hex, ) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, SignedTransactionAPI, TransactionExecutorAPI, ) @@ -14,14 +16,18 @@ HomesteadTransactionExecutor, ) -from .computation import SpuriousDragonMessageComputation -from ._utils import collect_touched_accounts +from ._utils import ( + collect_touched_accounts, +) +from .computation import ( + SpuriousDragonComputation, +) class SpuriousDragonTransactionExecutor(HomesteadTransactionExecutor): def finalize_computation(self, transaction: SignedTransactionAPI, - computation: MessageComputationAPI) -> MessageComputationAPI: + computation: ComputationAPI) -> ComputationAPI: computation = super().finalize_computation(transaction, computation) # @@ -45,5 +51,5 @@ def finalize_computation(self, class SpuriousDragonState(HomesteadState): - message_computation_class: Type[MessageComputationAPI] = SpuriousDragonMessageComputation + computation_class: Type[ComputationAPI] = SpuriousDragonComputation transaction_executor_class: Type[TransactionExecutorAPI] = SpuriousDragonTransactionExecutor diff --git a/eth/vm/forks/spurious_dragon/transactions.py b/eth/vm/forks/spurious_dragon/transactions.py index 394bcdf916..55761e6b70 100644 --- a/eth/vm/forks/spurious_dragon/transactions.py +++ b/eth/vm/forks/spurious_dragon/transactions.py @@ -1,28 +1,30 @@ -from typing import Optional - -from eth_keys.datatypes import PrivateKey +from typing import ( + Optional, +) +from eth_keys.datatypes import ( + PrivateKey, +) from eth_typing import ( Address, ) - from eth_utils import ( int_to_big_endian, ) - import rlp -from eth.vm.forks.homestead.transactions import ( - HomesteadTransaction, - HomesteadUnsignedTransaction, +from eth._utils.numeric import ( + is_even, ) - -from eth._utils.numeric import is_even from eth._utils.transactions import ( create_transaction_signature, extract_chain_id, is_eip_155_signed_transaction, ) +from eth.vm.forks.homestead.transactions import ( + HomesteadTransaction, + HomesteadUnsignedTransaction, +) class SpuriousDragonTransaction(HomesteadTransaction): diff --git a/eth/vm/forks/tangerine_whistle/computation.py b/eth/vm/forks/tangerine_whistle/computation.py index cec0fd2c42..49cac680f4 100644 --- a/eth/vm/forks/tangerine_whistle/computation.py +++ b/eth/vm/forks/tangerine_whistle/computation.py @@ -1,13 +1,16 @@ -from ..homestead.computation import HomesteadMessageComputation +from ..homestead.computation import ( + HomesteadComputation, +) +from .opcodes import ( + TANGERINE_WHISTLE_OPCODES, +) -from .opcodes import TANGERINE_WHISTLE_OPCODES - -class TangerineWhistleMessageComputation(HomesteadMessageComputation): +class TangerineWhistleComputation(HomesteadComputation): """ A class for all execution *message* computations in the ``TangerineWhistle`` fork. Inherits from - :class:`~eth.vm.forks.homestead.computation.HomesteadMessageComputation` + :class:`~eth.vm.forks.homestead.computation.HomesteadComputation` """ # Override opcodes = TANGERINE_WHISTLE_OPCODES diff --git a/eth/vm/forks/tangerine_whistle/opcodes.py b/eth/vm/forks/tangerine_whistle/opcodes.py index c4f158f9ff..64d8da9645 100644 --- a/eth/vm/forks/tangerine_whistle/opcodes.py +++ b/eth/vm/forks/tangerine_whistle/opcodes.py @@ -1,20 +1,31 @@ import copy -from eth_utils.toolz import merge +from eth_utils.toolz import ( + merge, +) -from eth.vm.forks.tangerine_whistle import constants -from eth.constants import GAS_CREATE -from eth.vm import opcode_values -from eth.vm import mnemonics -from eth.vm.forks.homestead.opcodes import HOMESTEAD_OPCODES +from eth.constants import ( + GAS_CREATE, +) +from eth.vm import ( + mnemonics, + opcode_values, +) +from eth.vm.forks.homestead.opcodes import ( + HOMESTEAD_OPCODES, +) +from eth.vm.forks.tangerine_whistle import ( + constants, +) from eth.vm.logic import ( call, context, storage, system, ) -from eth.vm.opcode import as_opcode - +from eth.vm.opcode import ( + as_opcode, +) UPDATED_OPCODES = { opcode_values.EXTCODESIZE: as_opcode( diff --git a/eth/vm/forks/tangerine_whistle/state.py b/eth/vm/forks/tangerine_whistle/state.py index ca61cab5c7..101ff5e62c 100644 --- a/eth/vm/forks/tangerine_whistle/state.py +++ b/eth/vm/forks/tangerine_whistle/state.py @@ -1,7 +1,11 @@ -from eth.vm.forks.homestead.state import HomesteadState +from eth.vm.forks.homestead.state import ( + HomesteadState, +) -from .computation import TangerineWhistleMessageComputation +from .computation import ( + TangerineWhistleComputation, +) class TangerineWhistleState(HomesteadState): - message_computation_class = TangerineWhistleMessageComputation + computation_class = TangerineWhistleComputation diff --git a/eth/vm/gas_meter.py b/eth/vm/gas_meter.py index ea9a30f218..0d6e6780e4 100644 --- a/eth/vm/gas_meter.py +++ b/eth/vm/gas_meter.py @@ -1,12 +1,15 @@ from typing import ( Callable, ) + from eth_utils import ( ValidationError, get_extended_debug_logger, ) -from eth.abc import GasMeterAPI +from eth.abc import ( + GasMeterAPI, +) from eth.exceptions import ( OutOfGas, ) diff --git a/eth/vm/header.py b/eth/vm/header.py index 09222db60d..1f0071e1e8 100644 --- a/eth/vm/header.py +++ b/eth/vm/header.py @@ -1,4 +1,6 @@ -from eth.vm.forks.shanghai.blocks import ShanghaiBackwardsHeader +from eth.vm.forks.shanghai.blocks import ( + ShanghaiBackwardsHeader, +) HeaderSedes = ShanghaiBackwardsHeader """ diff --git a/eth/vm/logic/arithmetic.py b/eth/vm/logic/arithmetic.py index 8be2c52380..ae6282dbb8 100644 --- a/eth/vm/logic/arithmetic.py +++ b/eth/vm/logic/arithmetic.py @@ -2,18 +2,20 @@ curry, ) -from eth import constants - +from eth import ( + constants, +) from eth._utils.numeric import ( - unsigned_to_signed, - signed_to_unsigned, ceil8, + signed_to_unsigned, + unsigned_to_signed, +) +from eth.abc import ( + ComputationAPI, ) - -from eth.vm.computation import MessageComputation -def add(computation: MessageComputation) -> None: +def add(computation: ComputationAPI) -> None: """ Addition """ @@ -24,7 +26,7 @@ def add(computation: MessageComputation) -> None: computation.stack_push_int(result) -def addmod(computation: MessageComputation) -> None: +def addmod(computation: ComputationAPI) -> None: """ Modulo Addition """ @@ -38,7 +40,7 @@ def addmod(computation: MessageComputation) -> None: computation.stack_push_int(result) -def sub(computation: MessageComputation) -> None: +def sub(computation: ComputationAPI) -> None: """ Subtraction """ @@ -49,7 +51,7 @@ def sub(computation: MessageComputation) -> None: computation.stack_push_int(result) -def mod(computation: MessageComputation) -> None: +def mod(computation: ComputationAPI) -> None: """ Modulo """ @@ -63,7 +65,7 @@ def mod(computation: MessageComputation) -> None: computation.stack_push_int(result) -def smod(computation: MessageComputation) -> None: +def smod(computation: ComputationAPI) -> None: """ Signed Modulo """ @@ -82,7 +84,7 @@ def smod(computation: MessageComputation) -> None: computation.stack_push_int(signed_to_unsigned(result)) -def mul(computation: MessageComputation) -> None: +def mul(computation: ComputationAPI) -> None: """ Multiplication """ @@ -93,7 +95,7 @@ def mul(computation: MessageComputation) -> None: computation.stack_push_int(result) -def mulmod(computation: MessageComputation) -> None: +def mulmod(computation: ComputationAPI) -> None: """ Modulo Multiplication """ @@ -106,7 +108,7 @@ def mulmod(computation: MessageComputation) -> None: computation.stack_push_int(result) -def div(computation: MessageComputation) -> None: +def div(computation: ComputationAPI) -> None: """ Division """ @@ -120,7 +122,7 @@ def div(computation: MessageComputation) -> None: computation.stack_push_int(result) -def sdiv(computation: MessageComputation) -> None: +def sdiv(computation: ComputationAPI) -> None: """ Signed Division """ @@ -140,7 +142,7 @@ def sdiv(computation: MessageComputation) -> None: @curry -def exp(computation: MessageComputation, gas_per_byte: int) -> None: +def exp(computation: ComputationAPI, gas_per_byte: int) -> None: """ Exponentiation """ @@ -164,7 +166,7 @@ def exp(computation: MessageComputation, gas_per_byte: int) -> None: computation.stack_push_int(result) -def signextend(computation: MessageComputation) -> None: +def signextend(computation: ComputationAPI) -> None: """ Signed Extend """ @@ -183,7 +185,7 @@ def signextend(computation: MessageComputation) -> None: computation.stack_push_int(result) -def shl(computation: MessageComputation) -> None: +def shl(computation: ComputationAPI) -> None: """ Bitwise left shift """ @@ -197,7 +199,7 @@ def shl(computation: MessageComputation) -> None: computation.stack_push_int(result) -def shr(computation: MessageComputation) -> None: +def shr(computation: ComputationAPI) -> None: """ Bitwise right shift """ @@ -211,7 +213,7 @@ def shr(computation: MessageComputation) -> None: computation.stack_push_int(result) -def sar(computation: MessageComputation) -> None: +def sar(computation: ComputationAPI) -> None: """ Arithmetic bitwise right shift """ diff --git a/eth/vm/logic/block.py b/eth/vm/logic/block.py index fe75890b12..15dd4c2aa2 100644 --- a/eth/vm/logic/block.py +++ b/eth/vm/logic/block.py @@ -1,37 +1,43 @@ -from eth.vm.computation import MessageComputation +from eth_typing import ( + BlockNumber, +) +from eth.abc import ( + ComputationAPI, +) -def blockhash(computation: MessageComputation) -> None: + +def blockhash(computation: ComputationAPI) -> None: block_number = computation.stack_pop1_int() - block_hash = computation.state.get_ancestor_hash(block_number) + block_hash = computation.state.get_ancestor_hash(BlockNumber(block_number)) computation.stack_push_bytes(block_hash) -def coinbase(computation: MessageComputation) -> None: +def coinbase(computation: ComputationAPI) -> None: computation.stack_push_bytes(computation.state.coinbase) -def timestamp(computation: MessageComputation) -> None: +def timestamp(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.timestamp) -def number(computation: MessageComputation) -> None: +def number(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.block_number) -def difficulty(computation: MessageComputation) -> None: +def difficulty(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.difficulty) -def gaslimit(computation: MessageComputation) -> None: +def gaslimit(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.gas_limit) -def basefee(computation: MessageComputation) -> None: +def basefee(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.base_fee) -def mixhash(computation: MessageComputation) -> None: +def mixhash(computation: ComputationAPI) -> None: computation.stack_push_bytes(computation.state.mix_hash) diff --git a/eth/vm/logic/call.py b/eth/vm/logic/call.py index f704ca7e6d..3ffaf3bc94 100644 --- a/eth/vm/logic/call.py +++ b/eth/vm/logic/call.py @@ -1,20 +1,23 @@ from abc import ( ABC, - abstractmethod + abstractmethod, ) - from typing import ( Tuple, ) -from eth import constants - from eth_typing import ( Address, ) +from eth import ( + constants, +) +from eth._utils.address import ( + force_bytes_to_address, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, ) from eth.exceptions import ( OutOfGas, @@ -24,29 +27,24 @@ Opcode, ) -from eth._utils.address import ( - force_bytes_to_address, -) - - CallParams = Tuple[int, int, Address, Address, Address, int, int, int, int, bool, bool] class BaseCall(Opcode, ABC): @abstractmethod def compute_msg_extra_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> int: raise NotImplementedError("Must be implemented by subclasses") @abstractmethod - def get_call_params(self, computation: MessageComputationAPI) -> CallParams: + def get_call_params(self, computation: ComputationAPI) -> CallParams: raise NotImplementedError("Must be implemented by subclasses") def compute_msg_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> Tuple[int, int]: @@ -57,7 +55,7 @@ def compute_msg_gas(self, def get_account_load_fee( self, - computation: MessageComputationAPI, + computation: ComputationAPI, code_address: Address, ) -> int: """ @@ -66,7 +64,7 @@ def get_account_load_fee( """ return 0 - def __call__(self, computation: MessageComputationAPI) -> None: + def __call__(self, computation: ComputationAPI) -> None: computation.consume_gas( self.gas_cost, reason=self.mnemonic, @@ -163,7 +161,7 @@ def __call__(self, computation: MessageComputationAPI) -> None: # TODO: after upgrade to py3.6, use a TypedDict and try again child_msg = computation.prepare_child_message(**child_msg_kwargs) # type: ignore - child_computation = computation.apply_child_message_computation(child_msg) + child_computation = computation.apply_child_computation(child_msg) if child_computation.is_error: computation.stack_push_int(0) @@ -184,7 +182,7 @@ def __call__(self, computation: MessageComputationAPI) -> None: class Call(BaseCall): def compute_msg_extra_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> int: @@ -194,7 +192,7 @@ def compute_msg_extra_gas(self, create_gas_fee = constants.GAS_NEWACCOUNT if not account_exists else 0 return transfer_gas_fee + create_gas_fee - def get_call_params(self, computation: MessageComputationAPI) -> CallParams: + def get_call_params(self, computation: ComputationAPI) -> CallParams: gas = computation.stack_pop1_int() to = force_bytes_to_address(computation.stack_pop1_bytes()) @@ -223,13 +221,13 @@ def get_call_params(self, computation: MessageComputationAPI) -> CallParams: class CallCode(BaseCall): def compute_msg_extra_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> int: return constants.GAS_CALLVALUE if value else 0 - def get_call_params(self, computation: MessageComputationAPI) -> CallParams: + def get_call_params(self, computation: ComputationAPI) -> CallParams: gas = computation.stack_pop1_int() code_address = force_bytes_to_address(computation.stack_pop1_bytes()) @@ -261,20 +259,20 @@ def get_call_params(self, computation: MessageComputationAPI) -> CallParams: class DelegateCall(BaseCall): def compute_msg_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> Tuple[int, int]: return gas, gas def compute_msg_extra_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> int: return 0 - def get_call_params(self, computation: MessageComputationAPI) -> CallParams: + def get_call_params(self, computation: ComputationAPI) -> CallParams: gas = computation.stack_pop1_int() code_address = force_bytes_to_address(computation.stack_pop1_bytes()) @@ -309,7 +307,7 @@ def get_call_params(self, computation: MessageComputationAPI) -> CallParams: # class CallEIP150(Call): def compute_msg_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> Tuple[int, int]: @@ -326,7 +324,7 @@ def compute_msg_gas(self, class CallCodeEIP150(CallCode): def compute_msg_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> Tuple[int, int]: @@ -343,7 +341,7 @@ def compute_msg_gas(self, class DelegateCallEIP150(DelegateCall): def compute_msg_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> Tuple[int, int]: @@ -364,7 +362,7 @@ def max_child_gas_eip150(gas: int) -> int: def compute_eip150_msg_gas(*, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, extra_gas: int, value: int, @@ -391,7 +389,7 @@ def compute_eip150_msg_gas(*, # class CallEIP161(CallEIP150): def compute_msg_extra_gas(self, - computation: MessageComputationAPI, + computation: ComputationAPI, gas: int, to: Address, value: int) -> int: @@ -409,7 +407,7 @@ def compute_msg_extra_gas(self, # Byzantium # class StaticCall(CallEIP161): - def get_call_params(self, computation: MessageComputationAPI) -> CallParams: + def get_call_params(self, computation: ComputationAPI) -> CallParams: gas = computation.stack_pop1_int() to = force_bytes_to_address(computation.stack_pop1_bytes()) @@ -436,7 +434,7 @@ def get_call_params(self, computation: MessageComputationAPI) -> CallParams: class CallByzantium(CallEIP161): - def get_call_params(self, computation: MessageComputationAPI) -> CallParams: + def get_call_params(self, computation: ComputationAPI) -> CallParams: call_params = super().get_call_params(computation) value = call_params[1] if computation.msg.is_static and value != 0: diff --git a/eth/vm/logic/comparison.py b/eth/vm/logic/comparison.py index 3f89ca2884..9980a0e102 100644 --- a/eth/vm/logic/comparison.py +++ b/eth/vm/logic/comparison.py @@ -1,14 +1,16 @@ -from eth import constants - +from eth import ( + constants, +) from eth._utils.numeric import ( signed_to_unsigned, unsigned_to_signed, ) - -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) -def lt(computation: MessageComputation) -> None: +def lt(computation: ComputationAPI) -> None: """ Lesser Comparison """ @@ -22,7 +24,7 @@ def lt(computation: MessageComputation) -> None: computation.stack_push_int(result) -def gt(computation: MessageComputation) -> None: +def gt(computation: ComputationAPI) -> None: """ Greater Comparison """ @@ -36,7 +38,7 @@ def gt(computation: MessageComputation) -> None: computation.stack_push_int(result) -def slt(computation: MessageComputation) -> None: +def slt(computation: ComputationAPI) -> None: """ Signed Lesser Comparison """ @@ -53,7 +55,7 @@ def slt(computation: MessageComputation) -> None: computation.stack_push_int(signed_to_unsigned(result)) -def sgt(computation: MessageComputation) -> None: +def sgt(computation: ComputationAPI) -> None: """ Signed Greater Comparison """ @@ -70,7 +72,7 @@ def sgt(computation: MessageComputation) -> None: computation.stack_push_int(signed_to_unsigned(result)) -def eq(computation: MessageComputation) -> None: +def eq(computation: ComputationAPI) -> None: """ Equality """ @@ -84,7 +86,7 @@ def eq(computation: MessageComputation) -> None: computation.stack_push_int(result) -def iszero(computation: MessageComputation) -> None: +def iszero(computation: ComputationAPI) -> None: """ Not """ @@ -98,7 +100,7 @@ def iszero(computation: MessageComputation) -> None: computation.stack_push_int(result) -def and_op(computation: MessageComputation) -> None: +def and_op(computation: ComputationAPI) -> None: """ Bitwise And """ @@ -109,7 +111,7 @@ def and_op(computation: MessageComputation) -> None: computation.stack_push_int(result) -def or_op(computation: MessageComputation) -> None: +def or_op(computation: ComputationAPI) -> None: """ Bitwise Or """ @@ -120,7 +122,7 @@ def or_op(computation: MessageComputation) -> None: computation.stack_push_int(result) -def xor(computation: MessageComputation) -> None: +def xor(computation: ComputationAPI) -> None: """ Bitwise XOr """ @@ -131,7 +133,7 @@ def xor(computation: MessageComputation) -> None: computation.stack_push_int(result) -def not_op(computation: MessageComputation) -> None: +def not_op(computation: ComputationAPI) -> None: """ Not """ @@ -142,7 +144,7 @@ def not_op(computation: MessageComputation) -> None: computation.stack_push_int(result) -def byte_op(computation: MessageComputation) -> None: +def byte_op(computation: ComputationAPI) -> None: """ Bitwise And """ diff --git a/eth/vm/logic/context.py b/eth/vm/logic/context.py index 74a89b16a9..a9845e5e48 100644 --- a/eth/vm/logic/context.py +++ b/eth/vm/logic/context.py @@ -1,59 +1,59 @@ -from typing import Tuple +from typing import ( + Tuple, +) from eth_typing import ( Address, ) -from eth import constants - -from eth.abc import ( - MessageComputationAPI, +from eth import ( + constants, ) -from eth.exceptions import ( - OutOfBoundsRead, -) - from eth._utils.address import ( force_bytes_to_address, ) from eth._utils.numeric import ( ceil32, ) - -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) +from eth.exceptions import ( + OutOfBoundsRead, +) -def balance(computation: MessageComputation) -> None: +def balance(computation: ComputationAPI) -> None: addr = force_bytes_to_address(computation.stack_pop1_bytes()) push_balance_of_address(addr, computation) -def selfbalance(computation: MessageComputation) -> None: +def selfbalance(computation: ComputationAPI) -> None: push_balance_of_address(computation.msg.storage_address, computation) -def push_balance_of_address(address: Address, computation: MessageComputationAPI) -> None: +def push_balance_of_address(address: Address, computation: ComputationAPI) -> None: balance = computation.state.get_balance(address) computation.stack_push_int(balance) -def origin(computation: MessageComputation) -> None: +def origin(computation: ComputationAPI) -> None: computation.stack_push_bytes(computation.transaction_context.origin) -def address(computation: MessageComputation) -> None: +def address(computation: ComputationAPI) -> None: computation.stack_push_bytes(computation.msg.storage_address) -def caller(computation: MessageComputation) -> None: +def caller(computation: ComputationAPI) -> None: computation.stack_push_bytes(computation.msg.sender) -def callvalue(computation: MessageComputation) -> None: +def callvalue(computation: ComputationAPI) -> None: computation.stack_push_int(computation.msg.value) -def calldataload(computation: MessageComputation) -> None: +def calldataload(computation: ComputationAPI) -> None: """ Load call data into memory. """ @@ -66,12 +66,12 @@ def calldataload(computation: MessageComputation) -> None: computation.stack_push_bytes(normalized_value) -def calldatasize(computation: MessageComputation) -> None: +def calldatasize(computation: ComputationAPI) -> None: size = len(computation.msg.data) computation.stack_push_int(size) -def calldatacopy(computation: MessageComputation) -> None: +def calldatacopy(computation: ComputationAPI) -> None: ( mem_start_position, calldata_start_position, @@ -93,16 +93,16 @@ def calldatacopy(computation: MessageComputation) -> None: computation.memory_write(mem_start_position, size, padded_value) -def chain_id(computation: MessageComputation) -> None: +def chain_id(computation: ComputationAPI) -> None: computation.stack_push_int(computation.state.execution_context.chain_id) -def codesize(computation: MessageComputation) -> None: +def codesize(computation: ComputationAPI) -> None: size = len(computation.code) computation.stack_push_int(size) -def codecopy(computation: MessageComputation) -> None: +def codecopy(computation: ComputationAPI) -> None: ( mem_start_position, code_start_position, @@ -127,18 +127,18 @@ def codecopy(computation: MessageComputation) -> None: computation.memory_write(mem_start_position, size, padded_code_bytes) -def gasprice(computation: MessageComputation) -> None: +def gasprice(computation: ComputationAPI) -> None: computation.stack_push_int(computation.transaction_context.gas_price) -def extcodesize(computation: MessageComputation) -> None: +def extcodesize(computation: ComputationAPI) -> None: account = force_bytes_to_address(computation.stack_pop1_bytes()) code_size = len(computation.state.get_code(account)) computation.stack_push_int(code_size) -def extcodecopy_execute(computation: MessageComputationAPI) -> Tuple[Address, int]: +def extcodecopy_execute(computation: ComputationAPI) -> Tuple[Address, int]: """ Runs the logical component of extcodecopy, without charging gas. @@ -163,7 +163,7 @@ def extcodecopy_execute(computation: MessageComputationAPI) -> Tuple[Address, in return account, size -def consume_extcodecopy_word_cost(computation: MessageComputationAPI, size: int) -> None: +def consume_extcodecopy_word_cost(computation: ComputationAPI, size: int) -> None: word_count = ceil32(size) // 32 copy_gas_cost = constants.GAS_COPY * word_count computation.consume_gas( @@ -172,12 +172,12 @@ def consume_extcodecopy_word_cost(computation: MessageComputationAPI, size: int) ) -def extcodecopy(computation: MessageComputation) -> None: +def extcodecopy(computation: ComputationAPI) -> None: _address, size = extcodecopy_execute(computation) consume_extcodecopy_word_cost(computation, size) -def extcodehash(computation: MessageComputation) -> None: +def extcodehash(computation: ComputationAPI) -> None: """ Return the code hash for a given address. EIP: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1052.md @@ -191,12 +191,12 @@ def extcodehash(computation: MessageComputation) -> None: computation.stack_push_bytes(state.get_code_hash(account)) -def returndatasize(computation: MessageComputation) -> None: +def returndatasize(computation: ComputationAPI) -> None: size = len(computation.return_data) computation.stack_push_int(size) -def returndatacopy(computation: MessageComputation) -> None: +def returndatacopy(computation: ComputationAPI) -> None: ( mem_start_position, returndata_start_position, diff --git a/eth/vm/logic/duplication.py b/eth/vm/logic/duplication.py index a2e89904be..fa3de9cc6d 100644 --- a/eth/vm/logic/duplication.py +++ b/eth/vm/logic/duplication.py @@ -1,9 +1,11 @@ import functools -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) -def dup_XX(computation: MessageComputation, position: int) -> None: +def dup_XX(computation: ComputationAPI, position: int) -> None: """ Stack item duplication. """ diff --git a/eth/vm/logic/flow.py b/eth/vm/logic/flow.py index b8533f454a..3ce44332fe 100644 --- a/eth/vm/logic/flow.py +++ b/eth/vm/logic/flow.py @@ -1,20 +1,21 @@ +from eth.abc import ( + ComputationAPI, +) from eth.exceptions import ( - InvalidJumpDestination, - InvalidInstruction, Halt, + InvalidInstruction, + InvalidJumpDestination, ) - -from eth.vm.computation import MessageComputation from eth.vm.opcode_values import ( JUMPDEST, ) -def stop(computation: MessageComputation) -> None: +def stop(computation: ComputationAPI) -> None: raise Halt('STOP') -def jump(computation: MessageComputation) -> None: +def jump(computation: ComputationAPI) -> None: jump_dest = computation.stack_pop1_int() computation.code.program_counter = jump_dest @@ -28,7 +29,7 @@ def jump(computation: MessageComputation) -> None: raise InvalidInstruction("Jump resulted in invalid instruction") -def jumpi(computation: MessageComputation) -> None: +def jumpi(computation: ComputationAPI) -> None: jump_dest, check_value = computation.stack_pop_ints(2) if check_value: @@ -43,17 +44,17 @@ def jumpi(computation: MessageComputation) -> None: raise InvalidInstruction("Jump resulted in invalid instruction") -def jumpdest(computation: MessageComputation) -> None: +def jumpdest(computation: ComputationAPI) -> None: pass -def program_counter(computation: MessageComputation) -> None: +def program_counter(computation: ComputationAPI) -> None: pc = max(computation.code.program_counter - 1, 0) computation.stack_push_int(pc) -def gas(computation: MessageComputation) -> None: +def gas(computation: ComputationAPI) -> None: gas_remaining = computation.get_gas_remaining() computation.stack_push_int(gas_remaining) diff --git a/eth/vm/logic/invalid.py b/eth/vm/logic/invalid.py index 4566f22b2d..e58f81e6ac 100644 --- a/eth/vm/logic/invalid.py +++ b/eth/vm/logic/invalid.py @@ -1,6 +1,12 @@ -from eth.abc import MessageComputationAPI -from eth.exceptions import InvalidInstruction -from eth.vm.opcode import Opcode +from eth.abc import ( + ComputationAPI, +) +from eth.exceptions import ( + InvalidInstruction, +) +from eth.vm.opcode import ( + Opcode, +) class InvalidOpcode(Opcode): @@ -11,7 +17,7 @@ def __init__(self, value: int) -> None: self.value = value super().__init__() - def __call__(self, computation: MessageComputationAPI) -> None: + def __call__(self, computation: ComputationAPI) -> None: raise InvalidInstruction( f"Invalid opcode 0x{self.value:x} @ {computation.code.program_counter - 1}" ) diff --git a/eth/vm/logic/logging.py b/eth/vm/logic/logging.py index 8be33e94a8..c7289d1c6e 100644 --- a/eth/vm/logic/logging.py +++ b/eth/vm/logic/logging.py @@ -1,11 +1,17 @@ import functools -from typing import Tuple -from eth import constants +from typing import ( + Tuple, +) -from eth.vm.computation import MessageComputation +from eth import ( + constants, +) +from eth.abc import ( + ComputationAPI, +) -def log_XX(computation: MessageComputation, topic_count: int) -> None: +def log_XX(computation: ComputationAPI, topic_count: int) -> None: if topic_count < 0 or topic_count > 4: raise TypeError("Invalid log topic size. Must be 0, 1, 2, 3, or 4") diff --git a/eth/vm/logic/memory.py b/eth/vm/logic/memory.py index 55790f3a70..5a3dc1be26 100644 --- a/eth/vm/logic/memory.py +++ b/eth/vm/logic/memory.py @@ -1,7 +1,9 @@ -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) -def mstore(computation: MessageComputation) -> None: +def mstore(computation: ComputationAPI) -> None: start_position = computation.stack_pop1_int() value = computation.stack_pop1_bytes() @@ -13,7 +15,7 @@ def mstore(computation: MessageComputation) -> None: computation.memory_write(start_position, 32, normalized_value) -def mstore8(computation: MessageComputation) -> None: +def mstore8(computation: ComputationAPI) -> None: start_position = computation.stack_pop1_int() value = computation.stack_pop1_bytes() @@ -25,7 +27,7 @@ def mstore8(computation: MessageComputation) -> None: computation.memory_write(start_position, 1, normalized_value) -def mload(computation: MessageComputation) -> None: +def mload(computation: ComputationAPI) -> None: start_position = computation.stack_pop1_int() computation.extend_memory(start_position, 32) @@ -34,5 +36,5 @@ def mload(computation: MessageComputation) -> None: computation.stack_push_bytes(value) -def msize(computation: MessageComputation) -> None: +def msize(computation: ComputationAPI) -> None: computation.stack_push_int(len(computation._memory)) diff --git a/eth/vm/logic/sha3.py b/eth/vm/logic/sha3.py index dbf488fd99..9f72021567 100644 --- a/eth/vm/logic/sha3.py +++ b/eth/vm/logic/sha3.py @@ -1,13 +1,19 @@ -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) -from eth import constants +from eth import ( + constants, +) from eth._utils.numeric import ( ceil32, ) -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) -def sha3(computation: MessageComputation) -> None: +def sha3(computation: ComputationAPI) -> None: start_position, size = computation.stack_pop_ints(2) computation.extend_memory(start_position, size) diff --git a/eth/vm/logic/stack.py b/eth/vm/logic/stack.py index 35bd1b7def..180eda890e 100644 --- a/eth/vm/logic/stack.py +++ b/eth/vm/logic/stack.py @@ -1,13 +1,15 @@ import functools -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) -def pop(computation: MessageComputation) -> None: +def pop(computation: ComputationAPI) -> None: computation.stack_pop1_any() -def push_XX(computation: MessageComputation, size: int) -> None: +def push_XX(computation: ComputationAPI, size: int) -> None: raw_value = computation.code.read(size) # This is a performance-sensitive area. diff --git a/eth/vm/logic/storage.py b/eth/vm/logic/storage.py index b13dde35ab..d76ec11a01 100644 --- a/eth/vm/logic/storage.py +++ b/eth/vm/logic/storage.py @@ -1,14 +1,20 @@ -from typing import NamedTuple +from typing import ( + NamedTuple, +) from eth_utils import ( encode_hex, ) -from eth import constants -from eth.vm.computation import MessageComputation +from eth import ( + constants, +) +from eth.abc import ( + ComputationAPI, +) -def sstore(computation: MessageComputation) -> None: +def sstore(computation: ComputationAPI) -> None: slot, value = computation.stack_pop_ints(2) current_value = computation.state.get_storage( @@ -52,7 +58,7 @@ def sstore(computation: MessageComputation) -> None: ) -def sload(computation: MessageComputation) -> None: +def sload(computation: ComputationAPI) -> None: slot = computation.stack_pop1_int() value = computation.state.get_storage( @@ -76,7 +82,7 @@ class NetSStoreGasSchedule(NamedTuple): sstore_clears_schedule: int -def net_sstore(gas_schedule: NetSStoreGasSchedule, computation: MessageComputation) -> int: +def net_sstore(gas_schedule: NetSStoreGasSchedule, computation: ComputationAPI) -> int: """ :return slot: where the new value was stored """ diff --git a/eth/vm/logic/swap.py b/eth/vm/logic/swap.py index c2709a82a6..bc6695213d 100644 --- a/eth/vm/logic/swap.py +++ b/eth/vm/logic/swap.py @@ -1,9 +1,11 @@ import functools -from eth.vm.computation import MessageComputation +from eth.abc import ( + ComputationAPI, +) -def swap_XX(computation: MessageComputation, position: int) -> None: +def swap_XX(computation: ComputationAPI, position: int) -> None: """ Stack item swapping """ diff --git a/eth/vm/logic/system.py b/eth/vm/logic/system.py index 5f57aa6f11..4dec142f7f 100644 --- a/eth/vm/logic/system.py +++ b/eth/vm/logic/system.py @@ -4,13 +4,10 @@ from eth_utils import ( encode_hex, ) -from eth import constants -from eth.exceptions import ( - Halt, - Revert, - WriteProtection, -) +from eth import ( + constants, +) from eth._utils.address import ( force_bytes_to_address, generate_contract_address, @@ -20,16 +17,27 @@ ceil32, ) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, MessageAPI, ) -from eth.vm import mnemonics -from eth.vm.opcode import Opcode +from eth.exceptions import ( + Halt, + Revert, + WriteProtection, +) +from eth.vm import ( + mnemonics, +) +from eth.vm.opcode import ( + Opcode, +) -from .call import max_child_gas_eip150 +from .call import ( + max_child_gas_eip150, +) -def return_op(computation: MessageComputationAPI) -> None: +def return_op(computation: ComputationAPI) -> None: start_position, size = computation.stack_pop_ints(2) computation.extend_memory(start_position, size) @@ -38,7 +46,7 @@ def return_op(computation: MessageComputationAPI) -> None: raise Halt('RETURN') -def revert(computation: MessageComputationAPI) -> None: +def revert(computation: ComputationAPI) -> None: start_position, size = computation.stack_pop_ints(2) computation.extend_memory(start_position, size) @@ -47,12 +55,12 @@ def revert(computation: MessageComputationAPI) -> None: raise Revert(computation.output) -def selfdestruct(computation: MessageComputationAPI) -> None: +def selfdestruct(computation: ComputationAPI) -> None: beneficiary = force_bytes_to_address(computation.stack_pop1_bytes()) _selfdestruct(computation, beneficiary) -def selfdestruct_eip150(computation: MessageComputationAPI) -> None: +def selfdestruct_eip150(computation: ComputationAPI) -> None: beneficiary = force_bytes_to_address(computation.stack_pop1_bytes()) if not computation.state.account_exists(beneficiary): computation.consume_gas( @@ -63,7 +71,7 @@ def selfdestruct_eip150(computation: MessageComputationAPI) -> None: def selfdestruct_eip161_on_address( - computation: MessageComputationAPI, + computation: ComputationAPI, beneficiary: Address, ) -> None: is_dead = ( @@ -78,12 +86,12 @@ def selfdestruct_eip161_on_address( _selfdestruct(computation, beneficiary) -def selfdestruct_eip161(computation: MessageComputationAPI) -> None: +def selfdestruct_eip161(computation: ComputationAPI) -> None: beneficiary = force_bytes_to_address(computation.stack_pop1_bytes()) selfdestruct_eip161_on_address(computation, beneficiary) -def _selfdestruct(computation: MessageComputationAPI, beneficiary: Address) -> None: +def _selfdestruct(computation: ComputationAPI, beneficiary: Address) -> None: local_balance = computation.state.get_balance(computation.msg.storage_address) beneficiary_balance = computation.state.get_balance(beneficiary) @@ -131,7 +139,7 @@ def get_gas_cost(self, data: CreateOpcodeStackData) -> int: def generate_contract_address(self, stack_data: CreateOpcodeStackData, call_data: bytes, - computation: MessageComputationAPI) -> Address: + computation: ComputationAPI) -> Address: creation_nonce = computation.state.get_nonce(computation.msg.storage_address) computation.state.increment_nonce(computation.msg.storage_address) @@ -143,12 +151,12 @@ def generate_contract_address(self, return contract_address - def get_stack_data(self, computation: MessageComputationAPI) -> CreateOpcodeStackData: + def get_stack_data(self, computation: ComputationAPI) -> CreateOpcodeStackData: endowment, memory_start, memory_length = computation.stack_pop_ints(3) return CreateOpcodeStackData(endowment, memory_start, memory_length) - def __call__(self, computation: MessageComputationAPI) -> None: + def __call__(self, computation: ComputationAPI) -> None: stack_data = self.get_stack_data(computation) @@ -211,10 +219,10 @@ def __call__(self, computation: MessageComputationAPI) -> None: def apply_create_message( self, - computation: MessageComputationAPI, + computation: ComputationAPI, child_msg: MessageAPI, ) -> None: - child_computation = computation.apply_child_message_computation(child_msg) + child_computation = computation.apply_child_computation(child_msg) if child_computation.is_error: computation.stack_push_int(0) @@ -230,7 +238,7 @@ def max_child_gas_modifier(self, gas: int) -> int: class CreateByzantium(CreateEIP150): - def __call__(self, computation: MessageComputationAPI) -> None: + def __call__(self, computation: ComputationAPI) -> None: if computation.msg.is_static: raise WriteProtection("Cannot modify state while inside of a STATICCALL context") return super().__call__(computation) @@ -238,7 +246,7 @@ def __call__(self, computation: MessageComputationAPI) -> None: class Create2(CreateByzantium): - def get_stack_data(self, computation: MessageComputationAPI) -> CreateOpcodeStackData: + def get_stack_data(self, computation: ComputationAPI) -> CreateOpcodeStackData: endowment, memory_start, memory_length, salt = computation.stack_pop_ints(4) return CreateOpcodeStackData(endowment, memory_start, memory_length, salt) @@ -249,7 +257,7 @@ def get_gas_cost(self, data: CreateOpcodeStackData) -> int: def generate_contract_address(self, stack_data: CreateOpcodeStackData, call_data: bytes, - computation: MessageComputationAPI) -> Address: + computation: ComputationAPI) -> Address: computation.state.increment_nonce(computation.msg.storage_address) return generate_safe_contract_address( @@ -260,7 +268,7 @@ def generate_contract_address(self, def apply_create_message( self, - computation: MessageComputationAPI, + computation: ComputationAPI, child_msg: MessageAPI, ) -> None: # We need to ensure that creation operates on empty storage **and** @@ -270,7 +278,7 @@ def apply_create_message( computation.state.delete_storage(child_msg.storage_address) - child_computation = computation.apply_child_message_computation(child_msg) + child_computation = computation.apply_child_computation(child_msg) if child_computation.is_error: computation.state.revert(snapshot) diff --git a/eth/vm/memory.py b/eth/vm/memory.py index cff7f2836e..074817eadf 100644 --- a/eth/vm/memory.py +++ b/eth/vm/memory.py @@ -1,6 +1,12 @@ import itertools import logging +from eth._utils.numeric import ( + ceil32, +) +from eth.abc import ( + MemoryAPI, +) from eth.validation import ( validate_is_bytes, validate_length, @@ -8,11 +14,6 @@ validate_uint256, ) -from eth._utils.numeric import ( - ceil32, -) -from eth.abc import MemoryAPI - class Memory(MemoryAPI): __slots__ = ['_bytes'] diff --git a/eth/vm/message.py b/eth/vm/message.py index f746566e66..ee2f0bc435 100644 --- a/eth/vm/message.py +++ b/eth/vm/message.py @@ -1,8 +1,12 @@ import logging -from eth_typing import Address +from eth_typing import ( + Address, +) -from eth.abc import MessageAPI +from eth.abc import ( + MessageAPI, +) from eth.constants import ( CREATE_CONTRACT_ADDRESS, ) @@ -11,12 +15,12 @@ ) from eth.validation import ( validate_canonical_address, + validate_gte, + validate_is_boolean, validate_is_bytes, validate_is_bytes_or_view, validate_is_integer, - validate_gte, validate_uint256, - validate_is_boolean, ) diff --git a/eth/vm/opcode.py b/eth/vm/opcode.py index 3da0487410..5ce7d8de3f 100644 --- a/eth/vm/opcode.py +++ b/eth/vm/opcode.py @@ -1,5 +1,4 @@ import functools - from typing import ( Any, Callable, @@ -12,13 +11,14 @@ get_extended_debug_logger, ) -from eth._utils.datatypes import Configurable +from eth._utils.datatypes import ( + Configurable, +) from eth.abc import ( - MessageComputationAPI, + ComputationAPI, OpcodeAPI, ) - T = TypeVar('T') @@ -43,7 +43,7 @@ def as_opcode(cls: Type[T], gas_cost: int) -> T: if gas_cost: @functools.wraps(logic_fn) - def wrapped_logic_fn(computation: MessageComputationAPI) -> Any: + def wrapped_logic_fn(computation: ComputationAPI) -> Any: """ Wrapper function for the logic function which consumes the base opcode gas cost prior to execution. diff --git a/eth/vm/spoof.py b/eth/vm/spoof.py index 1c81eec130..40d27cc0ff 100644 --- a/eth/vm/spoof.py +++ b/eth/vm/spoof.py @@ -1,7 +1,15 @@ -from typing import Any, Union +from typing import ( + Any, + Union, +) -from eth.abc import SignedTransactionAPI, UnsignedTransactionAPI -from eth._utils.spoof import SpoofAttributes +from eth._utils.spoof import ( + SpoofAttributes, +) +from eth.abc import ( + SignedTransactionAPI, + UnsignedTransactionAPI, +) class SpoofTransaction(SpoofAttributes): diff --git a/eth/vm/stack.py b/eth/vm/stack.py index d9be86ce27..74f21ceaa7 100644 --- a/eth/vm/stack.py +++ b/eth/vm/stack.py @@ -3,7 +3,7 @@ Iterable, List, Tuple, - Union + Union, ) from eth_utils import ( @@ -11,17 +11,19 @@ big_endian_to_int, int_to_big_endian, ) + +from eth.abc import ( + StackAPI, +) from eth.exceptions import ( - InsufficientStack, FullStack, + InsufficientStack, ) from eth.validation import ( validate_stack_bytes, validate_stack_int, ) -from eth.abc import StackAPI - def _busted_type(item_type: type, value: Union[int, bytes]) -> ValidationError: return ValidationError( diff --git a/eth/vm/state.py b/eth/vm/state.py index 311fd75d2e..1f38540d26 100644 --- a/eth/vm/state.py +++ b/eth/vm/state.py @@ -15,27 +15,31 @@ ExtendedDebugLogger, get_extended_debug_logger, ) -from eth_utils.toolz import nth +from eth_utils.toolz import ( + nth, +) +from eth._utils.datatypes import ( + Configurable, +) from eth.abc import ( AccountDatabaseAPI, AtomicDatabaseAPI, - MessageComputationAPI, + ComputationAPI, ExecutionContextAPI, MessageAPI, + MetaWitnessAPI, SignedTransactionAPI, StateAPI, TransactionContextAPI, TransactionExecutorAPI, - MetaWitnessAPI, WithdrawalAPI, ) from eth.constants import ( MAX_PREV_HEADER_DEPTH, ) -from eth.typing import JournalDBCheckpoint -from eth._utils.datatypes import ( - Configurable, +from eth.typing import ( + JournalDBCheckpoint, ) @@ -45,7 +49,7 @@ class BaseState(Configurable, StateAPI): # __slots__ = ['_db', 'execution_context', '_account_db'] - message_computation_class: Type[MessageComputationAPI] = None + computation_class: Type[ComputationAPI] = None transaction_context_class: Type[TransactionContextAPI] = None account_db_class: Type[AccountDatabaseAPI] = None transaction_executor_class: Type[TransactionExecutorAPI] = None @@ -188,7 +192,7 @@ def is_address_warm(self, address: Address) -> bool: """ return ( self._account_db.is_address_warm(address) - or address in self.message_computation_class.get_precompiles() + or address in self.computation_class.get_precompiles() ) def mark_address_warm(self, address: Address) -> None: @@ -242,11 +246,11 @@ def get_ancestor_hash(self, block_number: int) -> Hash32: # def get_computation(self, message: MessageAPI, - transaction_context: TransactionContextAPI) -> MessageComputationAPI: - if self.message_computation_class is None: - raise AttributeError("No `message_computation_class` has been set for this State") + transaction_context: TransactionContextAPI) -> ComputationAPI: + if self.computation_class is None: + raise AttributeError("No `computation_class` has been set for this State") else: - computation = self.message_computation_class(self, message, transaction_context) + computation = self.computation_class(self, message, transaction_context) return computation # @@ -265,7 +269,7 @@ def get_transaction_executor(self) -> TransactionExecutorAPI: return self.transaction_executor_class(self) def costless_execute_transaction(self, - transaction: SignedTransactionAPI) -> MessageComputationAPI: + transaction: SignedTransactionAPI) -> ComputationAPI: with self.override_transaction_context(gas_price=transaction.gas_price): free_transaction = transaction.copy(gas_price=0) return self.apply_transaction(free_transaction) @@ -309,7 +313,7 @@ class BaseTransactionExecutor(TransactionExecutorAPI): def __init__(self, vm_state: StateAPI) -> None: self.vm_state = vm_state - def __call__(self, transaction: SignedTransactionAPI) -> MessageComputationAPI: + def __call__(self, transaction: SignedTransactionAPI) -> ComputationAPI: self.validate_transaction(transaction) message = self.build_evm_message(transaction) computation = self.build_computation(message, transaction) diff --git a/eth/vm/transaction_context.py b/eth/vm/transaction_context.py index c4a12fa9dc..c73e0bd9c6 100644 --- a/eth/vm/transaction_context.py +++ b/eth/vm/transaction_context.py @@ -1,8 +1,12 @@ import itertools -from eth_typing import Address +from eth_typing import ( + Address, +) -from eth.abc import TransactionContextAPI +from eth.abc import ( + TransactionContextAPI, +) from eth.validation import ( validate_canonical_address, validate_uint256, diff --git a/newsfragments/2083.misc.rst b/newsfragments/2083.misc.rst new file mode 100644 index 0000000000..e4f89bf6ef --- /dev/null +++ b/newsfragments/2083.misc.rst @@ -0,0 +1 @@ +Add EIP170_CODE_SIZE_LIMIT tests. \ No newline at end of file diff --git a/newsfragments/2097.breaking.rst b/newsfragments/2097.breaking.rst deleted file mode 100644 index fbf9701d45..0000000000 --- a/newsfragments/2097.breaking.rst +++ /dev/null @@ -1 +0,0 @@ -Refactor ``BaseComputation`` as a simpler base class and subclass ``MessageComputation`` building on it, allowing flexibility for other types of computations such as EOF computations. diff --git a/newsfragments/2105.bugfix.rst b/newsfragments/2105.bugfix.rst new file mode 100644 index 0000000000..eb060740a7 --- /dev/null +++ b/newsfragments/2105.bugfix.rst @@ -0,0 +1 @@ +Add missing receipt builder for the `ShanghaiBlock` class. diff --git a/newsfragments/2106.internal.rst b/newsfragments/2106.internal.rst new file mode 100644 index 0000000000..793638c0e3 --- /dev/null +++ b/newsfragments/2106.internal.rst @@ -0,0 +1 @@ +Refactored the computation class hierarchy and cleaned up the code along the way. Some abstract API classes have more of the underlying properties that the subclasses implement. diff --git a/tests/conftest.py b/tests/conftest.py index dc0e29f028..64d2b0a774 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,40 +1,52 @@ -from pathlib import Path - +from pathlib import ( + Path, +) import pytest +from eth_keys import ( + keys, +) from eth_utils import ( decode_hex, + setup_DEBUG2_logging, to_tuple, to_wei, - setup_DEBUG2_logging, ) - -from eth_keys import keys import rlp -from eth import constants +from eth import ( + constants, +) from eth.chains.base import ( Chain, MiningChain, ) -from eth.consensus import PowConsensus -from eth.consensus.noproof import NoProofConsensus -from eth.db.atomic import AtomicDB -from eth.rlp.headers import BlockHeader +from eth.consensus import ( + PowConsensus, +) +from eth.consensus.noproof import ( + NoProofConsensus, +) +from eth.db.atomic import ( + AtomicDB, +) +from eth.rlp.headers import ( + BlockHeader, +) from eth.vm.forks import ( - FrontierVM, - HomesteadVM, - TangerineWhistleVM, - SpuriousDragonVM, + ArrowGlacierVM, + BerlinVM, ByzantiumVM, ConstantinopleVM, - PetersburgVM, + FrontierVM, + GrayGlacierVM, + HomesteadVM, IstanbulVM, - MuirGlacierVM, - BerlinVM, LondonVM, - ArrowGlacierVM, - GrayGlacierVM, + MuirGlacierVM, + PetersburgVM, + SpuriousDragonVM, + TangerineWhistleVM, ) # diff --git a/tests/core/address-utils/test_address_generation.py b/tests/core/address-utils/test_address_generation.py index f9df68aece..abe9742b89 100644 --- a/tests/core/address-utils/test_address_generation.py +++ b/tests/core/address-utils/test_address_generation.py @@ -1,10 +1,11 @@ import pytest from eth_utils import ( - decode_hex, big_endian_to_int, + decode_hex, is_same_address, ) + from eth._utils.address import ( generate_safe_contract_address, ) diff --git a/tests/core/builder-tools/test_chain_builder.py b/tests/core/builder-tools/test_chain_builder.py index 59d9e924c6..21eb6b6e2a 100644 --- a/tests/core/builder-tools/test_chain_builder.py +++ b/tests/core/builder-tools/test_chain_builder.py @@ -1,12 +1,17 @@ import pytest -from eth_utils import ValidationError, to_wei +from eth_utils import ( + ValidationError, + to_wei, +) from eth.chains.base import ( Chain, MiningChain, ) -from eth.constants import ZERO_ADDRESS +from eth.constants import ( + ZERO_ADDRESS, +) from eth.tools.builder.chain import ( at_block_number, build, @@ -20,7 +25,9 @@ mine_block, mine_blocks, ) -from eth.tools.factories.transaction import new_transaction +from eth.tools.factories.transaction import ( + new_transaction, +) @pytest.fixture diff --git a/tests/core/builder-tools/test_chain_construction.py b/tests/core/builder-tools/test_chain_construction.py index 4b96baaa7f..c1b0278767 100644 --- a/tests/core/builder-tools/test_chain_construction.py +++ b/tests/core/builder-tools/test_chain_construction.py @@ -1,9 +1,15 @@ import pytest -from eth_utils import ValidationError +from eth_utils import ( + ValidationError, +) -from eth.chains.base import MiningChain -from eth.consensus.pow import check_pow +from eth.chains.base import ( + MiningChain, +) +from eth.consensus.pow import ( + check_pow, +) from eth.tools.builder.chain import ( arrow_glacier_at, berlin_at, @@ -30,21 +36,21 @@ tangerine_whistle_at, ) from eth.vm.forks import ( - FrontierVM, - HomesteadVM, - TangerineWhistleVM, - SpuriousDragonVM, + ArrowGlacierVM, + BerlinVM, ByzantiumVM, ConstantinopleVM, - PetersburgVM, + FrontierVM, + GrayGlacierVM, + HomesteadVM, IstanbulVM, - MuirGlacierVM, - BerlinVM, LondonVM, - ArrowGlacierVM, - GrayGlacierVM, + MuirGlacierVM, ParisVM, + PetersburgVM, ShanghaiVM, + SpuriousDragonVM, + TangerineWhistleVM, ) diff --git a/tests/core/builder-tools/test_chain_initializer.py b/tests/core/builder-tools/test_chain_initializer.py index 9cb653703a..42961dbc55 100644 --- a/tests/core/builder-tools/test_chain_initializer.py +++ b/tests/core/builder-tools/test_chain_initializer.py @@ -1,11 +1,16 @@ -import time - import pytest +import time -from eth_utils.toolz import pipe +from eth_utils.toolz import ( + pipe, +) -from eth import constants -from eth.chains.base import Chain +from eth import ( + constants, +) +from eth.chains.base import ( + Chain, +) from eth.tools.builder.chain import ( frontier_at, genesis, diff --git a/tests/core/chain-object/test_build_block_incrementally.py b/tests/core/chain-object/test_build_block_incrementally.py index d1a96d086a..b4a1a4e671 100644 --- a/tests/core/chain-object/test_build_block_incrementally.py +++ b/tests/core/chain-object/test_build_block_incrementally.py @@ -1,11 +1,14 @@ import pytest -from eth.chains.base import MiningChain +from eth._utils.address import ( + force_bytes_to_address, +) +from eth.chains.base import ( + MiningChain, +) from eth.tools.factories.transaction import ( - new_transaction + new_transaction, ) -from eth._utils.address import force_bytes_to_address - ADDRESS_1010 = force_bytes_to_address(b'\x10\x10') diff --git a/tests/core/chain-object/test_chain.py b/tests/core/chain-object/test_chain.py index c58897a17f..5fce0ad8dc 100644 --- a/tests/core/chain-object/test_chain.py +++ b/tests/core/chain-object/test_chain.py @@ -1,26 +1,41 @@ import pytest -import rlp -from eth_utils import decode_hex -from eth_utils.toolz import sliding_window +from eth_utils import ( + decode_hex, +) +from eth_utils.toolz import ( + sliding_window, +) +import rlp -from eth import constants -from eth.abc import MiningChainAPI -from eth.chains.base import MiningChain +from eth import ( + constants, +) +from eth.abc import ( + MiningChainAPI, +) +from eth.chains.base import ( + MiningChain, +) from eth.chains.mainnet import ( MAINNET_GENESIS_HEADER, MINING_MAINNET_VMS, ) -from eth.chains.ropsten import ROPSTEN_GENESIS_HEADER -from eth.consensus.noproof import NoProofConsensus +from eth.chains.ropsten import ( + ROPSTEN_GENESIS_HEADER, +) +from eth.consensus.noproof import ( + NoProofConsensus, +) from eth.exceptions import ( TransactionNotFound, ) from eth.tools.factories.transaction import ( - new_transaction + new_transaction, +) +from eth.vm.forks.frontier.blocks import ( + FrontierBlock, ) -from eth.vm.forks.frontier.blocks import FrontierBlock - from tests.core.fixtures import ( valid_block_rlp, ) diff --git a/tests/core/chain-object/test_chain_get_ancestors.py b/tests/core/chain-object/test_chain_get_ancestors.py index 491b5123a5..16efdb1b23 100644 --- a/tests/core/chain-object/test_chain_get_ancestors.py +++ b/tests/core/chain-object/test_chain_get_ancestors.py @@ -1,8 +1,14 @@ import pytest -from eth.chains.base import MiningChain -from eth.db.backends.memory import MemoryDB -from eth.db.atomic import AtomicDB +from eth.chains.base import ( + MiningChain, +) +from eth.db.atomic import ( + AtomicDB, +) +from eth.db.backends.memory import ( + MemoryDB, +) @pytest.fixture diff --git a/tests/core/chain-object/test_chain_reorganization.py b/tests/core/chain-object/test_chain_reorganization.py index f3ace49e26..35ea3ab13f 100644 --- a/tests/core/chain-object/test_chain_reorganization.py +++ b/tests/core/chain-object/test_chain_reorganization.py @@ -1,8 +1,11 @@ import pytest -from eth.chains.base import MiningChain - -from eth.tools.builder.chain import api +from eth.chains.base import ( + MiningChain, +) +from eth.tools.builder.chain import ( + api, +) @pytest.fixture(params=api.mining_mainnet_fork_at_fns) diff --git a/tests/core/chain-object/test_chain_retrieval_of_vm_class.py b/tests/core/chain-object/test_chain_retrieval_of_vm_class.py index 3f52baa011..1c6e9f906a 100644 --- a/tests/core/chain-object/test_chain_retrieval_of_vm_class.py +++ b/tests/core/chain-object/test_chain_retrieval_of_vm_class.py @@ -1,6 +1,5 @@ import pytest - from eth.chains.base import ( Chain, MiningChain, @@ -10,14 +9,18 @@ GENESIS_DIFFICULTY, GENESIS_GAS_LIMIT, ) -from eth.db.chain import ChainDB +from eth.db.chain import ( + ChainDB, +) from eth.exceptions import ( VMNotFound, ) from eth.rlp.headers import ( BlockHeader, ) -from eth.vm.base import VM +from eth.vm.base import ( + VM, +) @pytest.fixture diff --git a/tests/core/chain-object/test_contract_call.py b/tests/core/chain-object/test_contract_call.py index 5a8b6160df..3ae3708b34 100644 --- a/tests/core/chain-object/test_contract_call.py +++ b/tests/core/chain-object/test_contract_call.py @@ -1,14 +1,13 @@ -from eth_utils.toolz import ( - assoc, -) - +import pytest from eth_utils import ( decode_hex, function_signature_to_4byte_selector, to_bytes, ) -import pytest +from eth_utils.toolz import ( + assoc, +) from eth.exceptions import ( InvalidInstruction, @@ -16,22 +15,22 @@ Revert, ) from eth.tools.factories.transaction import ( - new_transaction + new_transaction, ) from eth.vm.forks import ( - FrontierVM, - HomesteadVM, - TangerineWhistleVM, - SpuriousDragonVM, + ArrowGlacierVM, + BerlinVM, ByzantiumVM, ConstantinopleVM, - PetersburgVM, + FrontierVM, + GrayGlacierVM, + HomesteadVM, IstanbulVM, - MuirGlacierVM, - BerlinVM, LondonVM, - ArrowGlacierVM, - GrayGlacierVM, + MuirGlacierVM, + PetersburgVM, + SpuriousDragonVM, + TangerineWhistleVM, ) diff --git a/tests/core/chain-object/test_create_transaction.py b/tests/core/chain-object/test_create_transaction.py index 80d8630253..e569da3caa 100644 --- a/tests/core/chain-object/test_create_transaction.py +++ b/tests/core/chain-object/test_create_transaction.py @@ -1,10 +1,18 @@ import pytest -from eth_keys import keys +from eth_keys import ( + keys, +) -from eth.chains.base import MiningChain -from eth.chains.mainnet import MINING_MAINNET_VMS -from eth.tools.builder.chain import api +from eth.chains.base import ( + MiningChain, +) +from eth.chains.mainnet import ( + MINING_MAINNET_VMS, +) +from eth.tools.builder.chain import ( + api, +) @pytest.fixture(params=MINING_MAINNET_VMS) diff --git a/tests/core/chain-object/test_gas_estimation.py b/tests/core/chain-object/test_gas_estimation.py index 5f7a758bf1..32042347e2 100644 --- a/tests/core/chain-object/test_gas_estimation.py +++ b/tests/core/chain-object/test_gas_estimation.py @@ -1,30 +1,32 @@ import pytest -from eth.estimators.gas import binary_gas_search_1000_tolerance +from eth._utils.address import ( + force_bytes_to_address, +) +from eth.estimators.gas import ( + binary_gas_search_1000_tolerance, +) from eth.tools.factories.transaction import ( - new_transaction + new_transaction, ) from eth.vm.forks import ( - FrontierVM, - HomesteadVM, - TangerineWhistleVM, - SpuriousDragonVM, + ArrowGlacierVM, + BerlinVM, ByzantiumVM, ConstantinopleVM, - PetersburgVM, + FrontierVM, + HomesteadVM, IstanbulVM, - MuirGlacierVM, - BerlinVM, LondonVM, - ArrowGlacierVM, + MuirGlacierVM, + PetersburgVM, + SpuriousDragonVM, + TangerineWhistleVM, ) -from eth._utils.address import force_bytes_to_address - from tests.core.helpers import ( fill_block, ) - ADDRESS_2 = b'\0' * 19 + b'\x02' ADDR_1010 = force_bytes_to_address(b'\x10\x10') diff --git a/tests/core/code-stream/test_code_stream.py b/tests/core/code-stream/test_code_stream.py index 6199ca207f..ef3e3c3bea 100644 --- a/tests/core/code-stream/test_code_stream.py +++ b/tests/core/code-stream/test_code_stream.py @@ -1,20 +1,27 @@ import itertools -import sys - import pytest +import sys +from eth_utils import ( + ValidationError, +) +from eth_utils.toolz import ( + drop, +) from hypothesis import ( given, strategies as st, ) -from eth_utils import ValidationError - -from eth_utils.toolz import drop - -from eth.vm import opcode_values -from eth.vm.code_stream import CodeStream -from eth.tools._utils.slow_code_stream import SlowCodeStream +from eth.tools._utils.slow_code_stream import ( + SlowCodeStream, +) +from eth.vm import ( + opcode_values, +) +from eth.vm.code_stream import ( + CodeStream, +) def test_code_stream_accepts_bytes(): diff --git a/tests/core/consensus/test_clique_consensus.py b/tests/core/consensus/test_clique_consensus.py index e3f75105b6..5a80a5bfff 100644 --- a/tests/core/consensus/test_clique_consensus.py +++ b/tests/core/consensus/test_clique_consensus.py @@ -1,43 +1,54 @@ import pytest +from eth_keys import ( + keys, +) from eth_utils import ( + ValidationError, decode_hex, to_tuple, ) -from eth_keys import keys - -from eth_utils import ValidationError - -from eth.chains.base import MiningChain +from eth.chains.base import ( + MiningChain, +) from eth.chains.goerli import ( GOERLI_GENESIS_HEADER, ) from eth.consensus.clique import ( + NONCE_AUTH, + NONCE_DROP, CliqueApplier, CliqueConsensus, CliqueConsensusContext, - NONCE_AUTH, - NONCE_DROP, VoteAction, ) -from eth.consensus.clique.constants import ( - VANITY_LENGTH, - SIGNATURE_LENGTH, -) from eth.consensus.clique._utils import ( get_block_signer, sign_block_header, ) +from eth.consensus.clique.constants import ( + SIGNATURE_LENGTH, + VANITY_LENGTH, +) from eth.constants import ( - ZERO_ADDRESS + ZERO_ADDRESS, +) +from eth.rlp.headers import ( + BlockHeader, +) +from eth.tools.factories.keys import ( + PublicKeyFactory, +) +from eth.tools.factories.transaction import ( + new_transaction, +) +from eth.vm.forks.istanbul import ( + IstanbulVM, +) +from eth.vm.forks.petersburg import ( + PetersburgVM, ) -from eth.rlp.headers import BlockHeader -from eth.tools.factories.keys import PublicKeyFactory -from eth.tools.factories.transaction import new_transaction -from eth.vm.forks.istanbul import IstanbulVM -from eth.vm.forks.petersburg import PetersburgVM - ALICE_PK = keys.PrivateKey( decode_hex('0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8') diff --git a/tests/core/consensus/test_clique_encoding.py b/tests/core/consensus/test_clique_encoding.py index dbcf2b91d2..0d8823c817 100644 --- a/tests/core/consensus/test_clique_encoding.py +++ b/tests/core/consensus/test_clique_encoding.py @@ -1,27 +1,25 @@ import pytest -from eth.constants import ( - GENESIS_PARENT_HASH, - ZERO_ADDRESS, -) from eth.consensus.clique.datatypes import ( Snapshot, Tally, Vote, - VoteAction + VoteAction, ) from eth.consensus.clique.encoding import ( decode_address_tally_pair, - encode_address_tally_pair, - decode_snapshot, decode_tally, decode_vote, + encode_address_tally_pair, encode_snapshot, encode_tally, encode_vote, ) - +from eth.constants import ( + GENESIS_PARENT_HASH, + ZERO_ADDRESS, +) SOME_ADDRESS = b'\x85\x82\xa2\x89V\xb9%\x93M\x03\xdd\xb4Xu\xe1\x8e\x85\x93\x12\xc1' diff --git a/tests/core/consensus/test_clique_utils.py b/tests/core/consensus/test_clique_utils.py index 4077e8967e..af08a25501 100644 --- a/tests/core/consensus/test_clique_utils.py +++ b/tests/core/consensus/test_clique_utils.py @@ -1,26 +1,30 @@ import pytest +from eth_keys import ( + keys, +) +from eth_typing import ( + Address, +) from eth_utils import ( decode_hex, ) -from eth_keys import keys - -from eth_typing import Address - from eth.chains.goerli import ( GOERLI_GENESIS_HEADER, ) -from eth.consensus.clique.constants import ( - VANITY_LENGTH, - SIGNATURE_LENGTH, -) from eth.consensus.clique._utils import ( get_block_signer, get_signers_at_checkpoint, sign_block_header, ) -from eth.rlp.headers import BlockHeader +from eth.consensus.clique.constants import ( + SIGNATURE_LENGTH, + VANITY_LENGTH, +) +from eth.rlp.headers import ( + BlockHeader, +) ALICE_PK = keys.PrivateKey( decode_hex('0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8') diff --git a/tests/core/consensus/test_consensus_engine.py b/tests/core/consensus/test_consensus_engine.py index 8980066079..64f2c6a1cc 100644 --- a/tests/core/consensus/test_consensus_engine.py +++ b/tests/core/consensus/test_consensus_engine.py @@ -1,23 +1,25 @@ import pytest +from eth_utils import ( + ValidationError, +) + from eth.abc import ( ConsensusAPI, ) +from eth.chains.base import ( + MiningChain, +) from eth.consensus import ( ConsensusContext, ) - -from eth.chains.base import MiningChain from eth.tools.builder.chain import ( genesis, ) -from eth.vm.forks.istanbul import IstanbulVM - -from eth_utils import ( - ValidationError, +from eth.vm.forks.istanbul import ( + IstanbulVM, ) - CONSENSUS_DATA_LENGH = 9 WHITELISTED_ROOT = b"root" diff --git a/tests/core/consensus/test_pow_mining.py b/tests/core/consensus/test_pow_mining.py index b19ab7214f..e86f9a5851 100644 --- a/tests/core/consensus/test_pow_mining.py +++ b/tests/core/consensus/test_pow_mining.py @@ -3,18 +3,24 @@ import threading import time -from eth.chains.base import MiningChain -from eth.chains.mainnet import MINING_MAINNET_VMS +from eth.chains.base import ( + MiningChain, +) +from eth.chains.mainnet import ( + MINING_MAINNET_VMS, +) from eth.consensus.pow import ( CACHE_MAX_ITEMS, EPOCH_LENGTH, check_pow, get_cache, ) -from eth.tools.mining import POWMiningMixin from eth.tools.builder.chain import ( genesis, ) +from eth.tools.mining import ( + POWMiningMixin, +) def _concurrently_run_to_completion(target, concurrency): diff --git a/tests/core/fixture-tools/test_normalize_state.py b/tests/core/fixture-tools/test_normalize_state.py index 4e8c144117..3775eb39b1 100644 --- a/tests/core/fixture-tools/test_normalize_state.py +++ b/tests/core/fixture-tools/test_normalize_state.py @@ -1,12 +1,13 @@ import pytest from eth_utils import ( - big_endian_to_int, ValidationError, + big_endian_to_int, ) -from eth.tools._utils.normalization import normalize_state - +from eth.tools._utils.normalization import ( + normalize_state, +) ADDRESS_A = b'a' + b'\0' * 19 ADDRESS_B = b'b' + b'\0' * 19 diff --git a/tests/core/fixtures.py b/tests/core/fixtures.py index 9362fed4e6..767ca160d2 100644 --- a/tests/core/fixtures.py +++ b/tests/core/fixtures.py @@ -2,7 +2,6 @@ decode_hex, ) - # This block is a child of the genesis defined in the chain fixture above and contains a single tx # that transfers 10 wei from 0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b to # 0x095e7baea6a6c7c4c2dfeb977efac326af552d87. diff --git a/tests/core/gas_meter/test_gas_meter.py b/tests/core/gas_meter/test_gas_meter.py index 54f22f3848..738aedf0fe 100644 --- a/tests/core/gas_meter/test_gas_meter.py +++ b/tests/core/gas_meter/test_gas_meter.py @@ -1,13 +1,15 @@ import pytest + from eth_utils import ( ValidationError, ) -from eth.vm.gas_meter import ( - GasMeter, -) + from eth.exceptions import ( OutOfGas, ) +from eth.vm.gas_meter import ( + GasMeter, +) @pytest.fixture(params=[10, 100, 999]) diff --git a/tests/core/generator-utils/test_cached_iterable.py b/tests/core/generator-utils/test_cached_iterable.py index 433b6bf505..5eeaa864f7 100644 --- a/tests/core/generator-utils/test_cached_iterable.py +++ b/tests/core/generator-utils/test_cached_iterable.py @@ -1,10 +1,13 @@ -from eth._utils.generator import CachedIterable +import itertools from eth_utils.toolz import ( first, nth, ) -import itertools + +from eth._utils.generator import ( + CachedIterable, +) def test_cached_generator(): diff --git a/tests/core/helpers.py b/tests/core/helpers.py index f592a042f3..c59cedc4da 100644 --- a/tests/core/helpers.py +++ b/tests/core/helpers.py @@ -1,12 +1,16 @@ import pytest from eth_utils import ( - decode_hex, ValidationError, + decode_hex, ) -from eth.chains.base import MiningChain -from eth.tools.factories.transaction import new_transaction +from eth.chains.base import ( + MiningChain, +) +from eth.tools.factories.transaction import ( + new_transaction, +) def fill_block(chain, from_, key, gas, data): diff --git a/tests/core/hexadecimal-utils/test_encode_and_decode.py b/tests/core/hexadecimal-utils/test_encode_and_decode.py index 327d5fe4b6..3dbd490eeb 100644 --- a/tests/core/hexadecimal-utils/test_encode_and_decode.py +++ b/tests/core/hexadecimal-utils/test_encode_and_decode.py @@ -1,10 +1,9 @@ import pytest from eth_utils import ( - encode_hex, decode_hex, + encode_hex, ) - from hypothesis import ( given, strategies as st, diff --git a/tests/core/message-object/test_message_object.py b/tests/core/message-object/test_message_object.py index 1fb5ed5c5f..1789fbe830 100644 --- a/tests/core/message-object/test_message_object.py +++ b/tests/core/message-object/test_message_object.py @@ -1,17 +1,16 @@ import pytest from eth_utils import ( - to_normalized_address, ValidationError, + to_normalized_address, ) -from eth.vm.message import ( - Message, -) from eth.constants import ( CREATE_CONTRACT_ADDRESS, ) - +from eth.vm.message import ( + Message, +) ADDRESS_A = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0" ADDRESS_B = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1" diff --git a/tests/core/numeric-utils/test_int_to_bytes32.py b/tests/core/numeric-utils/test_int_to_bytes32.py index a8ef32c951..d71f5b1570 100644 --- a/tests/core/numeric-utils/test_int_to_bytes32.py +++ b/tests/core/numeric-utils/test_int_to_bytes32.py @@ -1,14 +1,13 @@ import pytest +from eth._utils.numeric import ( + int_to_bytes32, +) from eth.constants import ( NULL_BYTE, UINT_256_MAX, ) -from eth._utils.numeric import ( - int_to_bytes32, -) - @pytest.mark.parametrize( 'value, expected', diff --git a/tests/core/numeric-utils/test_integer_squareroot.py b/tests/core/numeric-utils/test_integer_squareroot.py index 2b3c511fb5..75d783591c 100644 --- a/tests/core/numeric-utils/test_integer_squareroot.py +++ b/tests/core/numeric-utils/test_integer_squareroot.py @@ -1,4 +1,5 @@ import pytest + from hypothesis import ( given, strategies as st, diff --git a/tests/core/opcodes/test_opcodes.py b/tests/core/opcodes/test_opcodes.py index 6b7941ecdf..ac958ebeff 100644 --- a/tests/core/opcodes/test_opcodes.py +++ b/tests/core/opcodes/test_opcodes.py @@ -1,66 +1,71 @@ -import warnings - import pytest +import warnings -from eth.chains.mainnet import ( - MAINNET_VMS, - POS_MAINNET_VMS, -) -from eth.vm.forks.shanghai.computation import ( - ShanghaiMessageComputation, -) from eth_utils import ( + ValidationError, decode_hex, encode_hex, hexstr_if_str, int_to_big_endian, to_bytes, to_canonical_address, - ValidationError, ) + from eth import ( - constants + constants, ) from eth._utils.address import ( force_bytes_to_address, ) -from eth.consensus import ConsensusContext +from eth._utils.padding import ( + pad32, +) +from eth.chains.mainnet import ( + MAINNET_VMS, + POS_MAINNET_VMS, +) +from eth.consensus import ( + ConsensusContext, +) from eth.db.atomic import ( - AtomicDB + AtomicDB, ) from eth.db.chain import ( - ChainDB + ChainDB, ) from eth.exceptions import ( InvalidInstruction, VMError, ) -from eth._utils.padding import ( - pad32 -) from eth.vm import ( - opcode_values + opcode_values, +) +from eth.vm.chain_context import ( + ChainContext, ) -from eth.vm.chain_context import ChainContext from eth.vm.forks import ( - FrontierVM, - HomesteadVM, - TangerineWhistleVM, - SpuriousDragonVM, + BerlinVM, ByzantiumVM, ConstantinopleVM, - PetersburgVM, + FrontierVM, + HomesteadVM, IstanbulVM, - MuirGlacierVM, - BerlinVM, LondonVM, + MuirGlacierVM, + PetersburgVM, ShanghaiVM, + SpuriousDragonVM, + TangerineWhistleVM, +) +from eth.vm.forks.shanghai.computation import ( + ShanghaiComputation, ) from eth.vm.message import ( Message, ) -from eth.vm.spoof import SpoofTransaction - +from eth.vm.spoof import ( + SpoofTransaction, +) NORMALIZED_ADDRESS_A = "0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" NORMALIZED_ADDRESS_B = "0xcd1722f3947def4cf144679da39c4c32bdc35681" @@ -1599,7 +1604,7 @@ def test_selfdestruct_does_not_issue_deprecation_warning_pre_shanghai(vm_class): def test_selfdestruct_issues_deprecation_warning_for_shanghai(): - available_vm_opcodes = ShanghaiMessageComputation.opcodes + available_vm_opcodes = ShanghaiComputation.opcodes vm_opcodes_without_selfdestruct = { k: available_vm_opcodes[k] for k in available_vm_opcodes.keys() diff --git a/tests/core/padding-utils/test_padding.py b/tests/core/padding-utils/test_padding.py index e9ed90abcd..631af7e161 100644 --- a/tests/core/padding-utils/test_padding.py +++ b/tests/core/padding-utils/test_padding.py @@ -2,7 +2,7 @@ from eth._utils.padding import ( pad32, - pad32r + pad32r, ) padding_byte = b"\x00" diff --git a/tests/core/precompiles/test_blake2.py b/tests/core/precompiles/test_blake2.py index 243dabca91..fb52b4c7aa 100644 --- a/tests/core/precompiles/test_blake2.py +++ b/tests/core/precompiles/test_blake2.py @@ -1,12 +1,16 @@ import pytest from eth_utils import ( - to_bytes, ValidationError, + to_bytes, ) -from eth._utils.blake2.coders import extract_blake2b_parameters -from eth._utils.blake2.compression import blake2b_compress +from eth._utils.blake2.coders import ( + extract_blake2b_parameters, +) +from eth._utils.blake2.compression import ( + blake2b_compress, +) @pytest.mark.parametrize( diff --git a/tests/core/stack/test_stack.py b/tests/core/stack/test_stack.py index 4b0c897d18..3f327eeb4c 100644 --- a/tests/core/stack/test_stack.py +++ b/tests/core/stack/test_stack.py @@ -4,13 +4,13 @@ ValidationError, ) -from eth.vm.stack import ( - Stack, -) from eth.exceptions import ( FullStack, InsufficientStack, ) +from eth.vm.stack import ( + Stack, +) @pytest.fixture diff --git a/tests/core/tester/test_generate_vm_configuration.py b/tests/core/tester/test_generate_vm_configuration.py index 440bc29dab..2a3db198be 100644 --- a/tests/core/tester/test_generate_vm_configuration.py +++ b/tests/core/tester/test_generate_vm_configuration.py @@ -1,11 +1,12 @@ -import pytest - import enum +import pytest -from eth.vm.forks.frontier import FrontierVM from eth.chains.tester import ( _generate_vm_configuration, ) +from eth.vm.forks.frontier import ( + FrontierVM, +) class Forks(enum.Enum): diff --git a/tests/core/transaction-utils/conftest.py b/tests/core/transaction-utils/conftest.py index f19df4e11a..c2e22dd074 100644 --- a/tests/core/transaction-utils/conftest.py +++ b/tests/core/transaction-utils/conftest.py @@ -1,6 +1,5 @@ import pytest - # from https://github.com/ethereum/tests/blob/c951a3c105d600ccd8f1c3fc87856b2bcca3df0a/BasicTests/txtest.json # noqa: E501 TRANSACTION_FIXTURES = [ { diff --git a/tests/core/transaction-utils/test_receipt_encoding.py b/tests/core/transaction-utils/test_receipt_encoding.py index 545dbdfcbd..5bafdcdd1a 100644 --- a/tests/core/transaction-utils/test_receipt_encoding.py +++ b/tests/core/transaction-utils/test_receipt_encoding.py @@ -1,13 +1,18 @@ +import pytest + from eth_utils import ( ValidationError, decode_hex, to_bytes, ) -import pytest import rlp -from eth.exceptions import UnrecognizedTransactionType -from eth.rlp.receipts import Receipt +from eth.exceptions import ( + UnrecognizedTransactionType, +) +from eth.rlp.receipts import ( + Receipt, +) from eth.vm.forks import ( BerlinVM, LondonVM, diff --git a/tests/core/transaction-utils/test_transaction_encoding.py b/tests/core/transaction-utils/test_transaction_encoding.py index df1e8d0b4e..db09afb603 100644 --- a/tests/core/transaction-utils/test_transaction_encoding.py +++ b/tests/core/transaction-utils/test_transaction_encoding.py @@ -1,13 +1,16 @@ +import pytest + from eth_utils import ( ValidationError, decode_hex, to_bytes, to_int, ) -import pytest import rlp -from eth.exceptions import UnrecognizedTransactionType +from eth.exceptions import ( + UnrecognizedTransactionType, +) from eth.vm.forks import ( BerlinVM, LondonVM, diff --git a/tests/core/transaction-utils/test_transaction_signature_validation.py b/tests/core/transaction-utils/test_transaction_signature_validation.py index 855d37d91f..8c8f41b1b3 100644 --- a/tests/core/transaction-utils/test_transaction_signature_validation.py +++ b/tests/core/transaction-utils/test_transaction_signature_validation.py @@ -1,15 +1,22 @@ import pytest -import rlp - +from eth_keys import ( + keys, +) from eth_utils import ( decode_hex, is_same_address, to_canonical_address, ) +import rlp -from eth_keys import keys - +from eth._utils.transactions import ( + extract_transaction_sender, + validate_transaction_signature, +) +from eth.vm.forks.berlin.transactions import ( + BerlinTransactionBuilder, +) from eth.vm.forks.frontier.transactions import ( FrontierTransaction, ) @@ -19,14 +26,6 @@ from eth.vm.forks.spurious_dragon.transactions import ( SpuriousDragonTransaction, ) -from eth.vm.forks.berlin.transactions import ( - BerlinTransactionBuilder, -) - -from eth._utils.transactions import ( - extract_transaction_sender, - validate_transaction_signature, -) @pytest.fixture(params=[ diff --git a/tests/core/validation/test_eth1_validation.py b/tests/core/validation/test_eth1_validation.py index fa86d1ecdb..4a448774c0 100644 --- a/tests/core/validation/test_eth1_validation.py +++ b/tests/core/validation/test_eth1_validation.py @@ -3,6 +3,7 @@ from eth_utils import ( ValidationError, ) + from eth.constants import ( SECPK1_N, ) @@ -19,9 +20,9 @@ validate_length, validate_length_lte, validate_lt, - validate_lte, validate_lt_secpk1n, validate_lt_secpk1n2, + validate_lte, validate_multiple_of, validate_stack_bytes, validate_stack_int, @@ -32,7 +33,6 @@ validate_word, ) - byte = b"\x00" diff --git a/tests/core/validation/test_transaction_validation.py b/tests/core/validation/test_transaction_validation.py index 3a14903ea7..d0c5bfe4ac 100644 --- a/tests/core/validation/test_transaction_validation.py +++ b/tests/core/validation/test_transaction_validation.py @@ -1,9 +1,15 @@ import pytest -from eth.vm.forks.london.transactions import UnsignedDynamicFeeTransaction -from eth.vm.forks.berlin.transactions import UnsignedAccessListTransaction +from eth_utils import ( + ValidationError, +) -from eth_utils import ValidationError +from eth.vm.forks.berlin.transactions import ( + UnsignedAccessListTransaction, +) +from eth.vm.forks.london.transactions import ( + UnsignedDynamicFeeTransaction, +) @pytest.mark.parametrize( diff --git a/tests/core/validation/test_withdrawal_validation.py b/tests/core/validation/test_withdrawal_validation.py index 210f2f41a6..6e0b279682 100644 --- a/tests/core/validation/test_withdrawal_validation.py +++ b/tests/core/validation/test_withdrawal_validation.py @@ -1,13 +1,20 @@ import pytest -from eth_typing import Address -from eth.vm.forks.shanghai.withdrawals import Withdrawal -from eth.validation import UINT_64_MAX +from eth_typing import ( + Address, +) from eth_utils import ( ValidationError, to_hex, ) +from eth.validation import ( + UINT_64_MAX, +) +from eth.vm.forks.shanghai.withdrawals import ( + Withdrawal, +) + @pytest.mark.parametrize( "withdrawal", diff --git a/tests/core/vm/conftest.py b/tests/core/vm/conftest.py index 338be378bf..bf77fc3044 100644 --- a/tests/core/vm/conftest.py +++ b/tests/core/vm/conftest.py @@ -1,7 +1,12 @@ import pytest -from eth_utils import to_canonical_address -from eth.vm.transaction_context import BaseTransactionContext +from eth_utils import ( + to_canonical_address, +) + +from eth.vm.transaction_context import ( + BaseTransactionContext, +) @pytest.fixture diff --git a/tests/core/vm/test_base_computation.py b/tests/core/vm/test_base_computation.py index e60f4aeaa0..820c3f7d1d 100644 --- a/tests/core/vm/test_base_computation.py +++ b/tests/core/vm/test_base_computation.py @@ -5,21 +5,21 @@ ) from eth.exceptions import ( - VMError, Revert, + VMError, +) +from eth.vm.computation import ( + BaseComputation, ) from eth.vm.message import ( Message, ) -from eth.vm.computation import ( - MessageComputation, -) from eth.vm.transaction_context import ( BaseTransactionContext, ) -class DummyComputation(MessageComputation): +class DummyComputation(BaseComputation): @classmethod def apply_message(cls, *args): return cls(*args) @@ -217,7 +217,7 @@ def test_get_log_entries_order_with_children(computation, child_message, canonic parent_log2 = (canonical_address_a, [4, 5, 6], b'2') child_log = (canonical_address_a, [1, 2, 3], b'child') computation.add_log_entry(*parent_log) - child_computation = computation.apply_child_message_computation(child_message) + child_computation = computation.apply_child_computation(child_message) # Pretend the child computation logged something. child_computation.add_log_entry(*child_log) computation.add_log_entry(*parent_log2) diff --git a/tests/core/vm/test_clique_validation.py b/tests/core/vm/test_clique_validation.py index e989e8da89..3d03607897 100644 --- a/tests/core/vm/test_clique_validation.py +++ b/tests/core/vm/test_clique_validation.py @@ -1,11 +1,13 @@ import pytest from eth_utils import ( - decode_hex, ValidationError, + decode_hex, ) -from eth.chains.base import MiningChain +from eth.chains.base import ( + MiningChain, +) from eth.chains.goerli import ( GOERLI_GENESIS_HEADER, ) @@ -13,14 +15,13 @@ CliqueApplier, CliqueConsensusContext, ) - -from eth.rlp.headers import BlockHeader - +from eth.rlp.headers import ( + BlockHeader, +) from eth.vm.forks.petersburg import ( PetersburgVM, ) - GOERLI_HEADER_ONE = BlockHeader( difficulty=2, block_number=1, diff --git a/tests/core/vm/test_computation.py b/tests/core/vm/test_computation.py index b11cee7ad3..35ddacd6ba 100644 --- a/tests/core/vm/test_computation.py +++ b/tests/core/vm/test_computation.py @@ -1,14 +1,25 @@ # test computation class behavior across VMs import pytest -from eth_typing import Address -from eth_utils import decode_hex - -from eth.chains.base import MiningChain -from eth.chains.mainnet import MINING_MAINNET_VMS +from eth_typing import ( + Address, +) +from eth_utils import ( + decode_hex, +) -from eth import constants -from eth.consensus import NoProofConsensus +from eth import ( + constants, +) +from eth.chains.base import ( + MiningChain, +) +from eth.chains.mainnet import ( + MINING_MAINNET_VMS, +) +from eth.consensus import ( + NoProofConsensus, +) from eth.exceptions import ( InvalidInstruction, ) diff --git a/tests/core/vm/test_contract_code_size_limit.py b/tests/core/vm/test_contract_code_size_limit.py new file mode 100644 index 0000000000..268b2a9296 --- /dev/null +++ b/tests/core/vm/test_contract_code_size_limit.py @@ -0,0 +1,106 @@ +import pytest + +from eth_utils import ( + hexstr_if_str, + to_bytes, + to_wei, +) + +from eth._utils.address import ( + generate_contract_address, +) +from eth.constants import ( + CREATE_CONTRACT_ADDRESS, +) +from eth.exceptions import ( + OutOfGas, +) +from eth.tools.factories.transaction import ( + new_transaction, +) +from eth.vm import ( + opcode_values, +) +from eth.vm.forks.spurious_dragon.computation import ( + SpuriousDragonComputation, +) +from eth.vm.forks.spurious_dragon.constants import ( + EIP170_CODE_SIZE_LIMIT, +) +from eth.vm.message import ( + Message, +) + + +def assemble(*codes): + return b"".join(hexstr_if_str(to_bytes, element) for element in codes) + + +@pytest.mark.parametrize( + "code_len", + [ + 0, + 1, + 0xFF, + EIP170_CODE_SIZE_LIMIT - 1, + EIP170_CODE_SIZE_LIMIT, + EIP170_CODE_SIZE_LIMIT + 1, + EIP170_CODE_SIZE_LIMIT + 0x10000, + ], +) +def test_contract_code_size_limit( + chain_without_block_validation, funded_address, funded_address_private_key, code_len +): + ZERO_OPCODE_32 = b"\x00" * 32 + CODE_LEN_OPCODE = code_len.to_bytes(32, byteorder="big") + + deploy_contract_opcodes = assemble( + # PUSH32, value, PUSH32, offset, MSTORE + opcode_values.PUSH32, + ZERO_OPCODE_32, + opcode_values.PUSH32, + ZERO_OPCODE_32, + opcode_values.MSTORE, + # PUSH32, length, PUSH32, offset, RETURN + opcode_values.PUSH32, + CODE_LEN_OPCODE, + opcode_values.PUSH32, + ZERO_OPCODE_32, + opcode_values.RETURN, + ) + + vm = chain_without_block_validation.get_vm() + + message = Message( + to=CREATE_CONTRACT_ADDRESS, + sender=funded_address, + create_address=generate_contract_address( + funded_address, vm.state.get_nonce(funded_address) + ), + value=0, + data=b"", + code=deploy_contract_opcodes, + gas=to_wei(1, "ether"), + ) + + transaction = new_transaction( + vm=vm, + from_=funded_address, + to=CREATE_CONTRACT_ADDRESS, + private_key=funded_address_private_key, + data=deploy_contract_opcodes, + ) + + computation = vm.state.get_transaction_executor().build_computation( + message, + transaction, + ) + + # EIP-170 apply after the SpuriousDragon fork. + if ( + issubclass(computation.__class__, SpuriousDragonComputation) + and code_len > EIP170_CODE_SIZE_LIMIT + ): + assert isinstance(computation.error, OutOfGas) + else: + assert computation.is_success diff --git a/tests/core/vm/test_frontier_computation.py b/tests/core/vm/test_frontier_computation.py index af890472ba..fc6f52dfcb 100644 --- a/tests/core/vm/test_frontier_computation.py +++ b/tests/core/vm/test_frontier_computation.py @@ -1,11 +1,11 @@ import pytest +from eth.vm.forks.frontier.computation import ( + FrontierComputation, +) from eth.vm.message import ( Message, ) -from eth.vm.forks.frontier.computation import ( - FrontierMessageComputation, -) @pytest.fixture @@ -30,7 +30,7 @@ def message(canonical_address_a, canonical_address_b): @pytest.fixture def computation(message, transaction_context, state): - computation = FrontierMessageComputation( + computation = FrontierComputation( state=state, message=message, transaction_context=transaction_context, @@ -52,7 +52,7 @@ def child_message(computation, canonical_address_b): @pytest.fixture def child_computation(computation, child_message): - child_computation = computation.generate_child_message_computation(child_message) + child_computation = computation.generate_child_computation(child_message) return child_computation diff --git a/tests/core/vm/test_interrupt.py b/tests/core/vm/test_interrupt.py index 4a777b994a..1e7290472c 100644 --- a/tests/core/vm/test_interrupt.py +++ b/tests/core/vm/test_interrupt.py @@ -1,6 +1,8 @@ import pytest -from eth_hash.auto import keccak +from eth_hash.auto import ( + keccak, +) from eth_utils import ( int_to_big_endian, ) diff --git a/tests/core/vm/test_london.py b/tests/core/vm/test_london.py index 4cfeaa19a2..66caab0ee6 100644 --- a/tests/core/vm/test_london.py +++ b/tests/core/vm/test_london.py @@ -1,18 +1,33 @@ import pytest -from eth_typing import Address -from eth_utils import decode_hex +from eth_typing import ( + Address, +) +from eth_utils import ( + decode_hex, +) -from eth import constants -from eth.consensus.noproof import NoProofConsensus -from eth.chains.base import MiningChain +from eth import ( + constants, +) +from eth.chains.base import ( + MiningChain, +) from eth.chains.mainnet import ( MINING_MAINNET_VMS, ) -from eth.exceptions import InvalidInstruction -from eth.vm.forks import BerlinVM +from eth.consensus.noproof import ( + NoProofConsensus, +) +from eth.exceptions import ( + InvalidInstruction, +) from eth.tools.factories.transaction import ( - new_dynamic_fee_transaction, new_transaction, + new_dynamic_fee_transaction, + new_transaction, +) +from eth.vm.forks import ( + BerlinVM, ) FOUR_TXN_GAS_LIMIT = 21000 * 4 diff --git a/tests/core/vm/test_mainnet_dao_fork.py b/tests/core/vm/test_mainnet_dao_fork.py index a6c7b9553b..8d2026df79 100644 --- a/tests/core/vm/test_mainnet_dao_fork.py +++ b/tests/core/vm/test_mainnet_dao_fork.py @@ -1,16 +1,19 @@ import pytest from eth_utils import ( - to_tuple, ValidationError, + to_tuple, +) +from eth_utils.toolz import ( + sliding_window, ) - -from eth_utils.toolz import sliding_window from eth.chains.mainnet import ( MainnetHomesteadVM, ) -from eth.rlp.headers import BlockHeader +from eth.rlp.headers import ( + BlockHeader, +) class ETC_VM(MainnetHomesteadVM): diff --git a/tests/core/vm/test_modexp_precompile.py b/tests/core/vm/test_modexp_precompile.py index 6e01175b2d..ca58b72f18 100644 --- a/tests/core/vm/test_modexp_precompile.py +++ b/tests/core/vm/test_modexp_precompile.py @@ -7,8 +7,8 @@ ) from eth.precompiles.modexp import ( - _modexp, _compute_modexp_gas_fee_eip_198, + _modexp, ) from eth.vm.forks.berlin.computation import ( _compute_modexp_gas_fee_eip_2565, diff --git a/tests/core/vm/test_rewards.py b/tests/core/vm/test_rewards.py index 45128b56b9..e63bd6a8ef 100644 --- a/tests/core/vm/test_rewards.py +++ b/tests/core/vm/test_rewards.py @@ -1,31 +1,33 @@ import pytest from eth_utils import ( - to_wei, ValidationError, + to_wei, ) from eth.chains.base import ( - MiningChain + MiningChain, ) from eth.tools.builder.chain import ( at_block_number, + berlin_at, build, - disable_pow_check, - mine_block, - mine_blocks, byzantium_at, + constantinople_at, + disable_pow_check, frontier_at, + genesis, homestead_at, + london_at, + mine_block, + mine_blocks, + petersburg_at, spurious_dragon_at, tangerine_whistle_at, - constantinople_at, - petersburg_at, - berlin_at, - london_at, - genesis, ) -from eth.tools.factories.transaction import new_dynamic_fee_transaction +from eth.tools.factories.transaction import ( + new_dynamic_fee_transaction, +) @pytest.mark.parametrize( diff --git a/tests/core/vm/test_shanghai.py b/tests/core/vm/test_shanghai.py index 547762f44e..bf3feb74bb 100644 --- a/tests/core/vm/test_shanghai.py +++ b/tests/core/vm/test_shanghai.py @@ -1,9 +1,17 @@ import pytest -from eth.chains.base import MiningChain -from eth.consensus import NoProofConsensus -from eth.vm.forks import ShanghaiVM -from eth.vm.forks.shanghai.withdrawals import Withdrawal +from eth.chains.base import ( + MiningChain, +) +from eth.consensus import ( + NoProofConsensus, +) +from eth.vm.forks import ( + ShanghaiVM, +) +from eth.vm.forks.shanghai.withdrawals import ( + Withdrawal, +) @pytest.fixture diff --git a/tests/core/vm/test_validate_transaction.py b/tests/core/vm/test_validate_transaction.py index 2571127bc9..370f873156 100644 --- a/tests/core/vm/test_validate_transaction.py +++ b/tests/core/vm/test_validate_transaction.py @@ -1,11 +1,24 @@ -from eth_utils import ValidationError import pytest -from eth._utils.address import force_bytes_to_address -from eth.chains.base import MiningChain -from eth.constants import GAS_TX -from eth.tools.factories.transaction import new_dynamic_fee_transaction -from eth.vm.forks import LondonVM +from eth_utils import ( + ValidationError, +) + +from eth._utils.address import ( + force_bytes_to_address, +) +from eth.chains.base import ( + MiningChain, +) +from eth.constants import ( + GAS_TX, +) +from eth.tools.factories.transaction import ( + new_dynamic_fee_transaction, +) +from eth.vm.forks import ( + LondonVM, +) @pytest.fixture diff --git a/tests/core/vm/test_vm.py b/tests/core/vm/test_vm.py index 6c3a65d4e8..af5dfd998f 100644 --- a/tests/core/vm/test_vm.py +++ b/tests/core/vm/test_vm.py @@ -1,12 +1,14 @@ import pytest -import rlp from eth_utils import ( - decode_hex, ValidationError, + decode_hex, ) +import rlp -from eth import constants +from eth import ( + constants, +) from eth.chains.base import ( MiningChain, ) @@ -14,9 +16,11 @@ MAINNET_VMS, MINING_MAINNET_VMS, ) -from eth.tools.builder.chain import api +from eth.tools.builder.chain import ( + api, +) from eth.tools.factories.transaction import ( - new_transaction + new_transaction, ) diff --git a/tests/core/vm/test_vm_class_configurations.py b/tests/core/vm/test_vm_class_configurations.py new file mode 100644 index 0000000000..512c815dd8 --- /dev/null +++ b/tests/core/vm/test_vm_class_configurations.py @@ -0,0 +1,48 @@ +import pytest + +from eth_bloom import ( + BloomFilter, +) + +from eth.abc import ( + ReceiptBuilderAPI, + TransactionBuilderAPI, +) +from eth.chains.mainnet import ( + MAINNET_VMS, +) +from eth.rlp.headers import ( + BlockHeader, +) + + +@pytest.fixture(scope="module") +def genesis_header(): + return BlockHeader( + difficulty=0, + block_number=0, + gas_limit=10000, + ) + + +@pytest.mark.parametrize("vm_class", MAINNET_VMS) +def test_vm_block_class_is_properly_configured( + vm_class, + genesis_header, +): + vm_block_instance = vm_class.get_block_class()(genesis_header) + + txn_builder = vm_block_instance.get_transaction_builder() + assert txn_builder is not None + assert issubclass(txn_builder, TransactionBuilderAPI) + + receipt_builder = vm_block_instance.get_receipt_builder() + assert receipt_builder is not None + assert issubclass(receipt_builder, ReceiptBuilderAPI) + + bloom_filter = vm_block_instance.bloom_filter + assert bloom_filter is not None + assert isinstance(bloom_filter, BloomFilter) + + assert vm_block_instance.number == genesis_header.block_number == 0 + assert vm_block_instance.hash == genesis_header.hash diff --git a/tests/core/vm/test_vm_state.py b/tests/core/vm/test_vm_state.py index 5004070f14..9ff5965368 100644 --- a/tests/core/vm/test_vm_state.py +++ b/tests/core/vm/test_vm_state.py @@ -1,12 +1,15 @@ import pytest -from eth_utils import ValidationError +from eth_utils import ( + ValidationError, +) from eth.tools.factories.transaction import ( - new_transaction + new_transaction, +) +from eth.vm.interrupt import ( + MissingAccountTrieNode, ) -from eth.vm.interrupt import MissingAccountTrieNode - ADDRESS = b'\xaa' * 20 OTHER_ADDRESS = b'\xbb' * 20 diff --git a/tests/database/test_accesslog.py b/tests/database/test_accesslog.py index cf7ccb5689..c4174fb254 100644 --- a/tests/database/test_accesslog.py +++ b/tests/database/test_accesslog.py @@ -1,14 +1,17 @@ +import pytest + from hypothesis import ( given, strategies as st, ) -import pytest from eth.db.accesslog import ( - KeyAccessLoggerDB, KeyAccessLoggerAtomicDB, + KeyAccessLoggerDB, +) +from eth.db.backends.memory import ( + MemoryDB, ) -from eth.db.backends.memory import MemoryDB @given(st.lists(st.binary())) diff --git a/tests/database/test_account_db.py b/tests/database/test_account_db.py index 1981bc711b..9c9e0cebce 100644 --- a/tests/database/test_account_db.py +++ b/tests/database/test_account_db.py @@ -1,21 +1,24 @@ import pytest -from eth_hash.auto import keccak - +from eth_hash.auto import ( + keccak, +) from eth_utils import ( ValidationError, ) -from eth.db.atomic import AtomicDB -from eth.db.backends.memory import MemoryDB +from eth.constants import ( + EMPTY_SHA3, +) from eth.db.account import ( AccountDB, ) - -from eth.constants import ( - EMPTY_SHA3, +from eth.db.atomic import ( + AtomicDB, +) +from eth.db.backends.memory import ( + MemoryDB, ) - ADDRESS = b'\xaa' * 20 OTHER_ADDRESS = b'\xbb' * 20 diff --git a/tests/database/test_atomic_database_api.py b/tests/database/test_atomic_database_api.py index 02a1591190..8d76cc86ee 100644 --- a/tests/database/test_atomic_database_api.py +++ b/tests/database/test_atomic_database_api.py @@ -1,10 +1,17 @@ import pytest -from eth.db.atomic import AtomicDB -from eth.db.backends.level import LevelDB - -from eth.tools.db.base import DatabaseAPITestSuite -from eth.tools.db.atomic import AtomicDatabaseBatchAPITestSuite +from eth.db.atomic import ( + AtomicDB, +) +from eth.db.backends.level import ( + LevelDB, +) +from eth.tools.db.atomic import ( + AtomicDatabaseBatchAPITestSuite, +) +from eth.tools.db.base import ( + DatabaseAPITestSuite, +) @pytest.fixture(params=['atomic', 'level']) diff --git a/tests/database/test_batch_db.py b/tests/database/test_batch_db.py index 0dfd742e23..c2ecabee89 100644 --- a/tests/database/test_batch_db.py +++ b/tests/database/test_batch_db.py @@ -1,10 +1,15 @@ import pytest + from eth_utils import ( ValidationError, ) -from eth.db.backends.memory import MemoryDB -from eth.db.batch import BatchDB +from eth.db.backends.memory import ( + MemoryDB, +) +from eth.db.batch import ( + BatchDB, +) @pytest.fixture diff --git a/tests/database/test_database_api.py b/tests/database/test_database_api.py index 7c822d8902..e297a5ad37 100644 --- a/tests/database/test_database_api.py +++ b/tests/database/test_database_api.py @@ -1,15 +1,27 @@ import pytest + from eth.db.accesslog import ( KeyAccessLoggerAtomicDB, KeyAccessLoggerDB, ) -from eth.db.backends.memory import MemoryDB -from eth.db.journal import JournalDB -from eth.db.batch import BatchDB -from eth.db.atomic import AtomicDB -from eth.db.cache import CacheDB - -from eth.tools.db.base import DatabaseAPITestSuite +from eth.db.atomic import ( + AtomicDB, +) +from eth.db.backends.memory import ( + MemoryDB, +) +from eth.db.batch import ( + BatchDB, +) +from eth.db.cache import ( + CacheDB, +) +from eth.db.journal import ( + JournalDB, +) +from eth.tools.db.base import ( + DatabaseAPITestSuite, +) @pytest.fixture(params=[ diff --git a/tests/database/test_eth1_chaindb.py b/tests/database/test_eth1_chaindb.py index 641f7405d1..c9da822a11 100644 --- a/tests/database/test_eth1_chaindb.py +++ b/tests/database/test_eth1_chaindb.py @@ -1,44 +1,56 @@ import pytest +from eth_hash.auto import ( + keccak, +) from hypothesis import ( given, strategies as st, ) - import rlp -from eth_hash.auto import keccak - +from eth._utils.address import ( + force_bytes_to_address, +) +from eth.chains.base import ( + MiningChain, +) from eth.constants import ( BLANK_ROOT_HASH, ZERO_ADDRESS, ) -from eth.chains.base import ( - MiningChain, +from eth.db.atomic import ( + AtomicDB, ) -from eth.db.atomic import AtomicDB from eth.db.chain import ( ChainDB, ) -from eth.db.chain_gaps import GENESIS_CHAIN_GAPS -from eth.db.schema import SchemaV1 +from eth.db.chain_gaps import ( + GENESIS_CHAIN_GAPS, +) +from eth.db.schema import ( + SchemaV1, +) from eth.exceptions import ( BlockNotFound, + CheckpointsMustBeCanonical, HeaderNotFound, ParentNotFound, ReceiptNotFound, - CheckpointsMustBeCanonical, ) from eth.rlp.headers import ( BlockHeader, ) -from eth.tools.builder.chain import api +from eth.tools.builder.chain import ( + api, +) +from eth.tools.factories.transaction import ( + new_access_list_transaction, + new_transaction, +) from eth.tools.rlp import ( assert_headers_eq, ) -from eth._utils.address import ( - force_bytes_to_address, -) from eth.vm.forks import ( BerlinVM, LondonVM, @@ -49,11 +61,6 @@ from eth.vm.forks.homestead.blocks import ( HomesteadBlock, ) -from eth.tools.factories.transaction import ( - new_access_list_transaction, - new_transaction, -) - A_ADDRESS = b"\xaa" * 20 B_ADDRESS = b"\xbb" * 20 diff --git a/tests/database/test_hash_trie.py b/tests/database/test_hash_trie.py index 2d83f28625..0fbb1429ad 100644 --- a/tests/database/test_hash_trie.py +++ b/tests/database/test_hash_trie.py @@ -1,10 +1,13 @@ +from eth_hash.auto import ( + keccak, +) from hypothesis import ( given, strategies as st, ) - -from eth_hash.auto import keccak -from trie import HexaryTrie +from trie import ( + HexaryTrie, +) from eth.db.hash_trie import ( HashTrie, diff --git a/tests/database/test_header_db.py b/tests/database/test_header_db.py index aacaadaae2..692407e2ae 100644 --- a/tests/database/test_header_db.py +++ b/tests/database/test_header_db.py @@ -1,27 +1,27 @@ import enum -from functools import partial +from functools import ( + partial, +) import operator +import pytest import random -from hypothesis import ( - example, - given, - settings, - strategies as st, +from eth_utils import ( + ValidationError, + keccak, + to_set, + to_tuple, ) -import pytest - from eth_utils.toolz import ( accumulate, compose, sliding_window, ) - -from eth_utils import ( - to_set, - to_tuple, - keccak, - ValidationError, +from hypothesis import ( + example, + given, + settings, + strategies as st, ) from eth.constants import ( @@ -29,13 +29,18 @@ GENESIS_DIFFICULTY, GENESIS_GAS_LIMIT, ) -from eth.db.atomic import AtomicDB +from eth.db.atomic import ( + AtomicDB, +) from eth.db.chain_gaps import ( - GapChange, GENESIS_CHAIN_GAPS, + GapChange, fill_gap, - reopen_gap, is_block_number_in_gap, + reopen_gap, +) +from eth.db.header import ( + HeaderDB, ) from eth.exceptions import ( CanonicalHeadNotFound, @@ -44,16 +49,15 @@ HeaderNotFound, ParentNotFound, ) -from eth.db.header import HeaderDB +from eth.tools.rlp import ( + assert_headers_eq, +) from eth.vm.forks.gray_glacier import ( GrayGlacierVM, ) from eth.vm.forks.gray_glacier.blocks import ( GrayGlacierBlockHeader as BlockHeader, ) -from eth.tools.rlp import ( - assert_headers_eq, -) @pytest.fixture diff --git a/tests/database/test_journal_db.py b/tests/database/test_journal_db.py index f55df0b2b5..2dbcbd7a25 100644 --- a/tests/database/test_journal_db.py +++ b/tests/database/test_journal_db.py @@ -1,16 +1,31 @@ -from eth_utils import ValidationError +import pytest + +from eth_utils import ( + ValidationError, +) from hypothesis import ( given, settings, strategies as st, ) -from hypothesis.stateful import Bundle, RuleBasedStateMachine, rule -import pytest +from hypothesis.stateful import ( + Bundle, + RuleBasedStateMachine, + rule, +) -from eth.db.backends.memory import MemoryDB -from eth.db.journal import JournalDB -from eth.db.slow_journal import JournalDB as SlowJournalDB -from eth.vm.interrupt import EVMMissingData +from eth.db.backends.memory import ( + MemoryDB, +) +from eth.db.journal import ( + JournalDB, +) +from eth.db.slow_journal import ( + JournalDB as SlowJournalDB, +) +from eth.vm.interrupt import ( + EVMMissingData, +) @pytest.fixture diff --git a/tests/database/test_leveldb_db_backend.py b/tests/database/test_leveldb_db_backend.py index e32b188a5e..88dc4c9b77 100644 --- a/tests/database/test_leveldb_db_backend.py +++ b/tests/database/test_leveldb_db_backend.py @@ -1,11 +1,14 @@ import pytest -from eth.db.backends.memory import MemoryDB -from eth.db.atomic import AtomicDB from eth.db import ( get_db_backend, ) - +from eth.db.atomic import ( + AtomicDB, +) +from eth.db.backends.memory import ( + MemoryDB, +) pytest.importorskip('leveldb') diff --git a/tests/fillers/build_json.py b/tests/fillers/build_json.py index 9576d24dcd..465b9c1217 100644 --- a/tests/fillers/build_json.py +++ b/tests/fillers/build_json.py @@ -1,21 +1,22 @@ -import os import json +import os -from eth_hash.auto import keccak - +from eth_hash.auto import ( + keccak, +) from eth_utils import ( encode_hex, ) -from eth.tools.fixtures.helpers import ( - get_test_name, -) + from eth.tools.fixtures.fillers import ( fill_test, ) from eth.tools.fixtures.fillers.formatters import ( filler_formatter, ) - +from eth.tools.fixtures.helpers import ( + get_test_name, +) PARENT_DIR = os.path.dirname(os.path.abspath(__file__)) OUTPUT_DIR = os.path.join(PARENT_DIR, "json") diff --git a/tests/json-fixtures/blockchain/test_blockchain.py b/tests/json-fixtures/blockchain/test_blockchain.py index 7e2d67227a..f42d7b6a92 100644 --- a/tests/json-fixtures/blockchain/test_blockchain.py +++ b/tests/json-fixtures/blockchain/test_blockchain.py @@ -1,17 +1,15 @@ import os -from pathlib import Path +from pathlib import ( + Path, +) import pytest -import rlp from eth_utils import ( - to_tuple, ValidationError, + to_tuple, ) +import rlp -from eth.tools.rlp import ( - assert_imported_block_unchanged, - assert_headers_eq, -) from eth.tools._utils.normalization import ( normalize_blockchain_fixtures, ) @@ -25,8 +23,13 @@ should_run_slow_tests, verify_state, ) -from eth.vm.header import HeaderSedes - +from eth.tools.rlp import ( + assert_headers_eq, + assert_imported_block_unchanged, +) +from eth.vm.header import ( + HeaderSedes, +) ROOT_PROJECT_DIR = Path(__file__).parents[3] diff --git a/tests/json-fixtures/test_difficulty.py b/tests/json-fixtures/test_difficulty.py index 0c59ee2769..2d4366192c 100644 --- a/tests/json-fixtures/test_difficulty.py +++ b/tests/json-fixtures/test_difficulty.py @@ -1,26 +1,33 @@ import os - import pytest -from eth_utils import to_int -from eth.constants import EMPTY_UNCLE_HASH -from eth.rlp.headers import BlockHeader +from eth_typing.enums import ( + ForkName, +) +from eth_utils import ( + to_int, +) + +from eth.constants import ( + EMPTY_UNCLE_HASH, +) +from eth.rlp.headers import ( + BlockHeader, +) from eth.tools.fixtures import ( filter_fixtures, generate_fixture_tests, load_fixture, ) from eth.vm.forks import ( - FrontierVM, - HomesteadVM, + ArrowGlacierVM, + BerlinVM, ByzantiumVM, ConstantinopleVM, - BerlinVM, - ArrowGlacierVM, + FrontierVM, GrayGlacierVM, + HomesteadVM, ) -from eth_typing.enums import ForkName - ROOT_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) diff --git a/tests/json-fixtures/test_transactions.py b/tests/json-fixtures/test_transactions.py index df00aaec7c..10640eeb48 100644 --- a/tests/json-fixtures/test_transactions.py +++ b/tests/json-fixtures/test_transactions.py @@ -1,61 +1,62 @@ import os - import pytest -import rlp - -from eth.exceptions import UnrecognizedTransactionType -from eth.vm.forks.shanghai.transactions import ShanghaiTransactionBuilder +from eth_typing.enums import ( + ForkName, +) from eth_utils import ( + ValidationError, is_same_address, to_tuple, - ValidationError, ) -from eth.tools.fixtures import ( - generate_fixture_tests, - load_fixture, +import rlp + +from eth.exceptions import ( + UnrecognizedTransactionType, ) from eth.tools._utils.normalization import ( normalize_transactiontest_fixture, ) -from eth.vm.forks.frontier.transactions import ( - FrontierTransaction +from eth.tools.fixtures import ( + generate_fixture_tests, + load_fixture, ) -from eth.vm.forks.homestead.transactions import ( - HomesteadTransaction +from eth.vm.forks.berlin.constants import ( + VALID_TRANSACTION_TYPES, ) -from eth.vm.forks.spurious_dragon.transactions import ( - SpuriousDragonTransaction +from eth.vm.forks.berlin.transactions import ( + BerlinTransactionBuilder, ) from eth.vm.forks.byzantium.transactions import ( - ByzantiumTransaction + ByzantiumTransaction, ) from eth.vm.forks.constantinople.transactions import ( - ConstantinopleTransaction + ConstantinopleTransaction, ) -from eth.vm.forks.petersburg.transactions import ( - PetersburgTransaction -) -from eth.vm.forks.istanbul.transactions import ( - IstanbulTransaction +from eth.vm.forks.frontier.transactions import ( + FrontierTransaction, ) -from eth.vm.forks.berlin.constants import ( - VALID_TRANSACTION_TYPES, +from eth.vm.forks.homestead.transactions import ( + HomesteadTransaction, ) -from eth.vm.forks.berlin.transactions import ( - BerlinTransactionBuilder +from eth.vm.forks.istanbul.transactions import ( + IstanbulTransaction, ) from eth.vm.forks.london.transactions import ( - LondonTransactionBuilder + LondonTransactionBuilder, ) from eth.vm.forks.paris.transactions import ( - ParisTransactionBuilder + ParisTransactionBuilder, ) - -from eth_typing.enums import ( - ForkName +from eth.vm.forks.petersburg.transactions import ( + PetersburgTransaction, +) +from eth.vm.forks.shanghai.transactions import ( + ShanghaiTransactionBuilder, +) +from eth.vm.forks.spurious_dragon.transactions import ( + SpuriousDragonTransaction, ) - ROOT_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) diff --git a/tests/json-fixtures/test_virtual_machine.py b/tests/json-fixtures/test_virtual_machine.py index 8ea42a1caa..8349048ff3 100644 --- a/tests/json-fixtures/test_virtual_machine.py +++ b/tests/json-fixtures/test_virtual_machine.py @@ -1,25 +1,34 @@ import os - import pytest +from eth_hash.auto import ( + keccak, +) from eth_utils import ( to_bytes, ) -from eth.consensus import ConsensusContext +from eth.consensus import ( + ConsensusContext, +) from eth.db import ( get_db_backend, ) -from eth.db.chain import ChainDB - -from eth_hash.auto import keccak - +from eth.db.chain import ( + ChainDB, +) from eth.exceptions import ( VMError, ) from eth.rlp.headers import ( BlockHeader, ) +from eth.tools._utils.hashing import ( + hash_log_entries, +) +from eth.tools._utils.normalization import ( + normalize_vmtest_fixture, +) from eth.tools.fixtures import ( filter_fixtures, generate_fixture_tests, @@ -27,20 +36,18 @@ setup_state, verify_state, ) -from eth.tools._utils.normalization import ( - normalize_vmtest_fixture, +from eth.vm.chain_context import ( + ChainContext, ) -from eth.tools._utils.hashing import ( - hash_log_entries, -) -from eth.vm.chain_context import ChainContext from eth.vm.forks import ( HomesteadVM, ) from eth.vm.forks.homestead.computation import ( - HomesteadMessageComputation, + HomesteadComputation, +) +from eth.vm.forks.homestead.state import ( + HomesteadState, ) -from eth.vm.forks.homestead.state import HomesteadState from eth.vm.message import ( Message, ) @@ -116,7 +123,7 @@ def get_block_hash_for_testing(self, block_number): return keccak(to_bytes(text=f"{block_number}")) -HomesteadComputationForTesting = HomesteadMessageComputation.configure( +HomesteadComputationForTesting = HomesteadComputation.configure( __name__='HomesteadComputationForTesting', apply_message=apply_message_for_testing, apply_create_message=apply_create_message_for_testing, @@ -124,7 +131,7 @@ def get_block_hash_for_testing(self, block_number): HomesteadStateForTesting = HomesteadState.configure( __name__='HomesteadStateForTesting', get_ancestor_hash=get_block_hash_for_testing, - message_computation_class=HomesteadComputationForTesting, + computation_class=HomesteadComputationForTesting, ) HomesteadVMForTesting = HomesteadVM.configure( __name__='HomesteadVMForTesting',