-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsession.py
1819 lines (1613 loc) · 74.2 KB
/
session.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 os
import sys
import math
import time
import errno
import codecs
import typing
import asyncio
import logging
import itertools
import collections
from bisect import bisect_right
from asyncio import Event, sleep
from collections import defaultdict, namedtuple
from contextlib import suppress
from functools import partial
from elasticsearch import ConnectionTimeout
from prometheus_client import Counter, Info, Histogram, Gauge
from hub.schema.result import Outputs
from hub.error import ResolveCensoredError, TooManyClaimSearchParametersError
from hub import __version__, PROMETHEUS_NAMESPACE
from hub.herald import PROTOCOL_MIN, PROTOCOL_MAX, HUB_PROTOCOL_VERSION
from hub.build_info import BUILD, COMMIT_HASH, DOCKER_TAG
from hub.herald.search import SearchIndex
from hub.common import sha256, hash_to_hex_str, hex_str_to_hash, HASHX_LEN, version_string, formatted_time, SIZE_BUCKETS
from hub.common import protocol_version, RPCError, DaemonError, TaskGroup, HISTOGRAM_BUCKETS, asyncify_for_loop
from hub.common import LRUCacheWithMetrics, LFUCacheWithMetrics, LargestValueCache
from hub.herald.jsonrpc import JSONRPCAutoDetect, JSONRPCConnection, JSONRPCv2, JSONRPC
from hub.herald.common import BatchRequest, ProtocolError, Request, Batch, Notification
from hub.herald.framer import NewlineFramer
if typing.TYPE_CHECKING:
from hub.db import SecondaryDB
from hub.herald.env import ServerEnv
from hub.scribe.daemon import LBCDaemon
from hub.herald.mempool import HubMemPool
PYTHON_VERSION = sys.version_info.major, sys.version_info.minor
TypedDict = dict if PYTHON_VERSION < (3, 8) else typing.TypedDict
BAD_REQUEST = 1
DAEMON_ERROR = 2
log = logging.getLogger(__name__)
SignatureInfo = namedtuple('SignatureInfo', 'min_args max_args '
'required_names other_names')
class CachedAddressHistoryItem(TypedDict):
tx_hash: str
height: int
def scripthash_to_hashX(scripthash: str) -> bytes:
try:
bin_hash = hex_str_to_hash(scripthash)
if len(bin_hash) == 32:
return bin_hash[:HASHX_LEN]
except Exception:
pass
raise RPCError(BAD_REQUEST, f'{scripthash} is not a valid script hash')
def non_negative_integer(value) -> int:
"""Return param value it is or can be converted to a non-negative
integer, otherwise raise an RPCError."""
try:
value = int(value)
if value >= 0:
return value
except ValueError:
pass
raise RPCError(BAD_REQUEST,
f'{value} should be a non-negative integer')
def assert_boolean(value) -> bool:
"""Return param value it is boolean otherwise raise an RPCError."""
if value in (False, True):
return value
raise RPCError(BAD_REQUEST, f'{value} should be a boolean value')
def assert_tx_hash(value: str) -> None:
"""Raise an RPCError if the value is not a valid transaction
hash."""
try:
if len(bytes.fromhex(value)) == 32:
return
except Exception:
pass
raise RPCError(BAD_REQUEST, f'{value} should be a transaction hash')
class Semaphores:
"""For aiorpcX's semaphore handling."""
def __init__(self, semaphores):
self.semaphores = semaphores
self.acquired = []
async def __aenter__(self):
for semaphore in self.semaphores:
await semaphore.acquire()
self.acquired.append(semaphore)
async def __aexit__(self, exc_type, exc_value, traceback):
for semaphore in self.acquired:
semaphore.release()
class SessionGroup:
def __init__(self, gid: int):
self.gid = gid
# Concurrency per group
self.semaphore = asyncio.Semaphore(20)
NAMESPACE = f"{PROMETHEUS_NAMESPACE}_hub"
class SessionManager:
"""Holds global state about all sessions."""
version_info_metric = Info(
'build', 'Wallet server build info (e.g. version, commit hash)', namespace=NAMESPACE
)
version_info_metric.info({
'build': BUILD,
"commit": COMMIT_HASH,
"docker_tag": DOCKER_TAG,
'version': __version__,
"min_version": version_string(PROTOCOL_MIN),
"cpu_count": str(os.cpu_count())
})
session_count_metric = Gauge("session_count", "Number of connected client sessions", namespace=NAMESPACE,
labelnames=("version",))
request_count_metric = Counter("requests_count", "Number of requests received", namespace=NAMESPACE,
labelnames=("method",))
tx_request_count_metric = Counter("requested_transaction", "Number of transactions requested", namespace=NAMESPACE)
tx_replied_count_metric = Counter("replied_transaction", "Number of transactions responded", namespace=NAMESPACE)
urls_to_resolve_count_metric = Counter("urls_to_resolve", "Number of urls to resolve", namespace=NAMESPACE)
resolved_url_count_metric = Counter("resolved_url", "Number of resolved urls", namespace=NAMESPACE)
db_operational_error_metric = Counter(
"operational_error", "Number of queries that raised operational errors", namespace=NAMESPACE
)
db_error_metric = Counter(
"internal_error", "Number of queries raising unexpected errors", namespace=NAMESPACE
)
executor_time_metric = Histogram(
"executor_time", "SQLite executor times", namespace=NAMESPACE, buckets=HISTOGRAM_BUCKETS
)
pending_query_metric = Gauge(
"pending_queries_count", "Number of pending and running sqlite queries", namespace=NAMESPACE
)
client_version_metric = Counter(
"clients", "Number of connections received per client version",
namespace=NAMESPACE, labelnames=("version",)
)
address_history_metric = Histogram(
"address_history", "Time to fetch an address history",
namespace=NAMESPACE, buckets=HISTOGRAM_BUCKETS
)
address_subscription_metric = Gauge(
"address_subscriptions", "Number of subscribed addresses",
namespace=NAMESPACE
)
address_history_size_metric = Histogram(
"history_size", "Sizes of histories for subscribed addresses",
namespace=NAMESPACE, buckets=SIZE_BUCKETS
)
notifications_in_flight_metric = Gauge(
"notifications_in_flight", "Count of notifications in flight",
namespace=NAMESPACE
)
notifications_sent_metric = Histogram(
"notifications_sent", "Time to send an address notification",
namespace=NAMESPACE, buckets=HISTOGRAM_BUCKETS
)
def __init__(self, env: 'ServerEnv', db: 'SecondaryDB', mempool: 'HubMemPool',
daemon: 'LBCDaemon', search_index: 'SearchIndex', shutdown_event: asyncio.Event,
on_available_callback: typing.Callable[[], None], on_unavailable_callback: typing.Callable[[], None]):
env.max_send = max(350000, env.max_send)
self.env = env
self.db = db
self.on_available_callback = on_available_callback
self.on_unavailable_callback = on_unavailable_callback
self.daemon = daemon
self.mempool = mempool
self.search_index = search_index
self.shutdown_event = shutdown_event
self.logger = logging.getLogger(__name__)
self.servers: typing.Dict[str, asyncio.AbstractServer] = {}
self.sessions: typing.Dict[int, 'LBRYElectrumX'] = {}
self.hashx_subscriptions_by_session: typing.DefaultDict[str, typing.Set[int]] = defaultdict(set)
self.mempool_statuses = {}
self.cur_group = SessionGroup(0)
self.txs_sent = 0
self.start_time = time.time()
self.resolve_cache = LRUCacheWithMetrics(
env.resolved_url_cache_size, metric_name='resolved_url', namespace=NAMESPACE
)
self.notified_height: typing.Optional[int] = None
# Cache some idea of room to avoid recounting on each subscription
self.subs_room = 0
self.protocol_class = LBRYElectrumX
self.session_event = Event()
self.running = False
# hashX: List[int]
self.hashX_raw_history_cache = LFUCacheWithMetrics(env.hashX_history_cache_size, metric_name='raw_history', namespace=NAMESPACE)
# hashX: List[CachedAddressHistoryItem]
self.hashX_history_cache = LargestValueCache(env.largest_hashX_history_cache_size)
# tx_num: Tuple[txid, height]
self.history_tx_info_cache = LFUCacheWithMetrics(env.history_tx_cache_size, metric_name='history_tx', namespace=NAMESPACE)
def clear_caches(self):
self.resolve_cache.clear()
def update_history_caches(self, touched_hashXs: typing.List[bytes]):
update_history_cache = {}
for hashX in set(touched_hashXs):
history_tx_nums = None
# if the history is the raw_history_cache, update it
# TODO: use a reversed iterator for this instead of rescanning it all
if hashX in self.hashX_raw_history_cache:
self.hashX_raw_history_cache[hashX] = history_tx_nums = self.db._read_history(hashX, None)
# if it's in hashX_history_cache, prepare to update it in a batch
if hashX in self.hashX_history_cache:
full_cached = self.hashX_history_cache[hashX]
if history_tx_nums is None:
history_tx_nums = self.db._read_history(hashX, None)
new_txs = history_tx_nums[len(full_cached):]
update_history_cache[hashX] = full_cached, new_txs
if update_history_cache:
# get the set of new tx nums that were touched in all of the new histories to be cached
total_tx_nums = set()
for _, new_txs in update_history_cache.values():
total_tx_nums.update(new_txs)
total_tx_nums = list(total_tx_nums)
# collect the total new tx infos
referenced_new_txs = {
tx_num: (CachedAddressHistoryItem(
tx_hash=tx_hash[::-1].hex(), height=bisect_right(self.db.tx_counts, tx_num)
)) for tx_num, tx_hash in zip(total_tx_nums, self.db._get_tx_hashes(total_tx_nums))
}
# update the cached history lists
get_referenced = referenced_new_txs.__getitem__
for hashX, (full, new_txs) in update_history_cache.items():
append_to_full = full.append
for tx_num in new_txs:
append_to_full(get_referenced(tx_num))
async def _start_server(self, kind, *args, **kw_args):
loop = asyncio.get_event_loop()
if kind == 'TCP':
protocol_class = self.protocol_class
else:
raise ValueError(kind)
protocol_factory = partial(protocol_class, self, kind)
host, port = args[:2]
try:
self.servers[kind] = await loop.create_server(protocol_factory, *args, **kw_args)
except Exception as e:
if not isinstance(e, asyncio.CancelledError):
self.logger.error(f'{kind} server failed to listen on '
f'{host}:{port:d} : {e!r}')
raise
else:
self.logger.info(f'{kind} server listening on {host}:{port:d}')
async def _start_external_servers(self):
"""Start listening on TCP and SSL ports, but only if the respective
port was given in the environment.
"""
env = self.env
host = env.cs_host()
if env.tcp_port is None:
return
started = False
while not started:
try:
await self._start_server('TCP', host, env.tcp_port)
started = True
except OSError as e:
if e.errno is errno.EADDRINUSE:
await asyncio.sleep(3)
continue
raise
async def _close_servers(self, kinds):
"""Close the servers of the given kinds (TCP etc.)."""
if kinds:
self.logger.info('closing down {} listening servers'
.format(', '.join(kinds)))
for kind in kinds:
server = self.servers.pop(kind, None)
if server:
server.close()
await server.wait_closed()
async def _manage_servers(self):
paused = False
max_sessions = self.env.max_sessions
low_watermark = int(max_sessions * 0.95)
while True:
await self.session_event.wait()
self.session_event.clear()
if not paused and len(self.sessions) >= max_sessions:
self.on_unavailable_callback()
self.logger.info(f'maximum sessions {max_sessions:,d} '
f'reached, stopping new connections until '
f'count drops to {low_watermark:,d}')
await self._close_servers(['TCP', 'SSL'])
paused = True
# Start listening for incoming connections if paused and
# session count has fallen
if paused and len(self.sessions) <= low_watermark:
self.on_available_callback()
self.logger.info('resuming listening for incoming connections')
await self._start_external_servers()
paused = False
def _group_map(self):
group_map = defaultdict(list)
for session in self.sessions.values():
group_map[session.group].append(session)
return group_map
def _sub_count(self) -> int:
return sum(s.sub_count() for s in self.sessions.values())
def _lookup_session(self, session_id):
try:
session_id = int(session_id)
except Exception:
pass
else:
for session in self.sessions.values():
if session.session_id == session_id:
return session
return None
async def _for_each_session(self, session_ids, operation):
if not isinstance(session_ids, list):
raise RPCError(BAD_REQUEST, 'expected a list of session IDs')
result = []
for session_id in session_ids:
session = self._lookup_session(session_id)
if session:
result.append(await operation(session))
else:
result.append(f'unknown session: {session_id}')
return result
async def _clear_stale_sessions(self):
"""Cut off sessions that haven't done anything for 10 minutes."""
session_timeout = self.env.session_timeout
while True:
await sleep(session_timeout // 10)
stale_cutoff = time.perf_counter() - session_timeout
stale_sessions = [session for session in self.sessions.values()
if session.last_recv < stale_cutoff]
if stale_sessions:
text = ', '.join(str(session.session_id)
for session in stale_sessions)
self.logger.info(f'closing stale connections {text}')
# Give the sockets some time to close gracefully
if stale_sessions:
await asyncio.wait([
session.close(force_after=session_timeout // 10) for session in stale_sessions
])
# Consolidate small groups
group_map = self._group_map()
groups = [group for group, sessions in group_map.items()
if len(sessions) <= 5] # fixme: apply session cost here
if len(groups) > 1:
new_group = groups[-1]
for group in groups:
for session in group_map[group]:
session.group = new_group
def _get_info(self):
"""A summary of server state."""
group_map = self._group_map()
method_counts = collections.defaultdict(int)
error_count = 0
logged = 0
paused = 0
pending_requests = 0
closing = 0
for s in self.sessions.values():
error_count += s.errors
if s.log_me:
logged += 1
if not s._can_send.is_set():
paused += 1
pending_requests += s.count_pending_items()
if s.is_closing():
closing += 1
for request, _ in s.connection._requests.values():
method_counts[request.method] += 1
return {
'closing': closing,
'daemon': self.daemon.logged_url(),
'daemon_height': self.daemon.cached_height(),
'db_height': self.db.db_height,
'errors': error_count,
'groups': len(group_map),
'logged': logged,
'paused': paused,
'pid': os.getpid(),
'peers': [],
'requests': pending_requests,
'method_counts': method_counts,
'sessions': self.session_count(),
'subs': self._sub_count(),
'txs_sent': self.txs_sent,
'uptime': formatted_time(time.time() - self.start_time),
'version': __version__,
}
def _group_data(self):
"""Returned to the RPC 'groups' call."""
result = []
group_map = self._group_map()
for group, sessions in group_map.items():
result.append([group.gid,
len(sessions),
sum(s.bw_charge for s in sessions),
sum(s.count_pending_items() for s in sessions),
sum(s.txs_sent for s in sessions),
sum(s.sub_count() for s in sessions),
sum(s.recv_count for s in sessions),
sum(s.recv_size for s in sessions),
sum(s.send_count for s in sessions),
sum(s.send_size for s in sessions),
])
return result
async def _electrum_and_raw_headers(self, height):
raw_header = await self.raw_header(height)
electrum_header = self.env.coin.electrum_header(raw_header, height)
return electrum_header, raw_header
async def _refresh_hsub_results(self, height):
"""Refresh the cached header subscription responses to be for height,
and record that as notified_height.
"""
# Paranoia: a reorg could race and leave db_height lower
height = min(height, self.db.db_height)
electrum, raw = await self._electrum_and_raw_headers(height)
self.hsub_results = (electrum, {'hex': raw.hex(), 'height': height})
self.notified_height = height
# --- LocalRPC command handlers
#
# async def rpc_add_peer(self, real_name):
# """Add a peer.
#
# real_name: "bch.electrumx.cash t50001 s50002" for example
# """
# await self._notify_peer(real_name)
# return f"peer '{real_name}' added"
#
# async def rpc_disconnect(self, session_ids):
# """Disconnect sessions.
#
# session_ids: array of session IDs
# """
# async def close(session):
# """Close the session's transport."""
# await session.close(force_after=2)
# return f'disconnected {session.session_id}'
#
# return await self._for_each_session(session_ids, close)
#
# async def rpc_log(self, session_ids):
# """Toggle logging of sessions.
#
# session_ids: array of session IDs
# """
# async def toggle_logging(session):
# """Toggle logging of the session."""
# session.toggle_logging()
# return f'log {session.session_id}: {session.log_me}'
#
# return await self._for_each_session(session_ids, toggle_logging)
#
# async def rpc_daemon_url(self, daemon_url):
# """Replace the daemon URL."""
# daemon_url = daemon_url or self.env.daemon_url
# try:
# self.daemon.set_url(daemon_url)
# except Exception as e:
# raise RPCError(BAD_REQUEST, f'an error occurred: {e!r}')
# return f'now using daemon at {self.daemon.logged_url()}'
#
# async def rpc_stop(self):
# """Shut down the server cleanly."""
# self.shutdown_event.set()
# return 'stopping'
#
# async def rpc_getinfo(self):
# """Return summary information about the server process."""
# return self._get_info()
#
# async def rpc_groups(self):
# """Return statistics about the session groups."""
# return self._group_data()
#
# async def rpc_peers(self):
# """Return a list of data about server peers."""
# return self.env.peer_hubs
#
# async def rpc_query(self, items, limit):
# """Return a list of data about server peers."""
# coin = self.env.coin
# db = self.db
# lines = []
#
# def arg_to_hashX(arg):
# try:
# script = bytes.fromhex(arg)
# lines.append(f'Script: {arg}')
# return coin.hashX_from_script(script)
# except ValueError:
# pass
#
# try:
# hashX = coin.address_to_hashX(arg)
# except Base58Error as e:
# lines.append(e.args[0])
# return None
# lines.append(f'Address: {arg}')
# return hashX
#
# for arg in items:
# hashX = arg_to_hashX(arg)
# if not hashX:
# continue
# n = None
# history = await db.limited_history(hashX, limit=limit)
# for n, (tx_hash, height) in enumerate(history):
# lines.append(f'History #{n:,d}: height {height:,d} '
# f'tx_hash {hash_to_hex_str(tx_hash)}')
# if n is None:
# lines.append('No history found')
# n = None
# utxos = await db.all_utxos(hashX)
# for n, utxo in enumerate(utxos, start=1):
# lines.append(f'UTXO #{n:,d}: tx_hash '
# f'{hash_to_hex_str(utxo.tx_hash)} '
# f'tx_pos {utxo.tx_pos:,d} height '
# f'{utxo.height:,d} value {utxo.value:,d}')
# if n == limit:
# break
# if n is None:
# lines.append('No UTXOs found')
#
# balance = sum(utxo.value for utxo in utxos)
# lines.append(f'Balance: {coin.decimal_value(balance):,f} '
# f'{coin.SHORTNAME}')
#
# return lines
# async def rpc_reorg(self, count):
# """Force a reorg of the given number of blocks.
#
# count: number of blocks to reorg
# """
# count = non_negative_integer(count)
# if not self.bp.force_chain_reorg(count):
# raise RPCError(BAD_REQUEST, 'still catching up with daemon')
# return f'scheduled a reorg of {count:,d} blocks'
# --- External Interface
async def serve(self, mempool, server_listening_event):
"""Start the RPC server if enabled. When the event is triggered,
start TCP and SSL servers."""
try:
self.logger.info(f'max session count: {self.env.max_sessions:,d}')
self.logger.info(f'session timeout: '
f'{self.env.session_timeout:,d} seconds')
self.logger.info(f'max response size {self.env.max_send:,d} bytes')
if self.env.drop_client is not None:
self.logger.info(f'drop clients matching: {self.env.drop_client.pattern}')
# Start notifications; initialize hsub_results
await mempool.start(self.db.db_height, self)
await self.start_other()
await self._start_external_servers()
server_listening_event.set()
self.on_available_callback()
# Peer discovery should start after the external servers
# because we connect to ourself
await asyncio.wait([
self._clear_stale_sessions(),
self._manage_servers()
])
except Exception as err:
if not isinstance(err, asyncio.CancelledError):
log.exception("hub server died")
raise err
finally:
await self._close_servers(list(self.servers.keys()))
log.info("disconnect %i sessions", len(self.sessions))
if self.sessions:
await asyncio.wait([
session.close(force_after=1) for session in self.sessions.values()
])
await self.stop_other()
async def start_other(self):
self.running = True
async def stop_other(self):
self.running = False
def session_count(self) -> int:
"""The number of connections that we've sent something to."""
return len(self.sessions)
async def daemon_request(self, method, *args):
"""Catch a DaemonError and convert it to an RPCError."""
try:
return await getattr(self.daemon, method)(*args)
except DaemonError as e:
raise RPCError(DAEMON_ERROR, f'daemon error: {e!r}') from None
async def raw_header(self, height):
"""Return the binary header at the given height."""
try:
return await self.db.raw_header(height)
except IndexError:
raise RPCError(BAD_REQUEST, f'height {height:,d} '
'out of range') from None
async def electrum_header(self, height):
"""Return the deserialized header at the given height."""
electrum_header, _ = await self._electrum_and_raw_headers(height)
return electrum_header
async def broadcast_transaction(self, raw_tx):
hex_hash = await self.daemon.broadcast_transaction(raw_tx)
self.txs_sent += 1
return hex_hash
async def _cached_raw_history(self, hashX: bytes, limit: typing.Optional[int] = None):
tx_nums = self.hashX_raw_history_cache.get(hashX)
if tx_nums is None:
self.hashX_raw_history_cache[hashX] = tx_nums = await self.db.read_history(hashX, limit)
return tx_nums
async def cached_confirmed_history(self, hashX: bytes,
limit: typing.Optional[int] = None) -> typing.List[CachedAddressHistoryItem]:
cached_full_history = self.hashX_history_cache.get(hashX)
# return the cached history
if cached_full_history is not None:
self.address_history_size_metric.observe(len(cached_full_history))
return cached_full_history
# return the history and update the caches
tx_nums = await self._cached_raw_history(hashX, limit)
needed_tx_infos = []
append_needed_tx_info = needed_tx_infos.append
tx_infos = {}
for cnt, tx_num in enumerate(tx_nums): # determine which tx_hashes are cached and which we need to look up
cached = self.history_tx_info_cache.get(tx_num)
if cached is not None:
tx_infos[tx_num] = cached
else:
append_needed_tx_info(tx_num)
if cnt % 1000 == 0:
await asyncio.sleep(0)
if needed_tx_infos: # request all the needed tx hashes in one batch, cache the txids and heights
for cnt, (tx_num, tx_hash) in enumerate(zip(needed_tx_infos, await self.db.get_tx_hashes(needed_tx_infos))):
hist = CachedAddressHistoryItem(tx_hash=tx_hash[::-1].hex(), height=bisect_right(self.db.tx_counts, tx_num))
tx_infos[tx_num] = self.history_tx_info_cache[tx_num] = hist
if cnt % 1000 == 0:
await asyncio.sleep(0)
# ensure the ordering of the txs
history = []
history_append = history.append
for cnt, tx_num in enumerate(tx_nums):
history_append(tx_infos[tx_num])
if cnt % 1000 == 0:
await asyncio.sleep(0)
self.hashX_history_cache[hashX] = history
self.address_history_size_metric.observe(len(history))
return history
def _notify_peer(self, peer):
notify_count = 0
for session in self.sessions.values():
if session.subscribe_peers:
notify_count += 1
session.send_notification('blockchain.peers.subscribe', [peer])
if notify_count:
self.logger.info(f'notify {notify_count} sessions of new peers')
def add_session(self, session):
self.sessions[id(session)] = session
self.session_event.set()
gid = int(session.start_time - self.start_time) // 900
if self.cur_group.gid != gid:
self.cur_group = SessionGroup(gid)
return self.cur_group
def remove_session(self, session):
"""Remove a session from our sessions list if there."""
session_id = id(session)
self.address_subscription_metric.dec(len(session.hashX_subs))
for hashX in session.hashX_subs:
sessions = self.hashx_subscriptions_by_session[hashX]
sessions.remove(session_id)
if not sessions:
self.hashx_subscriptions_by_session.pop(hashX)
self.sessions.pop(session_id)
self.session_event.set()
class LBRYElectrumX(asyncio.Protocol):
"""A TCP server that handles incoming Electrum connections."""
PROTOCOL_MIN = PROTOCOL_MIN
PROTOCOL_MAX = PROTOCOL_MAX
max_errors = math.inf # don't disconnect people for errors! let them happen...
version = HUB_PROTOCOL_VERSION
cached_server_features = {}
MAX_CHUNK_SIZE = 40960
session_counter = itertools.count()
RESPONSE_TIMES = Histogram("response_time", "Response times", namespace=NAMESPACE,
labelnames=("method",), buckets=HISTOGRAM_BUCKETS)
NOTIFICATION_COUNT = Counter("notification", "Number of notifications sent (for subscriptions)",
namespace=NAMESPACE, labelnames=("method",))
REQUEST_ERRORS_COUNT = Counter(
"request_error", "Number of requests that returned errors", namespace=NAMESPACE,
labelnames=("method", "version")
)
RESET_CONNECTIONS = Counter(
"reset_clients", "Number of reset connections by client version",
namespace=NAMESPACE, labelnames=("version",)
)
max_errors = 10
def __init__(self, session_manager: SessionManager, kind: str):
connection = JSONRPCConnection(JSONRPCAutoDetect)
self.env = session_manager.env
self.framer = self.default_framer()
self.loop = asyncio.get_event_loop()
self.logger = logging.getLogger(self.__class__.__name__)
self.transport = None
# Set when a connection is made
self._address = None
self._proxy_address = None
# For logger.debug messages
self.verbosity = 0
# Cleared when the send socket is full
self._can_send = Event()
self._can_send.set()
self._pm_task = None
self._task_group = TaskGroup(self.loop)
# Force-close a connection if a send doesn't succeed in this time
self.max_send_delay = 60
# Statistics. The RPC object also keeps its own statistics.
self.start_time = time.perf_counter()
self.errors = 0
self.send_count = 0
self.send_size = 0
self.last_send = self.start_time
self.recv_count = 0
self.recv_size = 0
self.last_recv = self.start_time
self.last_packet_received = self.start_time
self.connection = connection or self.default_connection()
self.client_version = 'unknown'
self.logger = logging.getLogger(__name__)
self.session_manager = session_manager
self.kind = kind # 'RPC', 'TCP' etc.
self.coin = self.env.coin
self.txs_sent = 0
self.log_me = False
self.daemon_request = self.session_manager.daemon_request
if not LBRYElectrumX.cached_server_features:
LBRYElectrumX.set_server_features(self.env)
self.subscribe_headers = False
self.subscribe_headers_raw = False
self.subscribe_peers = False
self.connection.max_response_size = self.env.max_send
self.hashX_subs = {}
self.sv_seen = False
self.protocol_tuple = self.PROTOCOL_MIN
self.protocol_string = None
self.daemon = self.session_manager.daemon
self.db = self.session_manager.db
self.mempool = self.session_manager.mempool
def data_received(self, framed_message):
"""Called by asyncio when a message comes in."""
self.last_packet_received = time.perf_counter()
if self.verbosity >= 4:
self.logger.debug(f'Received framed message {framed_message}')
self.recv_size += len(framed_message)
self.framer.received_bytes(framed_message)
def pause_writing(self):
"""Transport calls when the send buffer is full."""
if not self.is_closing():
self._can_send.clear()
self.transport.pause_reading()
def resume_writing(self):
"""Transport calls when the send buffer has room."""
if not self._can_send.is_set():
self._can_send.set()
self.transport.resume_reading()
def connection_made(self, transport):
"""Handle an incoming client connection."""
self.transport = transport
# This would throw if called on a closed SSL transport. Fixed
# in asyncio in Python 3.6.1 and 3.5.4
peer_address = transport.get_extra_info('peername')
# If the Socks proxy was used then _address is already set to
# the remote address
if self._address:
self._proxy_address = peer_address
else:
self._address = peer_address
self._pm_task = self.loop.create_task(self._receive_messages())
self.session_id = next(self.session_counter)
# context = {'conn_id': f'{self.session_id}'}
# self.logger = logging.getLogger(__name__) # util.ConnectionLogger(self.logger, context)
self.group = self.session_manager.add_session(self)
self.session_manager.session_count_metric.labels(version=self.client_version).inc()
# self.logger.info(f'{self.kind} {self.peer_address_str()}, {self.session_manager.session_count():,d} total')
def connection_lost(self, exc):
"""Handle client disconnection."""
self.connection.raise_pending_requests(exc)
self._address = None
self.transport = None
self._task_group.cancel()
if self._pm_task:
self._pm_task.cancel()
# Release waiting tasks
self._can_send.set()
self.session_manager.remove_session(self)
self.session_manager.session_count_metric.labels(version=self.client_version).dec()
msg = ''
if not self._can_send.is_set():
msg += ' whilst paused'
if self.send_size >= 1024 * 1024:
msg += ('. Sent {:,d} bytes in {:,d} messages'
.format(self.send_size, self.send_count))
if msg:
msg = 'disconnected' + msg
self.logger.info(msg)
def default_framer(self):
return NewlineFramer(self.env.max_receive)
def toggle_logging(self):
self.log_me = not self.log_me
def count_pending_items(self):
return len(self.connection.pending_requests())
def semaphore(self):
return Semaphores([self.group.semaphore])
async def handle_request(self, request):
"""Handle an incoming request. ElectrumX doesn't receive
notifications from client sessions.
"""
if isinstance(request, Request):
method = request.method
if method == 'blockchain.block.get_chunk':
coro = self.block_get_chunk
elif method == 'blockchain.block.get_header':
coro = self.block_get_header
elif method == 'blockchain.block.get_server_height':
coro = self.get_server_height
elif method == 'blockchain.scripthash.get_history':
coro = self.scripthash_get_history
elif method == 'blockchain.scripthash.get_mempool':
coro = self.scripthash_get_mempool
elif method == 'blockchain.scripthash.subscribe':
coro = self.scripthash_subscribe
elif method == 'blockchain.scripthash.unsubscribe':
coro = self.scripthash_unsubscribe
elif method == 'blockchain.scripthash.get_balance':
coro = self.scripthash_get_balance
elif method == 'blockchain.scripthash.listunspent':
coro = self.scripthash_listunspent
elif method == 'blockchain.transaction.broadcast':
coro = self.transaction_broadcast
elif method == 'blockchain.transaction.get':
coro = self.transaction_get
elif method == 'blockchain.transaction.get_batch':
coro = self.transaction_get_batch
elif method == 'blockchain.transaction.info':
coro = self.transaction_info
elif method == 'blockchain.transaction.get_merkle':
coro = self.transaction_merkle
elif method == 'blockchain.transaction.get_height':
coro = self.transaction_get_height
elif method == 'blockchain.block.headers':
coro = self.block_headers
elif method == 'server.banner':
coro = self.banner
elif method == 'server.payment_address':
coro = self.payment_address
elif method == 'server.donation_address':
coro = self.donation_address
elif method == 'server.features':
coro = self.server_features_async
elif method == 'server.peers.subscribe':
coro = self.peers_subscribe
elif method == 'server.version':
coro = self.server_version
elif method == 'blockchain.claimtrie.search':
coro = self.claimtrie_search
elif method == 'blockchain.claimtrie.resolve':
coro = self.claimtrie_resolve
elif method == 'blockchain.claimtrie.getclaimbyid':
coro = self.claimtrie_getclaimbyid
elif method == 'mempool.get_fee_histogram':
coro = self.mempool_compact_histogram
elif method == 'server.ping':
coro = self.ping
elif method == 'blockchain.headers.subscribe':
coro = self.headers_subscribe_False
elif method == 'blockchain.address.get_history':
coro = self.address_get_history
elif method == 'blockchain.address.get_mempool':
coro = self.address_get_mempool
elif method == 'blockchain.address.subscribe':
coro = self.address_subscribe
elif method == 'blockchain.address.unsubscribe':
coro = self.address_unsubscribe
elif method == 'blockchain.address.listunspent':
coro = self.address_listunspent
elif method == 'blockchain.address.getbalance':
coro = self.address_get_balance
elif method == 'blockchain.estimatefee':
coro = self.estimatefee
elif method == 'blockchain.relayfee':
coro = self.relayfee
else:
raise RPCError(JSONRPC.METHOD_NOT_FOUND, f'unknown method "{method}"')
else:
raise ValueError
self.session_manager.request_count_metric.labels(method=request.method).inc()
if isinstance(request.args, dict):
return await coro(**request.args)
return await coro(*request.args)
async def _limited_wait(self, secs):
try:
await asyncio.wait_for(self._can_send.wait(), secs)
except asyncio.TimeoutError:
self.abort()
raise asyncio.TimeoutError(f'task timed out after {secs}s')
async def _send_message(self, message):
if not self._can_send.is_set():
await self._limited_wait(self.max_send_delay)
if not self.is_closing():
framed_message = self.framer.frame(message)
self.send_size += len(framed_message)
self.send_count += 1
self.last_send = time.perf_counter()
if self.verbosity >= 4:
self.logger.debug(f'Sending framed message {framed_message}')
self.transport.write(framed_message)
def _bump_errors(self):
self.errors += 1
if self.errors >= self.max_errors:
# Don't await self.close() because that is self-cancelling
self._close()
def _close(self):
if self.transport: