Skip to content

Commit

Permalink
move FilterAddrs here from go-addr-util
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Dec 14, 2021
1 parent eb5c75f commit 8e0d03f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
19 changes: 19 additions & 0 deletions net/filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package manet

import ma "github.com/multiformats/go-multiaddr"

// 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 []ma.Multiaddr, filters ...func(ma.Multiaddr) bool) []ma.Multiaddr {
b := make([]ma.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
}
30 changes: 30 additions & 0 deletions net/filter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package manet

import (
"testing"

ma "github.com/multiformats/go-multiaddr"
"github.com/stretchr/testify/require"
)

func TestFilterAddrs(t *testing.T) {
bad := []ma.Multiaddr{
newMultiaddr(t, "/ip6/fe80::1/tcp/1234"), // link local
newMultiaddr(t, "/ip6/fe80::100/tcp/1234"), // link local
}

good := []ma.Multiaddr{
newMultiaddr(t, "/ip4/127.0.0.1/tcp/1234"),
newMultiaddr(t, "/ip6/::1/tcp/1234"),
newMultiaddr(t, "/ip4/1.2.3.4/udp/1234/utp"),
}

goodAndBad := append(good, bad...)

// test filters
filter := AddrOverNonLocalIP

require.Empty(t, FilterAddrs(bad, filter))
require.ElementsMatch(t, FilterAddrs(good, filter), good)
require.ElementsMatch(t, FilterAddrs(goodAndBad, filter), good)
}

0 comments on commit 8e0d03f

Please sign in to comment.