-
Notifications
You must be signed in to change notification settings - Fork 19
/
bootstrap.go
74 lines (65 loc) · 1.82 KB
/
bootstrap.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
71
72
73
74
package main
import (
"context"
"errors"
"fmt"
"sync"
host "github.com/libp2p/go-libp2p-host"
pstore "github.com/libp2p/go-libp2p-peerstore"
ma "github.com/multiformats/go-multiaddr"
)
func convertPeers(peers []string) ([]pstore.PeerInfo, error) {
pinfos := make([]pstore.PeerInfo, len(peers))
for i, peer := range peers {
maddr := ma.StringCast(peer)
p, err := pstore.InfoFromP2pAddr(maddr)
if err != nil {
return nil, err
}
pinfos[i] = *p
}
return pinfos, nil
}
// This code is borrowed from the go-ipfs bootstrap process
func bootstrapConnect(ctx context.Context, ph host.Host, peers []pstore.PeerInfo) error {
if len(peers) < 1 {
return errors.New("not enough bootstrap peers")
}
errs := make(chan error, len(peers))
var wg sync.WaitGroup
for _, p := range peers {
// performed asynchronously because when performed synchronously, if
// one `Connect` call hangs, subsequent calls are more likely to
// fail/abort due to an expiring context.
// Also, performed asynchronously for dial speed.
wg.Add(1)
go func(p pstore.PeerInfo) {
defer wg.Done()
defer logger.Debug(ctx, "bootstrapDial", ph.ID(), p.ID)
logger.Debugf("%s bootstrapping to %s", ph.ID(), p.ID)
ph.Peerstore().AddAddrs(p.ID, p.Addrs, pstore.PermanentAddrTTL)
if err := ph.Connect(ctx, p); err != nil {
logger.Errorf("Failed to bootstrap with %v: %s", p.ID, err)
errs <- err
return
}
logger.Debug(ctx, "bootstrapDialSuccess", p.ID)
logger.Debugf("Bootstrapped with %v", p.ID)
}(p)
}
wg.Wait()
// our failure condition is when no connection attempt succeeded.
// So drain the errs channel, counting the results.
close(errs)
count := 0
var err error
for err = range errs {
if err != nil {
count++
}
}
if count == len(peers) {
return fmt.Errorf("Failed to bootstrap. %s", err)
}
return nil
}