Skip to content

Commit 6fca8f7

Browse files
authored
Ensure network connection is closed when handshake with peer fails (#1476)
* Ensure network connection is closed when handshake with peer fails * clean up remaining unclosed transport warnings * Add comment
1 parent adf66da commit 6fca8f7

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

p2p/auth.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,20 @@ async def handshake(
5757
use_eip8 = False
5858
initiator = HandshakeInitiator(remote, privkey, use_eip8, token)
5959
reader, writer = await initiator.connect()
60-
aes_secret, mac_secret, egress_mac, ingress_mac = await _handshake(
61-
initiator, reader, writer, token)
60+
try:
61+
aes_secret, mac_secret, egress_mac, ingress_mac = await _handshake(
62+
initiator, reader, writer, token)
63+
except Exception:
64+
# Note: This is one of two places where we manually handle closing the
65+
# reader/writer connection pair in the event of an error during the
66+
# peer connection and handshake process.
67+
# See `p2p.peer.handshake` for the other.
68+
if not reader.at_eof():
69+
reader.feed_eof()
70+
writer.close()
71+
await asyncio.sleep(0)
72+
raise
73+
6274
return aes_secret, mac_secret, egress_mac, ingress_mac, reader, writer
6375

6476

p2p/peer.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,21 @@ async def handshake(remote: Node, factory: 'BasePeerFactory') -> 'BasePeer':
127127
connection=connection,
128128
inbound=False,
129129
)
130-
await peer.do_p2p_handshake()
131-
await peer.do_sub_proto_handshake()
130+
131+
try:
132+
await peer.do_p2p_handshake()
133+
await peer.do_sub_proto_handshake()
134+
except Exception:
135+
# Note: This is one of two places where we manually handle closing the
136+
# reader/writer connection pair in the event of an error during the
137+
# peer connection and handshake process.
138+
# See `p2p.auth.handshake` for the other.
139+
if not reader.at_eof():
140+
reader.feed_eof()
141+
writer.close()
142+
await asyncio.sleep(0)
143+
raise
144+
132145
return peer
133146

134147

@@ -342,9 +355,8 @@ def close(self) -> None:
342355
343356
If the streams have already been closed, do nothing.
344357
"""
345-
if self.reader.at_eof():
346-
return
347-
self.reader.feed_eof()
358+
if not self.reader.at_eof():
359+
self.reader.feed_eof()
348360
self.writer.close()
349361

350362
@property

0 commit comments

Comments
 (0)