@@ -3,9 +3,13 @@ package dht
33import (
44 "bytes"
55 "net"
6+ "sync"
7+ "time"
68
79 "github.com/libp2p/go-libp2p-core/network"
810 "github.com/libp2p/go-libp2p-core/peer"
11+
12+ "github.com/google/gopacket/routing"
913 netroute "github.com/libp2p/go-netroute"
1014
1115 ma "github.com/multiformats/go-multiaddr"
@@ -64,10 +68,42 @@ func PrivateQueryFilter(dht *IpfsDHT, ai peer.AddrInfo) bool {
6468
6569var _ QueryFilterFunc = PrivateQueryFilter
6670
71+ // We call this very frequently but routes can technically change at runtime.
72+ // Cache it for two minutes.
73+ const routerCacheTime = 2 * time .Minute
74+
75+ var routerCache struct {
76+ sync.RWMutex
77+ router routing.Router
78+ expires time.Time
79+ }
80+
81+ func getCachedRouter () routing.Router {
82+ routerCache .RLock ()
83+ router := routerCache .router
84+ expires := routerCache .expires
85+ routerCache .RUnlock ()
86+
87+ if time .Now ().Before (expires ) {
88+ return router
89+ }
90+
91+ routerCache .Lock ()
92+ defer routerCache .Unlock ()
93+
94+ now := time .Now ()
95+ if now .Before (routerCache .expires ) {
96+ return router
97+ }
98+ routerCache .router , _ = netroute .New ()
99+ routerCache .expires = now .Add (routerCacheTime )
100+ return router
101+ }
102+
67103// PrivateRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate
68104// that it is on a private network
69105func PrivateRoutingTableFilter (dht * IpfsDHT , conns []network.Conn ) bool {
70- router , _ := netroute . New ()
106+ router := getCachedRouter ()
71107 myAdvertisedIPs := make ([]net.IP , 0 )
72108 for _ , a := range dht .Host ().Addrs () {
73109 if manet .IsPublicAddr (a ) && ! isRelayAddr (a ) {
0 commit comments