Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
pipermerriam committed Jun 20, 2018
1 parent 81d71d9 commit dc0d83b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
6 changes: 4 additions & 2 deletions p2p/peer.py
Expand Up @@ -601,11 +601,13 @@ def is_full(self) -> bool:
def is_valid_connection_candidate(self, candidate: Node) -> bool:
# connect to no more then 2 nodes with the same IP
nodes_by_ip = groupby(
operator.attrgetter('remote.address.ip'), self.connected_nodes.values())
operator.attrgetter('remote.address.ip'),
self.connected_nodes.values(),
)
matching_ip_nodes = nodes_by_ip.get(candidate.address.ip, [])
return len(matching_ip_nodes) <= 2

def get_nodes_to_connect(self) -> Generator[Node, None, None]:
def get_nodes_to_connect(self) -> Iterator[Node]:
for node in self.discovery.get_random_nodes(self.max_peers):
if self.is_valid_connection_candidate(node):
yield node
Expand Down
31 changes: 19 additions & 12 deletions p2p/server.py
Expand Up @@ -58,6 +58,9 @@
from trinity.db.header import BaseAsyncHeaderDB # noqa: F401


DIAL_IN_OUT_RATIO = 0.75


class Server(BaseService):
"""Server listening for incoming connections"""
logger = logging.getLogger("p2p.server.Server")
Expand Down Expand Up @@ -256,19 +259,23 @@ async def _receive_handshake(

if self.peer_pool.is_full:
peer.disconnect(DisconnectReason.too_many_peers)
elif not self.peer_pool.is_valid_connection_candidate(peer.remote):
peer.disconnect(DisconnectReason.too_many_peers)

total_peers = len(self.peer_pool.connected_nodes)
inbound_peer_count = len([
peer
for peer
in self.peer_pool.connected_nodes.values()
if peer.inbound
])
if total_peers > 1 and inbound_peer_count / total_peers > DIAL_IN_OUT_RATIO:
# make sure to have at least 1/4 outbound connections
peer.disconnect(DisconnectReason.useless_peer)
else:
total_peers = len(self.peer_pool.connected_nodes)
inbound_peers = len(
[peer for peer in self.peer_pool.connected_nodes.values() if peer.inbound])
if total_peers > 1 and inbound_peers / total_peers > 0.75:
# make sure to have at least 1/4 outbound connections
peer.disconnect(DisconnectReason.useless_peer)
elif not self.peer_pool.is_valid_connection_candidate(peer.remote):
peer.disconnect(DisconnectReason.useless_peer)
else:
# We use self.wait() here as a workaround for
# https://github.com/ethereum/py-evm/issues/670.
await self.wait(self.do_handshake(peer))
# We use self.wait() here as a workaround for
# https://github.com/ethereum/py-evm/issues/670.
await self.wait(self.do_handshake(peer))

async def do_handshake(self, peer: BasePeer) -> None:
await peer.do_p2p_handshake(),
Expand Down

0 comments on commit dc0d83b

Please sign in to comment.