diff --git a/config/config.go b/config/config.go index f3ea35855a..ea94c067a3 100644 --- a/config/config.go +++ b/config/config.go @@ -446,12 +446,9 @@ func (cfg *Config) newBasicHost(swrm *swarm.Swarm, eventBus event.Bus) (*bhost.B return h, nil } -// NewNode constructs a new libp2p Host from the Config. -// -// This function consumes the config. Do not reuse it (really!). -func (cfg *Config) NewNode() (host.Host, error) { +func (cfg *Config) validate() error { if cfg.EnableAutoRelay && !cfg.Relay { - return nil, fmt.Errorf("cannot enable autorelay; relay is not enabled") + return fmt.Errorf("cannot enable autorelay; relay is not enabled") } // If possible check that the resource manager conn limit is higher than the // limit set in the conn manager. @@ -462,6 +459,33 @@ func (cfg *Config) NewNode() (host.Host, error) { } } + if len(cfg.PSK) > 0 && cfg.ShareTCPListener { + return errors.New("cannot use shared TCP listener with PSK") + } + + return nil +} + +// NewNode constructs a new libp2p Host from the Config. +// +// This function consumes the config. Do not reuse it (really!). +func (cfg *Config) NewNode() (host.Host, error) { + + validateErr := cfg.validate() + if validateErr != nil { + if cfg.ResourceManager != nil { + cfg.ResourceManager.Close() + } + if cfg.ConnManager != nil { + cfg.ConnManager.Close() + } + if cfg.Peerstore != nil { + cfg.Peerstore.Close() + } + + return nil, validateErr + } + if !cfg.DisableMetrics { rcmgr.MustRegisterWith(cfg.PrometheusRegisterer) } diff --git a/libp2p_test.go b/libp2p_test.go index 3de82946d8..3dc7f2e8ab 100644 --- a/libp2p_test.go +++ b/libp2p_test.go @@ -26,6 +26,7 @@ import ( "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/peerstore" + "github.com/libp2p/go-libp2p/core/pnet" "github.com/libp2p/go-libp2p/core/routing" "github.com/libp2p/go-libp2p/core/transport" rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager" @@ -761,6 +762,7 @@ func TestSharedTCPAddr(t *testing.T) { ListenAddrStrings("/ip4/0.0.0.0/tcp/8888/ws"), ) require.NoError(t, err) + defer h.Close() sawTCP := false sawWS := false for _, addr := range h.Addrs() { @@ -773,5 +775,12 @@ func TestSharedTCPAddr(t *testing.T) { } require.True(t, sawTCP) require.True(t, sawWS) - h.Close() + + _, err = New( + ShareTCPListener(), + Transport(tcp.NewTCPTransport), + Transport(websocket.New), + PrivateNetwork(pnet.PSK([]byte{1, 2, 3})), + ) + require.ErrorContains(t, err, "cannot use shared TCP listener with PSK") }