swarm.go 14.3 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package swarm

import (
4
	"context"
Steven Allen's avatar
Steven Allen committed
5
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"fmt"
7
	"io"
8
	"strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	"sync"
Steven Allen's avatar
Steven Allen committed
10
	"sync/atomic"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12
	"time"

tavit ohanian's avatar
tavit ohanian committed
13 14 15 16 17 18 19
	"gitlab.dms3.io/p2p/go-p2p-core/connmgr"
	"gitlab.dms3.io/p2p/go-p2p-core/metrics"
	"gitlab.dms3.io/p2p/go-p2p-core/network"
	"gitlab.dms3.io/p2p/go-p2p-core/peer"
	"gitlab.dms3.io/p2p/go-p2p-core/peerstore"
	"gitlab.dms3.io/p2p/go-p2p-core/transport"

Jeromy's avatar
Jeromy committed
20 21
	"github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
22
	logging "gitlab.dms3.io/dms3/go-log"
23

24
	ma "gitlab.dms3.io/mf/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26
)

27 28
// DialTimeoutLocal is the maximum duration a Dial to local network address
// is allowed to take.
Steven Allen's avatar
Steven Allen committed
29 30
// This includes the time between dialing the raw network connection,
// protocol selection as well the handshake, if applicable.
31
var DialTimeoutLocal = 5 * time.Second
32

Steven Allen's avatar
Steven Allen committed
33
var log = logging.Logger("swarm2")
34

Steven Allen's avatar
Steven Allen committed
35 36
// ErrSwarmClosed is returned when one attempts to operate on a closed swarm.
var ErrSwarmClosed = errors.New("swarm closed")
37

Steven Allen's avatar
Steven Allen committed
38 39 40 41
// ErrAddrFiltered is returned when trying to register a connection to a
// filtered address. You shouldn't see this error unless some underlying
// transport is misbehaving.
var ErrAddrFiltered = errors.New("address filtered")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42

43 44 45
// ErrDialTimeout is returned when one a dial times out due to the global timeout
var ErrDialTimeout = errors.New("dial timed out")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48 49 50
// Swarm is a connection muxer, allowing connections to other peers to
// be opened and closed, while still using the same Chan for all
// communication. The Chan sends/receives Messages, which note the
// destination or source Peer.
type Swarm struct {
Steven Allen's avatar
Steven Allen committed
51 52 53
	nextConnID   uint64 // guarded by atomic
	nextStreamID uint64 // guarded by atomic

Steven Allen's avatar
Steven Allen committed
54 55 56 57
	// Close refcount. This allows us to fully wait for the swarm to be torn
	// down before continuing.
	refs sync.WaitGroup

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58
	local peer.ID
59
	peers peerstore.Peerstore
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60

Steven Allen's avatar
Steven Allen committed
61 62 63 64
	conns struct {
		sync.RWMutex
		m map[peer.ID][]*Conn
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65

Steven Allen's avatar
Steven Allen committed
66 67
	listeners struct {
		sync.RWMutex
68

69 70
		ifaceListenAddres []ma.Multiaddr
		cacheEOL          time.Time
71

Steven Allen's avatar
Steven Allen committed
72 73
		m map[transport.Listener]struct{}
	}
Jeromy's avatar
Jeromy committed
74

Steven Allen's avatar
Steven Allen committed
75 76
	notifs struct {
		sync.RWMutex
77
		m map[network.Notifiee]struct{}
Steven Allen's avatar
Steven Allen committed
78
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79

Steven Allen's avatar
Steven Allen committed
80 81 82 83
	transports struct {
		sync.RWMutex
		m map[int]transport.Transport
	}
Jeromy's avatar
Jeromy committed
84

Steven Allen's avatar
Steven Allen committed
85 86 87
	// new connection and stream handlers
	connh   atomic.Value
	streamh atomic.Value
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88

Steven Allen's avatar
Steven Allen committed
89 90 91 92
	// dialing helpers
	dsync   *DialSync
	backf   DialBackoff
	limiter *dialLimiter
93
	gater   connmgr.ConnectionGater
Jeromy's avatar
Jeromy committed
94

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95 96 97
	proc goprocess.Process
	ctx  context.Context
	bwc  metrics.Reporter
98 99
}

100 101
// NewSwarm constructs a Swarm.
//
tavit ohanian's avatar
tavit ohanian committed
102
// NOTE: go-p2p will be moving to dependency injection soon. The variadic
103 104 105 106
// `extra` interface{} parameter facilitates the future migration. Supported
// elements are:
//  - connmgr.ConnectionGater
func NewSwarm(ctx context.Context, local peer.ID, peers peerstore.Peerstore, bwc metrics.Reporter, extra ...interface{}) *Swarm {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107
	s := &Swarm{
108 109 110
		local: local,
		peers: peers,
		bwc:   bwc,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111
	}
Steven Allen's avatar
Steven Allen committed
112 113 114 115

	s.conns.m = make(map[peer.ID][]*Conn)
	s.listeners.m = make(map[transport.Listener]struct{})
	s.transports.m = make(map[int]transport.Transport)
116
	s.notifs.m = make(map[network.Notifiee]struct{})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117

118 119 120 121 122 123 124
	for _, i := range extra {
		switch v := i.(type) {
		case connmgr.ConnectionGater:
			s.gater = v
		}
	}

vyzo's avatar
vyzo committed
125
	s.dsync = newDialSync(s.startDialWorker)
126
	s.limiter = newDialLimiter(s.dialAddr, isFdConsumingAddr)
127
	s.proc = goprocessctx.WithContext(ctx)
Steven Allen's avatar
Steven Allen committed
128
	s.ctx = goprocessctx.OnClosingContext(s.proc)
Will Scott's avatar
Will Scott committed
129
	s.backf.init(s.ctx)
Jeromy's avatar
Jeromy committed
130

131 132 133 134
	// Set teardown after setting the context/process so we don't start the
	// teardown process early.
	s.proc.SetTeardown(s.teardown)

Steven Allen's avatar
Steven Allen committed
135
	return s
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137
}

Steven Allen's avatar
Steven Allen committed
138
func (s *Swarm) teardown() error {
139 140 141 142 143
	// Wait for the context to be canceled.
	// This allows other parts of the swarm to detect that we're shutting
	// down.
	<-s.ctx.Done()

Steven Allen's avatar
Steven Allen committed
144 145 146 147 148 149 150 151 152 153 154 155
	// Prevents new connections and/or listeners from being added to the swarm.

	s.listeners.Lock()
	listeners := s.listeners.m
	s.listeners.m = nil
	s.listeners.Unlock()

	s.conns.Lock()
	conns := s.conns.m
	s.conns.m = nil
	s.conns.Unlock()

Matt Joiner's avatar
Matt Joiner committed
156 157
	// Lots of goroutines but we might as well do this in parallel. We want to shut down as fast as
	// possible.
Steven Allen's avatar
Steven Allen committed
158 159 160 161 162 163 164

	for l := range listeners {
		go func(l transport.Listener) {
			if err := l.Close(); err != nil {
				log.Errorf("error when shutting down listener: %s", err)
			}
		}(l)
165 166
	}

Steven Allen's avatar
Steven Allen committed
167 168 169 170 171 172 173 174 175
	for _, cs := range conns {
		for _, c := range cs {
			go func(c *Conn) {
				if err := c.Close(); err != nil {
					log.Errorf("error when shutting down connection: %s", err)
				}
			}(c)
		}
	}
176

Steven Allen's avatar
Steven Allen committed
177 178
	// Wait for everything to finish.
	s.refs.Wait()
179

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
	// Now close out any transports (if necessary). Do this after closing
	// all connections/listeners.
	s.transports.Lock()
	transports := s.transports.m
	s.transports.m = nil
	s.transports.Unlock()

	var wg sync.WaitGroup
	for _, t := range transports {
		if closer, ok := t.(io.Closer); ok {
			wg.Add(1)
			go func(c io.Closer) {
				defer wg.Done()
				if err := closer.Close(); err != nil {
					log.Errorf("error when closing down transport %T: %s", c, err)
				}
			}(closer)
		}
	}
	wg.Wait()

Steven Allen's avatar
Steven Allen committed
201
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203
}

Steven Allen's avatar
Steven Allen committed
204 205 206 207 208
// Process returns the Process of the swarm
func (s *Swarm) Process() goprocess.Process {
	return s.proc
}

209
func (s *Swarm) addConn(tc transport.CapableConn, dir network.Direction) (*Conn, error) {
210 211 212 213 214
	var (
		p    = tc.RemotePeer()
		addr = tc.RemoteMultiaddr()
	)

215 216
	// create the Stat object, initializing with the underlying connection Stat if available
	var stat network.Stat
vyzo's avatar
vyzo committed
217
	if cs, ok := tc.(network.ConnStat); ok {
218 219 220 221 222
		stat = cs.Stat()
	}
	stat.Direction = dir
	stat.Opened = time.Now()

223
	// Wrap and register the connection.
224 225 226 227
	c := &Conn{
		conn:  tc,
		swarm: s,
		stat:  stat,
Steven Allen's avatar
Steven Allen committed
228
		id:    atomic.AddUint64(&s.nextConnID, 1),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
229
	}
Jeromy's avatar
Jeromy committed
230

231 232 233 234 235 236 237 238 239 240 241 242
	// we ONLY check upgraded connections here so we can send them a Disconnect message.
	// If we do this in the Upgrader, we will not be able to do this.
	if s.gater != nil {
		if allow, _ := s.gater.InterceptUpgraded(c); !allow {
			// TODO Send disconnect with reason here
			err := tc.Close()
			if err != nil {
				log.Warnf("failed to close connection with peer %s and addr %s; err: %s", p.Pretty(), addr, err)
			}
			return nil, ErrGaterDisallowedConnection
		}
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243

Steven Allen's avatar
Steven Allen committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
	// Add the public key.
	if pk := tc.RemotePublicKey(); pk != nil {
		s.peers.AddPubKey(p, pk)
	}

	// Clear any backoffs
	s.backf.Clear(p)

	// Finally, add the peer.
	s.conns.Lock()
	// Check if we're still online
	if s.conns.m == nil {
		s.conns.Unlock()
		tc.Close()
		return nil, ErrSwarmClosed
	}

	c.streams.m = make(map[*Stream]struct{})
	s.conns.m[p] = append(s.conns.m[p], c)

	// Add two swarm refs:
	// * One will be decremented after the close notifications fire in Conn.doClose
	// * The other will be decremented when Conn.start exits.
	s.refs.Add(2)

269 270 271
	// Take the notification lock before releasing the conns lock to block
	// Disconnect notifications until after the Connect notifications done.
	c.notifyLk.Lock()
Steven Allen's avatar
Steven Allen committed
272 273
	s.conns.Unlock()

274
	s.notifyAll(func(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
275 276
		f.Connected(s, c)
	})
277
	c.notifyLk.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278

Steven Allen's avatar
Steven Allen committed
279 280 281 282 283 284 285 286 287 288
	c.start()

	// TODO: Get rid of this. We use it for identify but that happen much
	// earlier (really, inside the transport and, if not then, during the
	// notifications).
	if h := s.ConnHandler(); h != nil {
		go h(c)
	}

	return c, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
289 290
}

Steven Allen's avatar
Steven Allen committed
291
// Peerstore returns this swarms internal Peerstore.
292
func (s *Swarm) Peerstore() peerstore.Peerstore {
Steven Allen's avatar
Steven Allen committed
293
	return s.peers
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294 295 296 297 298 299 300 301 302 303 304 305
}

// Context returns the context of the swarm
func (s *Swarm) Context() context.Context {
	return s.ctx
}

// Close stops the Swarm.
func (s *Swarm) Close() error {
	return s.proc.Close()
}

Steven Allen's avatar
Steven Allen committed
306
// TODO: We probably don't need the conn handlers.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
307 308

// SetConnHandler assigns the handler for new connections.
Steven Allen's avatar
Steven Allen committed
309
// You will rarely use this. See SetStreamHandler
310
func (s *Swarm) SetConnHandler(handler network.ConnHandler) {
Steven Allen's avatar
Steven Allen committed
311 312
	s.connh.Store(handler)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
313

Steven Allen's avatar
Steven Allen committed
314
// ConnHandler gets the handler for new connections.
315 316
func (s *Swarm) ConnHandler() network.ConnHandler {
	handler, _ := s.connh.Load().(network.ConnHandler)
Steven Allen's avatar
Steven Allen committed
317
	return handler
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
318 319 320
}

// SetStreamHandler assigns the handler for new streams.
321
func (s *Swarm) SetStreamHandler(handler network.StreamHandler) {
Steven Allen's avatar
Steven Allen committed
322 323 324 325
	s.streamh.Store(handler)
}

// StreamHandler gets the handler for new streams.
326 327
func (s *Swarm) StreamHandler() network.StreamHandler {
	handler, _ := s.streamh.Load().(network.StreamHandler)
Steven Allen's avatar
Steven Allen committed
328 329 330 331 332
	return handler
}

// NewStream creates a new stream on any available connection to peer, dialing
// if necessary.
333
func (s *Swarm) NewStream(ctx context.Context, p peer.ID) (network.Stream, error) {
Steven Allen's avatar
Steven Allen committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
	log.Debugf("[%s] opening stream to peer [%s]", s.local, p)

	// Algorithm:
	// 1. Find the best connection, otherwise, dial.
	// 2. Try opening a stream.
	// 3. If the underlying connection is, in fact, closed, close the outer
	//    connection and try again. We do this in case we have a closed
	//    connection but don't notice it until we actually try to open a
	//    stream.
	//
	// Note: We only dial once.
	//
	// TODO: Try all connections even if we get an error opening a stream on
	// a non-closed connection.
	dials := 0
	for {
Aarsh Shah's avatar
Aarsh Shah committed
350
		// will prefer direct connections over relayed connections for opening streams
Steven Allen's avatar
Steven Allen committed
351 352
		c := s.bestConnToPeer(p)
		if c == nil {
353 354
			if nodial, _ := network.GetNoDial(ctx); nodial {
				return nil, network.ErrNoConn
355 356
			}

Steven Allen's avatar
Steven Allen committed
357 358 359 360 361 362 363 364 365 366 367
			if dials >= DialAttempts {
				return nil, errors.New("max dial attempts exceeded")
			}
			dials++

			var err error
			c, err = s.dialPeer(ctx, p)
			if err != nil {
				return nil, err
			}
		}
368

369
		s, err := c.NewStream(ctx)
Steven Allen's avatar
Steven Allen committed
370 371 372 373
		if err != nil {
			if c.conn.IsClosed() {
				continue
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
374 375
			return nil, err
		}
Steven Allen's avatar
Steven Allen committed
376
		return s, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
377 378 379
	}
}

Steven Allen's avatar
Steven Allen committed
380
// ConnsToPeer returns all the live connections to peer.
381
func (s *Swarm) ConnsToPeer(p peer.ID) []network.Conn {
Steven Allen's avatar
Steven Allen committed
382 383 384 385 386
	// TODO: Consider sorting the connection list best to worst. Currently,
	// it's sorted oldest to newest.
	s.conns.RLock()
	defer s.conns.RUnlock()
	conns := s.conns.m[p]
387
	output := make([]network.Conn, len(conns))
Steven Allen's avatar
Steven Allen committed
388 389 390 391 392 393
	for i, c := range conns {
		output[i] = c
	}
	return output
}

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
func isBetterConn(a, b *Conn) bool {
	// If one is transient and not the other, prefer the non-transient connection.
	aTransient := a.Stat().Transient
	bTransient := b.Stat().Transient
	if aTransient != bTransient {
		return !aTransient
	}

	// If one is direct and not the other, prefer the direct connection.
	aDirect := isDirectConn(a)
	bDirect := isDirectConn(b)
	if aDirect != bDirect {
		return aDirect
	}

	// Otherwise, prefer the connection with more open streams.
	a.streams.Lock()
	aLen := len(a.streams.m)
	a.streams.Unlock()

	b.streams.Lock()
	bLen := len(b.streams.m)
	b.streams.Unlock()

	if aLen != bLen {
		return aLen > bLen
	}

	// finally, pick the last connection.
	return true
}

Steven Allen's avatar
Steven Allen committed
426 427
// bestConnToPeer returns the best connection to peer.
func (s *Swarm) bestConnToPeer(p peer.ID) *Conn {
Aarsh Shah's avatar
Aarsh Shah committed
428 429 430 431

	// TODO: Prefer some transports over others.
	// For now, prefers direct connections over Relayed connections.
	// For tie-breaking, select the newest non-closed connection with the most streams.
Steven Allen's avatar
Steven Allen committed
432 433 434 435 436 437 438 439 440
	s.conns.RLock()
	defer s.conns.RUnlock()

	var best *Conn
	for _, c := range s.conns.m[p] {
		if c.conn.IsClosed() {
			// We *will* garbage collect this soon anyways.
			continue
		}
441
		if best == nil || isBetterConn(c, best) {
Steven Allen's avatar
Steven Allen committed
442 443 444 445
			best = c
		}
	}
	return best
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
446 447
}

Steven Allen's avatar
Steven Allen committed
448 449 450 451 452 453 454 455 456 457 458
func (s *Swarm) bestAcceptableConnToPeer(ctx context.Context, p peer.ID) *Conn {
	conn := s.bestConnToPeer(p)
	if conn != nil {
		forceDirect, _ := network.GetForceDirectDial(ctx)
		if !forceDirect || isDirectConn(conn) {
			return conn
		}
	}
	return nil
}

Aarsh Shah's avatar
Aarsh Shah committed
459 460 461 462
func isDirectConn(c *Conn) bool {
	return c != nil && !c.conn.Transport().Proxy()
}

Steven Allen's avatar
Steven Allen committed
463 464 465
// Connectedness returns our "connectedness" state with the given peer.
//
// To check if we have an open connection, use `s.Connectedness(p) ==
466 467
// network.Connected`.
func (s *Swarm) Connectedness(p peer.ID) network.Connectedness {
Steven Allen's avatar
Steven Allen committed
468
	if s.bestConnToPeer(p) != nil {
469
		return network.Connected
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
470
	}
471
	return network.NotConnected
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
472 473
}

Steven Allen's avatar
Steven Allen committed
474
// Conns returns a slice of all connections.
475
func (s *Swarm) Conns() []network.Conn {
Steven Allen's avatar
Steven Allen committed
476 477
	s.conns.RLock()
	defer s.conns.RUnlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
478

479
	conns := make([]network.Conn, 0, len(s.conns.m))
Steven Allen's avatar
Steven Allen committed
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
	for _, cs := range s.conns.m {
		for _, c := range cs {
			conns = append(conns, c)
		}
	}
	return conns
}

// ClosePeer closes all connections to the given peer.
func (s *Swarm) ClosePeer(p peer.ID) error {
	conns := s.ConnsToPeer(p)
	switch len(conns) {
	case 0:
		return nil
	case 1:
		return conns[0].Close()
	default:
		errCh := make(chan error)
		for _, c := range conns {
499
			go func(c network.Conn) {
Steven Allen's avatar
Steven Allen committed
500 501
				errCh <- c.Close()
			}(c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
502 503
		}

Steven Allen's avatar
Steven Allen committed
504
		var errs []string
Cory Schwartz's avatar
Cory Schwartz committed
505
		for range conns {
Steven Allen's avatar
Steven Allen committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
			err := <-errCh
			if err != nil {
				errs = append(errs, err.Error())
			}
		}
		if len(errs) > 0 {
			return fmt.Errorf("when disconnecting from peer %s: %s", p, strings.Join(errs, ", "))
		}
		return nil
	}
}

// Peers returns a copy of the set of peers swarm is connected to.
func (s *Swarm) Peers() []peer.ID {
	s.conns.RLock()
	defer s.conns.RUnlock()
	peers := make([]peer.ID, 0, len(s.conns.m))
	for p := range s.conns.m {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
524 525
		peers = append(peers, p)
	}
Steven Allen's avatar
Steven Allen committed
526

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
527 528 529 530 531 532 533 534
	return peers
}

// LocalPeer returns the local peer swarm is associated to.
func (s *Swarm) LocalPeer() peer.ID {
	return s.local
}

Steven Allen's avatar
Steven Allen committed
535 536
// Backoff returns the DialBackoff object for this swarm.
func (s *Swarm) Backoff() *DialBackoff {
Jeromy's avatar
Jeromy committed
537 538 539
	return &s.backf
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
540
// notifyAll sends a signal to all Notifiees
541
func (s *Swarm) notifyAll(notify func(network.Notifiee)) {
542 543
	var wg sync.WaitGroup

Steven Allen's avatar
Steven Allen committed
544
	s.notifs.RLock()
545
	wg.Add(len(s.notifs.m))
Steven Allen's avatar
Steven Allen committed
546
	for f := range s.notifs.m {
547
		go func(f network.Notifiee) {
548 549 550
			defer wg.Done()
			notify(f)
		}(f)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
551
	}
552 553

	wg.Wait()
Steven Allen's avatar
Steven Allen committed
554
	s.notifs.RUnlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
555 556 557
}

// Notify signs up Notifiee to receive signals when events happen
558
func (s *Swarm) Notify(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
559 560 561
	s.notifs.Lock()
	s.notifs.m[f] = struct{}{}
	s.notifs.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
562 563 564
}

// StopNotify unregisters Notifiee fromr receiving signals
565
func (s *Swarm) StopNotify(f network.Notifiee) {
Steven Allen's avatar
Steven Allen committed
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	s.notifs.Lock()
	delete(s.notifs.m, f)
	s.notifs.Unlock()
}

func (s *Swarm) removeConn(c *Conn) {
	p := c.RemotePeer()

	s.conns.Lock()
	defer s.conns.Unlock()
	cs := s.conns.m[p]
	for i, ci := range cs {
		if ci == c {
			if len(cs) == 1 {
				delete(s.conns.m, p)
			} else {
				// NOTE: We're intentionally preserving order.
				// This way, connections to a peer are always
				// sorted oldest to newest.
				copy(cs[i:], cs[i+1:])
				cs[len(cs)-1] = nil
				s.conns.m[p] = cs[:len(cs)-1]
			}
			return
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
591 592 593
	}
}

Steven Allen's avatar
Steven Allen committed
594 595 596
// String returns a string representation of Network.
func (s *Swarm) String() string {
	return fmt.Sprintf("<Swarm %s>", s.LocalPeer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
597 598
}

Steven Allen's avatar
Steven Allen committed
599
// Swarm is a Network.
600 601
var _ network.Network = (*Swarm)(nil)
var _ transport.TransportNetwork = (*Swarm)(nil)