-
Notifications
You must be signed in to change notification settings - Fork 54
/
util.go
47 lines (43 loc) · 1.03 KB
/
util.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"
iface "github.com/ipfs/kubo/core/coreiface"
peer "github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
func connect(ctx context.Context, ipfs iface.CoreAPI, peers []string) error {
var wg sync.WaitGroup
pinfos := make(map[peer.ID]*peer.AddrInfo, len(peers))
for _, addrStr := range peers {
addr, err := ma.NewMultiaddr(addrStr)
if err != nil {
return err
}
pii, err := peer.AddrInfoFromP2pAddr(addr)
if err != nil {
return err
}
pi, ok := pinfos[pii.ID]
if !ok {
pi = &peer.AddrInfo{ID: pii.ID}
pinfos[pi.ID] = pi
}
pi.Addrs = append(pi.Addrs, pii.Addrs...)
}
wg.Add(len(pinfos))
for _, pi := range pinfos {
go func(pi *peer.AddrInfo) {
defer wg.Done()
log.Printf("attempting to connect to peer: %q\n", pi)
err := ipfs.Swarm().Connect(ctx, *pi)
if err != nil {
log.Printf("failed to connect to %s: %s", pi.ID, err)
}
log.Printf("successfully connected to %s\n", pi.ID)
}(pi)
}
wg.Wait()
return nil
}