-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathutils.py
214 lines (161 loc) · 5.63 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import copy
import datetime
import functools
from typing import (
TYPE_CHECKING,
Any,
Callable,
Collection,
Optional,
Type,
TypeVar,
Union,
cast,
)
from eth_typing import (
Address,
ChecksumAddress,
HexAddress,
HexStr,
)
from eth_utils import (
is_same_address,
remove_0x_prefix,
to_normalized_address,
)
from hexbytes import (
HexBytes,
)
import idna
from ens.constants import (
ACCEPTABLE_STALE_HOURS,
AUCTION_START_GAS_CONSTANT,
AUCTION_START_GAS_MARGINAL,
EMPTY_ADDR_HEX,
EMPTY_SHA3_BYTES,
REVERSE_REGISTRAR_DOMAIN,
)
from ens.exceptions import (
InvalidName,
)
default = object()
if TYPE_CHECKING:
from web3 import Web3 as _Web3 # noqa: F401
from web3.providers import ( # noqa: F401
BaseProvider,
)
def Web3() -> Type['_Web3']:
from web3 import Web3 as Web3Main
return Web3Main
TFunc = TypeVar("TFunc", bound=Callable[..., Any])
def dict_copy(func: TFunc) -> TFunc:
"copy dict keyword args, to avoid modifying caller's copy"
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> TFunc:
copied_kwargs = copy.deepcopy(kwargs)
return func(*args, **copied_kwargs)
return cast(TFunc, wrapper)
def ensure_hex(data: HexBytes) -> HexBytes:
if not isinstance(data, str):
return Web3().toHex(data)
return data
def init_web3(provider: 'BaseProvider'=cast('BaseProvider', default)) -> '_Web3':
from web3 import Web3 as Web3Main
if provider is default:
w3 = Web3Main(ens=None)
else:
w3 = Web3Main(provider, ens=None)
return customize_web3(w3)
def customize_web3(w3: '_Web3') -> '_Web3':
from web3.middleware import make_stalecheck_middleware
w3.middleware_onion.remove('name_to_address')
w3.middleware_onion.add(
make_stalecheck_middleware(ACCEPTABLE_STALE_HOURS * 3600),
name='stalecheck',
)
return w3
def normalize_name(name: str) -> str:
"""
Clean the fully qualified name, as defined in ENS `EIP-137
<https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_
This does *not* enforce whether ``name`` is a label or fully qualified domain.
:param str name: the dot-separated ENS name
:raises InvalidName: if ``name`` has invalid syntax
"""
if not name:
return name
elif isinstance(name, (bytes, bytearray)):
name = name.decode('utf-8')
try:
return idna.uts46_remap(name, std3_rules=True)
except idna.IDNAError as exc:
raise InvalidName(f"{name} is an invalid name, because {exc}") from exc
def is_valid_name(name: str) -> bool:
"""
Validate whether the fully qualified name is valid, as defined in ENS `EIP-137
<https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_
:param str name: the dot-separated ENS name
:returns: True if ``name`` is set, and :meth:`~ens.main.ENS.nameprep` will not raise InvalidName
"""
if not name:
return False
try:
normalize_name(name)
return True
except InvalidName:
return False
def to_utc_datetime(timestamp: float) -> Optional[datetime.datetime]:
if timestamp:
return datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc)
else:
return None
def sha3_text(val: Union[str, bytes]) -> HexBytes:
if isinstance(val, str):
val = val.encode('utf-8')
return Web3().keccak(val)
def label_to_hash(label: str) -> HexBytes:
label = normalize_name(label)
if '.' in label:
raise ValueError("Cannot generate hash for label %r with a '.'" % label)
return Web3().keccak(text=label)
def normal_name_to_hash(name: str) -> HexBytes:
node = EMPTY_SHA3_BYTES
if name:
labels = name.split(".")
for label in reversed(labels):
labelhash = label_to_hash(label)
assert isinstance(labelhash, bytes)
assert isinstance(node, bytes)
node = Web3().keccak(node + labelhash)
return node
def raw_name_to_hash(name: str) -> HexBytes:
"""
Generate the namehash. This is also known as the ``node`` in ENS contracts.
In normal operation, generating the namehash is handled
behind the scenes. For advanced usage, it is a helpful utility.
This normalizes the name with `nameprep
<https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_
before hashing.
:param str name: ENS name to hash
:return: the namehash
:rtype: bytes
:raises InvalidName: if ``name`` has invalid syntax
"""
normalized_name = normalize_name(name)
return normal_name_to_hash(normalized_name)
def address_in(address: ChecksumAddress, addresses: Collection[ChecksumAddress]) -> bool:
return any(is_same_address(address, item) for item in addresses)
def address_to_reverse_domain(address: ChecksumAddress) -> str:
lower_unprefixed_address = remove_0x_prefix(HexStr(to_normalized_address(address)))
return lower_unprefixed_address + '.' + REVERSE_REGISTRAR_DOMAIN
def estimate_auction_start_gas(labels: Collection[str]) -> int:
return AUCTION_START_GAS_CONSTANT + AUCTION_START_GAS_MARGINAL * len(labels)
def assert_signer_in_modifier_kwargs(modifier_kwargs: Any) -> ChecksumAddress:
ERR_MSG = "You must specify the sending account"
assert len(modifier_kwargs) == 1, ERR_MSG
_modifier_type, modifier_dict = dict(modifier_kwargs).popitem()
if 'from' not in modifier_dict:
raise TypeError(ERR_MSG)
return modifier_dict['from']
def is_none_or_zero_address(addr: Union[Address, ChecksumAddress, HexAddress]) -> bool:
return not addr or addr == EMPTY_ADDR_HEX