github.com/amazechain/amc@v0.1.3/internal/p2p/watch_peers.go (about) 1 package p2p 2 3 import ( 4 "context" 5 6 "github.com/libp2p/go-libp2p/core/host" 7 "github.com/libp2p/go-libp2p/core/peer" 8 ) 9 10 // ensurePeerConnections will attempt to reestablish connection to the peers 11 // if there are currently no connections to that peer. 12 func ensurePeerConnections(ctx context.Context, h host.Host, peers ...string) { 13 if len(peers) == 0 { 14 return 15 } 16 for _, p := range peers { 17 if p == "" { 18 continue 19 } 20 peerInfo, err := MakePeer(p) 21 if err != nil { 22 log.Error("Could not make peer", "err", err) 23 continue 24 } 25 26 c := h.Network().ConnsToPeer(peerInfo.ID) 27 if len(c) == 0 { 28 if err := connectWithTimeout(ctx, h, peerInfo); err != nil { 29 log.Error("Failed to reconnect to peer", "peer", peerInfo.ID, "addrs", peerInfo.Addrs, "err", err) 30 continue 31 } 32 } 33 } 34 } 35 36 func connectWithTimeout(ctx context.Context, h host.Host, peer *peer.AddrInfo) error { 37 log.Debug("No connections to peer, reconnecting", "peer", peer.ID) 38 ctx, cancel := context.WithTimeout(ctx, maxDialTimeout) 39 defer cancel() 40 return h.Connect(ctx, *peer) 41 }