INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Arithmetic bitwise right shift
def sar(computation: BaseComputation) -> None: """ Arithmetic bitwise right shift """ shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256) value = unsigned_to_signed(value) if shift_length >= 256: result = 0 if value >= 0 else constants.UINT_255_NEGATIVE...
Computes the difficulty for a frontier block based on the parent block.
def compute_frontier_difficulty(parent_header: BlockHeader, timestamp: int) -> int: """ Computes the difficulty for a frontier block based on the parent block. """ validate_gt(timestamp, parent_header.timestamp, title="Header timestamp") offset = parent_header.difficulty // DIFFICULTY_ADJUSTMENT_DE...
Apply the message to the VM.
def build_computation(self, message: Message, transaction: BaseOrSpoofTransaction) -> BaseComputation: """Apply the message to the VM.""" transaction_context = self.vm_state.get_transaction_context(transaction) if message.is_create: ...
Push an item onto the stack.
def push(self, value: Union[int, bytes]) -> None: """ Push an item onto the stack. """ if len(self.values) > 1023: raise FullStack('Stack limit reached') validate_stack_item(value) self.values.append(value)
Pop an item off the stack. Note: This function is optimized for speed over readability.
def pop(self, num_items: int, type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]: """ Pop an item off the stack. Note: This function is optimized for speed over readability. """ try: if num_items == 1: return n...
Perform a SWAP operation on the stack.
def swap(self, position: int) -> None: """ Perform a SWAP operation on the stack. """ idx = -1 * position - 1 try: self.values[-1], self.values[idx] = self.values[idx], self.values[-1] except IndexError: raise InsufficientStack("Insufficient stack ...
Returns the block hash for the canonical block at the given number. Raises BlockNotFound if there's no block header with the given number in the canonical chain.
def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32: """ Returns the block hash for the canonical block at the given number. Raises BlockNotFound if there's no block header with the given number in the canonical chain. """ return self._get_canonical_b...
Perform a DUP operation on the stack.
def dup(self, position: int) -> None: """ Perform a DUP operation on the stack. """ idx = -1 * position try: self.push(self.values[idx]) except IndexError: raise InsufficientStack("Insufficient stack items for DUP{0}".format(position))
Returns the block header with the given number in the canonical chain. Raises BlockNotFound if there's no block header with the given number in the canonical chain.
def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeader: """ Returns the block header with the given number in the canonical chain. Raises BlockNotFound if there's no block header with the given number in the canonical chain. """ return s...
Returns the requested block header as specified by block hash. Raises BlockNotFound if it is not present in the db.
def _get_block_header_by_hash(db: BaseDB, block_hash: Hash32) -> BlockHeader: """ Returns the requested block header as specified by block hash. Raises BlockNotFound if it is not present in the db. """ validate_word(block_hash, title="Block Hash") try: header...
Return two iterable of headers, the first containing the new canonical headers, the second containing the old canonical headers
def persist_header_chain(self, headers: Iterable[BlockHeader] ) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]: """ Return two iterable of headers, the first containing the new canonical headers, the second containing the old ...
Sets the canonical chain HEAD to the block header as specified by the given block hash. :return: a tuple of the headers that are newly in the canonical chain, and the headers that are no longer in the canonical chain
def _set_as_canonical_chain_head(cls, db: BaseDB, block_hash: Hash32 ) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]: """ Sets the canonical chain HEAD to the block header as specified by the given block hash. :return: a tuple of the hea...
Returns the chain leading up from the given header until (but not including) the first ancestor it has in common with our canonical chain. If D is the canonical head in the following chain, and F is the new header, then this function returns (F, E). A - B - C - D \ ...
def _find_new_ancestors(cls, db: BaseDB, header: BlockHeader) -> Iterable[BlockHeader]: """ Returns the chain leading up from the given header until (but not including) the first ancestor it has in common with our canonical chain. If D is the canonical head in the following chain, and F...
Sets a record in the database to allow looking up this header by its block number.
def _add_block_number_to_hash_lookup(db: BaseDB, header: BlockHeader) -> None: """ Sets a record in the database to allow looking up this header by its block number. """ block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key( header.block_number ...
Compute the boundaries for the block gas limit based on the parent block.
def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]: """ Compute the boundaries for the block gas limit based on the parent block. """ boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR upper_bound = parent.gas_limit + boundary_range lower_bound = max(GAS_LIMIT_MIN...
A simple strategy for adjusting the gas limit. For each block: - decrease by 1/1024th of the gas limit from the previous block - increase by 50% of the total gas used by the previous block If the value is less than the given `gas_limit_floor`: - increase the gas limit by 1/1024th of the gas limi...
def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int: """ A simple strategy for adjusting the gas limit. For each block: - decrease by 1/1024th of the gas limit from the previous block - increase by 50% of the total gas used by the previous block If the value is less...
Generate BlockHeader from state_root and parent_header
def generate_header_from_parent_header( compute_difficulty_fn: Callable[[BlockHeader, int], int], parent_header: BlockHeader, coinbase: Address, timestamp: Optional[int] = None, extra_data: bytes = b'') -> BlockHeader: """ Generate BlockHeader from state_root and parent_h...
Robust to integer conversion, handling hex values, string representations, and special cases like `0x`.
def normalize_int(value: IntConvertible) -> int: """ Robust to integer conversion, handling hex values, string representations, and special cases like `0x`. """ if is_integer(value): return cast(int, value) elif is_bytes(value): return big_endian_to_int(value) elif is_hex(val...
Robust to integer conversion, handling hex values, string representations, and special cases like `0x`.
def to_int(value: str) -> int: """ Robust to integer conversion, handling hex values, string representations, and special cases like `0x`. """ if is_0x_prefixed(value): if len(value) == 2: return 0 else: return int(value, 16) else: return int(value...
Convert a state definition to the canonical dict form. State can either be defined in the canonical form, or as a list of sub states that are then merged to one. Sub states can either be given as dictionaries themselves, or as tuples where the last element is the value and all others the keys for this valu...
def state_definition_to_dict(state_definition: GeneralState) -> AccountState: """Convert a state definition to the canonical dict form. State can either be defined in the canonical form, or as a list of sub states that are then merged to one. Sub states can either be given as dictionaries themselves, or as...
Creates a new changeset. Changesets are referenced by a random uuid4 to prevent collisions between multiple changesets.
def record_changeset(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID: """ Creates a new changeset. Changesets are referenced by a random uuid4 to prevent collisions between multiple changesets. """ if custom_changeset_id is not None: if custom_changeset_id i...
Returns all changes from the given changeset. This includes all of the changes from any subsequent changeset, giving precidence to later changesets.
def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]: """ Returns all changes from the given changeset. This includes all of the changes from any subsequent changeset, giving precidence to later changesets. """ if changeset_id not i...
Treat as if the *underlying* database will also be cleared by some other mechanism. We build a special empty changeset just for marking that all previous data should be ignored.
def clear(self) -> None: """ Treat as if the *underlying* database will also be cleared by some other mechanism. We build a special empty changeset just for marking that all previous data should be ignored. """ # these internal records are used as a way to tell the differ...
Collapses all changes for the given changeset into the previous changesets if it exists.
def commit_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]: """ Collapses all changes for the given changeset into the previous changesets if it exists. """ does_clear = self.has_clear(changeset_id) changeset_data = self.pop_changeset(c...
Checks to be sure the changeset is known by the journal
def _validate_changeset(self, changeset_id: uuid.UUID) -> None: """ Checks to be sure the changeset is known by the journal """ if not self.journal.has_changeset(changeset_id): raise ValidationError("Changeset not found in journal: {0}".format( str(changeset_i...
Starts a new recording and returns an id for the associated changeset
def record(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID: """ Starts a new recording and returns an id for the associated changeset """ return self.journal.record_changeset(custom_changeset_id)
Commits a given changeset. This merges the given changeset and all subsequent changesets into the previous changeset giving precidence to later changesets in case of any conflicting keys. If this is the base changeset then all changes will be written to the underlying database and the J...
def commit(self, changeset_id: uuid.UUID) -> None: """ Commits a given changeset. This merges the given changeset and all subsequent changesets into the previous changeset giving precidence to later changesets in case of any conflicting keys. If this is the base changeset then a...
Throws away all journaled data starting at the given changeset
def discard(self, changeset_id: uuid.UUID) -> None: """ Throws away all journaled data starting at the given changeset """ self._validate_changeset(changeset_id) self.journal.pop_changeset(changeset_id)
Collect all of the accounts that *may* need to be deleted based on `EIP-161 <https://eips.ethereum.org/EIPS/eip-161>`_. Checking whether they *do* need to be deleted happens in the caller. See also: https://github.com/ethereum/EIPs/issues/716
def collect_touched_accounts(computation: BaseComputation) -> Iterable[bytes]: """ Collect all of the accounts that *may* need to be deleted based on `EIP-161 <https://eips.ethereum.org/EIPS/eip-161>`_. Checking whether they *do* need to be deleted happens in the caller. See also: https://github.c...
https://github.com/ethereum/EIPs/issues/100
def compute_difficulty( bomb_delay: int, parent_header: BlockHeader, timestamp: int) -> int: """ https://github.com/ethereum/EIPs/issues/100 """ parent_timestamp = parent_header.timestamp validate_gt(timestamp, parent_timestamp, title="Header.timestamp") parent_difficult...
Transform FQP to FQ2 for type hinting.
def FQP_point_to_FQ2_point(pt: Tuple[FQP, FQP, FQP]) -> Tuple[FQ2, FQ2, FQ2]: """ Transform FQP to FQ2 for type hinting. """ return ( FQ2(pt[0].coeffs), FQ2(pt[1].coeffs), FQ2(pt[2].coeffs), )
Class factory method for turning vanilla functions into Opcode classes.
def as_opcode(cls: Type[T], logic_fn: Callable[..., Any], mnemonic: str, gas_cost: int) -> Type[T]: """ Class factory method for turning vanilla functions into Opcode classes. """ if gas_cost: @functools.wraps(logic_fn) ...
Wipe out the storage, without explicitly handling the storage root update
def _wipe_storage(self, address: Address) -> None: """ Wipe out the storage, without explicitly handling the storage root update """ account_store = self._get_address_store(address) self._dirty_accounts.add(address) account_store.delete()
Kick off the filler generation process by creating the general filler scaffold with a test name and general information about the testing environment. For tests for the main chain, the `environment` parameter is expected to be a dictionary with some or all of the following keys: +---------------------...
def setup_main_filler(name: str, environment: Dict[Any, Any]=None) -> Dict[str, Dict[str, Any]]: """ Kick off the filler generation process by creating the general filler scaffold with a test name and general information about the testing environment. For tests for the main chain, the `environment` par...
Specify the state prior to the test execution. Multiple invocations don't override the state but extend it instead. In general, the elements of `state_definitions` are nested dictionaries of the following form: .. code-block:: python { address: { "nonce": <account nonc...
def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None: """ Specify the state prior to the test execution. Multiple invocations don't override the state but extend it instead. In general, the elements of `state_definitions` are nested dictionaries of the following form: .. code-bl...
Specify the expected result for the test. For state tests, multiple expectations can be given, differing in the transaction data, gas limit, and value, in the applicable networks, and as a result also in the post state. VM tests support only a single expectation with no specified network and no transaction...
def expect(post_state: Dict[str, Any]=None, networks: Any=None, transaction: TransactionDict=None) -> Callable[..., Dict[str, Any]]: """ Specify the expected result for the test. For state tests, multiple expectations can be given, differing in the transaction data, gas limit, an...
For VM tests, specify the code that is being run as well as the current state of the EVM. State tests don't support this object. The parameter is a dictionary specifying some or all of the following keys: +--------------------+------------------------------------------------------------+ | key ...
def execution(execution: Dict[str, Any], filler: Dict[str, Any]) -> Dict[str, Any]: """ For VM tests, specify the code that is being run as well as the current state of the EVM. State tests don't support this object. The parameter is a dictionary specifying some or all of the following keys: +-----...
Load call data into memory.
def calldataload(computation: BaseComputation) -> None: """ Load call data into memory. """ start_position = computation.stack_pop(type_hint=constants.UINT256) value = computation.msg.data_as_bytes[start_position:start_position + 32] padded_value = value.ljust(32, b'\x00') normalized_value ...
Return the code hash for a given address. EIP: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1052.md
def extcodehash(computation: BaseComputation) -> None: """ Return the code hash for a given address. EIP: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1052.md """ account = force_bytes_to_address(computation.stack_pop(type_hint=constants.BYTES)) state = computation.state if state.a...
Bound the given ``value`` between ``inclusive_lower_bound`` and ``inclusive_upper_bound``.
def clamp(inclusive_lower_bound: int, inclusive_upper_bound: int, value: int) -> int: """ Bound the given ``value`` between ``inclusive_lower_bound`` and ``inclusive_upper_bound``. """ if value <= inclusive_lower_bound: return inclusive_lower_bound elif value >= inclu...
Return the integer square root of ``value``. Uses Python's decimal module to compute the square root of ``value`` with a precision of 128-bits. The value 128 is chosen since the largest square root of a 256-bit integer is a 128-bit integer.
def integer_squareroot(value: int) -> int: """ Return the integer square root of ``value``. Uses Python's decimal module to compute the square root of ``value`` with a precision of 128-bits. The value 128 is chosen since the largest square root of a 256-bit integer is a 128-bit integer. """ ...
Commit all writes inside the context, unless an exception was raised. Although this is technically an external API, it (and this whole class) is only intended to be used by AtomicDB.
def _commit_unless_raises(cls, write_target_db: BaseDB) -> Iterator['AtomicDBWriteBatch']: """ Commit all writes inside the context, unless an exception was raised. Although this is technically an external API, it (and this whole class) is only intended to be used by AtomicDB. "...
Lesser Comparison
def lt(computation: BaseComputation) -> None: """ Lesser Comparison """ left, right = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if left < right: result = 1 else: result = 0 computation.stack_push(result)
Signed Lesser Comparison
def slt(computation: BaseComputation) -> None: """ Signed Lesser Comparison """ left, right = map( unsigned_to_signed, computation.stack_pop(num_items=2, type_hint=constants.UINT256), ) if left < right: result = 1 else: result = 0 computation.stack_push(...
Not
def iszero(computation: BaseComputation) -> None: """ Not """ value = computation.stack_pop(type_hint=constants.UINT256) if value == 0: result = 1 else: result = 0 computation.stack_push(result)
Not
def not_op(computation: BaseComputation) -> None: """ Not """ value = computation.stack_pop(type_hint=constants.UINT256) result = constants.UINT_256_MAX - value computation.stack_push(result)
Bitwise And
def byte_op(computation: BaseComputation) -> None: """ Bitwise And """ position, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if position >= 32: result = 0 else: result = (value // pow(256, 31 - position)) % 256 computation.stack_push(result)
Source: django.utils.module_loading Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed.
def import_string(dotted_path: str) -> ModuleType: """ Source: django.utils.module_loading Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.'...
Run the provided object through the series of applicator functions. If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the applicators will be run on a copy of the chain and thus will not mutate the provided chain instance.
def build(obj: Any, *applicators: Callable[..., Any]) -> Any: """ Run the provided object through the series of applicator functions. If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the applicators will be run on a copy of the chain and thus will not mutate the provided chain inst...
Assign the given name to the chain class.
def name(class_name: str, chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Assign the given name to the chain class. """ return chain_class.configure(__name__=class_name)
Set the ``chain_id`` for the chain class.
def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Set the ``chain_id`` for the chain class. """ return chain_class.configure(chain_id=chain_id)
Adds the ``vm_class`` to the chain's ``vm_configuration``. .. code-block:: python from eth.chains.base import MiningChain from eth.tools.builder.chain import build, fork_at FrontierOnlyChain = build(MiningChain, fork_at(FrontierVM, 0)) # these two classes are functionally equival...
def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Adds the ``vm_class`` to the chain's ``vm_configuration``. .. code-block:: python from eth.chains.base import MiningChain from eth.tools.builder.chain import build, fork_at Fro...
Set the ``support_dao_fork`` flag to ``False`` on the :class:`~eth.vm.forks.homestead.HomesteadVM`. Requires that presence of the :class:`~eth.vm.forks.homestead.HomesteadVM` in the ``vm_configuration``
def disable_dao_fork(chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Set the ``support_dao_fork`` flag to ``False`` on the :class:`~eth.vm.forks.homestead.HomesteadVM`. Requires that presence of the :class:`~eth.vm.forks.homestead.HomesteadVM` in the ``vm_configuration`` """ homstead...
Set the block number on which the DAO fork will happen. Requires that a version of the :class:`~eth.vm.forks.homestead.HomesteadVM` is present in the chain's ``vm_configuration``
def dao_fork_at(dao_fork_block_number: BlockNumber, chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Set the block number on which the DAO fork will happen. Requires that a version of the :class:`~eth.vm.forks.homestead.HomesteadVM` is present in the chain's ``vm_configuration`` ...
Inject on demand generation of the proof of work mining seal on newly mined blocks into each of the chain's vms.
def enable_pow_mining(chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Inject on demand generation of the proof of work mining seal on newly mined blocks into each of the chain's vms. """ if not chain_class.vm_configuration: raise ValidationError("Chain class has no vm_configuration") ...
Disable the proof of work validation check for each of the chain's vms. This allows for block mining without generation of the proof of work seal. .. note:: blocks mined this way will not be importable on any chain that does not have proof of work disabled.
def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Disable the proof of work validation check for each of the chain's vms. This allows for block mining without generation of the proof of work seal. .. note:: blocks mined this way will not be importable on any chain tha...
Initialize the given chain class with the given genesis header parameters and chain state.
def genesis(chain_class: BaseChain, db: BaseAtomicDB=None, params: Dict[str, HeaderParams]=None, state: GeneralState=None) -> BaseChain: """ Initialize the given chain class with the given genesis header parameters and chain state. """ if state is None: ge...
Mine a new block on the chain. Header parameters for the new block can be overridden using keyword arguments.
def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain: """ Mine a new block on the chain. Header parameters for the new block can be overridden using keyword arguments. """ if not isinstance(chain, MiningChain): raise ValidationError('`mine_block` may only be used on MiningChain...
Variadic argument version of :func:`~eth.tools.builder.chain.mine_block`
def mine_blocks(num_blocks: int, chain: MiningChain) -> MiningChain: """ Variadic argument version of :func:`~eth.tools.builder.chain.mine_block` """ if not isinstance(chain, MiningChain): raise ValidationError('`mine_block` may only be used on MiningChain instances') for _ in range(num_bloc...
Import the provided ``block`` into the chain.
def import_block(block: BaseBlock, chain: BaseChain) -> BaseChain: """ Import the provided ``block`` into the chain. """ chain.import_block(block) return chain
Variadic argument version of :func:`~eth.tools.builder.chain.import_block`
def import_blocks(*blocks: BaseBlock) -> Callable[[BaseChain], BaseChain]: """ Variadic argument version of :func:`~eth.tools.builder.chain.import_block` """ @functools.wraps(import_blocks) def _import_blocks(chain: BaseChain) -> BaseChain: for block in blocks: chain.import_block...
Make a copy of the chain at the given state. Actions performed on the resulting chain will not affect the original chain.
def copy(chain: MiningChain) -> MiningChain: """ Make a copy of the chain at the given state. Actions performed on the resulting chain will not affect the original chain. """ if not isinstance(chain, MiningChain): raise ValidationError("`at_block_number` may only be used with 'MiningChain")...
Construct and execute multiple concurrent forks of the chain. Any number of forks may be executed. For each fork, provide an iterable of commands. Returns the resulting chain objects for each fork. .. code-block:: python chain_a, chain_b = build( mining_chain, chain...
def chain_split(*splits: Iterable[Callable[..., Any]]) -> Callable[[BaseChain], Iterable[BaseChain]]: # noqa: E501 """ Construct and execute multiple concurrent forks of the chain. Any number of forks may be executed. For each fork, provide an iterable of commands. Returns the resulting chain o...
Rewind the chain back to the given block number. Calls to things like ``get_canonical_head`` will still return the canonical head of the chain, however, you can use ``mine_block`` to mine fork chains.
def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain: """ Rewind the chain back to the given block number. Calls to things like ``get_canonical_head`` will still return the canonical head of the chain, however, you can use ``mine_block`` to mine fork chains. """ if ...
Finds all of the (fixture_path, fixture_key) pairs for a given path under the JSON test fixtures directory.
def find_fixtures(fixtures_base_dir: str) -> Iterable[Tuple[str, str]]: """ Finds all of the (fixture_path, fixture_key) pairs for a given path under the JSON test fixtures directory. """ all_fixture_paths = find_fixture_files(fixtures_base_dir) for fixture_path in sorted(all_fixture_paths): ...
Loads a fixture file, caching the most recent files it loaded.
def load_json_fixture(fixture_path: str) -> Dict[str, Any]: """ Loads a fixture file, caching the most recent files it loaded. """ with open(fixture_path) as fixture_file: file_fixtures = json.load(fixture_file) return file_fixtures
Loads a specific fixture from a fixture file, optionally passing it through a normalization function.
def load_fixture(fixture_path: str, fixture_key: str, normalize_fn: Callable[..., Any]=identity) -> Dict[str, Any]: """ Loads a specific fixture from a fixture file, optionally passing it through a normalization function. """ file_fixtures = load_json_fixture(fixtur...
Helper function for filtering test fixtures. - `fixtures_base_dir` should be the base directory that the fixtures were collected from. - `mark_fn` should be a function which either returns `None` or a `pytest.mark` object. - `ignore_fn` should be a function which returns `True` for any fixture which...
def filter_fixtures(all_fixtures: Iterable[Any], fixtures_base_dir: str, mark_fn: Callable[[str, str], bool]=None, ignore_fn: Callable[..., bool]=None) -> Any: """ Helper function for filtering test fixtures. - `fixtures_base_dir` should be the ba...
:return: (premined_block, mined_block, rlp_encoded_mined_block)
def apply_fixture_block_to_chain( block_fixture: Dict[str, Any], chain: BaseChain, perform_validation: bool=True) -> Tuple[BaseBlock, BaseBlock, BaseBlock]: """ :return: (premined_block, mined_block, rlp_encoded_mined_block) """ # The block to import may be in a different block-c...
Constructs the EVM runtime identifier string e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5'
def construct_evm_runtime_identifier() -> str: """ Constructs the EVM runtime identifier string e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5' """ return "Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}".format( __version__, platform=sys.platform, v=sys.version_...
Run the transaction with various gas limits, progressively approaching the minimum needed to succeed without an OutOfGas exception. The starting range of possible estimates is: [transaction.intrinsic_gas, state.gas_limit]. After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, sta...
def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int: """ Run the transaction with various gas limits, progressively approaching the minimum needed to succeed without an OutOfGas exception. The starting range of possible estimates is: [transaction.intrinsic...
Trying to commit changes when nothing has been written will raise a ValidationError
def commit_to(self, db: BaseDB) -> None: """ Trying to commit changes when nothing has been written will raise a ValidationError """ self.logger.debug2('persist storage root to data store') if self._trie_nodes_batch is None: raise ValidationError( ...
Will raise an exception if there are some changes made since the last persist.
def _validate_flushed(self) -> None: """ Will raise an exception if there are some changes made since the last persist. """ journal_diff = self._journal_storage.diff() if len(journal_diff) > 0: raise ValidationError( "StorageDB had a dirty journal when...
Return a view into the memory
def read(self, start_position: int, size: int) -> memoryview: """ Return a view into the memory """ return memoryview(self._bytes)[start_position:start_position + size]
Write `value` into memory.
def write(self, start_position: int, size: int, value: bytes) -> None: """ Write `value` into memory. """ if size: validate_uint256(start_position) validate_uint256(size) validate_is_bytes(value) validate_length(value, length=size) ...
Read a value from memory and return a fresh bytes instance
def read_bytes(self, start_position: int, size: int) -> bytes: """ Read a value from memory and return a fresh bytes instance """ return bytes(self._bytes[start_position:start_position + size])
Extend the size of the memory to be at minimum ``start_position + size`` bytes in length. Raise `eth.exceptions.OutOfGas` if there is not enough gas to pay for extending the memory.
def extend_memory(self, start_position: int, size: int) -> None: """ Extend the size of the memory to be at minimum ``start_position + size`` bytes in length. Raise `eth.exceptions.OutOfGas` if there is not enough gas to pay for extending the memory. """ validate_uint256...
Write ``value`` to memory at ``start_position``. Require that ``len(value) == size``.
def memory_write(self, start_position: int, size: int, value: bytes) -> None: """ Write ``value`` to memory at ``start_position``. Require that ``len(value) == size``. """ return self._memory.write(start_position, size, value)
Read and return a view of ``size`` bytes from memory starting at ``start_position``.
def memory_read(self, start_position: int, size: int) -> memoryview: """ Read and return a view of ``size`` bytes from memory starting at ``start_position``. """ return self._memory.read(start_position, size)
Read and return ``size`` bytes from memory starting at ``start_position``.
def memory_read_bytes(self, start_position: int, size: int) -> bytes: """ Read and return ``size`` bytes from memory starting at ``start_position``. """ return self._memory.read_bytes(start_position, size)
Consume ``amount`` of gas from the remaining gas. Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining.
def consume_gas(self, amount: int, reason: str) -> None: """ Consume ``amount`` of gas from the remaining gas. Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining. """ return self._gas_meter.consume_gas(amount, reason)
Pop and return a number of items equal to ``num_items`` from the stack. ``type_hint`` can be either ``'uint256'`` or ``'bytes'``. The return value will be an ``int`` or ``bytes`` type depending on the value provided for the ``type_hint``. Raise `eth.exceptions.InsufficientStack` if the...
def stack_pop(self, num_items: int=1, type_hint: str=None) -> Any: # TODO: Needs to be replaced with # `Union[int, bytes, Tuple[Union[int, bytes], ...]]` if done properly """ Pop and return a number of items equal to ``num_items`` from the stack. ``type_hint`` can be either ``'ui...
Push ``value`` onto the stack. Raise `eth.exceptions.StackDepthLimit` if the stack is full.
def stack_push(self, value: Union[int, bytes]) -> None: """ Push ``value`` onto the stack. Raise `eth.exceptions.StackDepthLimit` if the stack is full. """ return self._stack.push(value)
Helper method for creating a child computation.
def prepare_child_message(self, gas: int, to: Address, value: int, data: BytesOrView, code: bytes, **kwargs: Any) -> Message: """ ...
Apply the vm message ``child_msg`` as a child computation.
def apply_child_computation(self, child_msg: Message) -> 'BaseComputation': """ Apply the vm message ``child_msg`` as a child computation. """ child_computation = self.generate_child_computation(child_msg) self.add_child_computation(child_computation) return child_computa...
Return the log entries for this computation and its children. They are sorted in the same order they were emitted during the transaction processing, and include the sequential counter as the first element of the tuple representing every entry.
def _get_log_entries(self) -> List[Tuple[int, bytes, List[int], bytes]]: """ Return the log entries for this computation and its children. They are sorted in the same order they were emitted during the transaction processing, and include the sequential counter as the first element of th...
Perform the computation that would be triggered by the VM message.
def apply_computation(cls, state: BaseState, message: Message, transaction_context: BaseTransactionContext) -> 'BaseComputation': """ Perform the computation that would be triggered by the VM message. """ with ...
Computes the difficulty for a homestead block based on the parent block.
def compute_homestead_difficulty(parent_header: BlockHeader, timestamp: int) -> int: """ Computes the difficulty for a homestead block based on the parent block. """ parent_tstamp = parent_header.timestamp validate_gt(timestamp, parent_tstamp, title="Header.timestamp") offset = parent_header.dif...
Return the :class:`~eth.db.account.BaseAccountDB` class that the state class uses.
def get_account_db_class(cls) -> Type[BaseAccountDB]: """ Return the :class:`~eth.db.account.BaseAccountDB` class that the state class uses. """ if cls.account_db_class is None: raise AttributeError("No account_db_class set for {0}".format(cls.__name__)) retur...
Perform a full snapshot of the current state. Snapshots are a combination of the :attr:`~state_root` at the time of the snapshot and the id of the changeset from the journaled DB.
def snapshot(self) -> Tuple[Hash32, UUID]: """ Perform a full snapshot of the current state. Snapshots are a combination of the :attr:`~state_root` at the time of the snapshot and the id of the changeset from the journaled DB. """ return self.state_root, self._account_db...
Revert the VM to the state at the snapshot
def revert(self, snapshot: Tuple[Hash32, UUID]) -> None: """ Revert the VM to the state at the snapshot """ state_root, account_snapshot = snapshot # first revert the database state root. self._account_db.state_root = state_root # now roll the underlying database...
Commit the journal to the point where the snapshot was taken. This will merge in any changesets that were recorded *after* the snapshot changeset.
def commit(self, snapshot: Tuple[Hash32, UUID]) -> None: """ Commit the journal to the point where the snapshot was taken. This will merge in any changesets that were recorded *after* the snapshot changeset. """ _, account_snapshot = snapshot self._account_db.commit(acco...
Return the hash for the ancestor block with number ``block_number``. Return the empty bytestring ``b''`` if the block number is outside of the range of available block numbers (typically the last 255 blocks).
def get_ancestor_hash(self, block_number: int) -> Hash32: """ Return the hash for the ancestor block with number ``block_number``. Return the empty bytestring ``b''`` if the block number is outside of the range of available block numbers (typically the last 255 blocks). """ ...
Return a computation instance for the given `message` and `transaction_context`
def get_computation(self, message: Message, transaction_context: 'BaseTransactionContext') -> 'BaseComputation': """ Return a computation instance for the given `message` and `transaction_context` """ if self.computation_class is None: ...
Apply transaction to the vm state :param transaction: the transaction to apply :return: the computation
def apply_transaction( self, transaction: BaseOrSpoofTransaction) -> 'BaseComputation': """ Apply transaction to the vm state :param transaction: the transaction to apply :return: the computation """ if self.state_root != BLANK_ROOT_HASH and not s...
Core function for extracting the environment variable. Enforces mutual exclusivity between `required` and `default` keywords. The `empty` sentinal value is used as the default `default` value to allow other function to handle default/empty logic in the appropriate way.
def get_env_value(name: str, required: bool=False, default: Any=empty) -> str: """ Core function for extracting the environment variable. Enforces mutual exclusivity between `required` and `default` keywords. The `empty` sentinal value is used as the default `default` value to allow other function...
Pulls an environment variable out of the environment and casts it to an integer. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if the environment value is not castable to an integer, a ``ValueError`` will be raised. :param...
def env_int(name: str, required: bool=False, default: Union[Type[empty], int]=empty) -> int: """Pulls an environment variable out of the environment and casts it to an integer. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if the ...
Pulls an environment variable out of the environment and casts it to an float. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if the environment value is not castable to an float, a ``ValueError`` will be raised. :param nam...
def env_float(name: str, required: bool=False, default: Union[Type[empty], float]=empty) -> float: """Pulls an environment variable out of the environment and casts it to an float. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if t...
Pulls an environment variable out of the environment returning it as a boolean. The strings ``'True'`` and ``'true'`` are the default *truthy* values. If not present in the environment and no default is specified, ``None`` is returned. :param name: The name of the environment variable be pulled :ty...
def env_bool(name: str, truthy_values: Iterable[Any]=TRUE_VALUES, required: bool=False, default: Union[Type[empty], bool]=empty) -> bool: """Pulls an environment variable out of the environment returning it as a boolean. The strings ``'True'`` and ``'true'`` are the defaul...
Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable i...
def env_string(name: str, required: bool=False, default: Union[Type[empty], str]=empty) -> str: """Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the envi...