From 7f690dcc6888b504b249d2b75b3273046b26aeda Mon Sep 17 00:00:00 2001 From: vyzo Date: Wed, 9 May 2018 11:47:16 +0300 Subject: [PATCH] refactor getPeers for locked scope --- p2p/host/autonat/autonat.go | 50 ++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/p2p/host/autonat/autonat.go b/p2p/host/autonat/autonat.go index 30255328..765996b1 100644 --- a/p2p/host/autonat/autonat.go +++ b/p2p/host/autonat/autonat.go @@ -85,30 +85,13 @@ func (as *AmbientAutoNAT) background() { } func (as *AmbientAutoNAT) autodetect() { - if len(as.peers) == 0 { + peers := as.getPeers() + + if len(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) - } - } - - 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) - } - } - - as.mx.Unlock() - - shufflePeers(peers) - for _, p := range peers { cli := NewAutoNATClient(as.host, p) ctx, cancel := context.WithTimeout(as.ctx, AutoNATRequestTimeout) @@ -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)