diff --git a/p2p/transport/webtransport/multiaddr.go b/p2p/transport/webtransport/multiaddr.go index 9d7999193..a61b1b896 100644 --- a/p2p/transport/webtransport/multiaddr.go +++ b/p2p/transport/webtransport/multiaddr.go @@ -3,6 +3,7 @@ package libp2pwebtransport import ( "errors" "net" + "strconv" ma "github.com/multiformats/go-multiaddr" mafmt "github.com/multiformats/go-multiaddr-fmt" @@ -23,3 +24,19 @@ func toWebtransportMultiaddr(na net.Addr) (ma.Multiaddr, error) { } return addr.Encapsulate(webtransportMA), nil } + +func stringToWebtransportMultiaddr(str string) (ma.Multiaddr, error) { + host, portStr, err := net.SplitHostPort(str) + if err != nil { + return nil, err + } + port, err := strconv.ParseInt(portStr, 10, 32) + if err != nil { + return nil, err + } + ip := net.ParseIP(host) + if ip == nil { + return nil, errors.New("failed to parse IP") + } + return toWebtransportMultiaddr(&net.UDPAddr{IP: ip, Port: int(port)}) +} diff --git a/p2p/transport/webtransport/multiaddr_test.go b/p2p/transport/webtransport/multiaddr_test.go index 2098babbd..5fc0432a3 100644 --- a/p2p/transport/webtransport/multiaddr_test.go +++ b/p2p/transport/webtransport/multiaddr_test.go @@ -19,3 +19,23 @@ func TestWebtransportMultiaddr(t *testing.T) { require.EqualError(t, err, "not a UDP address") }) } + +func TestWebtransportMultiaddrFromString(t *testing.T) { + t.Run("valid", func(t *testing.T) { + addr, err := stringToWebtransportMultiaddr("1.2.3.4:60042") + require.NoError(t, err) + require.Equal(t, "/ip4/1.2.3.4/udp/60042/quic/webtransport", addr.String()) + }) + + t.Run("invalid", func(t *testing.T) { + for _, addr := range [...]string{ + "1.2.3.4", // missing port + "1.2.3.4:123456", // invalid port + ":1234", // missing IP + "foobar", + } { + _, err := stringToWebtransportMultiaddr(addr) + require.Error(t, err) + } + }) +}