Skip to content

Commit 4e6eff8

Browse files
authored
Merge pull request #257 from libp2p/fix/typed-nil
fix: avoid returning typed nils
2 parents 19c7253 + 98d7eef commit 4e6eff8

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

p2p/net/swarm/swarm_dial.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,12 @@ func (s *Swarm) DialPeer(ctx context.Context, p peer.ID) (network.Conn, error) {
226226
return nil, &DialError{Peer: p, Cause: ErrGaterDisallowedConnection}
227227
}
228228

229-
return s.dialPeer(ctx, p)
229+
// Avoid typed nil issues.
230+
c, err := s.dialPeer(ctx, p)
231+
if err != nil {
232+
return nil, err
233+
}
234+
return c, nil
230235
}
231236

232237
// internal dial method that returns an unwrapped conn

p2p/net/swarm/swarm_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,19 @@ func TestCloseWithOpenStreams(t *testing.T) {
412412
}
413413
}
414414

415+
func TestTypedNilConn(t *testing.T) {
416+
ctx, cancel := context.WithCancel(context.Background())
417+
defer cancel()
418+
s := GenSwarm(t, ctx)
419+
defer s.Close()
420+
421+
// We can't dial ourselves.
422+
c, err := s.DialPeer(ctx, s.LocalPeer())
423+
require.Error(t, err)
424+
// If we fail to dial, the connection should be nil.
425+
require.True(t, c == nil)
426+
}
427+
415428
func TestPreventDialListenAddr(t *testing.T) {
416429
s := GenSwarm(t, context.Background(), OptDialOnly)
417430
if err := s.Listen(ma.StringCast("/ip4/0.0.0.0/udp/0/quic")); err != nil {

0 commit comments

Comments
 (0)