-
Notifications
You must be signed in to change notification settings - Fork 471
Expand file tree
/
Copy pathrpc.py
More file actions
1580 lines (1394 loc) · 52.1 KB
/
Copy pathrpc.py
File metadata and controls
1580 lines (1394 loc) · 52.1 KB
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
JSON-RPC methods and helper functions for EEST consume based hive simulators.
"""
import logging
import os
import time
from contextlib import AbstractContextManager, nullcontext
from itertools import count
from pprint import pprint
from typing import Any, Callable, ClassVar, Dict, List, Literal, Sequence
import requests
from jwt import encode
from pydantic import ValidationError
from tenacity import (
RetryCallState,
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential,
)
from tenacity import (
wait_fixed as wait_fixed_tenacity,
)
from execution_testing.base_types import (
Account,
Address,
Alloc,
Bytes,
Hash,
to_json,
)
from execution_testing.logging import (
get_logger,
)
from .rpc_types import (
EthConfigResponse,
ForkchoiceState,
ForkchoiceUpdateResponse,
GetBlobsResponse,
GetBlobsV4Response,
GetPayloadResponse,
JSONRPCRequest,
JSONRPCResponse,
PayloadAttributes,
PayloadStatus,
PayloadStatusEnum,
RPCCall,
TransactionByHashResponse,
TransactionProtocol,
)
logger = get_logger(__name__)
BlockNumberType = int | Literal["latest", "earliest", "pending"]
class SendTransactionExceptionError(Exception):
"""
Represent an exception that is raised when a transaction fails to be sent.
"""
tx: TransactionProtocol | None = None
tx_rlp: Bytes | None = None
def __init__(
self,
*args: Any,
tx: TransactionProtocol | None = None,
tx_rlp: Bytes | None = None,
) -> None:
"""
Initialize SendTransactionExceptionError class with the given
transaction.
"""
super().__init__(*args)
self.tx = tx
self.tx_rlp = tx_rlp
def __str__(self) -> str:
"""Return string representation of the exception."""
base = super().__str__()
if self.tx is not None:
return f"{base} Transaction={self.tx.model_dump_json()}"
elif self.tx_rlp is not None:
rlp_hex = self.tx_rlp.hex()
# Cap RLP output at 200 characters to avoid overwhelming output
max_rlp_length = 200
if len(rlp_hex) > max_rlp_length:
rlp_display = f"{rlp_hex[:max_rlp_length]}... (truncated)"
else:
rlp_display = rlp_hex
return f"{base} Transaction RLP={rlp_display}"
return base
class BlockNotAvailableError(Exception):
"""Raised when block is not available after retry attempts."""
def __init__(
self,
block_hash: Hash,
attempts: int,
elapsed: float,
interval: float,
):
"""Initialize with retry statistics."""
self.block_hash = block_hash
self.attempts = attempts
self.elapsed = elapsed
self.interval = interval
msg = (
f"Block {block_hash} not available after {attempts} attempts "
f"over {elapsed:.1f}s (interval: {interval}s)"
)
super().__init__(msg)
class ForkchoiceUpdateTimeoutError(Exception):
"""Raised when forkchoice update doesn't reach VALID in time."""
def __init__(
self,
attempts: int,
elapsed: float,
interval: float,
final_status: PayloadStatusEnum,
):
"""Initialize with retry statistics and final status."""
self.attempts = attempts
self.elapsed = elapsed
self.interval = interval
self.final_status = final_status
msg = (
f"Forkchoice update failed to reach VALID after {attempts} "
f"attempts over {elapsed:.1f}s (interval: {interval}s), "
f"final status: {final_status}"
)
super().__init__(msg)
class NewPayloadTimeoutError(Exception):
"""Raised when ``engine_newPayload`` stays SYNCING past the retry limit."""
def __init__(
self,
attempts: int,
elapsed: float,
interval: float,
final_status: PayloadStatusEnum,
):
"""Initialize with retry statistics and final status."""
self.attempts = attempts
self.elapsed = elapsed
self.interval = interval
self.final_status = final_status
msg = (
f"new_payload stayed SYNCING after {attempts} attempts over "
f"{elapsed:.1f}s (interval: {interval}s), final status: "
f"{final_status}"
)
super().__init__(msg)
class PeerConnectionTimeoutError(Exception):
"""Raised when peer connection is not established within retry limits."""
def __init__(
self,
attempts: int,
elapsed: float,
interval: float,
expected_peers: int,
actual_peers: int,
):
"""Initialize with retry statistics and peer counts."""
self.attempts = attempts
self.elapsed = elapsed
self.interval = interval
self.expected_peers = expected_peers
self.actual_peers = actual_peers
msg = (
f"Peer connection not established after {attempts} attempts "
f"over {elapsed:.1f}s (interval: {interval}s), "
f"expected >= {expected_peers} peers, got {actual_peers}"
)
super().__init__(msg)
class BaseRPC:
"""
Represents a base RPC class for every RPC call used within EEST based hive
simulators.
"""
namespace: ClassVar[str]
response_validation_context: Any | None
def __init__(
self,
url: str,
*,
response_validation_context: Any | None = None,
):
"""Initialize BaseRPC class with the given url."""
self.url = url
self.request_id_counter = count(1)
self.response_validation_context = response_validation_context
self.session = requests.Session()
def __init_subclass__(cls, namespace: str | None = None) -> None:
"""
Set namespace of the RPC class to the lowercase of the class name.
"""
if namespace is None:
namespace = cls.__name__
if namespace.endswith("RPC"):
namespace = namespace.removesuffix("RPC")
namespace = namespace.lower()
cls.namespace = namespace
@retry(
retry=retry_if_exception_type(
(requests.ConnectionError, ConnectionRefusedError)
),
stop=stop_after_attempt(5),
wait=wait_exponential(multiplier=0.5, min=0.5, max=4.0),
before_sleep=before_sleep_log(logger, logging.WARNING),
reraise=True,
)
def _make_request(
self,
url: str,
json_payload: dict[str, Any] | list[dict[str, Any]],
headers: dict[str, str],
timeout: int | None,
) -> requests.Response:
"""
Make HTTP POST request with retry logic for connection errors only.
This method only retries network-level connection failures
(ConnectionError, ConnectionRefusedError). HTTP status errors (4xx/5xx)
are handled by the caller using response.raise_for_status() WITHOUT
retries because:
- 4xx errors are client errors (permanent failures, no point retrying)
- 5xx errors are server errors that typically indicate
application-level issues rather than transient network problems
"""
logger.debug(f"Making HTTP request to {url}, timeout={timeout}")
return self.session.post(
url, json=json_payload, headers=headers, timeout=timeout
)
def _build_json_rpc_request(
self,
call: RPCCall,
) -> JSONRPCRequest:
"""Build a JSON-RPC request object with namespace prefix."""
assert self.namespace, "RPC namespace not set"
next_request_id_counter = next(self.request_id_counter)
request_id = call.request_id
if request_id is None:
request_id = next_request_id_counter
return JSONRPCRequest(
method=f"{self.namespace}_{call.method}",
params=call.params,
id=request_id,
)
def namespace_extra_headers(self) -> Dict[str, str]:
"""
Extra headers that are included by default in this namespace.
For non-jwt namespaces, this method returns an empty dictionary.
"""
return {}
def post_request(
self,
*,
request: RPCCall,
extra_headers: Dict[str, str] | None = None,
timeout: int | None = None,
) -> JSONRPCResponse:
"""
Send JSON-RPC POST request to the client RPC server at port defined in
the url.
"""
if extra_headers is None:
extra_headers = {}
json_rpc_request = self._build_json_rpc_request(request)
base_header = {
"Content-Type": "application/json",
}
headers = base_header | extra_headers | self.namespace_extra_headers()
logger.debug(
f"Sending RPC request to {self.url}, "
f"method={json_rpc_request.method}, timeout={timeout}..."
)
response = self._make_request(
self.url, json_rpc_request.model_dump(), headers, timeout
)
response.raise_for_status()
return JSONRPCResponse.model_validate(response.json())
def post_batch_request(
self,
*,
calls: Sequence[RPCCall],
extra_headers: Dict[str, str] | None = None,
timeout: int | None = None,
) -> List[JSONRPCResponse]:
"""
Send a JSON-RPC batch POST request to the client RPC server at port
defined in the url.
"""
if extra_headers is None:
extra_headers = {}
json_rpc_requests = [
self._build_json_rpc_request(call) for call in calls
]
payload = [r.model_dump() for r in json_rpc_requests]
base_header = {
"Content-Type": "application/json",
}
headers = base_header | extra_headers | self.namespace_extra_headers()
logger.debug(
f"Sending batch RPC request to {self.url}, "
f"{len(json_rpc_requests)} calls, timeout={timeout}..."
)
response = self._make_request(self.url, payload, headers, timeout)
response.raise_for_status()
response_json = response.json()
assert isinstance(response_json, list), (
"Batch RPC response is not a list"
)
response_map: dict[int | str, JSONRPCResponse] = {
r.id: r
for r in [
JSONRPCResponse.model_validate(item) for item in response_json
]
}
results = []
for json_rpc_request in json_rpc_requests:
assert json_rpc_request.id in response_map, (
f"Missing response for request ID {json_rpc_request.id}"
)
results.append(response_map[json_rpc_request.id])
logger.info(f"Batch RPC: {len(results)} responses received")
return results
class BaseJwtRPC(BaseRPC):
"""
Represents an RPC namespace class that uses JWT authentication.
"""
jwt_secret: bytes
# Default secret used in hive
DEFAULT_JWT_SECRET: bytes = b"secretsecretsecretsecretsecretse"
def __init__(
self,
*args: Any,
jwt_secret: bytes = DEFAULT_JWT_SECRET,
**kwargs: Any,
) -> None:
"""Initialize Engine RPC class with the given JWT secret."""
super().__init__(*args, **kwargs)
self.jwt_secret = jwt_secret
def namespace_extra_headers(self) -> Dict[str, str]:
"""
Overload to include JWT authentication header field.
"""
jwt_token = encode(
{"iat": int(time.time())},
self.jwt_secret,
algorithm="HS256",
)
return {
"Authorization": f"Bearer {jwt_token}",
}
class EthRPC(BaseRPC):
"""
Represents an `eth_X` RPC class for every default ethereum RPC method used
within EEST based hive simulators.
"""
OVERLOAD_THRESHOLD: int = 1000
DEFAULT_MAX_TRANSACTIONS_PER_BATCH: int = 750
transaction_wait_timeout: int = 60
poll_interval: float = 1.0 # how often to poll for tx inclusion
max_transactions_per_batch: int = DEFAULT_MAX_TRANSACTIONS_PER_BATCH
gas_information_stale_seconds: int
_gas_information_cache: Dict[str, int]
_gas_information_cache_timestamp: Dict[str, float]
BlockNumberType = int | Literal["latest", "earliest", "pending"]
def __init__(
self,
*args: Any,
transaction_wait_timeout: int = 60,
poll_interval: float | None = None,
gas_information_stale_seconds: int = 12,
max_transactions_per_batch: int | None = None,
**kwargs: Any,
) -> None:
"""Initialize JWT-authenticated RPC class with the given JWT secret."""
super().__init__(*args, **kwargs)
self.transaction_wait_timeout = transaction_wait_timeout
# Allow overriding via env "flag" EEST_POLL_INTERVAL or ctor arg
# Priority: ctor arg > env var > default (1.0)
env_val = os.getenv("EEST_POLL_INTERVAL")
if poll_interval is not None:
self.poll_interval = float(poll_interval)
elif env_val:
try:
self.poll_interval = float(env_val)
except ValueError:
logger.warning(
"Invalid EEST_POLL_INTERVAL=%r; falling back to 1.0s",
env_val,
)
self.poll_interval = 1.0
else:
self.poll_interval = 1.0
self.gas_information_stale_seconds = gas_information_stale_seconds
self._gas_information_cache = {
"gasPrice": 0,
"maxPriorityFeePerGas": 0,
"blobBaseFee": 0,
}
self._gas_information_cache_timestamp = {
"gasPrice": 0.0,
"maxPriorityFeePerGas": 0.0,
"blobBaseFee": 0.0,
}
# Transaction batching configuration
if max_transactions_per_batch is None:
max_transactions_per_batch = (
self.DEFAULT_MAX_TRANSACTIONS_PER_BATCH
)
self.max_transactions_per_batch = max_transactions_per_batch
if max_transactions_per_batch > self.OVERLOAD_THRESHOLD:
logger.warning(
f"max_transactions_per_batch ({max_transactions_per_batch}) "
f"exceeds the safe threshold ({self.OVERLOAD_THRESHOLD}). "
"This may cause RPC service instability or failures."
)
def config(self, timeout: int | None = None) -> EthConfigResponse | None:
"""
`eth_config`: Returns information about a fork configuration of the
client.
"""
try:
logger.info("Requesting eth_config..")
response = self.post_request(
request=RPCCall(method="config"), timeout=timeout
).result_or_raise()
if response is None:
logger.warning("eth_config request: failed to get response")
return None
return EthConfigResponse.model_validate(
response, context=self.response_validation_context
)
except ValidationError as e:
pprint(e.errors())
raise e
except Exception as e:
logger.debug(
f"exception occurred when sending JSON-RPC request: {e}"
)
raise e
def chain_id(self) -> int:
"""`eth_chainId`: Returns the current chain id."""
logger.info("Requesting chainid of provided RPC endpoint..")
response = self.post_request(
request=RPCCall(method="chainId"), timeout=10
).result_or_raise()
return int(response, 16)
def get_block_by_number(
self, block_number: BlockNumberType = "latest", full_txs: bool = True
) -> Any | None:
"""
`eth_getBlockByNumber`: Returns information about a block by block
number.
"""
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
logger.info(f"Requesting info about block {block}..")
params = [block, full_txs]
return self.post_request(
request=RPCCall(method="getBlockByNumber", params=params)
).result_or_raise()
def get_block_by_hash(
self, block_hash: Hash, full_txs: bool = True
) -> Any | None:
"""`eth_getBlockByHash`: Returns information about a block by hash."""
logger.info(f"Requesting block info of {block_hash}..")
params = [f"{block_hash}", full_txs]
return self.post_request(
request=RPCCall(method="getBlockByHash", params=params)
).result_or_raise()
def get_block_by_hash_with_retry(
self,
block_hash: Hash,
*,
max_attempts: int = 5,
wait_fixed: float = 1.0,
on_retry: Callable[[RetryCallState], None] | None = None,
) -> dict[str, Any]:
"""
Get block by hash, retrying if not yet available.
Args:
block_hash: The hash of the block to retrieve.
max_attempts: Maximum number of attempts before giving up.
wait_fixed: Fixed interval in seconds between retries.
on_retry: Optional callback invoked before each retry sleep.
Receives tenacity RetryCallState. If None, logs at debug level.
Returns:
Block data as a dictionary.
Raises:
BlockNotAvailableError: If block not available after max_attempts.
"""
attempts = 0
start_time = time.time()
def default_on_retry(retry_state: RetryCallState) -> None:
logger.debug(
f"Block {block_hash} not available, "
f"attempt {retry_state.attempt_number}, "
f"retrying in {wait_fixed}s..."
)
retry_callback = on_retry if on_retry is not None else default_on_retry
@retry(
stop=stop_after_attempt(max_attempts),
wait=wait_fixed_tenacity(wait_fixed),
before_sleep=retry_callback,
reraise=True,
)
def _get_block() -> dict[str, Any]:
nonlocal attempts
attempts += 1
block = self.get_block_by_hash(block_hash)
if block is None:
raise BlockNotAvailableError(
block_hash=block_hash,
attempts=attempts,
elapsed=time.time() - start_time,
interval=wait_fixed,
)
return block
return _get_block()
def get_balance(
self, address: Address, block_number: BlockNumberType = "latest"
) -> int:
"""
`eth_getBalance`: Returns the balance of the account of given address.
"""
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
logger.info(f"Requesting balance of {address} at block {block}")
params = [f"{address}", block]
response = self.post_request(
request=RPCCall(method="getBalance", params=params)
).result_or_raise()
return int(response, 16)
def get_balances(
self,
addresses: List[Address],
block_number: BlockNumberType = "latest",
) -> List[int]:
"""`eth_getBalance` batch: Return balance for multiple addresses."""
if not addresses:
return []
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
logger.info(
f"Batch requesting balance of {len(addresses)} addresses "
f"at block {block}"
)
calls = [
RPCCall(method="getBalance", params=[f"{addr}", block])
for addr in addresses
]
responses = self.post_batch_request(calls=calls)
return [int(r.result_or_raise(), 16) for r in responses]
def estimate_gas(
self,
transaction: Dict[str, Any],
block_number: BlockNumberType = "latest",
) -> int:
"""`eth_estimateGas`: Return the gas required to execute a tx."""
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
response = self.post_request(
request=RPCCall(method="estimateGas", params=[transaction, block])
).result_or_raise()
return int(response, 16)
def get_code(
self, address: Address, block_number: BlockNumberType = "latest"
) -> Bytes:
"""`eth_getCode`: Returns code at a given address."""
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
logger.info(f"Requesting code of {address} at block {block}")
params = [f"{address}", block]
response = self.post_request(
request=RPCCall(method="getCode", params=params)
).result_or_raise()
return Bytes(response)
def get_codes(
self,
addresses: List[Address],
block_number: BlockNumberType = "latest",
) -> List[Bytes]:
"""`eth_getCode` batch: Return code for multiple addresses."""
if not addresses:
return []
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
logger.info(
f"Batch requesting code of {len(addresses)} addresses "
f"at block {block}"
)
calls = [
RPCCall(method="getCode", params=[f"{addr}", block])
for addr in addresses
]
responses = self.post_batch_request(calls=calls)
return [Bytes(r.result_or_raise()) for r in responses]
def get_transaction_count(
self, address: Address, block_number: BlockNumberType = "latest"
) -> int:
"""
`eth_getTransactionCount`: Returns the number of transactions sent from
an address.
"""
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
logger.info(f"Requesting nonce of {address}")
params = [f"{address}", block]
response = self.post_request(
request=RPCCall(method="getTransactionCount", params=params)
).result_or_raise()
return int(response, 16)
def get_transaction_by_hash(
self, transaction_hash: Hash
) -> TransactionByHashResponse | None:
"""`eth_getTransactionByHash`: Returns transaction details."""
try:
logger.info(f"Requesting tx details of {transaction_hash}")
response = self.post_request(
request=RPCCall(
method="getTransactionByHash",
params=[f"{transaction_hash}"],
)
).result_or_raise()
if response is None:
return None
return TransactionByHashResponse.model_validate(
response, context=self.response_validation_context
)
except ValidationError as e:
pprint(e.errors())
raise e
def get_transactions_by_hash(
self, transaction_hashes: Sequence[Hash]
) -> List[TransactionByHashResponse | None]:
"""
Batch `eth_getTransactionByHash` for multiple hashes.
Return a list of responses in the same order as the input
hashes. Entries are `None` if the transaction was not found.
"""
if not transaction_hashes:
return []
calls = [
RPCCall(
method="getTransactionByHash",
params=[f"{tx_hash}"],
)
for tx_hash in transaction_hashes
]
responses = self.post_batch_request(calls=calls)
results: List[TransactionByHashResponse | None] = []
for response in responses:
result = response.result_or_raise()
if result is None:
results.append(None)
else:
results.append(
TransactionByHashResponse.model_validate(
result,
context=self.response_validation_context,
)
)
return results
def get_transaction_receipt(
self, transaction_hash: Hash
) -> dict[str, Any] | None:
"""
`eth_getTransactionReceipt`: Returns transaction receipt.
Used to get the actual gas used by a transaction for gas validation
in benchmark tests.
"""
logger.info(f"Requesting tx receipt of {transaction_hash}")
return self.post_request(
request=RPCCall(
method="getTransactionReceipt",
params=[f"{transaction_hash}"],
)
).result_or_raise()
def get_storage_at(
self,
address: Address,
position: Hash,
block_number: BlockNumberType = "latest",
) -> Hash:
"""
`eth_getStorageAt`: Returns the value from a storage position at a
given address.
"""
block = (
hex(block_number)
if isinstance(block_number, int)
else block_number
)
logger.info(
f"Requesting storage value mapped to key {position} "
f"of contract {address}"
)
params = [f"{address}", f"{position}", block]
response = self.post_request(
request=RPCCall(method="getStorageAt", params=params)
).result_or_raise()
return Hash(response)
def _get_gas_information(
self,
*,
method: Literal["gasPrice", "maxPriorityFeePerGas", "blobBaseFee"],
) -> int:
"""Get gas information from the cache or the RPC server."""
if (
time.time() - self._gas_information_cache_timestamp[method]
> self.gas_information_stale_seconds
):
response = self.post_request(
request=RPCCall(method=method)
).result_or_raise()
logger.info(f"Requesting stale {method}")
self._gas_information_cache[method] = int(response, 16)
self._gas_information_cache_timestamp[method] = time.time()
return self._gas_information_cache[method]
def gas_price(self) -> int:
"""
`eth_gasPrice`: Returns the gas price.
"""
return self._get_gas_information(method="gasPrice")
def max_priority_fee_per_gas(self) -> int:
"""
`eth_maxPriorityFeePerGas`: Return the current max priority fee per
gas of the network.
"""
return self._get_gas_information(method="maxPriorityFeePerGas")
def blob_base_fee(self) -> int:
"""Return the current blob base fee per gas of the network."""
return self._get_gas_information(method="blobBaseFee")
def send_raw_transaction(
self, transaction_rlp: Bytes, request_id: int | str | None = None
) -> Hash:
"""`eth_sendRawTransaction`: Send a transaction to the client."""
try:
logger.info("Sending raw tx..")
response = self.post_request(
request=RPCCall(
method="sendRawTransaction",
params=[transaction_rlp.hex()],
request_id=request_id,
)
).result_or_raise()
result_hash = Hash(response)
assert result_hash is not None
return result_hash
except Exception as e:
logger.error(e)
raise SendTransactionExceptionError(
str(e), tx_rlp=transaction_rlp
) from e
def send_transaction(self, transaction: TransactionProtocol) -> Hash:
"""
Convenience method to send a single transaction to the client via
`eth_sendRawTransaction`.
"""
try:
logger.info("Sending tx..")
response = self.post_request(
request=RPCCall(
method="sendRawTransaction",
params=[transaction.rlp().hex()],
request_id=transaction.metadata_string(),
)
).result_or_raise()
result_hash = Hash(response)
assert result_hash == transaction.hash
assert result_hash is not None
return transaction.hash
except Exception as e:
raise SendTransactionExceptionError(str(e), tx=transaction) from e
def send_transactions(
self, transactions: Sequence[TransactionProtocol]
) -> List[Hash]:
"""
Use `eth_sendRawTransaction` to send a batch of transactions to the
client.
"""
if not transactions:
return []
calls = [
RPCCall(
method="sendRawTransaction",
params=[tx.rlp().hex()],
request_id=tx.metadata_string(),
)
for tx in transactions
]
responses = self.post_batch_request(calls=calls)
results: List[Hash] = []
for tx, response in zip(transactions, responses, strict=True):
try:
result_hash = Hash(response.result_or_raise())
assert result_hash == tx.hash
assert result_hash is not None
results.append(tx.hash)
except Exception as e:
raise SendTransactionExceptionError(str(e), tx=tx) from e
return results
def _build_get_account_calls(
self,
address: Address,
account: Account | None,
block: str,
skip_code: bool = False,
) -> tuple[List[RPCCall], List[tuple[str, Any]]]:
"""Build the RPC calls needed to fetch an account's state."""
calls: List[RPCCall] = []
# (field_name, storage_key)
call_info: List[tuple[str, Any]] = []
calls.append(
RPCCall(
method="getBalance",
params=[f"{address}", block],
)
)
call_info.append(("balance", None))
if not skip_code:
calls.append(
RPCCall(
method="getCode",
params=[f"{address}", block],
)
)
call_info.append(("code", None))
calls.append(
RPCCall(
method="getTransactionCount",
params=[f"{address}", block],
)
)
call_info.append(("nonce", None))
if account is not None and "storage" in account.model_fields_set:
for key in account.storage.root:
calls.append(
RPCCall(
method="getStorageAt",
params=[
f"{address}",
f"{Hash(key)}",
block,
],
)
)
call_info.append(("storage", key))
return calls, call_info
@staticmethod
def _parse_account_responses(
call_info: List[tuple[str, Any]],
responses: List[JSONRPCResponse],
) -> Account:
"""Parse RPC responses into an Account."""
data: Dict[str, Any] = {}
for (field, key), response in zip(call_info, responses, strict=True):
result = response.result_or_raise()
if field == "balance":
data["balance"] = int(result, 16)
elif field == "code":
data["code"] = Bytes(result)
elif field == "nonce":
data["nonce"] = int(result, 16)
elif field == "storage":
if "storage" not in data:
data["storage"] = {}
data["storage"][key] = Hash(result)
return Account(**data)
def get_account(
self,
address: Address,
account: Account | None = None,
block_number: BlockNumberType = "latest",
skip_code: bool = False,
) -> Account:
"""
Fetch account state from the chain for a single address using
a batch RPC request.