From 7f1ffcbd4e69394b9babb5dead5b940c1aaca547 Mon Sep 17 00:00:00 2001 From: vyzo Date: Tue, 25 Jul 2017 12:15:41 +0300 Subject: [PATCH] basic_host: NewHost: don't panic on relay errors, return an error instead The legacy interface stays unchanged with a panic though. --- p2p/host/basic/basic_host.go | 17 +++++++++++------ p2p/net/mock/mock_net.go | 6 +++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/p2p/host/basic/basic_host.go b/p2p/host/basic/basic_host.go index ca0ce93..bc56072 100644 --- a/p2p/host/basic/basic_host.go +++ b/p2p/host/basic/basic_host.go @@ -107,7 +107,7 @@ type HostOpts struct { } // NewHost constructs a new *BasicHost and activates it by attaching its stream and connection handlers to the given inet.Network. -func NewHost(net inet.Network, opts *HostOpts) *BasicHost { +func NewHost(net inet.Network, opts *HostOpts) (*BasicHost, error) { h := &BasicHost{ network: net, mux: msmux.NewMultistreamMuxer(), @@ -156,9 +156,7 @@ func NewHost(net inet.Network, opts *HostOpts) *BasicHost { relayCtx, relayCancel = context.WithCancel(context.Background()) err := circuit.AddRelayTransport(relayCtx, h, opts.RelayOpts...) if err != nil { - // perhaps inappropriate, but otherwise we have to change the interface - // to return an error, which will nost likely lead to a fatality anyway - panic(err) + return nil, err } } @@ -175,7 +173,7 @@ func NewHost(net inet.Network, opts *HostOpts) *BasicHost { net.SetConnHandler(h.newConnHandler) net.SetStreamHandler(h.newStreamHandler) - return h + return h, nil } // New constructs and sets up a new *BasicHost with given Network and options. @@ -200,7 +198,14 @@ func New(net inet.Network, opts ...interface{}) *BasicHost { } } - return NewHost(net, hostopts) + h, err := NewHost(net, hostopts) + if err != nil { + // this cannot happen with legacy options + // plus we want to keep the (deprecated) legacy interface unchanged + panic(err) + } + + return h } // newConnHandler is the remote-opened conn handler for inet.Network diff --git a/p2p/net/mock/mock_net.go b/p2p/net/mock/mock_net.go index 357c810..b670c8f 100644 --- a/p2p/net/mock/mock_net.go +++ b/p2p/net/mock/mock_net.go @@ -87,7 +87,11 @@ func (mn *mocknet) AddPeerWithPeerstore(p peer.ID, ps pstore.Peerstore) (host.Ho opts := &bhost.HostOpts{ NegotiationTimeout: -1, } - h := bhost.NewHost(n, opts) + + h, err := bhost.NewHost(n, opts) + if err != nil { + return nil, err + } mn.proc.AddChild(n.proc) -- GitLab