-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
node_inquirer.py
1513 lines (1335 loc) · 61.5 KB
/
node_inquirer.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
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
import json
import logging
import random
from abc import ABCMeta, abstractmethod
from collections.abc import Callable, Sequence
from contextlib import suppress
from itertools import zip_longest
from typing import TYPE_CHECKING, Any, Literal
from urllib.parse import urlparse
import requests
from ens import ENS
from eth_abi.exceptions import InsufficientDataBytes
from eth_typing import BlockNumber
from requests import RequestException
from web3 import HTTPProvider, Web3
from web3._utils.abi import get_abi_output_types
from web3._utils.contracts import find_matching_event_abi
from web3._utils.filters import construct_event_filter_params
from web3.datastructures import MutableAttributeDict
from web3.exceptions import TransactionNotFound, Web3Exception
from web3.middleware import geth_poa_middleware
from web3.types import BlockIdentifier, FilterParams
from rotkehlchen.assets.asset import CryptoAsset
from rotkehlchen.chain.constants import DEFAULT_EVM_RPC_TIMEOUT
from rotkehlchen.chain.ethereum.constants import DEFAULT_TOKEN_DECIMALS
from rotkehlchen.chain.ethereum.utils import MULTICALL_CHUNKS, should_update_protocol_cache
from rotkehlchen.chain.evm.constants import (
ERC20_PROPERTIES,
ERC20_PROPERTIES_NUM,
ERC721_PROPERTIES,
FAKE_GENESIS_TX_RECEIPT,
GENESIS_HASH,
)
from rotkehlchen.chain.evm.contracts import EvmContract, EvmContracts
from rotkehlchen.chain.evm.proxies_inquirer import EvmProxiesInquirer
from rotkehlchen.chain.evm.types import NodeName, Web3Node, WeightedNode
from rotkehlchen.constants import ONE
from rotkehlchen.errors.misc import (
BlockchainQueryError,
EventNotInABI,
NotERC721Conformant,
RemoteError,
)
from rotkehlchen.errors.serialization import DeserializationError
from rotkehlchen.externalapis.etherscan import Etherscan
from rotkehlchen.fval import FVal
from rotkehlchen.globaldb.handler import GlobalDBHandler
from rotkehlchen.greenlets.manager import GreenletManager
from rotkehlchen.logging import RotkehlchenLogsAdapter
from rotkehlchen.serialization.deserialize import (
deserialize_evm_address,
deserialize_evm_transaction,
deserialize_int_from_hex,
)
from rotkehlchen.serialization.serialize import process_result
from rotkehlchen.types import (
SUPPORTED_CHAIN_IDS,
SUPPORTED_EVM_CHAINS,
CacheType,
ChainID,
ChecksumEvmAddress,
EvmTokenKind,
EvmTransaction,
EVMTxHash,
Timestamp,
)
from rotkehlchen.utils.data_structures import LRUCacheWithRemove
from rotkehlchen.utils.misc import from_wei, get_chunks, hex_or_bytes_to_str
from rotkehlchen.utils.mixins.lockable import LockableQueryMixIn, protect_with_lock
if TYPE_CHECKING:
from rotkehlchen.db.dbhandler import DBHandler
logger = logging.getLogger(__name__)
log = RotkehlchenLogsAdapter(logger)
def _connect_task_prefix(chain_name: str) -> str:
"""Helper function to create the connection task greenlet name"""
return f'Attempt connection to {chain_name} node'
def _is_synchronized(current_block: int, latest_block: int) -> tuple[bool, str]:
""" Validate that the evm node is synchronized
within 20 blocks of the latest block
Returns a tuple (results, message)
- result: Boolean for confirmation of synchronized
- message: A message containing information on what the status is.
"""
message = ''
if current_block < (latest_block - 20):
message = (
f'Found evm node but it is out of sync. {current_block} / '
f'{latest_block}. Will use etherscan.'
)
log.warning(message)
return False, message
return True, message
WEB3_LOGQUERY_BLOCK_RANGE = 250000
def _query_web3_get_logs(
web3: Web3,
filter_args: FilterParams,
from_block: int,
to_block: int | Literal['latest'],
contract_address: ChecksumEvmAddress,
event_name: str,
argument_filters: dict[str, Any],
initial_block_range: int,
) -> list[dict[str, Any]]:
until_block = web3.eth.block_number if to_block == 'latest' else to_block
events: list[dict[str, Any]] = []
start_block = from_block
block_range = initial_block_range
while start_block <= until_block:
filter_args['fromBlock'] = start_block
end_block = min(start_block + block_range, until_block)
filter_args['toBlock'] = end_block
log.debug(
'Querying web3 node for contract event',
contract_address=contract_address,
event_name=event_name,
argument_filters=argument_filters,
from_block=filter_args['fromBlock'],
to_block=filter_args['toBlock'],
)
# As seen in https://github.com/rotki/rotki/issues/1787, the json RPC, if it
# is infura can throw an error here which we can only parse by catching the exception
try:
new_events_web3: list[dict[str, Any]] = [dict(x) for x in web3.eth.get_logs(filter_args)] # noqa: E501
except (Web3Exception, ValueError, KeyError) as e:
if isinstance(e, ValueError):
try:
decoded_error = json.loads(str(e).replace("'", '"'))
except json.JSONDecodeError:
# reraise the value error if the error is not json
raise e from None
msg = decoded_error.get('message', '')
else: # temporary hack for key error seen from pokt
msg = 'query returned more than 10000 results'
# errors from: https://infura.io/docs/ethereum/json-rpc/eth-getLogs
if msg in {'query returned more than 10000 results', 'query timeout exceeded'}:
block_range = block_range // 2
if block_range < 50:
raise # stop retrying if block range gets too small
# repeat the query with smaller block range
continue
# else, well we tried .. reraise the error
raise
# Turn all HexBytes into hex strings
for e_idx, event in enumerate(new_events_web3):
new_events_web3[e_idx]['blockHash'] = event['blockHash'].hex()
new_topics = [topic.hex() for topic in event['topics']]
new_events_web3[e_idx]['topics'] = new_topics
new_events_web3[e_idx]['transactionHash'] = event['transactionHash'].hex()
start_block = end_block + 1
events.extend(new_events_web3)
# end of the loop, end of 1 query. Reset the block range to max
block_range = initial_block_range
return events
class EvmNodeInquirer(metaclass=ABCMeta):
"""Class containing generic functionality for querying evm nodes
The child class must implement the following methods:
- query_highest_block
- _have_archive
- _is_pruned
- get_blocknumber_by_time
The child class may optionally implement the following:
- logquery_block_range
"""
methods_that_query_past_data = (
'_get_transaction_receipt',
'_get_transaction_by_hash',
'_get_logs',
)
def __init__(
self,
greenlet_manager: GreenletManager,
database: 'DBHandler',
etherscan: Etherscan,
blockchain: SUPPORTED_EVM_CHAINS,
etherscan_node: WeightedNode,
etherscan_node_name: str,
contracts: EvmContracts,
contract_scan: 'EvmContract',
contract_multicall: 'EvmContract',
native_token: CryptoAsset,
rpc_timeout: int = DEFAULT_EVM_RPC_TIMEOUT,
) -> None:
self.greenlet_manager = greenlet_manager
self.database = database
self.blockchain = blockchain
self.etherscan = etherscan
self.etherscan_node = etherscan_node
self.etherscan_node_name = etherscan_node_name
self.contracts = contracts
self.web3_mapping: dict[NodeName, Web3Node] = {}
self.rpc_timeout = rpc_timeout
self.chain_id: SUPPORTED_CHAIN_IDS = blockchain.to_chain_id() # type: ignore[assignment]
self.chain_name = self.chain_id.to_name()
self.native_token = native_token
# BalanceScanner from mycrypto: https://github.com/MyCryptoHQ/eth-scan
self.contract_scan = contract_scan
# Multicall from MakerDAO: https://github.com/makerdao/multicall/
self.contract_multicall = contract_multicall
# A cache for erc20 and erc721 contract info to not requery the info
self.contract_info_erc20_cache: LRUCacheWithRemove[ChecksumEvmAddress, dict[str, Any]] = LRUCacheWithRemove(maxsize=1024) # noqa: E501
self.contract_info_erc721_cache: LRUCacheWithRemove[ChecksumEvmAddress, dict[str, Any]] = LRUCacheWithRemove(maxsize=512) # noqa: E501
self.maybe_connect_to_nodes(when_tracked_accounts=True)
def maybe_connect_to_nodes(self, when_tracked_accounts: bool) -> None:
"""Start async connect to the saved nodes for the given evm chain if needed.
If `when_tracked_accounts` is True then it will connect when we have some
tracked accounts in the DB. Otherwise when we have none.
"""
if self.connected_to_any_web3() or self.greenlet_manager.has_task(_connect_task_prefix(self.chain_name)): # noqa: E501
return
with self.database.conn.read_ctx() as cursor:
accounts = self.database.get_blockchain_accounts(cursor)
tracked_accounts_num = len(accounts.get(self.blockchain))
if (tracked_accounts_num != 0 and when_tracked_accounts) or (when_tracked_accounts is False and tracked_accounts_num == 0): # noqa: E501
rpc_nodes = self.database.get_rpc_nodes(blockchain=self.blockchain, only_active=True)
self.connect_to_multiple_nodes(rpc_nodes)
def connected_to_any_web3(self) -> bool:
return len(self.web3_mapping) != 0
def get_own_node_web3(self) -> Web3 | None:
for node, web3node in self.web3_mapping.items():
if node.owned:
return web3node.web3_instance
return None
def get_own_node_info(self) -> NodeName | None:
for node in self.web3_mapping:
if node.owned:
return node
return None
def get_connected_nodes(self) -> list[NodeName]:
return list(self.web3_mapping.keys())
def default_call_order(self, skip_etherscan: bool = False) -> list[WeightedNode]:
"""Default call order for evm nodes
Own node always has preference. Then all other node types are randomly queried
in sequence depending on a weighted probability.
Some benchmarks on weighted probability based random selection when compared
to simple random selection. Benchmark was on blockchain balance querying with
29 ethereum accounts and at the time 1010 different ethereum tokens.
With weights: etherscan: 0.5, mycrypto: 0.25, blockscout: 0.2, avado: 0.05
===> Runs: 66, 58, 60, 68, 58 seconds
---> Average: 62 seconds
- Without weights
===> Runs: 66, 82, 72, 58, 72 seconds
---> Average: 70 seconds
"""
open_nodes = self.database.get_rpc_nodes(blockchain=self.blockchain, only_active=True)
if skip_etherscan:
selection = [wnode for wnode in open_nodes if wnode.node_info.name != self.etherscan_node_name and wnode.node_info.owned is False] # noqa: E501
else:
selection = [wnode for wnode in open_nodes if wnode.node_info.owned is False]
ordered_list = []
while len(selection) != 0:
weights = [float(entry.weight) for entry in selection]
node = random.choices(selection, weights, k=1)
ordered_list.append(node[0])
selection.remove(node[0])
owned_nodes = [node for node in self.web3_mapping if node.owned]
if len(owned_nodes) != 0:
# Assigning one is just a default since we always use it.
# The weight is only important for the other nodes since they
# are selected using this parameter
ordered_list = [WeightedNode(node_info=node, weight=ONE, active=True) for node in owned_nodes] + ordered_list # noqa: E501
return ordered_list
def get_multi_balance(
self,
accounts: Sequence[ChecksumEvmAddress],
call_order: Sequence[WeightedNode] | None = None,
) -> dict[ChecksumEvmAddress, FVal]:
"""Returns a dict with keys being accounts and balances in the chain native token.
May raise:
- RemoteError if an external service such as Etherscan is queried and
there is a problem with its query.
"""
balances: dict[ChecksumEvmAddress, FVal] = {}
log.debug(
f'Querying {self.chain_name} chain for {self.blockchain.serialize()} balance',
eth_addresses=accounts,
)
result = self.contract_scan.call(
node_inquirer=self,
method_name='etherBalances',
arguments=[accounts],
call_order=call_order if call_order is not None else self.default_call_order(),
)
balances = {}
for idx, account in enumerate(accounts):
balances[account] = from_wei(result[idx])
return balances
def get_historical_balance(
self,
address: ChecksumEvmAddress,
block_number: int,
web3: Web3 | None = None,
) -> FVal | None:
"""Attempts to get the historical eth balance using the node provided.
If `web3` is None, it uses the local own node.
Returns None if there is no local node or node cannot query historical balance.
"""
web3 = web3 if web3 is not None else self.get_own_node_web3()
if web3 is None:
return None
try:
result = web3.eth.get_balance(address, block_identifier=block_number)
except (
requests.exceptions.RequestException,
BlockchainQueryError,
KeyError, # saw this happen inside web3.py if resulting json contains unexpected key. Happened with mycrypto's node # noqa: E501
Web3Exception,
ValueError, # can still happen in web3py v6 for missing trieerror. Essentially historical balance call # noqa: E501
):
return None
try:
balance = from_wei(FVal(result))
except ValueError:
return None
return balance
def _init_web3(self, node: NodeName) -> tuple[Web3, str]:
"""Initialize a new Web3 object based on a given endpoint"""
rpc_endpoint = node.endpoint
parsed_rpc_endpoint = urlparse(node.endpoint)
if not parsed_rpc_endpoint.scheme:
rpc_endpoint = f'http://{node.endpoint}'
provider = HTTPProvider(
endpoint_uri=node.endpoint,
request_kwargs={'timeout': self.rpc_timeout},
)
ens = ENS(provider) if self.chain_id == ChainID.ETHEREUM else None
web3 = Web3(provider, ens=ens)
for middleware in (
'validation', # validation middleware makes an un-needed for us chain ID validation causing 1 extra rpc call per eth_call # noqa: E501
'gas_price_strategy', # We do not need to automatically estimate gas
'gas_estimate',
'name_to_address', # we do our own handling for ens names
):
# https://github.com/ethereum/web3.py/blob/bba87a283d802bbebbfe3f8c7dc47560c7a08583/web3/middleware/validation.py#L137-L142 # noqa: E501
with suppress(ValueError): # If not existing raises ValuError, so ignore
web3.middleware_onion.remove(middleware)
if self.chain_id in (ChainID.OPTIMISM, ChainID.POLYGON_POS, ChainID.ARBITRUM_ONE, ChainID.BASE): # noqa: E501
# TODO: Is it needed for all non-mainet EVM chains?
# https://web3py.readthedocs.io/en/stable/middleware.html#why-is-geth-poa-middleware-necessary
web3.middleware_onion.inject(geth_poa_middleware, layer=0)
return web3, rpc_endpoint
def attempt_connect(
self,
node: NodeName,
connectivity_check: bool = True,
) -> tuple[bool, str]:
"""Attempt to connect to a particular node type
For our own node if the given rpc endpoint is not the same as the saved one
the connection is re-attempted to the new one
"""
message = ''
node_connected = self.web3_mapping.get(node, None) is not None
if node_connected:
return True, f'Already connected to {node} {self.chain_name} node'
web3, rpc_endpoint = self._init_web3(node)
try: # it is here that an actual connection is attempted
is_connected = web3.is_connected()
except requests.exceptions.RequestException:
message = f'Failed to connect to {self.chain_name} node {node} at endpoint {rpc_endpoint}' # noqa: E501
log.warning(message)
return False, message
except AssertionError:
# Terrible, terrible hack but needed due to https://github.com/rotki/rotki/issues/1817
is_connected = False
if is_connected:
# Also make sure we are actually connected to the right network
synchronized = True
msg = ''
try:
if connectivity_check:
try:
network_id = int(web3.net.version)
except requests.exceptions.RequestException as e:
msg = (
f'Connected to node {node} at endpoint {rpc_endpoint} but'
f'failed to request node version due to {e!s}'
)
log.warning(msg)
return False, msg
if network_id != self.chain_id.value:
message = (
f'Connected to {self.chain_name} node {node} at endpoint {rpc_endpoint} but ' # noqa: E501
f'it is not on the expected network value {self.chain_id.value}. '
f'The chain id the node is in is {network_id}.'
)
log.warning(message)
return False, message
try:
current_block = web3.eth.block_number # pylint: disable=no-member
if isinstance(current_block, int) is False: # Check for https://github.com/rotki/rotki/issues/6350 # TODO: Check if web3.py v6 has a check for this # noqa: E501
raise RemoteError(f'Found non-int current block:{current_block}')
latest_block = self.query_highest_block()
except (requests.exceptions.RequestException, RemoteError) as e:
msg = f'Could not query latest block due to {e!s}'
log.warning(msg)
synchronized = False
else:
synchronized, msg = _is_synchronized(current_block, latest_block)
except (Web3Exception, ValueError) as e:
message = (
f'Failed to connect to {self.chain_name} node {node} at endpoint '
f'{rpc_endpoint} due to {e!s}'
)
return False, message
if not synchronized:
log.warning(
f'We could not verify that {self.chain_name} node {node} is '
'synchronized with the network. Balances and other queries '
'may be incorrect.',
)
if node.endpoint.endswith('llamarpc.com'): # temporary. Seems to sometimes switch
is_pruned, is_archive = True, False # between pruned and non-pruned nodes
elif node.endpoint.endswith('blastapi.io'): # temporary
# After the bedrock update blastapi.io switches from archive to non archive nodes
# It has never reported pruned nodes.
is_pruned, is_archive = False, False
else:
is_pruned, is_archive = self.determine_capabilities(web3)
log.info(f'Connected {self.chain_name} node {node} at {rpc_endpoint}')
self.web3_mapping[node] = Web3Node(
web3_instance=web3,
is_pruned=is_pruned,
is_archive=is_archive,
)
return True, ''
# else
message = f'Failed to connect to {self.chain_name} node {node} at endpoint {rpc_endpoint}'
log.warning(message)
return False, message
def connect_to_multiple_nodes(self, nodes: Sequence[WeightedNode]) -> None:
self.web3_mapping = {}
for weighted_node in nodes:
if weighted_node.node_info.name == self.etherscan_node_name:
continue
task_name = f'{_connect_task_prefix(self.chain_name)} {weighted_node.node_info.name!s}'
self.greenlet_manager.spawn_and_track(
after_seconds=None,
task_name=task_name,
exception_is_error=True,
method=self.attempt_connect,
node=weighted_node.node_info,
connectivity_check=True,
)
def _query(self, method: Callable, call_order: Sequence[WeightedNode], **kwargs: Any) -> Any:
"""Queries evm related data by performing a query of the provided method to all given nodes
The first node in the call order that gets a successful response returns.
If none get a result then RemoteError is raised
"""
for weighted_node in call_order:
node_info = weighted_node.node_info
web3node = self.web3_mapping.get(node_info, None)
if web3node is None and node_info.name != self.etherscan_node_name:
continue
if (
web3node is not None and
method.__name__ in self.methods_that_query_past_data and
web3node.is_pruned is True
):
continue
try:
web3 = web3node.web3_instance if web3node is not None else None
result = method(web3, **kwargs)
except TransactionNotFound:
if kwargs.get('must_exist', False) is True:
continue # try other nodes, as transaction has to exist
return None
except (
RemoteError,
requests.exceptions.RequestException,
BlockchainQueryError,
Web3Exception,
ValueError, # not removing yet due to possibility of raising from missing trie error # noqa: E501
) as e:
log.warning(f'Failed to query {node_info} for {method!s} due to {e!s}')
# Catch all possible errors here and just try next node call
continue
return result
# no node in the call order list was succesfully queried
log.error(
f'Failed to query {method!s} after trying the following '
f'nodes: {[x.node_info.name for x in call_order]}',
)
raise RemoteError(
f'Please check your network and confirm sufficient nodes are connected for {self.blockchain!s}.', # noqa: E501
)
def _get_latest_block_number(self, web3: Web3 | None) -> int:
if web3 is not None:
return web3.eth.block_number
# else
return self.etherscan.get_latest_block_number()
def get_latest_block_number(self, call_order: Sequence[WeightedNode] | None = None) -> int:
return self._query(
method=self._get_latest_block_number,
call_order=call_order if call_order is not None else self.default_call_order(),
)
def get_block_by_number(
self,
num: int,
call_order: Sequence[WeightedNode] | None = None,
) -> dict[str, Any]:
return self._query(
method=self._get_block_by_number,
call_order=call_order if call_order is not None else self.default_call_order(),
num=num,
)
def _get_block_by_number(self, web3: Web3 | None, num: int) -> dict[str, Any]:
"""Returns the block object corresponding to the given block number
May raise:
- RemoteError if an external service such as Etherscan is queried and
there is a problem with its query.
- BlockNotFound if number used to lookup the block can't be found. Raised
by web3.eth.get_block().
"""
if web3 is None:
return self.etherscan.get_block_by_number(num)
block_data: MutableAttributeDict = MutableAttributeDict(web3.eth.get_block(num)) # type: ignore # pylint: disable=no-member
block_data['hash'] = hex_or_bytes_to_str(block_data['hash'])
return dict(block_data)
def get_code(
self,
account: ChecksumEvmAddress,
call_order: Sequence[WeightedNode] | None = None,
) -> str:
return self._query(
method=self._get_code,
call_order=call_order if call_order is not None else self.default_call_order(),
account=account,
)
def _get_code(self, web3: Web3 | None, account: ChecksumEvmAddress) -> str:
"""Gets the deployment bytecode at the given address
May raise:
- RemoteError if Etherscan is used and there is a problem querying it or
parsing its response
"""
if web3 is None:
return self.etherscan.get_code(account)
return hex_or_bytes_to_str(web3.eth.get_code(account))
def _call_contract_etherscan(
self,
contract_address: ChecksumEvmAddress,
abi: list,
method_name: str,
arguments: list[Any] | None = None,
) -> Any:
"""Performs an eth_call to an evm contract via etherscan
May raise:
- RemoteError if there is a problem with
reaching etherscan or with the returned result
"""
web3 = Web3()
contract = web3.eth.contract(address=contract_address, abi=abi)
input_data = contract.encodeABI(method_name, args=arguments if arguments else [])
result = self.etherscan.eth_call(
to_address=contract_address,
input_data=input_data,
)
if result == '0x':
raise BlockchainQueryError(
f'Error doing call on contract {contract_address} for {method_name} '
f'and chain {self.chain_name} with arguments: {arguments!s} '
f'via etherscan. Returned 0x result',
)
fn_abi = contract._find_matching_fn_abi(
fn_identifier=method_name,
args=arguments,
)
output_types = get_abi_output_types(fn_abi)
output_data = web3.codec.decode(output_types, bytes.fromhex(result[2:]))
if len(output_data) == 1:
# due to https://github.com/PyCQA/pylint/issues/4114
return output_data[0]
return output_data
def call_contract(
self,
contract_address: ChecksumEvmAddress,
abi: list,
method_name: str,
arguments: list[Any] | None = None,
call_order: Sequence[WeightedNode] | None = None,
block_identifier: BlockIdentifier = 'latest',
) -> Any:
return self._query(
method=self._call_contract,
call_order=call_order if call_order is not None else self.default_call_order(),
contract_address=contract_address,
abi=abi,
method_name=method_name,
arguments=arguments,
block_identifier=block_identifier,
)
def _call_contract(
self,
web3: Web3 | None,
contract_address: ChecksumEvmAddress,
abi: list,
method_name: str,
arguments: list[Any] | None = None,
block_identifier: BlockIdentifier = 'latest',
) -> Any:
"""Performs an eth_call to an evm contract
May raise:
- RemoteError if etherscan is used and there is a problem with
reaching it or with the returned result
- BlockchainQueryError if web3 is used and there is a VM execution error
"""
if web3 is None:
return self._call_contract_etherscan(
contract_address=contract_address,
abi=abi,
method_name=method_name,
arguments=arguments,
)
contract = web3.eth.contract(address=contract_address, abi=abi)
try:
method = getattr(contract.caller(block_identifier=block_identifier), method_name)
result = method(*arguments if arguments else [])
except (Web3Exception, ValueError) as e:
raise BlockchainQueryError(
f'Error doing call on contract {contract_address}: {e!s}',
) from e
return result
def _get_transaction_receipt(
self,
web3: Web3 | None,
tx_hash: EVMTxHash,
must_exist: bool = False,
) -> dict[str, Any] | None:
if tx_hash == GENESIS_HASH:
return FAKE_GENESIS_TX_RECEIPT
if web3 is None:
tx_receipt = self.etherscan.get_transaction_receipt(tx_hash)
if tx_receipt is None:
if must_exist: # fail, so other nodes can be tried
raise RemoteError(f'Querying for {self.chain_name} receipt {tx_hash.hex()} returned None') # noqa: E501
return None # else it does not exist
try:
# Turn hex numbers to int
block_number = int(tx_receipt['blockNumber'], 16)
tx_receipt['blockNumber'] = block_number
tx_receipt['cumulativeGasUsed'] = int(tx_receipt['cumulativeGasUsed'], 16)
tx_receipt['gasUsed'] = int(tx_receipt['gasUsed'], 16)
tx_receipt['status'] = int(tx_receipt.get('status', '0x1'), 16)
tx_index = int(tx_receipt['transactionIndex'], 16)
tx_receipt['transactionIndex'] = tx_index
for receipt_log in tx_receipt['logs']:
receipt_log['blockNumber'] = block_number
receipt_log['logIndex'] = deserialize_int_from_hex(
symbol=receipt_log['logIndex'],
location='etherscan tx receipt',
)
receipt_log['transactionIndex'] = tx_index
# This is only implemented for some evm chains
self._additional_receipt_processing(tx_receipt)
except (DeserializationError, Web3Exception, ValueError, KeyError) as e:
msg = str(e)
if isinstance(e, KeyError):
msg = f'missing key {msg}'
log.error(
f'Couldnt deserialize transaction receipt {tx_receipt} data from '
f'etherscan due to {msg}',
)
raise RemoteError(
f'Couldnt deserialize transaction receipt data from etherscan '
f'due to {msg}. Check logs for details',
) from e
if must_exist and tx_receipt is None: # fail, so other nodes can be tried
raise RemoteError(f'Querying for {self.chain_name} receipt {tx_hash.hex()} returned None') # noqa: E501
return tx_receipt
# Can raise TransactionNotFound if the user's node is pruned and transaction is old
try:
tx_receipt = web3.eth.get_transaction_receipt(tx_hash) # type: ignore
except TransactionNotFound as e:
if must_exist: # fail, so other nodes can be tried
raise RemoteError(f'Querying for {self.chain_name} receipt {tx_hash.hex()} returned None') from e # noqa: E501
raise # else re-raise e
return process_result(tx_receipt)
def maybe_get_transaction_receipt(
self,
tx_hash: EVMTxHash,
call_order: Sequence[WeightedNode] | None = None,
must_exist: bool = False,
) -> dict[str, Any] | None:
return self._query(
method=self._get_transaction_receipt,
call_order=call_order if call_order is not None else self.default_call_order(),
tx_hash=tx_hash,
must_exist=must_exist,
)
def get_transaction_receipt(
self,
tx_hash: EVMTxHash,
call_order: Sequence[WeightedNode] | None = None,
) -> dict[str, Any]:
"""Retrieves the transaction receipt for the tx_hash provided.
This method assumes the tx_hash is present on-chain,
and we are connected to at least one node that can retrieve it.
"""
tx_receipt = self.maybe_get_transaction_receipt(
call_order=call_order if call_order is not None else self.default_call_order(),
tx_hash=tx_hash,
must_exist=True,
)
if tx_receipt is None:
raise RemoteError(f'{self.chain_name} tx_receipt should exist for {tx_hash.hex()}')
return tx_receipt
def _get_transaction_by_hash(
self,
web3: Web3 | None,
tx_hash: EVMTxHash,
must_exist: bool = False,
) -> tuple[EvmTransaction, dict[str, Any]] | None:
if web3 is None:
tx_data = self.etherscan.get_transaction_by_hash(tx_hash=tx_hash)
else:
tx_data = web3.eth.get_transaction(tx_hash) # type: ignore
if tx_data is None:
if must_exist: # fail, so other nodes can be tried
raise RemoteError(f'Querying for {self.chain_name} transaction {tx_hash.hex()} returned None') # noqa: E501
return None # else it does not exist
try:
transaction, receipt_data = deserialize_evm_transaction(
data=tx_data,
internal=False,
chain_id=self.chain_id,
evm_inquirer=self,
)
except (DeserializationError, ValueError) as e:
raise RemoteError(
f'Couldnt deserialize evm transaction data from {tx_data}. Error: {e!s}',
) from e
if receipt_data is None:
raise RemoteError(f'{self.chain_name} transaction {tx_hash.hex()} receipt_data is expected to exist') # noqa: E501 # as etherscan getTransactionByHash does not contains gasUsed'
return transaction, receipt_data
def maybe_get_transaction_by_hash(
self,
tx_hash: EVMTxHash,
call_order: Sequence[WeightedNode] | None = None,
must_exist: bool = False,
) -> tuple[EvmTransaction, dict[str, Any]] | None:
"""Gets transaction by hash and raw receipt data"""
return self._query(
method=self._get_transaction_by_hash,
call_order=call_order if call_order is not None else self.default_call_order(),
tx_hash=tx_hash,
must_exist=must_exist,
)
def get_transaction_by_hash(
self,
tx_hash: EVMTxHash,
call_order: Sequence[WeightedNode] | None = None,
) -> tuple[EvmTransaction, dict[str, Any]]:
"""Retrieves information about a transaction from its hash.
This method assumes the tx_hash is present on-chain,
and we are connected to at least 1 node that can retrieve it.
"""
result = self.maybe_get_transaction_by_hash(
call_order=call_order if call_order is not None else self.default_call_order(),
tx_hash=tx_hash,
must_exist=True,
)
if result is None:
raise RemoteError(f'{self.chain_name} transaction {tx_hash.hex()} is expected to exist') # noqa: E501
return result
def get_logs(
self,
contract_address: ChecksumEvmAddress,
abi: list,
event_name: str,
argument_filters: dict[str, Any],
from_block: int,
to_block: int | Literal['latest'] = 'latest',
call_order: Sequence[WeightedNode] | None = None,
) -> list[dict[str, Any]]:
if call_order is None: # Default call order for logs
call_order = [self.etherscan_node]
if (node_info := self.get_own_node_info()) is not None:
call_order.append(
WeightedNode(
node_info=node_info,
active=True,
weight=ONE,
),
)
return self._query(
method=self._get_logs,
call_order=call_order,
contract_address=contract_address,
abi=abi,
event_name=event_name,
argument_filters=argument_filters,
from_block=from_block,
to_block=to_block,
)
def _get_logs(
self,
web3: Web3 | None,
contract_address: ChecksumEvmAddress,
abi: list,
event_name: str,
argument_filters: dict[str, Any],
from_block: int,
to_block: int | Literal['latest'] = 'latest',
) -> list[dict[str, Any]]:
"""Queries logs of an evm contract
May raise:
- EventNotInABI if the given event is not in the ABI
- RemoteError if etherscan is used and there is a problem with
reaching it or with the returned result
"""
try:
event_abi = find_matching_event_abi(abi=abi, event_name=event_name)
except ValueError as e:
raise EventNotInABI from e
_, filter_args = construct_event_filter_params(
event_abi=event_abi,
abi_codec=Web3().codec,
contract_address=contract_address,
argument_filters=argument_filters,
fromBlock=from_block,
toBlock=to_block,
)
if event_abi['anonymous']:
# web3.py does not handle the anonymous events correctly and adds the first topic
filter_args['topics'] = filter_args['topics'][1:]
events: list[dict[str, Any]] = []
start_block = from_block
if web3 is not None:
events = _query_web3_get_logs(
web3=web3,
filter_args=filter_args,
from_block=from_block,
to_block=to_block,
contract_address=contract_address,
event_name=event_name,
argument_filters=argument_filters,
initial_block_range=self.logquery_block_range(web3=web3, contract_address=contract_address), # noqa: E501
)
else: # etherscan
until_block = (
self.etherscan.get_latest_block_number() if to_block == 'latest' else to_block
)
blocks_step = 300000
while start_block <= until_block:
while True: # loop to continuously reduce block range if need b
end_block = min(start_block + blocks_step, until_block)
try:
new_events = self.etherscan.get_logs(
contract_address=contract_address,
topics=filter_args['topics'], # type: ignore
from_block=start_block,
to_block=end_block,
)
except RemoteError as e:
if 'Please select a smaller result dataset' in str(e):
blocks_step = blocks_step // 2
if blocks_step < 100:
raise # stop trying
# else try with the smaller step
continue
# else some other error
raise
break # we must have a result
# Turn all Hex ints to ints
for e_idx, event in enumerate(new_events):
try:
block_number = deserialize_int_from_hex(
symbol=event['blockNumber'],
location='etherscan log query',
)
log_index = deserialize_int_from_hex(
symbol=event['logIndex'],
location='etherscan log query',
)
# Try to see if the event is a duplicate that got returned
# in the previous iteration
for previous_event in reversed(events):
if previous_event['blockNumber'] < block_number:
break
same_event = (
previous_event['logIndex'] == log_index and
previous_event['transactionHash'] == event['transactionHash']
)
if same_event:
events.pop()