Skip to content

Commit

Permalink
feat(p2p): added helpers to count relays found in peerstore, check if…
Browse files Browse the repository at this point in the history
… they're connected and reconnect to them
  • Loading branch information
aeddi committed Jan 31, 2019
1 parent 8268c52 commit 9713b28
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions core/network/p2p/relay_conn.go
@@ -0,0 +1,56 @@
package p2p

import (
"context"

host "github.com/libp2p/go-libp2p-host"
inet "github.com/libp2p/go-libp2p-net"
peer "github.com/libp2p/go-libp2p-peer"
)

func getRelaysFromPeerstore(host host.Host) peer.IDSlice {
var relays peer.IDSlice
peers := host.Peerstore().Peers()

for _, peer := range peers {
tags := host.ConnManager().GetTagInfo(peer)
if tags != nil {
val, exist := tags.Tags["relay-hop"]
if exist && val == 2 {
relays = append(relays, peer)
}
}
}

return relays
}

func CountConnectedRelays(host host.Host) int {
relays := getRelaysFromPeerstore(host)
connectedRelays := 0

for _, relay := range relays {
if host.Network().Connectedness(relay) == inet.Connected {
connectedRelays++
}
}

return connectedRelays
}

func ReconnectToRelays(host host.Host, limit int) int {
connectedRelays := 0
relays := getRelaysFromPeerstore(host)

for _, relay := range relays {
relayInfo := host.Peerstore().PeerInfo(relay)
if host.Connect(context.Background(), relayInfo) == nil {
connectedRelays++
if connectedRelays == limit {
break
}
}
}

return connectedRelays
}

0 comments on commit 9713b28

Please sign in to comment.