Skip to content

Commit

Permalink
refactor(p2p): rename ConnectionsManager to P2PManager
Browse files Browse the repository at this point in the history
  • Loading branch information
glevco committed Oct 15, 2024
1 parent f3a5c96 commit ec8c2eb
Show file tree
Hide file tree
Showing 24 changed files with 127 additions and 149 deletions.
13 changes: 6 additions & 7 deletions hathor/builder/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@
from hathor.indexes import IndexesManager, MemoryIndexesManager, RocksDBIndexesManager
from hathor.manager import HathorManager
from hathor.mining.cpu_mining_service import CpuMiningService
from hathor.p2p import P2PDependencies, SingleProcessP2PDependencies
from hathor.p2p.manager import ConnectionsManager
from hathor.p2p import P2PDependencies, P2PManager, SingleProcessP2PDependencies
from hathor.p2p.peer import PrivatePeer
from hathor.pubsub import PubSubManager
from hathor.reactor import ReactorProtocol as Reactor
Expand Down Expand Up @@ -65,7 +64,7 @@ class SyncSupportLevel(IntEnum):
@classmethod
def add_factories(
cls,
p2p_manager: ConnectionsManager,
p2p_manager: P2PManager,
dependencies: P2PDependencies,
sync_v1_support: 'SyncSupportLevel',
sync_v2_support: 'SyncSupportLevel',
Expand Down Expand Up @@ -99,7 +98,7 @@ class BuildArtifacts(NamedTuple):
rng: Random
reactor: Reactor
manager: HathorManager
p2p_manager: ConnectionsManager
p2p_manager: P2PManager
pubsub: PubSubManager
consensus: ConsensusAlgorithm
tx_storage: TransactionStorage
Expand Down Expand Up @@ -191,7 +190,7 @@ def __init__(self) -> None:
self._vertex_handler: VertexHandler | None = None
self._vertex_parser: VertexParser | None = None
self._consensus: ConsensusAlgorithm | None = None
self._p2p_manager: ConnectionsManager | None = None
self._p2p_manager: P2PManager | None = None
self._poa_signer: PoaSigner | None = None
self._poa_block_producer: PoaBlockProducer | None = None

Expand Down Expand Up @@ -402,7 +401,7 @@ def _get_or_create_rocksdb_storage(self) -> RocksDBStorage:

return self._rocksdb_storage

def _get_or_create_p2p_manager(self) -> ConnectionsManager:
def _get_or_create_p2p_manager(self) -> P2PManager:
if self._p2p_manager:
return self._p2p_manager

Expand All @@ -419,7 +418,7 @@ def _get_or_create_p2p_manager(self) -> ConnectionsManager:
pubsub=self._get_or_create_pubsub(),
)

self._p2p_manager = ConnectionsManager(
self._p2p_manager = P2PManager(
dependencies=dependencies,
my_peer=my_peer,
ssl=enable_ssl,
Expand Down
5 changes: 2 additions & 3 deletions hathor/builder/cli_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,8 @@
from hathor.indexes import IndexesManager, MemoryIndexesManager, RocksDBIndexesManager
from hathor.manager import HathorManager
from hathor.mining.cpu_mining_service import CpuMiningService
from hathor.p2p import SingleProcessP2PDependencies
from hathor.p2p import P2PManager, SingleProcessP2PDependencies
from hathor.p2p.entrypoint import Entrypoint
from hathor.p2p.manager import ConnectionsManager
from hathor.p2p.peer import PrivatePeer
from hathor.p2p.utils import discover_hostname, get_genesis_short_hash
from hathor.pubsub import PubSubManager
Expand Down Expand Up @@ -342,7 +341,7 @@ def create_manager(self, reactor: Reactor) -> HathorManager:
)

capabilities = settings.get_default_capabilities()
p2p_manager = ConnectionsManager(
p2p_manager = P2PManager(
dependencies=p2p_dependencies,
my_peer=peer,
ssl=True,
Expand Down
4 changes: 2 additions & 2 deletions hathor/builder/sysctl_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@

from hathor.builder import BuildArtifacts
from hathor.sysctl import (
ConnectionsManagerSysctl,
FeatureActivationSysctl,
HathorManagerSysctl,
P2PManagerSysctl,
Sysctl,
WebsocketManagerSysctl,
)
Expand All @@ -36,7 +36,7 @@ def build(self) -> Sysctl:
core.put_child('features', FeatureActivationSysctl(self.artifacts.bit_signaling_service))

root.put_child('core', core)
root.put_child('p2p', ConnectionsManagerSysctl(self.artifacts.p2p_manager))
root.put_child('p2p', P2PManagerSysctl(self.artifacts.p2p_manager))

ws_factory = self.artifacts.manager.websocket_factory
if ws_factory is not None:
Expand Down
4 changes: 2 additions & 2 deletions hathor/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
from hathor.feature_activation.bit_signaling_service import BitSignalingService
from hathor.mining import BlockTemplate, BlockTemplates
from hathor.mining.cpu_mining_service import CpuMiningService
from hathor.p2p.manager import ConnectionsManager
from hathor.p2p.p2p_manager import P2PManager
from hathor.p2p.peer import PrivatePeer
from hathor.pubsub import HathorEvents, PubSubManager
from hathor.reactor import ReactorProtocol as Reactor
Expand Down Expand Up @@ -99,7 +99,7 @@ def __init__(
daa: DifficultyAdjustmentAlgorithm,
peer: PrivatePeer,
tx_storage: TransactionStorage,
p2p_manager: ConnectionsManager,
p2p_manager: P2PManager,
event_manager: EventManager,
bit_signaling_service: BitSignalingService,
verification_service: VerificationService,
Expand Down
4 changes: 2 additions & 2 deletions hathor/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from twisted.internet.task import LoopingCall

from hathor.conf import HathorSettings
from hathor.p2p.manager import ConnectionsManager, PeerConnectionsMetrics
from hathor.p2p.p2p_manager import P2PManager, PeerConnectionsMetrics
from hathor.pubsub import EventArguments, HathorEvents, PubSubManager
from hathor.reactor import ReactorProtocol as Reactor
from hathor.transaction.base_transaction import sum_weights
Expand Down Expand Up @@ -60,7 +60,7 @@ class PeerConnectionMetrics:
class Metrics:
pubsub: PubSubManager
avg_time_between_blocks: int
connections: ConnectionsManager
connections: P2PManager
tx_storage: TransactionStorage
# Twisted reactor that handles the time and callLater
reactor: Reactor
Expand Down
2 changes: 2 additions & 0 deletions hathor/p2p/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@

from hathor.p2p.dependencies.p2p_dependencies import P2PDependencies
from hathor.p2p.dependencies.single_process_p2p_dependencies import SingleProcessP2PDependencies
from hathor.p2p.p2p_manager import P2PManager

__all__ = [
'P2PManager',
'P2PDependencies',
'SingleProcessP2PDependencies'
]
5 changes: 2 additions & 3 deletions hathor/p2p/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@
from twisted.internet import protocol
from twisted.internet.interfaces import IAddress

from hathor.p2p import P2PDependencies
from hathor.p2p.manager import ConnectionsManager
from hathor.p2p import P2PDependencies, P2PManager
from hathor.p2p.peer import PrivatePeer
from hathor.p2p.protocol import HathorLineReceiver

Expand All @@ -29,7 +28,7 @@ class _HathorLineReceiverFactory(ABC, protocol.Factory):
def __init__(
self,
my_peer: PrivatePeer,
p2p_manager: ConnectionsManager,
p2p_manager: P2PManager,
*,
dependencies: P2PDependencies,
use_ssl: bool,
Expand Down
4 changes: 2 additions & 2 deletions hathor/p2p/netfilter/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
if TYPE_CHECKING:
from twisted.internet.interfaces import IAddress

from hathor.p2p.manager import ConnectionsManager
from hathor.p2p.p2p_manager import P2PManager
from hathor.p2p.protocol import HathorProtocol


class NetfilterContext:
"""Context sent to the targets when a match occurs."""
def __init__(self, *, connections: Optional['ConnectionsManager'] = None, addr: Optional['IAddress'] = None,
def __init__(self, *, connections: Optional['P2PManager'] = None, addr: Optional['IAddress'] = None,
protocol: Optional['HathorProtocol'] = None):
"""Initialize the context."""
self.addr = addr
Expand Down
4 changes: 2 additions & 2 deletions hathor/p2p/netfilter/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@
from hathor.p2p.netfilter.context import NetfilterContext

if TYPE_CHECKING:
from hathor.p2p.manager import ConnectionsManager
from hathor.p2p.p2p_manager import P2PManager


class NetfilterFactory(WrappingFactory):
"""Wrapper factory to easily check new connections."""
def __init__(self, connections: 'ConnectionsManager', wrappedFactory: 'IProtocolFactory'):
def __init__(self, connections: 'P2PManager', wrappedFactory: 'IProtocolFactory'):
super().__init__(wrappedFactory)
self.connections = connections

Expand Down
2 changes: 1 addition & 1 deletion hathor/p2p/manager.py → hathor/p2p/p2p_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class PeerConnectionsMetrics(NamedTuple):
known_peers_count: int


class ConnectionsManager:
class P2PManager:
""" It manages all peer-to-peer connections and events related to control messages.
"""

Expand Down
25 changes: 10 additions & 15 deletions hathor/p2p/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

if TYPE_CHECKING:
from hathor.manager import HathorManager # noqa: F401
from hathor.p2p.manager import ConnectionsManager # noqa: F401
from hathor.p2p.p2p_manager import P2PManager # noqa: F401

logger = get_logger()
cpu = get_cpu_profiler()
Expand Down Expand Up @@ -74,7 +74,7 @@ class WarningFlags(str, Enum):
NO_ENTRYPOINTS = 'no_entrypoints'

my_peer: PrivatePeer
connections: 'ConnectionsManager'
p2p_manager: 'P2PManager'
app_version: str
last_message: float
_peer: Optional[PublicPeer]
Expand All @@ -98,7 +98,7 @@ def peer(self) -> PublicPeer:
def __init__(
self,
my_peer: PrivatePeer,
p2p_manager: 'ConnectionsManager',
p2p_manager: 'P2PManager',
*,
dependencies: P2PDependencies,
use_ssl: bool,
Expand All @@ -107,10 +107,8 @@ def __init__(
self.dependencies = dependencies
self._settings = dependencies.settings
self.my_peer = my_peer
self.connections = p2p_manager

assert self.connections.reactor is not None
self.reactor = self.connections.reactor
self.p2p_manager = p2p_manager
self.reactor = self.dependencies.reactor

# Indicate whether it is an inbound connection (true) or an outbound connection (false).
self.inbound = inbound
Expand Down Expand Up @@ -154,7 +152,7 @@ def __init__(
# Set of warning flags that may be added during the connection process
self.warning_flags: set[str] = set()

# This property is used to indicate the connection is being dropped (either because of a prototcol error or
# This property is used to indicate the connection is being dropped (either because of a protocol error or
# because the remote disconnected), and the following buffered lines are ignored.
# See `HathorLineReceiver.lineReceived`
self.aborting = False
Expand Down Expand Up @@ -248,19 +246,17 @@ def on_connect(self) -> None:
# The initial state is HELLO.
self.change_state(self.PeerState.HELLO)

if self.connections:
self.connections.on_peer_connect(self)
if self.p2p_manager:
self.p2p_manager.on_peer_connect(self)

def on_outbound_connect(self, entrypoint: Entrypoint) -> None:
"""Called when we successfully establish an outbound connection to a peer."""
# Save the used entrypoint in protocol so we can validate that it matches the entrypoints data
self.entrypoint = entrypoint

def on_peer_ready(self) -> None:
assert self.connections is not None
assert self.peer is not None
self.update_log_context()
self.connections.on_peer_ready(self)
self.p2p_manager.on_peer_ready(self)
self.log.info('peer connected', peer_id=self.peer.id)

def on_disconnect(self, reason: Failure) -> None:
Expand All @@ -278,8 +274,7 @@ def on_disconnect(self, reason: Failure) -> None:
if self.state:
self.state.on_exit()
self.state = None
if self.connections:
self.connections.on_peer_disconnect(self)
self.p2p_manager.on_peer_disconnect(self)

def send_message(self, cmd: ProtocolMessages, payload: Optional[str] = None) -> None:
""" A generic message which must be implemented to send a message
Expand Down
10 changes: 4 additions & 6 deletions hathor/p2p/states/hello.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,15 @@ def _get_hello_data(self) -> dict[str, Any]:
'genesis_short_hash': get_genesis_short_hash(),
'timestamp': self.dependencies.reactor.seconds(),
'settings_dict': get_settings_hello_dict(self._settings),
'capabilities': protocol.connections.capabilities,
'capabilities': protocol.p2p_manager.capabilities,
}
if protocol.connections.has_sync_version_capability():
if protocol.p2p_manager.has_sync_version_capability():
data['sync_versions'] = [x.value for x in self._get_sync_versions()]
return data

def _get_sync_versions(self) -> set[SyncVersion]:
"""Shortcut to ConnectionManager.get_enabled_sync_versions"""
connections_manager = self.protocol.connections
assert connections_manager is not None
return connections_manager.get_enabled_sync_versions()
return self.protocol.p2p_manager.get_enabled_sync_versions()

def on_enter(self) -> None:
# After a connection is made, we just send a HELLO message.
Expand Down Expand Up @@ -161,7 +159,7 @@ def handle_hello(self, payload: str) -> None:

context = NetfilterContext(
protocol=protocol,
connections=protocol.connections,
connections=protocol.p2p_manager,
addr=protocol.transport.getPeer(),
)
verdict = get_table('filter').get_chain('post_hello').process(context)
Expand Down
12 changes: 6 additions & 6 deletions hathor/p2p/states/peer_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ async def handle_peer_id(self, payload: str) -> None:
protocol.send_error_and_close_connection('Are you my clone?!')
return

if protocol.connections is not None:
if protocol.connections.is_peer_connected(peer.id):
if protocol.p2p_manager is not None:
if protocol.p2p_manager.is_peer_connected(peer.id):
protocol.send_error_and_close_connection('We are already connected.')
return

Expand All @@ -130,7 +130,7 @@ async def handle_peer_id(self, payload: str) -> None:

context = NetfilterContext(
protocol=protocol,
connections=protocol.connections,
connections=protocol.p2p_manager,
addr=protocol.transport.getPeer(),
)
verdict = get_table('filter').get_chain('post_peerid').process(context)
Expand All @@ -145,7 +145,7 @@ def _should_block_peer(self, peer_id: PeerId) -> bool:
Currently this is only because the peer is not in a whitelist and whitelist blocking is active.
"""
peer_is_whitelisted = peer_id in self.protocol.connections.peers_whitelist
peer_is_whitelisted = peer_id in self.protocol.p2p_manager.peers_whitelist
# never block whitelisted peers
if peer_is_whitelisted:
return False
Expand All @@ -160,8 +160,8 @@ def _should_block_peer(self, peer_id: PeerId) -> bool:
return True

# otherwise we block non-whitelisted peers when on "whitelist-only mode"
if self.protocol.connections is not None:
protocol_is_whitelist_only = self.protocol.connections.whitelist_only
if self.protocol.p2p_manager is not None:
protocol_is_whitelist_only = self.protocol.p2p_manager.whitelist_only
if protocol_is_whitelist_only and not peer_is_whitelisted:
return True

Expand Down
Loading

0 comments on commit ec8c2eb

Please sign in to comment.