-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiscover.go
50 lines (46 loc) · 1.2 KB
/
discover.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
package main
import (
"context"
"fmt"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/p2p/discovery/routing"
discoveryUtil "github.com/libp2p/go-libp2p/p2p/discovery/util"
"log"
"time"
)
func Discover(ctx context.Context, node host.Host, routingDiscovery *routing.RoutingDiscovery) {
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
peers, err := discoveryUtil.FindPeers(ctx, routingDiscovery, Rendezvous)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d peers\n\n", len(peers))
for i, p := range peers {
if p.ID == node.ID() {
continue
}
fmt.Printf("Peer %d: %s\n", i+1, p.ID)
fmt.Printf("Addresses: %s\n\n\n\n", p.Addrs)
if node.Network().Connectedness(p.ID) != network.Connected {
_, err = node.Network().DialPeer(ctx, p.ID)
if err != nil {
fmt.Println("Error:", err)
continue
}
}
}
fmt.Printf("Connected to %d peers\n", len(node.Network().Peers()))
if len(node.Network().Peers()) == TotalNumberOfPeers-1 {
fmt.Println("Connected to all peers")
return
}
}
}
}