-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkdht.go
52 lines (45 loc) · 1.13 KB
/
kdht.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
package main
import (
"context"
"log"
"sync"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
disc "github.com/libp2p/go-libp2p-discovery"
"github.com/libp2p/go-libp2p-kad-dht"
)
func NewKDHT(ctx context.Context, host host.Host, config Config) (*disc.RoutingDiscovery, error) {
var options []dht.Option
if len(config.DiscoveryPeers) == 0 {
options = append(options, dht.Mode(dht.ModeServer))
}
kdht, err := dht.New(
ctx,
host,
options...,
)
if err != nil {
return nil, err
}
if err = kdht.Bootstrap(ctx); err != nil {
return nil, err
}
// Let's connect to the bootstrap nodes first. They will tell us about the
// other nodes in the network.
var wg sync.WaitGroup
for _, peerAddr := range config.DiscoveryPeers {
peerinfo, _ := peer.AddrInfoFromP2pAddr(peerAddr)
wg.Add(1)
go func() {
defer wg.Done()
if err := host.Connect(ctx, *peerinfo); err != nil {
log.Println(err)
} else {
log.Println("Connection established with bootstrap node:", *peerinfo)
}
}()
}
wg.Wait()
routingDiscovery := disc.NewRoutingDiscovery(kdht)
return routingDiscovery, nil
}