Skip to content
This repository has been archived by the owner on May 11, 2022. It is now read-only.

Commit

Permalink
refactor getPeers for locked scope
Browse files Browse the repository at this point in the history
  • Loading branch information
vyzo committed May 9, 2018
1 parent fa14117 commit d16ca79
Showing 1 changed file with 30 additions and 20 deletions.
50 changes: 30 additions & 20 deletions autonat.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,30 +85,13 @@ func (as *AmbientAutoNAT) background() {
}

func (as *AmbientAutoNAT) autodetect() {
if len(as.peers) == 0 {
log.Debugf("skipping NAT auto detection; no autonat peers")
return
}

as.mx.Lock()
peers := make([]peer.ID, 0, len(as.peers))
for p := range as.peers {
if len(as.host.Network().ConnsToPeer(p)) > 0 {
peers = append(peers, p)
}
}
peers := as.getPeers()

if len(peers) == 0 {
// we don't have any open connections, try any autonat peer that we know about
for p := range as.peers {
peers = append(peers, p)
}
log.Debugf("skipping NAT auto detection; no autonat peers")
return
}

as.mx.Unlock()

shufflePeers(peers)

for _, p := range peers {
cli := NewAutoNATClient(as.host, p)
ctx, cancel := context.WithTimeout(as.ctx, AutoNATRequestTimeout)
Expand Down Expand Up @@ -141,6 +124,33 @@ func (as *AmbientAutoNAT) autodetect() {
as.mx.Unlock()
}

func (as *AmbientAutoNAT) getPeers() []peer.ID {
as.mx.Lock()
defer as.mx.Unlock()

if len(as.peers) == 0 {
return nil
}

peers := make([]peer.ID, 0, len(as.peers))
for p := range as.peers {
if len(as.host.Network().ConnsToPeer(p)) > 0 {
peers = append(peers, p)
}
}

if len(peers) == 0 {
// we don't have any open connections, try any autonat peer that we know about
for p := range as.peers {
peers = append(peers, p)
}
}

shufflePeers(peers)

return peers
}

func shufflePeers(peers []peer.ID) {
for i := range peers {
j := rand.Intn(i + 1)
Expand Down

0 comments on commit d16ca79

Please sign in to comment.