diff --git a/boa/environment.py b/boa/environment.py index a0ab6ce8..c90e479f 100644 --- a/boa/environment.py +++ b/boa/environment.py @@ -3,6 +3,7 @@ import contextlib import logging +import random import sys import warnings from typing import Any, Iterator, Optional, Union @@ -258,7 +259,7 @@ def __call__(self, computation): # wrapper class around py-evm which provides a "contract-centric" API class Env: _singleton = None - _initial_address_counter = 100 + _random = random.Random("titanoboa") # something reproducible _coverage_enabled = False def __init__(self): @@ -266,8 +267,6 @@ def __init__(self): self._gas_price = None - self._address_counter = self.__class__._initial_address_counter - self._aliases = {} # TODO differentiate between origin and sender @@ -286,6 +285,9 @@ def __init__(self): self._init_vm() + def set_random_seed(self, seed=None): + self._random = random.Random(seed) + def get_gas_price(self): return self._gas_price or 0 @@ -460,8 +462,7 @@ def get_singleton(cls): return cls._singleton def generate_address(self, alias: Optional[str] = None) -> AddressType: - self._address_counter += 1 - t = self._address_counter.to_bytes(length=20, byteorder="big") + t = self._random.randbytes(20) # checksum addr easier for humans to debug ret = to_checksum_address(t) if alias is not None: diff --git a/boa/vm/fork.py b/boa/vm/fork.py index 3a692359..3da9e15c 100644 --- a/boa/vm/fork.py +++ b/boa/vm/fork.py @@ -36,6 +36,7 @@ def __init__(self, url: str, cache_file: str = DEFAULT_CACHE_DIR): # LevelDB has been removed from py-evm 0.8.1 onwards from eth.db.backends.level import LevelDB from eth.db.cache import CacheDB + cache_file = os.path.expanduser(cache_file) # use CacheDB as an additional layer over disk # (ideally would use leveldb lru cache but it's not configurable diff --git a/docs/source/api.rst b/docs/source/api.rst index 2fbce0dc..6fac31e3 100644 --- a/docs/source/api.rst +++ b/docs/source/api.rst @@ -357,7 +357,22 @@ Low-Level Functionality >>> import boa >>> boa.env.generate_address() - '0x0000000000000000000000000000000000000066' + '0xd13f0Bd22AFF8176761AEFBfC052a7490bDe268E' + + .. method:: set_random_seed(seed: Any = None) -> None + + Set the random seed used by this ``Env`` to generate addresses. Useful in case you want to introduce some more randomization to how ``Env`` generates addresses. + + :param seed: The seed to pass to this ``Env``'s instance of ``random.Random``. Can be any value that ``random.Random()`` accepts. + + .. rubric:: Example + + .. code-block:: python + + >>> import boa + >>> boa.env.set_random_seed(100) + >>> boa.env.generate_address() + '0x93944a25b3ADa3759918767471C5A3F3601652c5 .. method:: set_balance(address: str, value: int)