-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer_discovery.go
70 lines (65 loc) · 1.74 KB
/
peer_discovery.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package cassette
import (
"context"
"time"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/multiformats/go-multiaddr"
)
type peerDiscoverer struct {
discoveryTicker *time.Ticker
c *Cassette
}
func newPeerDiscoverer(c *Cassette) *peerDiscoverer {
return &peerDiscoverer{
c: c,
discoveryTicker: time.NewTicker(c.peerDiscoveryInterval),
}
}
func (pd *peerDiscoverer) start(ctx context.Context) error {
peerRouter, err := dht.New(context.Background(), pd.c.peerDiscoveryHost,
dht.Mode(dht.ModeClient),
dht.BootstrapPeers(dht.GetDefaultBootstrapPeerAddrInfos()...),
)
if err != nil {
return err
}
go func() {
discover := func() {
var count int
for _, p := range pd.c.peers {
if len(p.Addrs) == 0 {
count++
pid := p.ID
found, err := peerRouter.FindPeer(ctx, pid)
if err != nil {
logger.Errorw("Failed to discover addrs for peer", "peer", pid, "err", err)
continue
}
addrs := multiaddr.FilterAddrs(found.Addrs, IsPubliclyDialableAddr)
if len(addrs) == 0 {
logger.Errorw("No publicly dialable addrs found for peer", "peer", pid, "addrs", found.Addrs)
continue
}
prev := pd.c.h.Peerstore().Addrs(pid)
pd.c.h.Peerstore().ClearAddrs(pid)
pd.c.h.Peerstore().SetAddrs(pid, addrs, pd.c.peerDiscoveryAddrTTL)
logger.Infow("Discovered addrs for peer", "peer", pid, "addrs", addrs, "previous", prev)
}
}
logger.Infow("Finished discovery cycle for peers with no addrs", "count", count)
}
discover()
for {
select {
case <-ctx.Done():
logger.Info("Stopping peer discovery")
_ = peerRouter.Close()
pd.discoveryTicker.Stop()
return
case <-pd.discoveryTicker.C:
discover()
}
}
}()
return nil
}