From 07b1bf9d7b7f1f6c1999d8d2cf4cacf7806c6dbd Mon Sep 17 00:00:00 2001 From: Christian Stewart Date: Wed, 22 Jun 2022 12:56:24 -0700 Subject: [PATCH] muxer: expose func to create MuxedConn from backing Conn Expose a function to create a MuxedConn from the base type: if a user has a *mp.Multiplex or a *yamux.Session, they should be able to construct the libp2p wrapper without going through the Transport interfaces. Signed-off-by: Christian Stewart --- p2p/muxer/mplex/conn.go | 5 +++++ p2p/muxer/mplex/transport.go | 2 +- p2p/muxer/yamux/conn.go | 5 +++++ p2p/muxer/yamux/transport.go | 5 ++++- 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/p2p/muxer/mplex/conn.go b/p2p/muxer/mplex/conn.go index 9c681d162a..1abef546f5 100644 --- a/p2p/muxer/mplex/conn.go +++ b/p2p/muxer/mplex/conn.go @@ -12,6 +12,11 @@ type conn mp.Multiplex var _ network.MuxedConn = &conn{} +// NewMuxedConn constructs a new Conn from a *mp.Multiplex. +func NewMuxedConn(m *mp.Multiplex) network.MuxedConn { + return (*conn)(m) +} + func (c *conn) Close() error { return c.mplex().Close() } diff --git a/p2p/muxer/mplex/transport.go b/p2p/muxer/mplex/transport.go index f4f0b21955..f24c1cc7ca 100644 --- a/p2p/muxer/mplex/transport.go +++ b/p2p/muxer/mplex/transport.go @@ -22,5 +22,5 @@ func (t *Transport) NewConn(nc net.Conn, isServer bool, scope network.PeerScope) if err != nil { return nil, err } - return (*conn)(m), nil + return NewMuxedConn(m), nil } diff --git a/p2p/muxer/yamux/conn.go b/p2p/muxer/yamux/conn.go index a7c6dc00de..4feff1dea6 100644 --- a/p2p/muxer/yamux/conn.go +++ b/p2p/muxer/yamux/conn.go @@ -13,6 +13,11 @@ type conn yamux.Session var _ network.MuxedConn = &conn{} +// NewMuxedConn constructs a new MuxedConn from a yamux.Session. +func NewMuxedConn(m *yamux.Session) network.MuxedConn { + return (*conn)(m) +} + // Close closes underlying yamux func (c *conn) Close() error { return c.yamux().Close() diff --git a/p2p/muxer/yamux/transport.go b/p2p/muxer/yamux/transport.go index 0d43208ad0..74ed7145bd 100644 --- a/p2p/muxer/yamux/transport.go +++ b/p2p/muxer/yamux/transport.go @@ -45,7 +45,10 @@ func (t *Transport) NewConn(nc net.Conn, isServer bool, scope network.PeerScope) } else { s, err = yamux.Client(nc, t.Config(), scope) } - return (*conn)(s), err + if err != nil { + return nil, err + } + return NewMuxedConn(s), nil } func (t *Transport) Config() *yamux.Config {