From 334b79e5a960e55d3ce5b24cbb3af660b7b902d4 Mon Sep 17 00:00:00 2001 From: Marten Seemann Date: Tue, 14 Dec 2021 17:01:42 +0400 Subject: [PATCH] move FilterAddrs here from go-addr-util --- multiaddr.go | 16 ++++++++++++++++ multiaddr_test.go | 25 ++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/multiaddr.go b/multiaddr.go index 58fe8ce..4f046cb 100644 --- a/multiaddr.go +++ b/multiaddr.go @@ -184,3 +184,19 @@ func (m *multiaddr) ValueForProtocol(code int) (value string, err error) { }) return } + +// FilterAddrs is a filter that removes certain addresses, according to the given filters. +// If all filters return true, the address is kept. +func FilterAddrs(a []Multiaddr, filters ...func(Multiaddr) bool) []Multiaddr { + b := make([]Multiaddr, 0, len(a)) + for _, addr := range a { + good := true + for _, filter := range filters { + good = good && filter(addr) + } + if good { + b = append(b, addr) + } + } + return b +} diff --git a/multiaddr_test.go b/multiaddr_test.go index f617ff9..d130081 100644 --- a/multiaddr_test.go +++ b/multiaddr_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/ipfs/go-cid" mh "github.com/multiformats/go-multihash" ) @@ -226,7 +228,7 @@ func TestStringToBytes(t *testing.T) { t.Error("failed to decode hex", h) } - //t.Log("196", h, []byte(b1)) + // t.Log("196", h, []byte(b1)) b2, err := stringToBytes(s) if err != nil { @@ -739,3 +741,24 @@ func TestComponentJSONMarshaler(t *testing.T) { t.Error("expected equal components in circular marshaling test") } } + +func TestFilterAddrs(t *testing.T) { + bad := []Multiaddr{ + newMultiaddr(t, "/ip6/fe80::1/tcp/1234"), + newMultiaddr(t, "/ip6/fe80::100/tcp/1234"), + } + good := []Multiaddr{ + newMultiaddr(t, "/ip4/127.0.0.1/tcp/1234"), + newMultiaddr(t, "/ip4/1.1.1.1/tcp/999"), + newMultiaddr(t, "/ip4/1.2.3.4/udp/1234/utp"), + } + goodAndBad := append(good, bad...) + + filter := func(addr Multiaddr) bool { + return addr.Protocols()[0].Code == P_IP4 + } + + require.Empty(t, FilterAddrs(bad, filter)) + require.ElementsMatch(t, FilterAddrs(good, filter), good) + require.ElementsMatch(t, FilterAddrs(goodAndBad, filter), good) +}