-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
dht.go
47 lines (38 loc) · 1017 Bytes
/
dht.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
package main
import (
"context"
"log"
"sync"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-kad-dht"
"github.com/multiformats/go-multiaddr"
)
func NewDHT(ctx context.Context, host host.Host, bootstrapPeers []multiaddr.Multiaddr) (*dht.IpfsDHT, error) {
var options []dht.Option
if len(bootstrapPeers) == 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
}
var wg sync.WaitGroup
for _, peerAddr := range bootstrapPeers {
peerinfo, _ := peer.AddrInfoFromP2pAddr(peerAddr)
wg.Add(1)
go func() {
defer wg.Done()
if err := host.Connect(ctx, *peerinfo); err != nil {
log.Printf("Error while connecting to node %q: %-v", peerinfo, err)
} else {
log.Printf("Connection established with bootstrap node: %q", *peerinfo)
}
}()
}
wg.Wait()
return kdht, nil
}