web3 7.1.0__py3-none-any.whl → 7.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
web3/_utils/http.py CHANGED
@@ -1,9 +1,12 @@
1
1
  DEFAULT_HTTP_TIMEOUT = 30.0
2
2
 
3
3
 
4
- def construct_user_agent(class_type: type) -> str:
4
+ def construct_user_agent(
5
+ module: str,
6
+ class_name: str,
7
+ ) -> str:
5
8
  from web3 import (
6
9
  __version__ as web3_version,
7
10
  )
8
11
 
9
- return f"web3.py/{web3_version}/{class_type.__module__}.{class_type.__qualname__}"
12
+ return f"web3.py/{web3_version}/{module}.{class_name}"
@@ -88,6 +88,7 @@ from web3.exceptions import (
88
88
  )
89
89
  from web3.middleware import (
90
90
  ExtraDataToPOAMiddleware,
91
+ SignAndSendRawMiddlewareBuilder,
91
92
  )
92
93
  from web3.types import (
93
94
  ENS,
@@ -725,6 +726,26 @@ class AsyncEthModuleTest:
725
726
  txn_hash = await async_w3.eth.send_raw_transaction(signed.raw_transaction)
726
727
  assert txn_hash == HexBytes(signed.hash)
727
728
 
729
+ @pytest.mark.asyncio
730
+ async def test_async_sign_and_send_raw_middleware(
731
+ self, async_w3: "AsyncWeb3", keyfile_account_pkey: HexStr
732
+ ) -> None:
733
+ keyfile_account = async_w3.eth.account.from_key(keyfile_account_pkey)
734
+ txn: TxParams = {
735
+ "from": keyfile_account.address,
736
+ "to": keyfile_account.address,
737
+ "value": Wei(0),
738
+ "gas": 21000,
739
+ }
740
+ async_w3.middleware_onion.add(
741
+ SignAndSendRawMiddlewareBuilder.build(keyfile_account), "signing"
742
+ )
743
+ txn_hash = await async_w3.eth.send_transaction(txn)
744
+ assert isinstance(txn_hash, HexBytes)
745
+
746
+ # clean up
747
+ async_w3.middleware_onion.remove("signing")
748
+
728
749
  @pytest.mark.asyncio
729
750
  async def test_GasPriceStrategyMiddleware(
730
751
  self,
@@ -3716,6 +3737,25 @@ class EthModuleTest:
3716
3737
  txn_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
3717
3738
  assert txn_hash == HexBytes(signed.hash)
3718
3739
 
3740
+ def test_sign_and_send_raw_middleware(
3741
+ self, w3: "Web3", keyfile_account_pkey: HexStr
3742
+ ) -> None:
3743
+ keyfile_account = w3.eth.account.from_key(keyfile_account_pkey)
3744
+ txn: TxParams = {
3745
+ "from": keyfile_account.address,
3746
+ "to": keyfile_account.address,
3747
+ "value": Wei(0),
3748
+ "gas": 21000,
3749
+ }
3750
+ w3.middleware_onion.add(
3751
+ SignAndSendRawMiddlewareBuilder.build(keyfile_account), "signing"
3752
+ )
3753
+ txn_hash = w3.eth.send_transaction(txn)
3754
+ assert isinstance(txn_hash, HexBytes)
3755
+
3756
+ # cleanup
3757
+ w3.middleware_onion.remove("signing")
3758
+
3719
3759
  def test_eth_call(self, w3: "Web3", math_contract: "Contract") -> None:
3720
3760
  txn_params = math_contract._prepare_transaction(
3721
3761
  abi_element_identifier="add",
@@ -189,7 +189,7 @@ class SignAndSendRawMiddlewareBuilder(Web3MiddlewareBuilder):
189
189
 
190
190
  return (
191
191
  RPCEndpoint("eth_sendRawTransaction"),
192
- [raw_tx.hex()],
192
+ [raw_tx.to_0x_hex()],
193
193
  )
194
194
 
195
195
  # -- async -- #
@@ -220,5 +220,5 @@ class SignAndSendRawMiddlewareBuilder(Web3MiddlewareBuilder):
220
220
 
221
221
  return (
222
222
  RPCEndpoint("eth_sendRawTransaction"),
223
- [raw_tx.hex()],
223
+ [raw_tx.to_0x_hex()],
224
224
  )
@@ -19,6 +19,7 @@ from eth_typing import (
19
19
  URI,
20
20
  )
21
21
  from eth_utils import (
22
+ combomethod,
22
23
  to_dict,
23
24
  )
24
25
 
@@ -108,10 +109,17 @@ class AsyncHTTPProvider(AsyncJSONBaseProvider):
108
109
  yield "headers", self.get_request_headers()
109
110
  yield from self._request_kwargs.items()
110
111
 
111
- def get_request_headers(self) -> Dict[str, str]:
112
+ @combomethod
113
+ def get_request_headers(cls) -> Dict[str, str]:
114
+ if isinstance(cls, AsyncHTTPProvider):
115
+ cls_name = cls.__class__.__name__
116
+ else:
117
+ cls_name = cls.__name__
118
+ module = cls.__module__
119
+
112
120
  return {
113
121
  "Content-Type": "application/json",
114
- "User-Agent": construct_user_agent(type(self)),
122
+ "User-Agent": construct_user_agent(module, cls_name),
115
123
  }
116
124
 
117
125
  async def _make_request(self, method: RPCEndpoint, request_data: bytes) -> bytes:
web3/providers/rpc/rpc.py CHANGED
@@ -16,6 +16,7 @@ from eth_typing import (
16
16
  URI,
17
17
  )
18
18
  from eth_utils import (
19
+ combomethod,
19
20
  to_dict,
20
21
  )
21
22
  import requests
@@ -116,10 +117,18 @@ class HTTPProvider(JSONBaseProvider):
116
117
  yield "headers", self.get_request_headers()
117
118
  yield from self._request_kwargs.items()
118
119
 
119
- def get_request_headers(self) -> Dict[str, str]:
120
+ @combomethod
121
+ def get_request_headers(cls) -> Dict[str, str]:
122
+ if isinstance(cls, HTTPProvider):
123
+ cls_name = cls.__class__.__name__
124
+ else:
125
+ cls_name = cls.__name__
126
+
127
+ module = cls.__module__
128
+
120
129
  return {
121
130
  "Content-Type": "application/json",
122
- "User-Agent": construct_user_agent(type(self)),
131
+ "User-Agent": construct_user_agent(module, cls_name),
123
132
  }
124
133
 
125
134
  def _make_request(self, method: RPCEndpoint, request_data: bytes) -> bytes:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: web3
3
- Version: 7.1.0
3
+ Version: 7.2.0
4
4
  Summary: web3: A Python library for interacting with Ethereum
5
5
  Home-page: https://github.com/ethereum/web3.py
6
6
  Author: The Ethereum Foundation
@@ -45,7 +45,7 @@ web3/_utils/events.py,sha256=sVAXWUMmWKwYguWzk_jqra3rI6NZ55T3XfDp4_aDa-8,17044
45
45
  web3/_utils/fee_utils.py,sha256=MFt27R9E3qFP-Hf87-Lzv0JAiuYRE_qqafyTmzctAYA,2145
46
46
  web3/_utils/filters.py,sha256=1WX2Vgmat8QKj0WNm_GoRcVp4iJ0BhaIpM_RbcZlBzs,11860
47
47
  web3/_utils/formatters.py,sha256=RfRZU0aXC99s6OoLMY7D-fcYJyVAYBEwdbw-JIDjbZE,3067
48
- web3/_utils/http.py,sha256=NNcbf_K814Ggpt0YiGTWjV3CCUrLkpZpQDru4f-3C9E,235
48
+ web3/_utils/http.py,sha256=2R3UOeZmwiQGc3ladf78R9AnufbGaTXAntqf-ZQlZPI,230
49
49
  web3/_utils/http_session_manager.py,sha256=Q5K9qJVOAjpO6490McC5kdO4lgjt-c-zxkp0kyDY2pI,11520
50
50
  web3/_utils/hypothesis.py,sha256=4Cm4iOWv-uP9irg_Pv63kYNDYUAGhnUH6fOPWRw3A0g,209
51
51
  web3/_utils/math.py,sha256=4oU5YdbQBXElxK00CxmUZ94ApXFu9QT_TrO0Kho1HTs,1083
@@ -86,7 +86,7 @@ web3/_utils/contract_sources/contract_data/storage_contract.py,sha256=vP1Qaekjld
86
86
  web3/_utils/contract_sources/contract_data/string_contract.py,sha256=y6EFnum4zDrrRUmuXExCGr2bhZMrerbMiqJiamUU2Tw,11210
87
87
  web3/_utils/contract_sources/contract_data/tuple_contracts.py,sha256=QuqPfv3BxjqDjeLScnxJDEPtPZMAB4jwHxsAOeVd6kk,23176
88
88
  web3/_utils/module_testing/__init__.py,sha256=tPFAaX7xOR50CPTq24UeY-1CX1LQxxmEOPr0-tIRkoE,376
89
- web3/_utils/module_testing/eth_module.py,sha256=gX-7yDry-fcz1UtOI3_DQQKFSnwrA1dKuBaEJTGdjrE,186255
89
+ web3/_utils/module_testing/eth_module.py,sha256=0Ke5-Ayh2MJuzT8-zL3jlUy4WbHvE7nYi2fBM__FcmM,187661
90
90
  web3/_utils/module_testing/go_ethereum_admin_module.py,sha256=_c-6SyzZkfAJ-7ySXUpw9FEr4cg-ShRdAGSAHWanCtY,3406
91
91
  web3/_utils/module_testing/go_ethereum_txpool_module.py,sha256=5f8XL8-2x3keyGRaITxMQYl9oQzjgqGn8zobB-j9BPs,1176
92
92
  web3/_utils/module_testing/module_testing_utils.py,sha256=koDvLoR5q8wFOz_8o9oRpEpjbuvU8cUbBe1PM39LjG0,7304
@@ -122,7 +122,7 @@ web3/middleware/gas_price_strategy.py,sha256=ZjZ6pe3z0mDGLZHYoFXp4_fZIePqukljEh9
122
122
  web3/middleware/names.py,sha256=OBpsvCmcTItth4TcvUNUvcYmINnudtCHq3n6YO_BkNs,4309
123
123
  web3/middleware/proof_of_authority.py,sha256=0AT4jr5CmTdrvl8Jiy-WYy8IFDYBOEaesgHDwpn0c7M,1429
124
124
  web3/middleware/pythonic.py,sha256=awc8I6lLzVc2Iv138sps2uf6dMQipskLRBTdvTEEIgQ,348
125
- web3/middleware/signing.py,sha256=O5kOY6xcCjms7W57H53nYJ22N47TZrO-hnd3Lx2ThHs,5887
125
+ web3/middleware/signing.py,sha256=1DOYxpmCra-Qq5r42237q3b54uDO-QHjMVMulxVpLVQ,5899
126
126
  web3/middleware/stalecheck.py,sha256=oWRA69BGIbNGjHSnUVOBnoxOYJZYjzRzlqqL5RRlnzk,2680
127
127
  web3/middleware/validation.py,sha256=QxActrJk_zsXXiwpadP2MUjZBS5E50OJOtUwVrm9XVo,4280
128
128
  web3/providers/__init__.py,sha256=YkcSzE9AubvSp-UfvJjyCrdepvziysbqeq2LT0ImDoc,936
@@ -143,27 +143,22 @@ web3/providers/persistent/request_processor.py,sha256=E1jJwsvrPBTbufCy2LeNvMdRXf
143
143
  web3/providers/persistent/utils.py,sha256=gfY7w1HB8xuE7OujSrbwWYjQuQ8nzRBoxoL8ESinqWM,1140
144
144
  web3/providers/persistent/websocket.py,sha256=2EuBOdkEBTp6ge53UlJbjV0eAUJ143TkmqrOLTQl9kk,4231
145
145
  web3/providers/rpc/__init__.py,sha256=mObsuwjr7xyHnnRlwzsmbp2JgZdn2NXSSctvpye4AuQ,149
146
- web3/providers/rpc/async_rpc.py,sha256=hibsCoyrAD199ExAEyHRsEnZ0_rDP_2EC2k5g-D2zhw,5609
147
- web3/providers/rpc/rpc.py,sha256=ePlGdlkvQTaf2Wi2khxiY-rRj-OFcPlpDMuTPLKaAyU,5655
146
+ web3/providers/rpc/async_rpc.py,sha256=fRZh36q735OI7HFt_QsueFC4zgSSkm3MsYMh9C4b3ds,5824
147
+ web3/providers/rpc/rpc.py,sha256=9_ju2UZX3Ew2HhmyRWnXGhRW9NTvW0roFQ9BI2JzuI0,5866
148
148
  web3/providers/rpc/utils.py,sha256=_mtoZMMIoZpPA8J8U5DfRxaNQmi8bw0ZVUiqn1Nz4co,2154
149
149
  web3/scripts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
150
150
  web3/scripts/install_pre_releases.py,sha256=uVxsZk239640yxiqlPhfXxZKSsh3858pURKppi9kM5U,821
151
151
  web3/scripts/parse_pygeth_version.py,sha256=BZjWOsJmYuFbAnFuB1jec9Rl6z0tJJNFFV38sJvDfGo,416
152
152
  web3/scripts/release/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
153
153
  web3/scripts/release/test_package.py,sha256=DH0AryllcF4zfpWSd0NLPSQGHNoC-Qng5WYYbS5_4c8,1534
154
- web3/tools/benchmark/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
155
- web3/tools/benchmark/main.py,sha256=9nBC8yvdiNPoRuNlcqKC6HKWly_iwOYSeG0cOQCjfpg,5810
156
- web3/tools/benchmark/node.py,sha256=n73GckmBKLm4_urC7HfF_Z3ZURffNMjq6ymzb9HM9c8,3252
157
- web3/tools/benchmark/reporting.py,sha256=G2bj_Eo2kBV06GARDYK9zr0VqesiR0_5JLKvhAo6zRM,912
158
- web3/tools/benchmark/utils.py,sha256=7OOdUD71AVWi0cowAE9ekMgqlfcJwk3vrNnMCHtiGdU,1696
159
154
  web3/utils/__init__.py,sha256=XwpyVR4EBkfqV5SHBH3maNyNBy624EwqujRgetLc7PU,1781
160
155
  web3/utils/abi.py,sha256=iSBaCW41UxB1q1UHDPwJ1QJbdiuYmTWNu8m6E28DqlY,18672
161
156
  web3/utils/address.py,sha256=KC_IpEbixSCuMhaW6V2QCyyJTYKYGS9c8QtI9_aH7zQ,967
162
157
  web3/utils/async_exception_handling.py,sha256=GZWSBFC0-Wmwz1tpTie-1AKRbIQH7JkmBpf5bXrUTzY,3320
163
158
  web3/utils/caching.py,sha256=IG_IxW-jyiRklrIyUgjOj3GQvcXrok0KLDX3ch_6wuA,2390
164
159
  web3/utils/exception_handling.py,sha256=k31JROfUyKIm9PoEWOtYSkIq9wL8SOBwQfnSLNQyfnM,3097
165
- web3-7.1.0.dist-info/LICENSE,sha256=ScEyLx1vWrB0ybKiZKKTXm5QhVksHCEUtTp4lwYV45I,1095
166
- web3-7.1.0.dist-info/METADATA,sha256=p_1iA6mObqMRYbT9SN-0xI9fr_Wh-AN6-fZcOknn1BU,4986
167
- web3-7.1.0.dist-info/WHEEL,sha256=UvcQYKBHoFqaQd6LKyqHw9fxEolWLQnlzP0h_LgJAfI,91
168
- web3-7.1.0.dist-info/top_level.txt,sha256=iwupuJh7wgypXrpk_awszyri3TahRr5vxSphNyvt1bU,9
169
- web3-7.1.0.dist-info/RECORD,,
160
+ web3-7.2.0.dist-info/LICENSE,sha256=ScEyLx1vWrB0ybKiZKKTXm5QhVksHCEUtTp4lwYV45I,1095
161
+ web3-7.2.0.dist-info/METADATA,sha256=gKCHrOjfTAYhnhPMuMatLqkhL2cBlKrpnHuuPsWOaUo,4986
162
+ web3-7.2.0.dist-info/WHEEL,sha256=UvcQYKBHoFqaQd6LKyqHw9fxEolWLQnlzP0h_LgJAfI,91
163
+ web3-7.2.0.dist-info/top_level.txt,sha256=iwupuJh7wgypXrpk_awszyri3TahRr5vxSphNyvt1bU,9
164
+ web3-7.2.0.dist-info/RECORD,,
File without changes
@@ -1,190 +0,0 @@
1
- import argparse
2
- import asyncio
3
- from collections import (
4
- defaultdict,
5
- )
6
- import logging
7
- import sys
8
- import timeit
9
- from typing import (
10
- Any,
11
- Callable,
12
- Dict,
13
- Union,
14
- )
15
-
16
- from web3 import (
17
- AsyncHTTPProvider,
18
- AsyncWeb3,
19
- HTTPProvider,
20
- Web3,
21
- )
22
- from web3.middleware import (
23
- BufferedGasEstimateMiddleware,
24
- GasPriceStrategyMiddleware,
25
- )
26
- from web3.tools.benchmark.node import (
27
- GethBenchmarkFixture,
28
- )
29
- from web3.tools.benchmark.reporting import (
30
- print_entry,
31
- print_footer,
32
- print_header,
33
- )
34
- from web3.tools.benchmark.utils import (
35
- wait_for_aiohttp,
36
- wait_for_http,
37
- )
38
- from web3.types import (
39
- Wei,
40
- )
41
-
42
- KEYFILE_PW = "web3py-test"
43
-
44
- parser = argparse.ArgumentParser()
45
- parser.add_argument(
46
- "--num-calls",
47
- type=int,
48
- default=10,
49
- help="The number of RPC calls to make",
50
- )
51
-
52
- # TODO - layers to test:
53
- # contract.functions.method(...).call()
54
- # w3.eth.call(...)
55
- # HTTPProvider.make_request(...)
56
-
57
-
58
- def build_web3_http(endpoint_uri: str) -> Web3:
59
- wait_for_http(endpoint_uri)
60
- _w3 = Web3(
61
- HTTPProvider(endpoint_uri),
62
- middleware=[GasPriceStrategyMiddleware, BufferedGasEstimateMiddleware],
63
- )
64
- return _w3
65
-
66
-
67
- async def build_async_w3_http(endpoint_uri: str) -> AsyncWeb3:
68
- await wait_for_aiohttp(endpoint_uri)
69
- _w3 = AsyncWeb3(
70
- AsyncHTTPProvider(endpoint_uri),
71
- middleware=[GasPriceStrategyMiddleware, BufferedGasEstimateMiddleware],
72
- )
73
- return _w3
74
-
75
-
76
- def sync_benchmark(func: Callable[..., Any], n: int) -> Union[float, str]:
77
- try:
78
- starttime = timeit.default_timer()
79
- for _ in range(n):
80
- func()
81
- endtime = timeit.default_timer()
82
- execution_time = endtime - starttime
83
- return execution_time
84
- except Exception:
85
- return "N/A"
86
-
87
-
88
- async def async_benchmark(func: Callable[..., Any], n: int) -> Union[float, str]:
89
- try:
90
- starttime = timeit.default_timer()
91
- for result in asyncio.as_completed([func() for _ in range(n)]):
92
- await result
93
- execution_time = timeit.default_timer() - starttime
94
- return execution_time
95
- except Exception:
96
- return "N/A"
97
-
98
-
99
- def main(logger: logging.Logger, num_calls: int) -> None:
100
- fixture = GethBenchmarkFixture()
101
- for built_fixture in fixture.build():
102
- for _ in built_fixture:
103
- w3_http = build_web3_http(fixture.endpoint_uri)
104
- try:
105
- loop = asyncio.get_running_loop()
106
- except RuntimeError:
107
- loop = asyncio.new_event_loop()
108
- asyncio.set_event_loop(loop)
109
-
110
- # -- sync -- #
111
- account = w3_http.eth.accounts[0]
112
-
113
- # -- async -- #
114
- async_w3_http = loop.run_until_complete(
115
- build_async_w3_http(fixture.endpoint_uri)
116
- )
117
- async_accounts = loop.run_until_complete(async_w3_http.eth.accounts)
118
- async_account = async_accounts[0]
119
-
120
- methods = [
121
- {
122
- "name": "eth_gasPrice",
123
- "params": {},
124
- "exec": lambda w3_http=w3_http: w3_http.eth.gas_price,
125
- "async_exec": lambda async_w3_http=async_w3_http: async_w3_http.eth.gas_price, # noqa: E501
126
- },
127
- {
128
- "name": "eth_sendTransaction",
129
- "params": {},
130
- "exec": lambda w3_http=w3_http, account=account: w3_http.eth.send_transaction( # noqa: E501
131
- {
132
- "to": "0xd3CdA913deB6f67967B99D67aCDFa1712C293601",
133
- "from": account,
134
- "value": Wei(1),
135
- }
136
- ),
137
- "async_exec": lambda async_w3_http=async_w3_http, async_account=async_account: async_w3_http.eth.send_transaction( # noqa: E501
138
- {
139
- "to": "0xd3CdA913deB6f67967B99D67aCDFa1712C293601",
140
- "from": async_account,
141
- "value": Wei(1),
142
- }
143
- ),
144
- },
145
- {
146
- "name": "eth_blockNumber",
147
- "params": {},
148
- "exec": lambda w3_http=w3_http: w3_http.eth.block_number,
149
- "async_exec": lambda async_w3_http=async_w3_http: async_w3_http.eth.block_number, # noqa: E501
150
- },
151
- {
152
- "name": "eth_getBlock",
153
- "params": {},
154
- "exec": lambda w3_http=w3_http: w3_http.eth.get_block(1),
155
- "async_exec": lambda async_w3_http=async_w3_http: async_w3_http.eth.get_block( # noqa: E501
156
- 1
157
- ),
158
- },
159
- ]
160
-
161
- def benchmark(
162
- method: Dict[str, Any], loop: asyncio.AbstractEventLoop = loop
163
- ) -> None:
164
- outcomes: Dict[str, Union[str, float]] = defaultdict(lambda: "N/A")
165
- outcomes["name"] = method["name"]
166
- outcomes["HTTPProvider"] = sync_benchmark(
167
- method["exec"],
168
- num_calls,
169
- )
170
- outcomes["AsyncHTTPProvider"] = loop.run_until_complete(
171
- async_benchmark(method["async_exec"], num_calls)
172
- )
173
- print_entry(logger, outcomes)
174
-
175
- print_header(logger, num_calls)
176
-
177
- for method in methods:
178
- benchmark(method)
179
-
180
- print_footer(logger)
181
-
182
-
183
- if __name__ == "__main__":
184
- args = parser.parse_args()
185
-
186
- logger = logging.getLogger()
187
- logger.setLevel(logging.INFO)
188
- logger.addHandler(logging.StreamHandler(sys.stdout))
189
-
190
- main(logger, args.num_calls)
@@ -1,120 +0,0 @@
1
- import os
2
- import socket
3
- from subprocess import (
4
- PIPE,
5
- Popen,
6
- check_output,
7
- )
8
- from tempfile import (
9
- TemporaryDirectory,
10
- )
11
- from typing import (
12
- Any,
13
- Generator,
14
- Sequence,
15
- )
16
- import zipfile
17
-
18
- from geth.install import (
19
- get_executable_path,
20
- install_geth,
21
- )
22
-
23
- from web3.tools.benchmark.utils import (
24
- kill_proc_gracefully,
25
- )
26
-
27
- GETH_FIXTURE_ZIP = "geth-1.14.5-fixture.zip"
28
-
29
-
30
- class GethBenchmarkFixture:
31
- def __init__(self) -> None:
32
- self.rpc_port = self._rpc_port()
33
- self.endpoint_uri = self._endpoint_uri()
34
- self.geth_binary = self._geth_binary()
35
-
36
- def build(self) -> Generator[Any, None, None]:
37
- with TemporaryDirectory() as base_dir:
38
- zipfile_path = os.path.abspath(
39
- os.path.join(
40
- os.path.dirname(__file__),
41
- "../../../tests/integration/",
42
- GETH_FIXTURE_ZIP,
43
- )
44
- )
45
- tmp_datadir = os.path.join(str(base_dir), "datadir")
46
- with zipfile.ZipFile(zipfile_path, "r") as zip_ref:
47
- zip_ref.extractall(tmp_datadir)
48
- self.datadir = tmp_datadir
49
-
50
- genesis_file = os.path.join(self.datadir, "genesis.json")
51
-
52
- yield self._geth_process(self.datadir, genesis_file, self.rpc_port)
53
-
54
- def _rpc_port(self) -> str:
55
- sock = socket.socket()
56
- sock.bind(("127.0.0.1", 0))
57
- port = sock.getsockname()[1]
58
- sock.close()
59
- return str(port)
60
-
61
- def _endpoint_uri(self) -> str:
62
- return f"http://localhost:{self.rpc_port}"
63
-
64
- def _geth_binary(self) -> str:
65
- if "GETH_BINARY" in os.environ:
66
- return os.environ["GETH_BINARY"]
67
- elif "GETH_VERSION" in os.environ:
68
- geth_version = os.environ["GETH_VERSION"]
69
- _geth_binary = get_executable_path(geth_version)
70
- if not os.path.exists(_geth_binary):
71
- install_geth(geth_version)
72
- assert os.path.exists(_geth_binary)
73
- return _geth_binary
74
- else:
75
- return "geth"
76
-
77
- def _geth_command_arguments(self, datadir: str) -> Sequence[str]:
78
- return (
79
- self.geth_binary,
80
- "--dev",
81
- "--dev.period",
82
- "100",
83
- "--datadir",
84
- datadir,
85
- "--nodiscover",
86
- "--http",
87
- "--http.port",
88
- self.rpc_port,
89
- "--http.api",
90
- "admin,eth,net,web3",
91
- "--ipcdisable",
92
- "--password",
93
- os.path.join(datadir, "keystore", "pw.txt"),
94
- )
95
-
96
- def _geth_process(
97
- self, datadir: str, genesis_file: str, rpc_port: str
98
- ) -> Generator[Any, None, None]:
99
- init_datadir_command = (
100
- self.geth_binary,
101
- "--datadir",
102
- str(datadir),
103
- "init",
104
- str(genesis_file),
105
- )
106
- check_output(
107
- init_datadir_command,
108
- stdin=PIPE,
109
- stderr=PIPE,
110
- )
111
- proc = Popen(
112
- self._geth_command_arguments(datadir),
113
- stdin=PIPE,
114
- stdout=PIPE,
115
- stderr=PIPE,
116
- )
117
- try:
118
- yield proc
119
- finally:
120
- kill_proc_gracefully(proc)
@@ -1,39 +0,0 @@
1
- from logging import (
2
- Logger,
3
- )
4
- from typing import (
5
- Any,
6
- Dict,
7
- )
8
-
9
-
10
- def print_header(logger: Logger, num_calls: int) -> None:
11
- logger.info(
12
- "|{:^26}|{:^20}|{:^20}|{:^20}|{:^20}|".format(
13
- f"Method ({num_calls} calls)",
14
- "HTTPProvider",
15
- "AsyncHTTProvider",
16
- "IPCProvider",
17
- "WebSocketProvider",
18
- )
19
- )
20
- logger.info("-" * 112)
21
-
22
-
23
- def print_entry(
24
- logger: Logger,
25
- method_benchmarks: Dict[str, Any],
26
- ) -> None:
27
- logger.info(
28
- "|{:^26}|{:^20.10}|{:^20.10}|{:^20.10}|{:^20.10}|".format(
29
- method_benchmarks["name"],
30
- method_benchmarks["HTTPProvider"],
31
- method_benchmarks["AsyncHTTPProvider"],
32
- method_benchmarks["IPCProvider"],
33
- method_benchmarks["WebSocketProvider"],
34
- )
35
- )
36
-
37
-
38
- def print_footer(logger: Logger) -> None:
39
- logger.info("-" * 112)
@@ -1,69 +0,0 @@
1
- import asyncio
2
- import signal
3
- import socket
4
- import time
5
- from typing import (
6
- Any,
7
- )
8
-
9
- import aiohttp
10
- import requests
11
-
12
-
13
- def wait_for_socket(ipc_path: str, timeout: int = 30) -> None:
14
- start = time.time()
15
- while time.time() < start + timeout:
16
- try:
17
- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
18
- sock.connect(ipc_path)
19
- sock.settimeout(timeout)
20
- except OSError:
21
- time.sleep(0.01)
22
- else:
23
- break
24
-
25
-
26
- def wait_for_http(endpoint_uri: str, timeout: int = 60) -> None:
27
- start = time.time()
28
- while time.time() < start + timeout:
29
- try:
30
- requests.get(endpoint_uri)
31
- except requests.ConnectionError:
32
- time.sleep(0.01)
33
- else:
34
- break
35
-
36
-
37
- async def wait_for_aiohttp(endpoint_uri: str, timeout: int = 60) -> None:
38
- start = time.time()
39
- while time.time() < start + timeout:
40
- try:
41
- async with aiohttp.ClientSession() as session:
42
- await session.get(endpoint_uri)
43
- except aiohttp.client_exceptions.ClientConnectorError:
44
- await asyncio.sleep(0.01)
45
- else:
46
- break
47
-
48
-
49
- def wait_for_popen(proc: Any, timeout: int) -> None:
50
- start = time.time()
51
- while time.time() < start + timeout:
52
- if proc.poll() is None:
53
- time.sleep(0.01)
54
- else:
55
- break
56
-
57
-
58
- def kill_proc_gracefully(proc: Any) -> None:
59
- if proc.poll() is None:
60
- proc.send_signal(signal.SIGINT)
61
- wait_for_popen(proc, 13)
62
-
63
- if proc.poll() is None:
64
- proc.terminate()
65
- wait_for_popen(proc, 5)
66
-
67
- if proc.poll() is None:
68
- proc.kill()
69
- wait_for_popen(proc, 2)
File without changes
File without changes