@@ -3,6 +3,7 @@ package bitswap
3
3
import (
4
4
"context"
5
5
"errors"
6
+ "sync"
6
7
7
8
bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
8
9
bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network"
@@ -29,13 +30,17 @@ func VirtualNetwork(rs mockrouting.Server, d delay.D) Network {
29
30
}
30
31
31
32
type network struct {
33
+ mu sync.Mutex
32
34
clients map [peer.ID ]bsnet.Receiver
33
35
routingserver mockrouting.Server
34
36
delay delay.D
35
37
conns map [string ]struct {}
36
38
}
37
39
38
40
func (n * network ) Adapter (p testutil.Identity ) bsnet.BitSwapNetwork {
41
+ n .mu .Lock ()
42
+ defer n .mu .Unlock ()
43
+
39
44
client := & networkClient {
40
45
local : p .ID (),
41
46
network : n ,
@@ -46,6 +51,9 @@ func (n *network) Adapter(p testutil.Identity) bsnet.BitSwapNetwork {
46
51
}
47
52
48
53
func (n * network ) HasPeer (p peer.ID ) bool {
54
+ n .mu .Lock ()
55
+ defer n .mu .Unlock ()
56
+
49
57
_ , found := n .clients [p ]
50
58
return found
51
59
}
@@ -58,6 +66,9 @@ func (n *network) SendMessage(
58
66
to peer.ID ,
59
67
message bsmsg.BitSwapMessage ) error {
60
68
69
+ n .mu .Lock ()
70
+ defer n .mu .Unlock ()
71
+
61
72
receiver , ok := n .clients [to ]
62
73
if ! ok {
63
74
return errors .New ("Cannot locate peer on network" )
@@ -161,18 +172,26 @@ func (nc *networkClient) SetDelegate(r bsnet.Receiver) {
161
172
}
162
173
163
174
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 ()
165
180
return errors .New ("no such peer in network" )
166
181
}
182
+
167
183
tag := tagForPeers (nc .local , p )
168
184
if _ , ok := nc .network .conns [tag ]; ok {
185
+ nc .network .mu .Unlock ()
169
186
log .Warning ("ALREADY CONNECTED TO PEER (is this a reconnect? test lib needs fixing)" )
170
187
return nil
171
188
}
172
189
nc .network .conns [tag ] = struct {}{}
190
+ nc .network .mu .Unlock ()
191
+
173
192
// TODO: add handling for disconnects
174
193
175
- nc . network . clients [ p ] .PeerConnected (nc .local )
194
+ otherClient .PeerConnected (nc .local )
176
195
nc .Receiver .PeerConnected (p )
177
196
return nil
178
197
}
0 commit comments