Skip to content

Commit a77e0e4

Browse files
committed
fix races in testnet
ConnectTo can be called concurrently from within bitswap. License: MIT Signed-off-by: Steven Allen <[email protected]>
1 parent 4d8c443 commit a77e0e4

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

exchange/bitswap/testnet/virtual.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package bitswap
33
import (
44
"context"
55
"errors"
6+
"sync"
67

78
bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
89
bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network"
@@ -29,13 +30,17 @@ func VirtualNetwork(rs mockrouting.Server, d delay.D) Network {
2930
}
3031

3132
type network struct {
33+
mu sync.Mutex
3234
clients map[peer.ID]bsnet.Receiver
3335
routingserver mockrouting.Server
3436
delay delay.D
3537
conns map[string]struct{}
3638
}
3739

3840
func (n *network) Adapter(p testutil.Identity) bsnet.BitSwapNetwork {
41+
n.mu.Lock()
42+
defer n.mu.Unlock()
43+
3944
client := &networkClient{
4045
local: p.ID(),
4146
network: n,
@@ -46,6 +51,9 @@ func (n *network) Adapter(p testutil.Identity) bsnet.BitSwapNetwork {
4651
}
4752

4853
func (n *network) HasPeer(p peer.ID) bool {
54+
n.mu.Lock()
55+
defer n.mu.Unlock()
56+
4957
_, found := n.clients[p]
5058
return found
5159
}
@@ -58,6 +66,9 @@ func (n *network) SendMessage(
5866
to peer.ID,
5967
message bsmsg.BitSwapMessage) error {
6068

69+
n.mu.Lock()
70+
defer n.mu.Unlock()
71+
6172
receiver, ok := n.clients[to]
6273
if !ok {
6374
return errors.New("Cannot locate peer on network")
@@ -161,18 +172,26 @@ func (nc *networkClient) SetDelegate(r bsnet.Receiver) {
161172
}
162173

163174
func (nc *networkClient) ConnectTo(_ context.Context, p peer.ID) error {
164-
if !nc.network.HasPeer(p) {
175+
nc.network.mu.Lock()
176+
177+
otherClient, ok := nc.network.clients[p]
178+
if !ok {
179+
nc.network.mu.Unlock()
165180
return errors.New("no such peer in network")
166181
}
182+
167183
tag := tagForPeers(nc.local, p)
168184
if _, ok := nc.network.conns[tag]; ok {
185+
nc.network.mu.Unlock()
169186
log.Warning("ALREADY CONNECTED TO PEER (is this a reconnect? test lib needs fixing)")
170187
return nil
171188
}
172189
nc.network.conns[tag] = struct{}{}
190+
nc.network.mu.Unlock()
191+
173192
// TODO: add handling for disconnects
174193

175-
nc.network.clients[p].PeerConnected(nc.local)
194+
otherClient.PeerConnected(nc.local)
176195
nc.Receiver.PeerConnected(p)
177196
return nil
178197
}

0 commit comments

Comments
 (0)