diff --git a/p2p/net/mock/mock.go b/p2p/net/mock/mock.go index 8760b4d489..55256f867f 100644 --- a/p2p/net/mock/mock.go +++ b/p2p/net/mock/mock.go @@ -44,14 +44,9 @@ func FullMeshConnected(ctx context.Context, n int) (Mocknet, error) { return nil, err } - nets := m.Nets() - for _, n1 := range nets { - for _, n2 := range nets { - if _, err := m.ConnectNets(n1, n2); err != nil { - return nil, err - } - } + err = m.ConnectAllButSelf() + if err != nil { + return nil, err } - return m, nil } diff --git a/p2p/net/mock/mock_peernet.go b/p2p/net/mock/mock_peernet.go index 3c5710bf91..35c9bbe647 100644 --- a/p2p/net/mock/mock_peernet.go +++ b/p2p/net/mock/mock_peernet.go @@ -118,6 +118,10 @@ func (pn *peernet) DialPeer(ctx context.Context, p peer.ID) (inet.Conn, error) { } func (pn *peernet) connect(p peer.ID) (*conn, error) { + if p == pn.peer { + return nil, fmt.Errorf("attempted to dial self %s", p) + } + // first, check if we already have live connections pn.RLock() cs, found := pn.connsByPeer[p] @@ -326,26 +330,10 @@ func (pn *peernet) Connectedness(p peer.ID) inet.Connectedness { // NewStream returns a new stream to given peer p. // If there is no connection to p, attempts to create one. func (pn *peernet) NewStream(ctx context.Context, p peer.ID) (inet.Stream, error) { - pn.Lock() - cs, found := pn.connsByPeer[p] - if !found || len(cs) < 1 { - pn.Unlock() - return nil, fmt.Errorf("no connection to peer") + c, err := pn.DialPeer(ctx, p) + if err != nil { + return nil, err } - - // if many conns are found, how do we select? for now, randomly... - // this would be an interesting place to test logic that can measure - // links (network interfaces) and select properly - n := rand.Intn(len(cs)) - var c *conn - for c = range cs { - if n == 0 { - break - } - n-- - } - pn.Unlock() - return c.NewStream() } diff --git a/p2p/net/mock/mock_test.go b/p2p/net/mock/mock_test.go index 0f888a7098..d6d3c72680 100644 --- a/p2p/net/mock/mock_test.go +++ b/p2p/net/mock/mock_test.go @@ -225,14 +225,14 @@ func TestNetworkSetup(t *testing.T) { t.Error("should not be able to connect") } - // connect p1->p1 (should work) - if _, err := n1.DialPeer(ctx, p1); err != nil { - t.Error("p1 should be able to dial self.", err) + // connect p1->p1 (should fail) + if _, err := n1.DialPeer(ctx, p1); err == nil { + t.Error("p1 shouldn't be able to dial self") } // and a stream too - if _, err := n1.NewStream(ctx, p1); err != nil { - t.Error(err) + if _, err := n1.NewStream(ctx, p1); err == nil { + t.Error("p1 shouldn't be able to dial self") } // connect p1->p2 @@ -383,8 +383,11 @@ func TestStreamsStress(t *testing.T) { wg.Add(1) go func(i int) { defer wg.Done() - from := rand.Intn(len(hosts)) - to := rand.Intn(len(hosts)) + var from, to int + for from == to { + from = rand.Intn(len(hosts)) + to = rand.Intn(len(hosts)) + } s, err := hosts[from].NewStream(ctx, hosts[to].ID(), protocol.TestingID) if err != nil { log.Debugf("%d (%s) %d (%s)", from, hosts[from], to, hosts[to])