2022-09-30 11:40:22 +03:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2019-08-22 07:19:24 +03:00
|
|
|
import asyncio
|
2019-11-18 07:49:39 +03:00
|
|
|
import logging
|
2020-11-05 09:34:34 +03:00
|
|
|
import ssl
|
2021-01-26 17:38:39 +03:00
|
|
|
import time
|
2021-03-10 05:27:27 +03:00
|
|
|
import traceback
|
2022-11-03 19:28:23 +03:00
|
|
|
from dataclasses import dataclass, field
|
2023-02-22 21:03:41 +03:00
|
|
|
from ipaddress import IPv4Network, IPv6Network, ip_network
|
2020-10-09 01:50:39 +03:00
|
|
|
from pathlib import Path
|
2023-07-28 22:48:32 +03:00
|
|
|
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union, cast
|
2021-03-10 05:27:27 +03:00
|
|
|
|
2022-10-01 01:50:46 +03:00
|
|
|
from aiohttp import (
|
|
|
|
ClientResponseError,
|
|
|
|
ClientSession,
|
|
|
|
ClientTimeout,
|
|
|
|
ServerDisconnectedError,
|
|
|
|
WSCloseCode,
|
|
|
|
client_exceptions,
|
|
|
|
web,
|
|
|
|
)
|
2021-02-04 04:57:52 +03:00
|
|
|
from cryptography import x509
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
|
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
2022-11-03 19:28:23 +03:00
|
|
|
from typing_extensions import final
|
2020-10-28 20:45:10 +03:00
|
|
|
|
2021-04-04 06:55:26 +03:00
|
|
|
from chia.protocols.protocol_message_types import ProtocolMessageTypes
|
2021-09-20 21:31:15 +03:00
|
|
|
from chia.protocols.protocol_state_machine import message_requires_reply
|
2022-12-09 12:47:46 +03:00
|
|
|
from chia.protocols.protocol_timing import INVALID_PROTOCOL_BAN_SECONDS
|
|
|
|
from chia.protocols.shared_protocol import protocol_version
|
2023-06-14 04:12:25 +03:00
|
|
|
from chia.server.api_protocol import ApiProtocol
|
2021-04-04 06:55:26 +03:00
|
|
|
from chia.server.introducer_peers import IntroducerPeers
|
|
|
|
from chia.server.outbound_message import Message, NodeType
|
|
|
|
from chia.server.ssl_context import private_ssl_paths, public_ssl_paths
|
2022-12-09 12:47:46 +03:00
|
|
|
from chia.server.ws_connection import ConnectionCallback, WSChiaConnection
|
2021-04-04 06:55:26 +03:00
|
|
|
from chia.types.blockchain_format.sized_bytes import bytes32
|
|
|
|
from chia.types.peer_info import PeerInfo
|
|
|
|
from chia.util.errors import Err, ProtocolError
|
2022-12-09 12:47:46 +03:00
|
|
|
from chia.util.ints import uint16
|
2023-02-20 19:23:39 +03:00
|
|
|
from chia.util.network import WebServer, is_in_network, is_localhost, is_trusted_peer
|
2021-10-12 23:59:29 +03:00
|
|
|
from chia.util.ssl_check import verify_ssl_certs_and_keys
|
2023-07-28 22:48:32 +03:00
|
|
|
from chia.util.streamable import Streamable
|
2021-03-10 09:48:34 +03:00
|
|
|
|
2022-04-05 20:19:09 +03:00
|
|
|
max_message_size = 50 * 1024 * 1024 # 50MB
|
|
|
|
|
2020-05-20 21:36:53 +03:00
|
|
|
|
2020-11-05 09:34:34 +03:00
|
|
|
def ssl_context_for_server(
|
2021-08-16 01:53:54 +03:00
|
|
|
ca_cert: Path,
|
|
|
|
ca_key: Path,
|
2023-03-30 04:16:22 +03:00
|
|
|
cert_path: Path,
|
|
|
|
key_path: Path,
|
2021-08-16 01:53:54 +03:00
|
|
|
*,
|
|
|
|
check_permissions: bool = True,
|
|
|
|
log: Optional[logging.Logger] = None,
|
2022-03-17 19:06:22 +03:00
|
|
|
) -> ssl.SSLContext:
|
2021-08-16 01:53:54 +03:00
|
|
|
if check_permissions:
|
2023-03-30 04:16:22 +03:00
|
|
|
verify_ssl_certs_and_keys([ca_cert, cert_path], [ca_key, key_path], log)
|
2021-08-16 01:53:54 +03:00
|
|
|
|
2022-04-20 21:05:52 +03:00
|
|
|
ssl_context = ssl._create_unverified_context(purpose=ssl.Purpose.CLIENT_AUTH, cafile=str(ca_cert))
|
2021-02-04 04:57:52 +03:00
|
|
|
ssl_context.check_hostname = False
|
2022-01-11 08:02:23 +03:00
|
|
|
ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
|
|
ssl_context.set_ciphers(
|
2023-10-24 20:01:23 +03:00
|
|
|
"ECDHE-ECDSA-AES256-GCM-SHA384:"
|
|
|
|
"ECDHE-RSA-AES256-GCM-SHA384:"
|
|
|
|
"ECDHE-ECDSA-CHACHA20-POLY1305:"
|
|
|
|
"ECDHE-RSA-CHACHA20-POLY1305:"
|
|
|
|
"ECDHE-ECDSA-AES128-GCM-SHA256:"
|
|
|
|
"ECDHE-RSA-AES128-GCM-SHA256:"
|
|
|
|
"ECDHE-ECDSA-AES256-SHA384:"
|
|
|
|
"ECDHE-RSA-AES256-SHA384:"
|
|
|
|
"ECDHE-ECDSA-AES128-SHA256:"
|
|
|
|
"ECDHE-RSA-AES128-SHA256"
|
2022-01-11 08:02:23 +03:00
|
|
|
)
|
2023-03-30 04:16:22 +03:00
|
|
|
ssl_context.load_cert_chain(certfile=str(cert_path), keyfile=str(key_path))
|
2021-02-04 04:57:52 +03:00
|
|
|
ssl_context.verify_mode = ssl.CERT_REQUIRED
|
2020-11-05 09:34:34 +03:00
|
|
|
return ssl_context
|
|
|
|
|
|
|
|
|
2021-03-04 04:26:26 +03:00
|
|
|
def ssl_context_for_root(
|
2021-08-16 01:53:54 +03:00
|
|
|
ca_cert_file: str, *, check_permissions: bool = True, log: Optional[logging.Logger] = None
|
2022-03-17 19:06:22 +03:00
|
|
|
) -> ssl.SSLContext:
|
2021-08-16 01:53:54 +03:00
|
|
|
if check_permissions:
|
2021-08-26 01:32:17 +03:00
|
|
|
verify_ssl_certs_and_keys([Path(ca_cert_file)], [], log)
|
2021-08-16 01:53:54 +03:00
|
|
|
|
2021-03-05 01:25:35 +03:00
|
|
|
ssl_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=ca_cert_file)
|
2021-03-04 04:26:26 +03:00
|
|
|
return ssl_context
|
|
|
|
|
|
|
|
|
2021-02-04 04:57:52 +03:00
|
|
|
def ssl_context_for_client(
|
|
|
|
ca_cert: Path,
|
|
|
|
ca_key: Path,
|
2023-03-30 04:18:51 +03:00
|
|
|
cert_path: Path,
|
|
|
|
key_path: Path,
|
2021-08-16 01:53:54 +03:00
|
|
|
*,
|
|
|
|
check_permissions: bool = True,
|
|
|
|
log: Optional[logging.Logger] = None,
|
2022-03-17 19:06:22 +03:00
|
|
|
) -> ssl.SSLContext:
|
2021-08-16 01:53:54 +03:00
|
|
|
if check_permissions:
|
2023-03-30 04:18:51 +03:00
|
|
|
verify_ssl_certs_and_keys([ca_cert, cert_path], [ca_key, key_path], log)
|
2021-08-16 01:53:54 +03:00
|
|
|
|
2021-02-04 04:57:52 +03:00
|
|
|
ssl_context = ssl._create_unverified_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=str(ca_cert))
|
|
|
|
ssl_context.check_hostname = False
|
2023-03-30 04:18:51 +03:00
|
|
|
ssl_context.load_cert_chain(certfile=str(cert_path), keyfile=str(key_path))
|
2021-02-04 04:57:52 +03:00
|
|
|
ssl_context.verify_mode = ssl.CERT_REQUIRED
|
2020-11-05 09:34:34 +03:00
|
|
|
return ssl_context
|
|
|
|
|
|
|
|
|
2022-09-29 20:14:20 +03:00
|
|
|
def calculate_node_id(cert_path: Path) -> bytes32:
|
|
|
|
pem_cert = x509.load_pem_x509_certificate(cert_path.read_bytes(), default_backend())
|
|
|
|
der_cert_bytes = pem_cert.public_bytes(encoding=serialization.Encoding.DER)
|
|
|
|
der_cert = x509.load_der_x509_certificate(der_cert_bytes, default_backend())
|
|
|
|
return bytes32(der_cert.fingerprint(hashes.SHA256()))
|
|
|
|
|
|
|
|
|
2022-11-03 19:28:23 +03:00
|
|
|
@final
|
|
|
|
@dataclass
|
2019-10-29 19:37:43 +03:00
|
|
|
class ChiaServer:
|
2023-10-04 04:24:04 +03:00
|
|
|
_port: Optional[int]
|
2022-11-03 19:28:23 +03:00
|
|
|
_local_type: NodeType
|
|
|
|
_local_capabilities_for_handshake: List[Tuple[uint16, str]]
|
|
|
|
_ping_interval: int
|
|
|
|
_network_id: str
|
|
|
|
_inbound_rate_limit_percent: int
|
|
|
|
_outbound_rate_limit_percent: int
|
2023-06-14 04:12:25 +03:00
|
|
|
api: ApiProtocol
|
2022-11-03 19:28:23 +03:00
|
|
|
node: Any
|
|
|
|
root_path: Path
|
|
|
|
config: Dict[str, Any]
|
|
|
|
log: logging.Logger
|
|
|
|
ssl_context: ssl.SSLContext
|
|
|
|
ssl_client_context: ssl.SSLContext
|
|
|
|
node_id: bytes32
|
|
|
|
exempt_peer_networks: List[Union[IPv4Network, IPv6Network]]
|
|
|
|
all_connections: Dict[bytes32, WSChiaConnection] = field(default_factory=dict)
|
2022-11-18 19:43:14 +03:00
|
|
|
on_connect: Optional[ConnectionCallback] = None
|
2022-11-03 19:28:23 +03:00
|
|
|
shut_down_event: asyncio.Event = field(default_factory=asyncio.Event)
|
|
|
|
introducer_peers: Optional[IntroducerPeers] = None
|
2022-11-18 19:43:14 +03:00
|
|
|
gc_task: Optional[asyncio.Task[None]] = None
|
2022-11-03 19:28:23 +03:00
|
|
|
webserver: Optional[WebServer] = None
|
2022-11-18 19:43:14 +03:00
|
|
|
connection_close_task: Optional[asyncio.Task[None]] = None
|
|
|
|
received_message_callback: Optional[ConnectionCallback] = None
|
2022-11-03 19:28:23 +03:00
|
|
|
banned_peers: Dict[str, float] = field(default_factory=dict)
|
|
|
|
invalid_protocol_ban_seconds = INVALID_PROTOCOL_BAN_SECONDS
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def create(
|
|
|
|
cls,
|
2023-10-04 04:24:04 +03:00
|
|
|
port: Optional[int],
|
2021-01-06 07:13:39 +03:00
|
|
|
node: Any,
|
2023-06-14 04:12:25 +03:00
|
|
|
api: ApiProtocol,
|
2020-04-08 10:47:17 +03:00
|
|
|
local_type: NodeType,
|
|
|
|
ping_interval: int,
|
2021-03-11 02:43:02 +03:00
|
|
|
network_id: str,
|
2021-03-10 09:48:34 +03:00
|
|
|
inbound_rate_limit_percent: int,
|
|
|
|
outbound_rate_limit_percent: int,
|
2022-06-11 09:35:41 +03:00
|
|
|
capabilities: List[Tuple[uint16, str]],
|
2020-11-11 07:14:06 +03:00
|
|
|
root_path: Path,
|
2022-11-18 19:43:14 +03:00
|
|
|
config: Dict[str, Any],
|
2021-02-04 04:57:52 +03:00
|
|
|
private_ca_crt_key: Tuple[Path, Path],
|
|
|
|
chia_ca_crt_key: Tuple[Path, Path],
|
2022-11-18 19:43:14 +03:00
|
|
|
name: str = __name__,
|
2022-11-03 19:28:23 +03:00
|
|
|
) -> ChiaServer:
|
2022-11-18 19:43:14 +03:00
|
|
|
log = logging.getLogger(name)
|
2022-11-03 19:28:23 +03:00
|
|
|
log.info("Service capabilities: %s", capabilities)
|
2020-10-16 04:03:46 +03:00
|
|
|
|
2022-09-29 20:14:20 +03:00
|
|
|
ca_private_crt_path, ca_private_key_path = private_ca_crt_key
|
|
|
|
chia_ca_crt_path, chia_ca_key_path = chia_ca_crt_key
|
|
|
|
|
|
|
|
private_cert_path, private_key_path = None, None
|
|
|
|
public_cert_path, public_key_path = None, None
|
|
|
|
|
|
|
|
authenticated_client_types = {NodeType.HARVESTER}
|
|
|
|
authenticated_server_types = {NodeType.HARVESTER, NodeType.FARMER, NodeType.WALLET, NodeType.DATA_LAYER}
|
|
|
|
|
2022-11-03 19:28:23 +03:00
|
|
|
if local_type in authenticated_client_types:
|
2022-09-29 20:14:20 +03:00
|
|
|
# Authenticated clients
|
|
|
|
private_cert_path, private_key_path = private_ssl_paths(root_path, config)
|
2022-11-03 19:28:23 +03:00
|
|
|
ssl_client_context = ssl_context_for_client(
|
2023-03-30 04:16:22 +03:00
|
|
|
ca_cert=ca_private_crt_path,
|
|
|
|
ca_key=ca_private_key_path,
|
2023-03-30 04:18:51 +03:00
|
|
|
cert_path=private_cert_path,
|
|
|
|
key_path=private_key_path,
|
2022-09-29 20:14:20 +03:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
# Public clients
|
|
|
|
public_cert_path, public_key_path = public_ssl_paths(root_path, config)
|
2022-11-03 19:28:23 +03:00
|
|
|
ssl_client_context = ssl_context_for_client(
|
2023-03-30 04:16:22 +03:00
|
|
|
ca_cert=chia_ca_crt_path,
|
|
|
|
ca_key=chia_ca_key_path,
|
2023-03-30 04:18:51 +03:00
|
|
|
cert_path=public_cert_path,
|
|
|
|
key_path=public_key_path,
|
2022-09-29 20:14:20 +03:00
|
|
|
)
|
|
|
|
|
2022-11-03 19:28:23 +03:00
|
|
|
if local_type in authenticated_server_types:
|
2022-09-29 20:14:20 +03:00
|
|
|
# Authenticated servers
|
|
|
|
private_cert_path, private_key_path = private_ssl_paths(root_path, config)
|
2022-11-03 19:28:23 +03:00
|
|
|
ssl_context = ssl_context_for_server(
|
2023-03-30 04:16:22 +03:00
|
|
|
ca_cert=ca_private_crt_path,
|
|
|
|
ca_key=ca_private_key_path,
|
|
|
|
cert_path=private_cert_path,
|
|
|
|
key_path=private_key_path,
|
2022-11-03 19:28:23 +03:00
|
|
|
log=log,
|
2022-09-29 20:14:20 +03:00
|
|
|
)
|
2021-02-04 04:57:52 +03:00
|
|
|
else:
|
2022-09-29 20:14:20 +03:00
|
|
|
# Public servers
|
|
|
|
public_cert_path, public_key_path = public_ssl_paths(root_path, config)
|
2022-11-03 19:28:23 +03:00
|
|
|
ssl_context = ssl_context_for_server(
|
2023-03-30 04:16:22 +03:00
|
|
|
ca_cert=chia_ca_crt_path,
|
|
|
|
ca_key=chia_ca_key_path,
|
|
|
|
cert_path=public_cert_path,
|
|
|
|
key_path=public_key_path,
|
|
|
|
log=log,
|
2022-09-29 20:14:20 +03:00
|
|
|
)
|
|
|
|
|
2022-11-29 03:00:45 +03:00
|
|
|
node_id_cert_path = private_cert_path if public_cert_path is None else public_cert_path
|
|
|
|
assert node_id_cert_path is not None
|
|
|
|
|
2022-11-03 19:28:23 +03:00
|
|
|
return cls(
|
|
|
|
_port=port,
|
|
|
|
_local_type=local_type,
|
|
|
|
_local_capabilities_for_handshake=capabilities,
|
|
|
|
_ping_interval=ping_interval,
|
|
|
|
_network_id=network_id,
|
|
|
|
_inbound_rate_limit_percent=inbound_rate_limit_percent,
|
|
|
|
_outbound_rate_limit_percent=outbound_rate_limit_percent,
|
|
|
|
log=log,
|
|
|
|
api=api,
|
|
|
|
node=node,
|
|
|
|
root_path=root_path,
|
|
|
|
config=config,
|
|
|
|
ssl_context=ssl_context,
|
|
|
|
ssl_client_context=ssl_client_context,
|
2022-11-29 03:00:45 +03:00
|
|
|
node_id=calculate_node_id(node_id_cert_path),
|
2022-11-03 19:28:23 +03:00
|
|
|
exempt_peer_networks=[ip_network(net, strict=False) for net in config.get("exempt_peer_networks", [])],
|
|
|
|
introducer_peers=IntroducerPeers() if local_type is NodeType.INTRODUCER else None,
|
|
|
|
)
|
2021-01-06 20:30:08 +03:00
|
|
|
|
2022-11-18 19:43:14 +03:00
|
|
|
def set_received_message_callback(self, callback: ConnectionCallback) -> None:
|
2021-01-06 20:30:08 +03:00
|
|
|
self.received_message_callback = callback
|
2020-11-30 11:54:18 +03:00
|
|
|
|
2021-04-02 20:37:01 +03:00
|
|
|
async def garbage_collect_connections_task(self) -> None:
|
2021-02-02 15:42:56 +03:00
|
|
|
"""
|
|
|
|
Periodically checks for connections with no activity (have not sent us any data), and removes them,
|
|
|
|
to allow room for other peers.
|
|
|
|
"""
|
2021-11-28 05:30:25 +03:00
|
|
|
is_crawler = getattr(self.node, "crawl", None)
|
2021-02-02 15:42:56 +03:00
|
|
|
while True:
|
2021-11-28 05:30:25 +03:00
|
|
|
await asyncio.sleep(600 if is_crawler is None else 2)
|
2021-02-02 15:42:56 +03:00
|
|
|
to_remove: List[WSChiaConnection] = []
|
|
|
|
for connection in self.all_connections.values():
|
2022-11-16 01:23:06 +03:00
|
|
|
if connection.closed:
|
|
|
|
to_remove.append(connection)
|
|
|
|
elif (
|
2022-02-27 02:31:10 +03:00
|
|
|
self._local_type == NodeType.FULL_NODE or self._local_type == NodeType.WALLET
|
|
|
|
) and connection.connection_type == NodeType.FULL_NODE:
|
2021-11-28 05:30:25 +03:00
|
|
|
if is_crawler is not None:
|
|
|
|
if time.time() - connection.creation_time > 5:
|
|
|
|
to_remove.append(connection)
|
|
|
|
else:
|
|
|
|
if time.time() - connection.last_message_time > 1800:
|
|
|
|
to_remove.append(connection)
|
2021-02-02 15:42:56 +03:00
|
|
|
for connection in to_remove:
|
2023-04-12 20:14:38 +03:00
|
|
|
self.log.debug(f"Garbage collecting connection {connection.peer_info.host} due to inactivity")
|
2022-11-16 01:23:06 +03:00
|
|
|
if connection.closed:
|
|
|
|
self.all_connections.pop(connection.peer_node_id)
|
|
|
|
else:
|
|
|
|
await connection.close()
|
2021-02-02 15:42:56 +03:00
|
|
|
|
2021-03-03 21:27:00 +03:00
|
|
|
# Also garbage collect banned_peers dict
|
|
|
|
to_remove_ban = []
|
|
|
|
for peer_ip, ban_until_time in self.banned_peers.items():
|
|
|
|
if time.time() > ban_until_time:
|
|
|
|
to_remove_ban.append(peer_ip)
|
|
|
|
for peer_ip in to_remove_ban:
|
|
|
|
del self.banned_peers[peer_ip]
|
|
|
|
|
2023-03-30 04:21:15 +03:00
|
|
|
async def start(
|
2023-03-29 04:22:05 +03:00
|
|
|
self,
|
|
|
|
prefer_ipv6: bool,
|
|
|
|
on_connect: Optional[ConnectionCallback] = None,
|
|
|
|
) -> None:
|
2022-10-03 22:43:04 +03:00
|
|
|
if self.webserver is not None:
|
|
|
|
raise RuntimeError("ChiaServer already started")
|
2021-12-15 05:03:59 +03:00
|
|
|
if self.gc_task is None:
|
|
|
|
self.gc_task = asyncio.create_task(self.garbage_collect_connections_task())
|
|
|
|
|
2023-10-04 04:24:04 +03:00
|
|
|
if self._port is not None:
|
2023-03-29 04:22:05 +03:00
|
|
|
self.on_connect = on_connect
|
|
|
|
self.webserver = await WebServer.create(
|
|
|
|
hostname="",
|
2023-10-04 04:24:04 +03:00
|
|
|
port=self.get_port(),
|
2023-03-29 04:22:05 +03:00
|
|
|
routes=[web.get("/ws", self.incoming_connection)],
|
|
|
|
ssl_context=self.ssl_context,
|
|
|
|
prefer_ipv6=prefer_ipv6,
|
|
|
|
logger=self.log,
|
|
|
|
)
|
|
|
|
self._port = int(self.webserver.listen_port)
|
|
|
|
self.log.info(f"Started listening on port: {self._port}")
|
2020-10-16 04:03:46 +03:00
|
|
|
|
2022-11-18 19:43:14 +03:00
|
|
|
async def incoming_connection(self, request: web.Request) -> web.StreamResponse:
|
2021-11-28 05:30:25 +03:00
|
|
|
if getattr(self.node, "crawl", None) is not None:
|
2022-11-18 19:43:14 +03:00
|
|
|
raise web.HTTPForbidden(reason="incoming connections not allowed for crawler")
|
|
|
|
if request.remote is None:
|
|
|
|
raise web.HTTPInternalServerError(reason=f"remote is None for request {request}")
|
2021-03-03 21:27:00 +03:00
|
|
|
if request.remote in self.banned_peers and time.time() < self.banned_peers[request.remote]:
|
2022-11-18 19:43:14 +03:00
|
|
|
reason = f"Peer {request.remote} is banned, refusing connection"
|
|
|
|
self.log.warning(reason)
|
|
|
|
raise web.HTTPForbidden(reason=reason)
|
2022-04-05 20:19:09 +03:00
|
|
|
ws = web.WebSocketResponse(max_msg_size=max_message_size)
|
2020-10-16 04:03:46 +03:00
|
|
|
await ws.prepare(request)
|
2022-10-01 01:50:46 +03:00
|
|
|
ssl_object = request.get_extra_info("ssl_object")
|
|
|
|
if ssl_object is None:
|
|
|
|
reason = f"ssl_object is None for request {request}"
|
|
|
|
self.log.warning(reason)
|
|
|
|
raise web.HTTPInternalServerError(reason=reason)
|
|
|
|
cert_bytes = ssl_object.getpeercert(True)
|
2021-02-04 04:57:52 +03:00
|
|
|
der_cert = x509.load_der_x509_certificate(cert_bytes)
|
|
|
|
peer_id = bytes32(der_cert.fingerprint(hashes.SHA256()))
|
|
|
|
if peer_id == self.node_id:
|
|
|
|
return ws
|
2021-02-11 07:42:42 +03:00
|
|
|
connection: Optional[WSChiaConnection] = None
|
2020-10-16 04:03:46 +03:00
|
|
|
try:
|
2022-11-16 22:38:28 +03:00
|
|
|
connection = WSChiaConnection.create(
|
2023-03-30 04:16:22 +03:00
|
|
|
local_type=self._local_type,
|
|
|
|
ws=ws,
|
|
|
|
api=self.api,
|
2023-10-04 04:24:04 +03:00
|
|
|
server_port=self.get_port(),
|
2023-03-30 04:16:22 +03:00
|
|
|
log=self.log,
|
|
|
|
is_outbound=False,
|
|
|
|
received_message_callback=self.received_message_callback,
|
|
|
|
close_callback=self.connection_closed,
|
|
|
|
peer_id=peer_id,
|
|
|
|
inbound_rate_limit_percent=self._inbound_rate_limit_percent,
|
|
|
|
outbound_rate_limit_percent=self._outbound_rate_limit_percent,
|
|
|
|
local_capabilities_for_handshake=self._local_capabilities_for_handshake,
|
2020-10-16 04:03:46 +03:00
|
|
|
)
|
2023-10-04 04:24:04 +03:00
|
|
|
await connection.perform_handshake(self._network_id, protocol_version, self.get_port(), self._local_type)
|
2022-11-18 19:43:14 +03:00
|
|
|
assert connection.connection_type is not None, "handshake failed to set connection type, still None"
|
2020-05-16 21:56:03 +03:00
|
|
|
|
2021-01-21 22:20:50 +03:00
|
|
|
# Limit inbound connections to config's specifications.
|
2021-05-13 03:44:26 +03:00
|
|
|
if not self.accept_inbound_connections(connection.connection_type) and not is_in_network(
|
2023-04-12 20:14:38 +03:00
|
|
|
connection.peer_info.host, self.exempt_peer_networks
|
2021-05-13 03:44:26 +03:00
|
|
|
):
|
2021-08-18 23:02:30 +03:00
|
|
|
self.log.info(
|
|
|
|
f"Not accepting inbound connection: {connection.get_peer_logging()}.Inbound limit reached."
|
|
|
|
)
|
2021-01-21 22:20:50 +03:00
|
|
|
await connection.close()
|
|
|
|
else:
|
|
|
|
await self.connection_added(connection, self.on_connect)
|
2022-11-18 19:43:14 +03:00
|
|
|
if self.introducer_peers is not None and connection.connection_type is NodeType.FULL_NODE:
|
2021-01-21 22:20:50 +03:00
|
|
|
self.introducer_peers.add(connection.get_peer_info())
|
2020-12-11 16:58:17 +03:00
|
|
|
except ProtocolError as e:
|
2021-02-11 07:47:09 +03:00
|
|
|
if connection is not None:
|
2021-03-03 21:27:00 +03:00
|
|
|
await connection.close(self.invalid_protocol_ban_seconds, WSCloseCode.PROTOCOL_ERROR, e.code)
|
2021-02-11 07:42:42 +03:00
|
|
|
if e.code == Err.INVALID_HANDSHAKE:
|
|
|
|
self.log.warning("Invalid handshake with peer. Maybe the peer is running old software.")
|
2021-02-19 07:56:21 +03:00
|
|
|
elif e.code == Err.INCOMPATIBLE_NETWORK_ID:
|
|
|
|
self.log.warning("Incompatible network ID. Maybe the peer is on another network")
|
2020-12-03 06:49:05 +03:00
|
|
|
else:
|
|
|
|
error_stack = traceback.format_exc()
|
2020-12-11 16:58:17 +03:00
|
|
|
self.log.error(f"Exception {e}, exception Stack: {error_stack}")
|
2021-07-22 19:05:31 +03:00
|
|
|
except ValueError as e:
|
|
|
|
if connection is not None:
|
|
|
|
await connection.close(self.invalid_protocol_ban_seconds, WSCloseCode.PROTOCOL_ERROR, Err.UNKNOWN)
|
|
|
|
self.log.warning(f"{e} - closing connection")
|
2020-12-11 16:58:17 +03:00
|
|
|
except Exception as e:
|
2021-03-03 21:27:00 +03:00
|
|
|
if connection is not None:
|
|
|
|
await connection.close(ws_close_code=WSCloseCode.PROTOCOL_ERROR, error=Err.UNKNOWN)
|
2020-12-11 16:58:17 +03:00
|
|
|
error_stack = traceback.format_exc()
|
|
|
|
self.log.error(f"Exception {e}, exception Stack: {error_stack}")
|
2020-10-08 22:34:56 +03:00
|
|
|
|
2022-12-08 05:48:04 +03:00
|
|
|
if connection is not None:
|
|
|
|
await connection.wait_until_closed()
|
|
|
|
|
2020-10-16 04:03:46 +03:00
|
|
|
return ws
|
2020-04-14 03:51:47 +03:00
|
|
|
|
2022-11-18 19:43:14 +03:00
|
|
|
async def connection_added(
|
|
|
|
self, connection: WSChiaConnection, on_connect: Optional[ConnectionCallback] = None
|
|
|
|
) -> None:
|
2021-03-03 21:27:00 +03:00
|
|
|
# If we already had a connection to this peer_id, close the old one. This is secure because peer_ids are based
|
|
|
|
# on TLS public keys
|
2022-11-16 01:23:06 +03:00
|
|
|
if connection.closed:
|
2023-04-12 20:14:38 +03:00
|
|
|
self.log.debug(f"ignoring unexpected request to add closed connection {connection.peer_info.host} ")
|
2022-11-16 01:23:06 +03:00
|
|
|
return
|
|
|
|
|
2020-12-26 23:04:44 +03:00
|
|
|
if connection.peer_node_id in self.all_connections:
|
|
|
|
con = self.all_connections[connection.peer_node_id]
|
|
|
|
await con.close()
|
2020-10-30 04:45:47 +03:00
|
|
|
self.all_connections[connection.peer_node_id] = connection
|
2020-12-10 19:34:56 +03:00
|
|
|
if connection.connection_type is not None:
|
|
|
|
if on_connect is not None:
|
|
|
|
await on_connect(connection)
|
|
|
|
else:
|
|
|
|
self.log.error(f"Invalid connection type for connection {connection}")
|
2020-10-30 04:45:47 +03:00
|
|
|
|
2021-01-06 20:30:08 +03:00
|
|
|
def is_duplicate_or_self_connection(self, target_node: PeerInfo) -> bool:
|
2021-03-10 09:48:34 +03:00
|
|
|
if is_localhost(target_node.host) and target_node.port == self._port:
|
2021-01-06 20:30:08 +03:00
|
|
|
# Don't connect to self
|
|
|
|
self.log.debug(f"Not connecting to {target_node}")
|
|
|
|
return True
|
|
|
|
for connection in self.all_connections.values():
|
2023-04-12 20:14:38 +03:00
|
|
|
if connection.peer_info.host == target_node.host and connection.peer_server_port == target_node.port:
|
2021-01-06 20:30:08 +03:00
|
|
|
self.log.debug(f"Not connecting to {target_node}, duplicate connection")
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2019-11-18 07:50:31 +03:00
|
|
|
async def start_client(
|
2020-03-16 10:21:22 +03:00
|
|
|
self,
|
|
|
|
target_node: PeerInfo,
|
2022-11-18 19:43:14 +03:00
|
|
|
on_connect: Optional[ConnectionCallback] = None,
|
2020-09-23 20:12:31 +03:00
|
|
|
is_feeler: bool = False,
|
2019-11-18 07:50:31 +03:00
|
|
|
) -> bool:
|
2019-11-01 04:33:03 +03:00
|
|
|
"""
|
|
|
|
Tries to connect to the target node, adding one connection into the pipeline, if successful.
|
|
|
|
An on connect method can also be specified, and this will be saved into the instance variables.
|
|
|
|
"""
|
2021-01-06 20:30:08 +03:00
|
|
|
if self.is_duplicate_or_self_connection(target_node):
|
2022-12-13 10:29:05 +03:00
|
|
|
self.log.warning(f"cannot connect to {target_node.host}, duplicate/self connection")
|
2020-12-03 16:49:14 +03:00
|
|
|
return False
|
|
|
|
|
2021-03-03 21:27:00 +03:00
|
|
|
if target_node.host in self.banned_peers and time.time() < self.banned_peers[target_node.host]:
|
|
|
|
self.log.warning(f"Peer {target_node.host} is still banned, not connecting to it")
|
|
|
|
return False
|
|
|
|
|
2020-10-16 04:03:46 +03:00
|
|
|
session = None
|
2021-02-11 07:42:42 +03:00
|
|
|
connection: Optional[WSChiaConnection] = None
|
2019-12-02 21:38:00 +03:00
|
|
|
try:
|
2021-09-18 04:35:06 +03:00
|
|
|
# Crawler/DNS introducer usually uses a lower timeout than the default
|
2022-02-14 22:48:35 +03:00
|
|
|
timeout_value = float(self.config.get("peer_connect_timeout", 30))
|
2021-09-18 04:35:06 +03:00
|
|
|
timeout = ClientTimeout(total=timeout_value)
|
2020-12-10 09:17:54 +03:00
|
|
|
session = ClientSession(timeout=timeout)
|
2023-02-22 21:03:41 +03:00
|
|
|
ip = f"[{target_node.ip}]" if target_node.ip.is_v6 else f"{target_node.ip}"
|
|
|
|
url = f"wss://{ip}:{target_node.port}/ws"
|
2021-01-26 17:38:39 +03:00
|
|
|
self.log.debug(f"Connecting: {url}, Peer info: {target_node}")
|
2020-12-11 16:29:51 +03:00
|
|
|
try:
|
2020-12-16 13:31:59 +03:00
|
|
|
ws = await session.ws_connect(
|
2022-09-29 20:14:20 +03:00
|
|
|
url,
|
|
|
|
autoclose=True,
|
|
|
|
autoping=True,
|
|
|
|
heartbeat=60,
|
|
|
|
ssl=self.ssl_client_context,
|
|
|
|
max_msg_size=max_message_size,
|
2020-12-16 13:31:59 +03:00
|
|
|
)
|
2021-03-11 16:37:01 +03:00
|
|
|
except ServerDisconnectedError:
|
|
|
|
self.log.debug(f"Server disconnected error connecting to {url}. Perhaps we are banned by the peer.")
|
|
|
|
return False
|
2022-10-01 01:50:46 +03:00
|
|
|
except ClientResponseError as e:
|
|
|
|
self.log.warning(f"Connection failed to {url}. Error: {e}")
|
|
|
|
return False
|
2020-12-11 19:40:02 +03:00
|
|
|
except asyncio.TimeoutError:
|
2021-01-26 17:38:39 +03:00
|
|
|
self.log.debug(f"Timeout error connecting to {url}")
|
2020-12-11 16:29:51 +03:00
|
|
|
return False
|
2021-06-08 20:49:13 +03:00
|
|
|
if ws is None:
|
2022-12-13 10:29:05 +03:00
|
|
|
self.log.warning(f"Connection failed to {url}. ws was None")
|
2020-12-11 19:40:02 +03:00
|
|
|
return False
|
2021-06-08 20:49:13 +03:00
|
|
|
|
2022-10-01 01:50:46 +03:00
|
|
|
ssl_object = ws.get_extra_info("ssl_object")
|
|
|
|
if ssl_object is None:
|
|
|
|
raise ValueError(f"ssl_object is None for {ws}")
|
|
|
|
cert_bytes = ssl_object.getpeercert(True)
|
2021-06-08 20:49:13 +03:00
|
|
|
der_cert = x509.load_der_x509_certificate(cert_bytes, default_backend())
|
|
|
|
peer_id = bytes32(der_cert.fingerprint(hashes.SHA256()))
|
|
|
|
if peer_id == self.node_id:
|
2023-04-03 15:24:16 +03:00
|
|
|
self.log.info(f"Connected to a node with the same peer ID, disconnecting: {target_node} {peer_id}")
|
|
|
|
return False
|
2021-06-08 20:49:13 +03:00
|
|
|
|
2023-10-04 04:24:04 +03:00
|
|
|
server_port: uint16
|
|
|
|
try:
|
|
|
|
server_port = self.get_port()
|
|
|
|
except ValueError:
|
|
|
|
server_port = uint16(0)
|
|
|
|
|
2022-11-16 22:38:28 +03:00
|
|
|
connection = WSChiaConnection.create(
|
2023-03-30 04:16:22 +03:00
|
|
|
local_type=self._local_type,
|
|
|
|
ws=ws,
|
|
|
|
api=self.api,
|
2023-10-04 04:24:04 +03:00
|
|
|
server_port=server_port,
|
2023-03-30 04:16:22 +03:00
|
|
|
log=self.log,
|
|
|
|
is_outbound=True,
|
|
|
|
received_message_callback=self.received_message_callback,
|
|
|
|
close_callback=self.connection_closed,
|
|
|
|
peer_id=peer_id,
|
|
|
|
inbound_rate_limit_percent=self._inbound_rate_limit_percent,
|
|
|
|
outbound_rate_limit_percent=self._outbound_rate_limit_percent,
|
|
|
|
local_capabilities_for_handshake=self._local_capabilities_for_handshake,
|
2021-06-08 20:49:13 +03:00
|
|
|
session=session,
|
|
|
|
)
|
2023-10-04 04:24:04 +03:00
|
|
|
await connection.perform_handshake(self._network_id, protocol_version, server_port, self._local_type)
|
2021-06-08 20:49:13 +03:00
|
|
|
await self.connection_added(connection, on_connect)
|
|
|
|
# the session has been adopted by the connection, don't close it at
|
|
|
|
# the end of the function
|
|
|
|
session = None
|
|
|
|
connection_type_str = ""
|
|
|
|
if connection.connection_type is not None:
|
|
|
|
connection_type_str = connection.connection_type.name.lower()
|
|
|
|
self.log.info(f"Connected with {connection_type_str} {target_node}")
|
|
|
|
if is_feeler:
|
|
|
|
asyncio.create_task(connection.close())
|
|
|
|
return True
|
2020-12-10 09:17:54 +03:00
|
|
|
except client_exceptions.ClientConnectorError as e:
|
2021-01-26 17:38:39 +03:00
|
|
|
self.log.info(f"{e}")
|
2020-12-11 16:58:17 +03:00
|
|
|
except ProtocolError as e:
|
2021-02-11 07:47:09 +03:00
|
|
|
if connection is not None:
|
2021-03-03 21:27:00 +03:00
|
|
|
await connection.close(self.invalid_protocol_ban_seconds, WSCloseCode.PROTOCOL_ERROR, e.code)
|
2021-02-11 07:42:42 +03:00
|
|
|
if e.code == Err.INVALID_HANDSHAKE:
|
|
|
|
self.log.warning(f"Invalid handshake with peer {target_node}. Maybe the peer is running old software.")
|
2021-02-19 07:56:21 +03:00
|
|
|
elif e.code == Err.INCOMPATIBLE_NETWORK_ID:
|
|
|
|
self.log.warning("Incompatible network ID. Maybe the peer is on another network")
|
2021-02-11 07:42:42 +03:00
|
|
|
elif e.code == Err.SELF_CONNECTION:
|
2021-02-11 07:47:09 +03:00
|
|
|
pass
|
2020-12-03 06:49:05 +03:00
|
|
|
else:
|
|
|
|
error_stack = traceback.format_exc()
|
2020-12-11 16:58:17 +03:00
|
|
|
self.log.error(f"Exception {e}, exception Stack: {error_stack}")
|
|
|
|
except Exception as e:
|
2021-03-03 21:27:00 +03:00
|
|
|
if connection is not None:
|
|
|
|
await connection.close(self.invalid_protocol_ban_seconds, WSCloseCode.PROTOCOL_ERROR, Err.UNKNOWN)
|
2020-12-11 16:58:17 +03:00
|
|
|
error_stack = traceback.format_exc()
|
|
|
|
self.log.error(f"Exception {e}, exception Stack: {error_stack}")
|
2021-06-08 20:49:13 +03:00
|
|
|
finally:
|
|
|
|
if session is not None:
|
|
|
|
await session.close()
|
2020-10-16 04:03:46 +03:00
|
|
|
|
|
|
|
return False
|
|
|
|
|
2023-12-11 17:27:25 +03:00
|
|
|
async def connection_closed(
|
|
|
|
self, connection: WSChiaConnection, ban_time: int, closed_connection: bool = False
|
|
|
|
) -> None:
|
2022-11-16 01:23:06 +03:00
|
|
|
# closed_connection is true if the callback is being called with a connection that was previously closed
|
|
|
|
# in this case we still want to do the banning logic and remove the conection from the list
|
|
|
|
# but the other cleanup should already have been done so we skip that
|
|
|
|
|
2023-04-12 20:14:38 +03:00
|
|
|
if is_localhost(connection.peer_info.host) and ban_time != 0:
|
2021-03-10 21:57:38 +03:00
|
|
|
self.log.warning(f"Trying to ban localhost for {ban_time}, but will not ban")
|
|
|
|
ban_time = 0
|
2021-03-03 21:27:00 +03:00
|
|
|
if ban_time > 0:
|
|
|
|
ban_until: float = time.time() + ban_time
|
2023-04-12 20:14:38 +03:00
|
|
|
self.log.warning(f"Banning {connection.peer_info.host} for {ban_time} seconds")
|
|
|
|
if connection.peer_info.host in self.banned_peers:
|
|
|
|
if ban_until > self.banned_peers[connection.peer_info.host]:
|
|
|
|
self.banned_peers[connection.peer_info.host] = ban_until
|
2021-03-03 21:27:00 +03:00
|
|
|
else:
|
2023-04-12 20:14:38 +03:00
|
|
|
self.banned_peers[connection.peer_info.host] = ban_until
|
2021-03-03 21:27:00 +03:00
|
|
|
|
2023-04-15 00:19:17 +03:00
|
|
|
present_connection = self.all_connections.get(connection.peer_node_id)
|
|
|
|
if present_connection is connection:
|
2020-10-28 20:45:10 +03:00
|
|
|
self.all_connections.pop(connection.peer_node_id)
|
2022-11-16 01:23:06 +03:00
|
|
|
|
|
|
|
if not closed_connection:
|
2023-04-12 20:14:38 +03:00
|
|
|
self.log.info(f"Connection closed: {connection.peer_info.host}, node id: {connection.peer_node_id}")
|
2022-11-16 01:23:06 +03:00
|
|
|
|
|
|
|
if connection.connection_type is None:
|
|
|
|
# This means the handshake was never finished with this peer
|
|
|
|
self.log.debug(
|
2023-04-12 20:14:38 +03:00
|
|
|
f"Invalid connection type for connection {connection.peer_info.host},"
|
2022-11-16 01:23:06 +03:00
|
|
|
f" while closing. Handshake never finished."
|
|
|
|
)
|
2022-12-09 12:47:46 +03:00
|
|
|
connection.cancel_tasks()
|
2022-11-16 01:23:06 +03:00
|
|
|
on_disconnect = getattr(self.node, "on_disconnect", None)
|
|
|
|
if on_disconnect is not None:
|
2023-12-11 17:27:25 +03:00
|
|
|
await on_disconnect(connection)
|
2020-10-16 04:03:46 +03:00
|
|
|
|
2022-11-18 19:43:14 +03:00
|
|
|
async def validate_broadcast_message_type(self, messages: List[Message], node_type: NodeType) -> None:
|
2021-09-20 21:31:15 +03:00
|
|
|
for message in messages:
|
|
|
|
if message_requires_reply(ProtocolMessageTypes(message.type)):
|
|
|
|
# Internal protocol logic error - we will raise, blocking messages to all peers
|
|
|
|
self.log.error(f"Attempt to broadcast message requiring protocol response: {message.type}")
|
|
|
|
for _, connection in self.all_connections.items():
|
|
|
|
if connection.connection_type is node_type:
|
|
|
|
await connection.close(
|
2023-03-30 04:16:22 +03:00
|
|
|
ban_time=self.invalid_protocol_ban_seconds,
|
|
|
|
ws_close_code=WSCloseCode.INTERNAL_ERROR,
|
|
|
|
error=Err.INTERNAL_PROTOCOL_ERROR,
|
2021-09-20 21:31:15 +03:00
|
|
|
)
|
|
|
|
raise ProtocolError(Err.INTERNAL_PROTOCOL_ERROR, [message.type])
|
|
|
|
|
2023-01-03 06:39:11 +03:00
|
|
|
async def send_to_all(
|
|
|
|
self,
|
|
|
|
messages: List[Message],
|
|
|
|
node_type: NodeType,
|
|
|
|
exclude: Optional[bytes32] = None,
|
|
|
|
) -> None:
|
2021-09-20 21:31:15 +03:00
|
|
|
await self.validate_broadcast_message_type(messages, node_type)
|
2020-11-30 11:54:18 +03:00
|
|
|
for _, connection in self.all_connections.items():
|
2020-12-02 05:53:35 +03:00
|
|
|
if connection.connection_type is node_type and connection.peer_node_id != exclude:
|
2020-10-28 20:45:10 +03:00
|
|
|
for message in messages:
|
|
|
|
await connection.send_message(message)
|
|
|
|
|
2022-11-18 19:43:14 +03:00
|
|
|
async def send_to_specific(self, messages: List[Message], node_id: bytes32) -> None:
|
2020-10-28 20:45:10 +03:00
|
|
|
if node_id in self.all_connections:
|
|
|
|
connection = self.all_connections[node_id]
|
2020-10-16 04:03:46 +03:00
|
|
|
for message in messages:
|
|
|
|
await connection.send_message(message)
|
|
|
|
|
2023-07-28 22:48:32 +03:00
|
|
|
async def call_api_of_specific(
|
|
|
|
self, request_method: Callable[..., Awaitable[Optional[Message]]], message_data: Streamable, node_id: bytes32
|
|
|
|
) -> Optional[Any]:
|
|
|
|
if node_id in self.all_connections:
|
|
|
|
connection = self.all_connections[node_id]
|
|
|
|
return await connection.call_api(request_method, message_data)
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
2022-11-16 02:40:16 +03:00
|
|
|
def get_connections(
|
|
|
|
self, node_type: Optional[NodeType] = None, *, outbound: Optional[bool] = None
|
|
|
|
) -> List[WSChiaConnection]:
|
2020-10-21 11:19:40 +03:00
|
|
|
result = []
|
2020-11-30 11:54:18 +03:00
|
|
|
for _, connection in self.all_connections.items():
|
2022-11-16 02:40:16 +03:00
|
|
|
node_type_match = node_type is None or connection.connection_type == node_type
|
|
|
|
outbound_match = outbound is None or connection.is_outbound == outbound
|
|
|
|
if node_type_match and outbound_match:
|
2021-07-15 17:42:06 +03:00
|
|
|
result.append(connection)
|
2020-10-21 11:19:40 +03:00
|
|
|
return result
|
|
|
|
|
2021-04-02 20:37:01 +03:00
|
|
|
async def close_all_connections(self) -> None:
|
2022-11-16 22:57:30 +03:00
|
|
|
for connection in self.all_connections.copy().values():
|
2020-10-21 04:45:09 +03:00
|
|
|
try:
|
2022-11-16 22:57:30 +03:00
|
|
|
await connection.close()
|
2020-10-21 04:45:09 +03:00
|
|
|
except Exception as e:
|
2020-12-02 06:43:30 +03:00
|
|
|
self.log.error(f"Exception while closing connection {e}")
|
2020-10-21 04:45:09 +03:00
|
|
|
|
2021-04-02 20:37:01 +03:00
|
|
|
def close_all(self) -> None:
|
2020-11-30 11:54:18 +03:00
|
|
|
self.connection_close_task = asyncio.create_task(self.close_all_connections())
|
2022-10-03 22:43:04 +03:00
|
|
|
if self.webserver is not None:
|
|
|
|
self.webserver.close()
|
2019-10-30 21:51:27 +03:00
|
|
|
|
2020-10-16 04:03:46 +03:00
|
|
|
self.shut_down_event.set()
|
2021-12-15 05:03:59 +03:00
|
|
|
if self.gc_task is not None:
|
|
|
|
self.gc_task.cancel()
|
|
|
|
self.gc_task = None
|
2019-12-10 02:27:38 +03:00
|
|
|
|
2021-04-02 20:37:01 +03:00
|
|
|
async def await_closed(self) -> None:
|
2021-01-26 17:38:39 +03:00
|
|
|
self.log.debug("Await Closed")
|
2020-10-16 04:03:46 +03:00
|
|
|
await self.shut_down_event.wait()
|
2020-11-30 11:54:18 +03:00
|
|
|
if self.connection_close_task is not None:
|
|
|
|
await self.connection_close_task
|
2022-10-03 22:43:04 +03:00
|
|
|
if self.webserver is not None:
|
|
|
|
await self.webserver.await_closed()
|
|
|
|
self.webserver = None
|
2020-12-10 20:38:06 +03:00
|
|
|
|
2020-10-20 09:40:55 +03:00
|
|
|
async def get_peer_info(self) -> Optional[PeerInfo]:
|
|
|
|
ip = None
|
2023-11-08 19:40:21 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
port = self.get_port()
|
|
|
|
except ValueError:
|
|
|
|
return None # server doesn't have a local port, just return None here
|
2020-10-20 09:40:55 +03:00
|
|
|
|
2021-08-17 00:12:43 +03:00
|
|
|
# Use chia's service first.
|
2020-10-20 09:40:55 +03:00
|
|
|
try:
|
2021-08-17 00:12:43 +03:00
|
|
|
timeout = ClientTimeout(total=15)
|
|
|
|
async with ClientSession(timeout=timeout) as session:
|
|
|
|
async with session.get("https://ip.chia.net/") as resp:
|
2020-10-20 09:40:55 +03:00
|
|
|
if resp.status == 200:
|
|
|
|
ip = str(await resp.text())
|
|
|
|
ip = ip.rstrip()
|
|
|
|
except Exception:
|
|
|
|
ip = None
|
2021-08-17 00:12:43 +03:00
|
|
|
|
|
|
|
# Fallback to `checkip` from amazon.
|
|
|
|
if ip is None:
|
|
|
|
try:
|
|
|
|
timeout = ClientTimeout(total=15)
|
|
|
|
async with ClientSession(timeout=timeout) as session:
|
|
|
|
async with session.get("https://checkip.amazonaws.com/") as resp:
|
|
|
|
if resp.status == 200:
|
|
|
|
ip = str(await resp.text())
|
|
|
|
ip = ip.rstrip()
|
|
|
|
except Exception:
|
|
|
|
ip = None
|
2020-10-20 09:40:55 +03:00
|
|
|
if ip is None:
|
|
|
|
return None
|
2023-02-22 21:03:41 +03:00
|
|
|
try:
|
|
|
|
return PeerInfo(ip, uint16(port))
|
|
|
|
except ValueError:
|
2020-10-20 09:40:55 +03:00
|
|
|
return None
|
2021-01-21 22:20:50 +03:00
|
|
|
|
2022-05-23 18:13:49 +03:00
|
|
|
def get_port(self) -> uint16:
|
2023-10-04 04:24:04 +03:00
|
|
|
if self._port is None:
|
|
|
|
raise ValueError("Port not set")
|
2022-05-23 18:13:49 +03:00
|
|
|
return uint16(self._port)
|
|
|
|
|
2021-05-13 03:44:26 +03:00
|
|
|
def accept_inbound_connections(self, node_type: NodeType) -> bool:
|
2021-01-21 22:23:32 +03:00
|
|
|
if not self._local_type == NodeType.FULL_NODE:
|
2021-01-21 22:20:50 +03:00
|
|
|
return True
|
2022-11-16 02:40:16 +03:00
|
|
|
inbound_count = len(self.get_connections(node_type, outbound=False))
|
2021-01-21 22:20:50 +03:00
|
|
|
if node_type == NodeType.FULL_NODE:
|
2023-12-23 01:28:31 +03:00
|
|
|
return inbound_count < cast(int, self.config.get("target_peer_count", 40)) - cast(
|
|
|
|
int, self.config.get("target_outbound_peer_count", 8)
|
2022-11-18 19:43:14 +03:00
|
|
|
)
|
2021-01-21 22:20:50 +03:00
|
|
|
if node_type == NodeType.WALLET:
|
2023-12-23 01:28:31 +03:00
|
|
|
return inbound_count < cast(int, self.config.get("max_inbound_wallet", 20))
|
2021-01-21 22:20:50 +03:00
|
|
|
if node_type == NodeType.FARMER:
|
2023-12-23 01:28:31 +03:00
|
|
|
return inbound_count < cast(int, self.config.get("max_inbound_farmer", 10))
|
2021-01-21 22:20:50 +03:00
|
|
|
if node_type == NodeType.TIMELORD:
|
2023-12-23 01:28:31 +03:00
|
|
|
return inbound_count < cast(int, self.config.get("max_inbound_timelord", 5))
|
2021-01-21 22:20:50 +03:00
|
|
|
return True
|
2021-03-29 14:26:55 +03:00
|
|
|
|
2022-11-18 19:43:14 +03:00
|
|
|
def is_trusted_peer(self, peer: WSChiaConnection, trusted_peers: Dict[str, Any]) -> bool:
|
2023-02-20 19:23:39 +03:00
|
|
|
return is_trusted_peer(
|
2023-04-12 20:14:38 +03:00
|
|
|
host=peer.peer_info.host,
|
2023-02-20 19:23:39 +03:00
|
|
|
node_id=peer.peer_node_id,
|
|
|
|
trusted_peers=trusted_peers,
|
|
|
|
testing=self.config.get("testing", False),
|
|
|
|
)
|
2022-12-08 05:47:21 +03:00
|
|
|
|
|
|
|
def set_capabilities(self, capabilities: List[Tuple[uint16, str]]) -> None:
|
|
|
|
self._local_capabilities_for_handshake = capabilities
|