From bc652aebd95dd5a11f36d14fd2dd407a9c8dfcc4 Mon Sep 17 00:00:00 2001 From: Janos Guljas Date: Thu, 11 Apr 2019 15:12:55 +0200 Subject: [PATCH] swarm/network: add Kademlia.Saturation method with lock --- swarm/network/discovery_test.go | 4 +--- swarm/network/kademlia.go | 12 +++++++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/swarm/network/discovery_test.go b/swarm/network/discovery_test.go index 137205ca60..17324f3972 100644 --- a/swarm/network/discovery_test.go +++ b/swarm/network/discovery_test.go @@ -174,9 +174,7 @@ func testInitialPeersMsg(t *testing.T, peerPO, peerDepth int) { } // pivotDepth is the advertised depth of the pivot node we expect in the outgoing subPeersMsg - hive.Kademlia.lock.RLock() // protect Kademlia.conns that are read in Kademlia.saturation() - pivotDepth := hive.saturation() - hive.Kademlia.lock.RUnlock() + pivotDepth := hive.Saturation() // the test exchange is as follows: // 1. pivot sends to the control peer a `subPeersMsg` advertising its depth (ignored) // 2. peer sends to pivot a `subPeersMsg` advertising its own depth (arbitrarily chosen) diff --git a/swarm/network/kademlia.go b/swarm/network/kademlia.go index 304f9cd778..ec0ffd23ac 100644 --- a/swarm/network/kademlia.go +++ b/swarm/network/kademlia.go @@ -735,8 +735,18 @@ func NewPeerPotMap(neighbourhoodSize int, addrs [][]byte) map[string]*PeerPot { return ppmap } -// saturation returns the smallest po value in which the node has less than MinBinSize peers +// Saturation returns the smallest po value in which the node has less than MinBinSize peers // if the iterator reaches neighbourhood radius, then the last bin + 1 is returned +func (k *Kademlia) Saturation() int { + k.lock.RLock() + defer k.lock.RUnlock() + + return k.saturation() +} + +// saturation returns the smallest po value in which the node has less than MinBinSize peers +// if the iterator reaches neighbourhood radius, then the last bin + 1 is returned. +// This function is safe to use in Kademlia methods that use the lock. func (k *Kademlia) saturation() int { prev := -1 radius := neighbourhoodRadiusForPot(k.conns, k.NeighbourhoodSize, k.base)