From 37043f0d916959d35b17b8b524d6f9b2bebfa8ab Mon Sep 17 00:00:00 2001 From: Zahary Karadjov Date: Wed, 11 Sep 2019 11:01:36 -0400 Subject: [PATCH] Handle gracefully a pre-mature closing of a libp2p stream by another peer --- beacon_chain/libp2p_backend.nim | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/beacon_chain/libp2p_backend.nim b/beacon_chain/libp2p_backend.nim index f8a1d24eb..e95648794 100644 --- a/beacon_chain/libp2p_backend.nim +++ b/beacon_chain/libp2p_backend.nim @@ -126,6 +126,10 @@ proc getPeer*(node: Eth2Node, peerId: PeerID): Peer {.gcsafe.} = proc peerFromStream(daemon: DaemonAPI, stream: P2PStream): Peer {.gcsafe.} = Eth2Node(daemon.userData).getPeer(stream.peer) +proc safeClose(stream: P2PStream) {.async.} = + if P2PStreamFlags.Closed notin stream.flags: + await close(stream) + proc disconnect*(peer: Peer, reason: DisconnectionReason, notifyOtherPeer = false) {.async.} = # TODO: How should we notify the other peer? if peer.connectionState notin {Disconnecting, Disconnected}: @@ -327,7 +331,7 @@ proc sendNotificationMsg(peer: Peer, protocolId: string, requestBytes: Bytes) {. let stream = streamFut.read defer: - await close(stream) + await safeClose(stream) var s = init OutputStream s.appendVarint requestBytes.len.uint64 @@ -407,7 +411,7 @@ proc makeEth2Request(peer: Peer, protocolId: string, requestBytes: Bytes, let stream = streamFut.read defer: - await close(stream) + await safeClose(stream) # Send the request var s = init OutputStream @@ -589,7 +593,7 @@ proc p2pProtocolBackendImpl*(p: P2PProtocol): Backend = proc `thunkName`(`daemonVar`: `DaemonAPI`, `streamVar`: `P2PStream`) {.async, gcsafe.} = defer: - `await` close(`streamVar`) + `await` safeClose(`streamVar`) let `deadlineVar` = sleepAsync RESP_TIMEOUT