diff --git a/dht_filters.go b/dht_filters.go index fe2885922..236934735 100644 --- a/dht_filters.go +++ b/dht_filters.go @@ -3,9 +3,13 @@ package dht import ( "bytes" "net" + "sync" + "time" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/peer" + + "github.com/google/gopacket/routing" netroute "github.com/libp2p/go-netroute" ma "github.com/multiformats/go-multiaddr" @@ -64,10 +68,42 @@ func PrivateQueryFilter(dht *IpfsDHT, ai peer.AddrInfo) bool { var _ QueryFilterFunc = PrivateQueryFilter +// We call this very frequently but routes can technically change at runtime. +// Cache it for two minutes. +const routerCacheTime = 2 * time.Minute + +var routerCache struct { + sync.RWMutex + router routing.Router + expires time.Time +} + +func getCachedRouter() routing.Router { + routerCache.RLock() + router := routerCache.router + expires := routerCache.expires + routerCache.RUnlock() + + if time.Now().Before(expires) { + return router + } + + routerCache.Lock() + defer routerCache.Unlock() + + now := time.Now() + if now.Before(routerCache.expires) { + return router + } + routerCache.router, _ = netroute.New() + routerCache.expires = now.Add(routerCacheTime) + return router +} + // PrivateRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate // that it is on a private network func PrivateRoutingTableFilter(dht *IpfsDHT, conns []network.Conn) bool { - router, _ := netroute.New() + router := getCachedRouter() myAdvertisedIPs := make([]net.IP, 0) for _, a := range dht.Host().Addrs() { if manet.IsPublicAddr(a) && !isRelayAddr(a) { diff --git a/go.mod b/go.mod index 87e3785a5..edd3a3f12 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.14 require ( github.com/gogo/protobuf v1.3.1 + github.com/google/gopacket v1.1.17 github.com/google/uuid v1.1.1 github.com/hashicorp/go-multierror v1.1.0 github.com/hashicorp/golang-lru v0.5.4 @@ -24,7 +25,6 @@ require ( github.com/libp2p/go-libp2p-testing v0.1.1 github.com/libp2p/go-msgio v0.0.4 github.com/libp2p/go-netroute v0.1.2 - github.com/mr-tron/base58 v1.1.3 github.com/multiformats/go-base32 v0.0.3 github.com/multiformats/go-multiaddr v0.2.1 github.com/multiformats/go-multiaddr-dns v0.2.0