2022-02-16 06:49:32 +00:00
|
|
|
import socks
|
|
|
|
|
2022-08-03 05:23:22 +00:00
|
|
|
from gossip.peerset import gossip_peer_set
|
|
|
|
import logger
|
|
|
|
|
2022-08-17 00:30:05 +00:00
|
|
|
|
2022-08-03 05:23:22 +00:00
|
|
|
class HandleRevc:
|
|
|
|
def __init__(self, sock):
|
|
|
|
self.sock_recv = sock.recv
|
2022-08-17 00:30:05 +00:00
|
|
|
self.sock = sock
|
2022-08-03 05:23:22 +00:00
|
|
|
|
|
|
|
def recv(self, *args, **kwargs):
|
2022-08-17 00:30:05 +00:00
|
|
|
try:
|
|
|
|
got_data = self.sock_recv(*args, **kwargs)
|
|
|
|
if not len(got_data):
|
|
|
|
raise ConnectionError("Peer socket returned empty value")
|
|
|
|
return got_data
|
|
|
|
except Exception:
|
|
|
|
try:
|
|
|
|
gossip_peer_set.remove(self.sock)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
raise
|
2022-08-03 05:23:22 +00:00
|
|
|
|
2022-02-16 06:49:32 +00:00
|
|
|
|
|
|
|
class TorPeer:
|
|
|
|
|
|
|
|
def __init__(self, socks_host, socks_port, onion_address):
|
2022-03-02 13:29:59 +00:00
|
|
|
if not onion_address or onion_address == '.onion':
|
|
|
|
raise ValueError("Invalid transport address")
|
2022-04-20 05:28:29 +00:00
|
|
|
if not onion_address.endswith('.onion'):
|
|
|
|
self.onion_address = onion_address.strip() + '.onion'
|
|
|
|
|
2022-02-22 20:34:19 +00:00
|
|
|
self.transport_address = self.onion_address = onion_address
|
2022-02-16 06:49:32 +00:00
|
|
|
self.socks_host = socks_host
|
|
|
|
self.socks_port = socks_port
|
|
|
|
|
2022-03-20 17:51:25 +00:00
|
|
|
def get_socket(self, connect_timeout) -> socks.socksocket:
|
2022-04-20 05:28:29 +00:00
|
|
|
|
2022-02-16 06:49:32 +00:00
|
|
|
s = socks.socksocket()
|
2022-02-21 21:15:26 +00:00
|
|
|
s.set_proxy(socks.SOCKS4, self.socks_host, self.socks_port, rdns=True)
|
2022-03-20 17:51:25 +00:00
|
|
|
s.settimeout(connect_timeout)
|
2022-08-03 05:23:22 +00:00
|
|
|
try:
|
|
|
|
s.connect((self.onion_address, 80))
|
|
|
|
except socks.GeneralProxyError:
|
|
|
|
try:
|
|
|
|
gossip_peer_set.remove(self)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
else:
|
2022-09-02 02:31:49 +00:00
|
|
|
logger.debug(
|
|
|
|
f"Could not create socket to peer {self.transport_address}",
|
|
|
|
terminal=True)
|
2022-08-17 00:30:05 +00:00
|
|
|
raise TimeoutError
|
2022-08-03 05:23:22 +00:00
|
|
|
mock_recv = HandleRevc(s)
|
|
|
|
s.recv = mock_recv.recv
|
2022-02-16 06:49:32 +00:00
|
|
|
return s
|
2022-02-26 07:06:17 +00:00
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
return hash(self.transport_address)
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
try:
|
|
|
|
return self.transport_address == other.transport_address
|
|
|
|
except AttributeError:
|
|
|
|
return False
|