server.go 16.1 KB
Newer Older
Z
zelig 已提交
1 2 3 4
package p2p

import (
	"bytes"
F
Felix Lange 已提交
5
	"crypto/ecdsa"
F
Felix Lange 已提交
6
	"crypto/rand"
7
	"errors"
Z
zelig 已提交
8 9 10 11 12
	"fmt"
	"net"
	"sync"
	"time"

13
	"github.com/ethereum/go-ethereum/logger"
O
obscuren 已提交
14
	"github.com/ethereum/go-ethereum/logger/glog"
F
Felix Lange 已提交
15
	"github.com/ethereum/go-ethereum/p2p/discover"
16
	"github.com/ethereum/go-ethereum/p2p/nat"
17
	"github.com/ethereum/go-ethereum/rlp"
Z
zelig 已提交
18 19 20
)

const (
21 22 23
	defaultDialTimeout      = 10 * time.Second
	refreshPeersInterval    = 30 * time.Second
	staticPeerCheckInterval = 15 * time.Second
F
Felix Lange 已提交
24

25
	// Maximum number of concurrently handshaking inbound connections.
26
	maxAcceptConns = 10
27

28
	// Maximum number of concurrently dialing outbound connections.
29
	maxDialingConns = 10
30

F
Felix Lange 已提交
31 32 33 34 35 36 37 38
	// total timeout for encryption handshake and protocol
	// handshake in both directions.
	handshakeTimeout = 5 * time.Second
	// maximum time allowed for reading a complete message.
	// this is effectively the amount of time a connection can be idle.
	frameReadTimeout = 1 * time.Minute
	// maximum amount of time allowed for writing a complete message.
	frameWriteTimeout = 5 * time.Second
Z
zelig 已提交
39 40
)

41
var srvjslog = logger.NewJsonLogger()
Z
zelig 已提交
42

43 44 45 46 47
// Server manages all peer connections.
//
// The fields of Server are used as configuration parameters.
// You should set them before starting the Server. Fields may not be
// modified while the server is running.
Z
zelig 已提交
48
type Server struct {
F
Felix Lange 已提交
49 50
	// This field must be set to a valid secp256k1 private key.
	PrivateKey *ecdsa.PrivateKey
51 52 53 54 55

	// MaxPeers is the maximum number of peers that can be
	// connected. It must be greater than zero.
	MaxPeers int

56 57 58 59 60
	// MaxPendingPeers is the maximum number of peers that can be pending in the
	// handshake phase, counted separately for inbound and outbound connections.
	// Zero defaults to preset values.
	MaxPendingPeers int

F
Felix Lange 已提交
61
	// Name sets the node name of this server.
O
obscuren 已提交
62
	// Use common.MakeName to create a name that follows existing conventions.
F
Felix Lange 已提交
63 64 65 66
	Name string

	// Bootstrap nodes are used to establish connectivity
	// with the rest of the network.
67
	BootstrapNodes []*discover.Node
F
Felix Lange 已提交
68

69 70 71
	// Static nodes are used as pre-configured connections which are always
	// maintained and re-connected on disconnects.
	StaticNodes []*discover.Node
72

73 74 75 76
	// Trusted nodes are used as pre-configured connections which are always
	// allowed to connect, even above the peer limit.
	TrustedNodes []*discover.Node

77 78 79
	// NodeDatabase is the path to the database containing the previously seen
	// live nodes in the network.
	NodeDatabase string
80

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
	// Protocols should contain the protocols supported
	// by the server. Matching protocols are launched for
	// each peer.
	Protocols []Protocol

	// If ListenAddr is set to a non-nil address, the server
	// will listen for incoming connections.
	//
	// If the port is zero, the operating system will pick a port. The
	// ListenAddr field will be updated with the actual address when
	// the server is started.
	ListenAddr string

	// If set to a non-nil value, the given NAT port mapper
	// is used to make the listening port available to the
	// Internet.
97
	NAT nat.Interface
98 99 100 101 102 103 104 105

	// If Dialer is set to a non-nil value, the given Dialer
	// is used to dial outbound peer connections.
	Dialer *net.Dialer

	// If NoDial is true, the server will not dial any peers.
	NoDial bool

F
Felix Lange 已提交
106
	// Hooks for testing. These are useful because we can inhibit
107
	// the whole protocol stack.
F
Felix Lange 已提交
108
	setupFunc
F
Felix Lange 已提交
109
	newPeerHook
Z
zelig 已提交
110

F
Felix Lange 已提交
111 112
	ourHandshake *protoHandshake

113 114 115 116 117 118 119
	lock         sync.RWMutex // protects running, peers and the trust fields
	running      bool
	peers        map[discover.NodeID]*Peer
	staticNodes  map[discover.NodeID]*discover.Node // Map of currently maintained static remote nodes
	staticDial   chan *discover.Node                // Dial request channel reserved for the static nodes
	staticCycle  time.Duration                      // Overrides staticPeerCheckInterval, used for testing
	trustedNodes map[discover.NodeID]bool           // Set of currently trusted remote nodes
F
Felix Lange 已提交
120

121 122
	ntab     *discover.Table
	listener net.Listener
F
Felix Lange 已提交
123

124 125 126
	quit   chan struct{}
	loopWG sync.WaitGroup // {dial,listen,nat}Loop
	peerWG sync.WaitGroup // active peer goroutines
Z
zelig 已提交
127 128
}

129
type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool, map[discover.NodeID]bool) (*conn, error)
F
Felix Lange 已提交
130
type newPeerHook func(*Peer)
Z
zelig 已提交
131

132 133 134 135 136
// Peers returns all connected peers.
func (srv *Server) Peers() (peers []*Peer) {
	srv.lock.RLock()
	defer srv.lock.RUnlock()
	for _, peer := range srv.peers {
Z
zelig 已提交
137 138 139 140 141 142 143
		if peer != nil {
			peers = append(peers, peer)
		}
	}
	return
}

144 145 146
// PeerCount returns the number of connected peers.
func (srv *Server) PeerCount() int {
	srv.lock.RLock()
F
Felix Lange 已提交
147 148 149
	n := len(srv.peers)
	srv.lock.RUnlock()
	return n
Z
zelig 已提交
150 151
}

152 153 154 155
// AddPeer connects to the given node and maintains the connection until the
// server is shut down. If the connection fails for any reason, the server will
// attempt to reconnect the peer.
func (srv *Server) AddPeer(node *discover.Node) {
156 157 158
	srv.lock.Lock()
	defer srv.lock.Unlock()

159
	srv.staticNodes[node.ID] = node
Z
zelig 已提交
160 161
}

162 163
// Broadcast sends an RLP-encoded message to all connected peers.
// This method is deprecated and will be removed later.
164
func (srv *Server) Broadcast(protocol string, code uint64, data interface{}) error {
165 166 167 168 169 170
	return srv.BroadcastLimited(protocol, code, func(i float64) float64 { return i }, data)
}

// BroadcastsRange an RLP-encoded message to a random set of peers using the limit function to limit the amount
// of peers.
func (srv *Server) BroadcastLimited(protocol string, code uint64, limit func(float64) float64, data interface{}) error {
F
Felix Lange 已提交
171 172
	var payload []byte
	if data != nil {
173 174 175 176 177
		var err error
		payload, err = rlp.EncodeToBytes(data)
		if err != nil {
			return err
		}
F
Felix Lange 已提交
178
	}
179 180
	srv.lock.RLock()
	defer srv.lock.RUnlock()
181 182

	i, max := 0, int(limit(float64(len(srv.peers))))
183
	for _, peer := range srv.peers {
184 185 186 187
		if i >= max {
			break
		}

Z
zelig 已提交
188
		if peer != nil {
F
Felix Lange 已提交
189 190 191 192 193
			var msg = Msg{Code: code}
			if data != nil {
				msg.Payload = bytes.NewReader(payload)
				msg.Size = uint32(len(payload))
			}
194
			peer.writeProtoMsg(protocol, msg)
195
			i++
Z
zelig 已提交
196 197
		}
	}
198
	return nil
Z
zelig 已提交
199 200
}

201 202 203 204 205 206 207 208
// Start starts running the server.
// Servers can be re-used and started again after stopping.
func (srv *Server) Start() (err error) {
	srv.lock.Lock()
	defer srv.lock.Unlock()
	if srv.running {
		return errors.New("server already running")
	}
O
obscuren 已提交
209
	glog.V(logger.Info).Infoln("Starting Server")
210

211
	// static fields
F
Felix Lange 已提交
212 213
	if srv.PrivateKey == nil {
		return fmt.Errorf("Server.PrivateKey must be set to a non-nil key")
Z
zelig 已提交
214
	}
215 216 217 218
	if srv.MaxPeers <= 0 {
		return fmt.Errorf("Server.MaxPeers must be > 0")
	}
	srv.quit = make(chan struct{})
F
Felix Lange 已提交
219
	srv.peers = make(map[discover.NodeID]*Peer)
220

221 222 223 224 225
	// Create the current trust maps, and the associated dialing channel
	srv.trustedNodes = make(map[discover.NodeID]bool)
	for _, node := range srv.TrustedNodes {
		srv.trustedNodes[node.ID] = true
	}
226
	srv.staticNodes = make(map[discover.NodeID]*discover.Node)
227
	for _, node := range srv.StaticNodes {
228
		srv.staticNodes[node.ID] = node
229
	}
230
	srv.staticDial = make(chan *discover.Node)
231

F
Felix Lange 已提交
232 233
	if srv.setupFunc == nil {
		srv.setupFunc = setupConn
234
	}
F
Felix Lange 已提交
235

236
	// node table
237
	ntab, err := discover.ListenUDP(srv.PrivateKey, srv.ListenAddr, srv.NAT, srv.NodeDatabase)
F
Felix Lange 已提交
238 239 240
	if err != nil {
		return err
	}
F
Felix Lange 已提交
241 242
	srv.ntab = ntab

243
	// handshake
244
	srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: ntab.Self().ID}
F
Felix Lange 已提交
245 246 247 248
	for _, p := range srv.Protocols {
		srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
	}

249 250 251 252 253 254
	// listen/dial
	if srv.ListenAddr != "" {
		if err := srv.startListening(); err != nil {
			return err
		}
	}
F
Felix Lange 已提交
255 256 257
	if srv.Dialer == nil {
		srv.Dialer = &net.Dialer{Timeout: defaultDialTimeout}
	}
258
	if !srv.NoDial {
F
Felix Lange 已提交
259
		srv.loopWG.Add(1)
260 261 262
		go srv.dialLoop()
	}
	if srv.NoDial && srv.ListenAddr == "" {
O
obscuren 已提交
263
		glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.")
264
	}
265 266
	// maintain the static peers
	go srv.staticNodesLoop()
267 268 269

	srv.running = true
	return nil
Z
zelig 已提交
270 271
}

272 273 274 275 276
func (srv *Server) startListening() error {
	listener, err := net.Listen("tcp", srv.ListenAddr)
	if err != nil {
		return err
	}
277 278
	laddr := listener.Addr().(*net.TCPAddr)
	srv.ListenAddr = laddr.String()
279
	srv.listener = listener
F
Felix Lange 已提交
280
	srv.loopWG.Add(1)
281
	go srv.listenLoop()
282
	if !laddr.IP.IsLoopback() && srv.NAT != nil {
F
Felix Lange 已提交
283
		srv.loopWG.Add(1)
284 285 286 287
		go func() {
			nat.Map(srv.NAT, srv.quit, "tcp", laddr.Port, laddr.Port, "ethereum p2p")
			srv.loopWG.Done()
		}()
288 289 290 291 292 293 294 295 296 297 298
	}
	return nil
}

// Stop terminates the server and all active peer connections.
// It blocks until all active connections have been closed.
func (srv *Server) Stop() {
	srv.lock.Lock()
	if !srv.running {
		srv.lock.Unlock()
		return
Z
zelig 已提交
299
	}
300 301 302
	srv.running = false
	srv.lock.Unlock()

O
obscuren 已提交
303
	glog.V(logger.Info).Infoln("Stopping Server")
F
Felix Lange 已提交
304
	srv.ntab.Close()
305 306 307 308 309
	if srv.listener != nil {
		// this unblocks listener Accept
		srv.listener.Close()
	}
	close(srv.quit)
F
Felix Lange 已提交
310
	srv.loopWG.Wait()
311

F
Felix Lange 已提交
312 313 314
	// No new peers can be added at this point because dialLoop and
	// listenLoop are down. It is safe to call peerWG.Wait because
	// peerWG.Add is not called outside of those loops.
315
	srv.lock.Lock()
F
Felix Lange 已提交
316 317
	for _, peer := range srv.peers {
		peer.Disconnect(DiscQuitting)
318
	}
319
	srv.lock.Unlock()
F
Felix Lange 已提交
320
	srv.peerWG.Wait()
321
}
Z
zelig 已提交
322

323 324
// Self returns the local node's endpoint information.
func (srv *Server) Self() *discover.Node {
325 326 327 328 329
	srv.lock.RLock()
	defer srv.lock.RUnlock()
	if !srv.running {
		return &discover.Node{IP: net.ParseIP("0.0.0.0")}
	}
330 331 332
	return srv.ntab.Self()
}

333 334
// main loop for adding connections via listening
func (srv *Server) listenLoop() {
F
Felix Lange 已提交
335
	defer srv.loopWG.Done()
336 337 338 339

	// This channel acts as a semaphore limiting
	// active inbound connections that are lingering pre-handshake.
	// If all slots are taken, no further connections are accepted.
340 341 342 343 344 345
	tokens := maxAcceptConns
	if srv.MaxPendingPeers > 0 {
		tokens = srv.MaxPendingPeers
	}
	slots := make(chan struct{}, tokens)
	for i := 0; i < tokens; i++ {
346 347 348
		slots <- struct{}{}
	}

O
obscuren 已提交
349
	glog.V(logger.Info).Infoln("Listening on", srv.listener.Addr())
Z
zelig 已提交
350
	for {
351
		<-slots
F
Felix Lange 已提交
352 353
		conn, err := srv.listener.Accept()
		if err != nil {
354
			return
Z
zelig 已提交
355
		}
O
obscuren 已提交
356
		glog.V(logger.Debug).Infof("Accepted conn %v\n", conn.RemoteAddr())
F
Felix Lange 已提交
357
		srv.peerWG.Add(1)
358 359 360 361
		go func() {
			srv.startPeer(conn, nil)
			slots <- struct{}{}
		}()
Z
zelig 已提交
362 363 364
	}
}

365
// staticNodesLoop is responsible for periodically checking that static
366
// connections are actually live, and requests dialing if not.
367
func (srv *Server) staticNodesLoop() {
368 369 370 371 372 373 374
	// Create a default maintenance ticker, but override it requested
	cycle := staticPeerCheckInterval
	if srv.staticCycle != 0 {
		cycle = srv.staticCycle
	}
	tick := time.NewTicker(cycle)

375 376 377 378 379
	for {
		select {
		case <-srv.quit:
			return

380
		case <-tick.C:
381
			// Collect all the non-connected static nodes
382 383
			needed := []*discover.Node{}
			srv.lock.RLock()
384
			for id, node := range srv.staticNodes {
385 386 387 388 389 390 391 392
				if _, ok := srv.peers[id]; !ok {
					needed = append(needed, node)
				}
			}
			srv.lock.RUnlock()

			// Try to dial each of them (don't hang if server terminates)
			for _, node := range needed {
393
				glog.V(logger.Debug).Infof("Dialing static peer %v", node)
394
				select {
395
				case srv.staticDial <- node:
396 397 398 399 400 401 402 403
				case <-srv.quit:
					return
				}
			}
		}
	}
}

404
func (srv *Server) dialLoop() {
F
Felix Lange 已提交
405 406 407 408 409 410
	var (
		dialed      = make(chan *discover.Node)
		dialing     = make(map[discover.NodeID]bool)
		findresults = make(chan []*discover.Node)
		refresh     = time.NewTimer(0)
	)
F
Felix Lange 已提交
411 412 413
	defer srv.loopWG.Done()
	defer refresh.Stop()

414
	// Limit the number of concurrent dials
415 416 417 418 419 420
	tokens := maxAcceptConns
	if srv.MaxPendingPeers > 0 {
		tokens = srv.MaxPendingPeers
	}
	slots := make(chan struct{}, tokens)
	for i := 0; i < tokens; i++ {
421 422
		slots <- struct{}{}
	}
F
Felix Lange 已提交
423 424 425 426 427
	dial := func(dest *discover.Node) {
		// Don't dial nodes that would fail the checks in addPeer.
		// This is important because the connection handshake is a lot
		// of work and we'd rather avoid doing that work for peers
		// that can't be added.
428 429 430
		srv.lock.RLock()
		ok, _ := srv.checkPeer(dest.ID)
		srv.lock.RUnlock()
F
Felix Lange 已提交
431 432 433
		if !ok || dialing[dest.ID] {
			return
		}
434 435
		// Request a dial slot to prevent CPU exhaustion
		<-slots
436

F
Felix Lange 已提交
437 438 439 440
		dialing[dest.ID] = true
		srv.peerWG.Add(1)
		go func() {
			srv.dialNode(dest)
441
			slots <- struct{}{}
442
			dialed <- dest
F
Felix Lange 已提交
443 444
		}()
	}
F
Felix Lange 已提交
445

F
Felix Lange 已提交
446
	srv.ntab.Bootstrap(srv.BootstrapNodes)
Z
zelig 已提交
447 448
	for {
		select {
F
Felix Lange 已提交
449
		case <-refresh.C:
450 451
			// Grab some nodes to connect to if we're not at capacity.
			srv.lock.RLock()
452
			needpeers := len(srv.peers) < srv.MaxPeers/2
453
			srv.lock.RUnlock()
F
Felix Lange 已提交
454 455 456 457 458 459
			if needpeers {
				go func() {
					var target discover.NodeID
					rand.Read(target[:])
					findresults <- srv.ntab.Lookup(target)
				}()
F
Felix Lange 已提交
460 461 462 463
			} else {
				// Make sure we check again if the peer count falls
				// below MaxPeers.
				refresh.Reset(refreshPeersInterval)
Z
zelig 已提交
464
			}
465
		case dest := <-srv.staticDial:
F
Felix Lange 已提交
466 467 468 469 470 471
			dial(dest)
		case dests := <-findresults:
			for _, dest := range dests {
				dial(dest)
			}
			refresh.Reset(refreshPeersInterval)
F
Felix Lange 已提交
472 473
		case dest := <-dialed:
			delete(dialing, dest.ID)
F
Felix Lange 已提交
474 475 476 477
			if len(dialing) == 0 {
				// Check again immediately after dialing all current candidates.
				refresh.Reset(0)
			}
F
Felix Lange 已提交
478 479
		case <-srv.quit:
			// TODO: maybe wait for active dials
Z
zelig 已提交
480 481 482 483 484
			return
		}
	}
}

F
Felix Lange 已提交
485
func (srv *Server) dialNode(dest *discover.Node) {
F
Felix Lange 已提交
486
	addr := &net.TCPAddr{IP: dest.IP, Port: int(dest.TCP)}
O
obscuren 已提交
487
	glog.V(logger.Debug).Infof("Dialing %v\n", dest)
488
	conn, err := srv.Dialer.Dial("tcp", addr.String())
Z
zelig 已提交
489
	if err != nil {
490 491 492 493
		// dialLoop adds to the wait group counter when launching
		// dialNode, so we need to count it down again. startPeer also
		// does that when an error occurs.
		srv.peerWG.Done()
O
obscuren 已提交
494
		glog.V(logger.Detail).Infof("dial error: %v", err)
F
Felix Lange 已提交
495
		return
Z
zelig 已提交
496
	}
F
Felix Lange 已提交
497
	srv.startPeer(conn, dest)
Z
zelig 已提交
498 499
}

F
Felix Lange 已提交
500
func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
501
	// TODO: handle/store session token
502 503 504 505 506

	// Run setupFunc, which should create an authenticated connection
	// and run the capability exchange. Note that any early error
	// returns during that exchange need to call peerWG.Done because
	// the callers of startPeer added the peer to the wait group already.
F
Felix Lange 已提交
507
	fd.SetDeadline(time.Now().Add(handshakeTimeout))
508

509
	// Check capacity, but override for static nodes
510 511
	srv.lock.RLock()
	atcap := len(srv.peers) == srv.MaxPeers
512
	if dest != nil {
513
		if _, ok := srv.staticNodes[dest.ID]; ok {
514 515
			atcap = false
		}
516
	}
517
	srv.lock.RUnlock()
518

519
	conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap, srv.trustedNodes)
F
Felix Lange 已提交
520
	if err != nil {
F
Felix Lange 已提交
521
		fd.Close()
O
obscuren 已提交
522
		glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err)
523
		srv.peerWG.Done()
F
Felix Lange 已提交
524 525
		return
	}
F
Felix Lange 已提交
526 527 528 529
	conn.MsgReadWriter = &netWrapper{
		wrapped: conn.MsgReadWriter,
		conn:    fd, rtimeout: frameReadTimeout, wtimeout: frameWriteTimeout,
	}
F
Felix Lange 已提交
530
	p := newPeer(fd, conn, srv.Protocols)
F
Felix Lange 已提交
531
	if ok, reason := srv.addPeer(conn.ID, p); !ok {
O
obscuren 已提交
532
		glog.V(logger.Detail).Infof("Not adding %v (%v)\n", p, reason)
533
		p.politeDisconnect(reason)
534
		srv.peerWG.Done()
F
Felix Lange 已提交
535
		return
Z
zelig 已提交
536
	}
F
Felix Lange 已提交
537 538 539 540
	// The handshakes are done and it passed all checks.
	// Spawn the Peer loops.
	go srv.runPeer(p)
}
541

F
Felix Lange 已提交
542
func (srv *Server) runPeer(p *Peer) {
O
obscuren 已提交
543
	glog.V(logger.Debug).Infof("Added %v\n", p)
544
	srvjslog.LogJson(&logger.P2PConnected{
F
Felix Lange 已提交
545 546 547
		RemoteId:            p.ID().String(),
		RemoteAddress:       p.RemoteAddr().String(),
		RemoteVersionString: p.Name(),
548 549
		NumConnections:      srv.PeerCount(),
	})
F
Felix Lange 已提交
550 551 552
	if srv.newPeerHook != nil {
		srv.newPeerHook(p)
	}
553
	discreason := p.run()
F
Felix Lange 已提交
554
	srv.removePeer(p)
O
obscuren 已提交
555
	glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
556
	srvjslog.LogJson(&logger.P2PDisconnected{
F
Felix Lange 已提交
557
		RemoteId:       p.ID().String(),
558 559
		NumConnections: srv.PeerCount(),
	})
Z
zelig 已提交
560 561
}

F
Felix Lange 已提交
562
func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) {
563 564
	srv.lock.Lock()
	defer srv.lock.Unlock()
F
Felix Lange 已提交
565 566 567 568 569 570 571
	if ok, reason := srv.checkPeer(id); !ok {
		return false, reason
	}
	srv.peers[id] = p
	return true, 0
}

572 573
// checkPeer verifies whether a peer looks promising and should be allowed/kept
// in the pool, or if it's of no use.
F
Felix Lange 已提交
574
func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) {
575
	// First up, figure out if the peer is static or trusted
576
	_, static := srv.staticNodes[id]
577
	trusted := srv.trustedNodes[id]
578 579

	// Make sure the peer passes all required checks
F
Felix Lange 已提交
580 581 582
	switch {
	case !srv.running:
		return false, DiscQuitting
583
	case !static && !trusted && len(srv.peers) >= srv.MaxPeers:
F
Felix Lange 已提交
584 585 586
		return false, DiscTooManyPeers
	case srv.peers[id] != nil:
		return false, DiscAlreadyConnected
587
	case id == srv.ntab.Self().ID:
F
Felix Lange 已提交
588
		return false, DiscSelf
F
Felix Lange 已提交
589 590
	default:
		return true, 0
F
Felix Lange 已提交
591
	}
Z
zelig 已提交
592 593
}

F
Felix Lange 已提交
594 595
func (srv *Server) removePeer(p *Peer) {
	srv.lock.Lock()
F
Felix Lange 已提交
596
	delete(srv.peers, p.ID())
F
Felix Lange 已提交
597 598
	srv.lock.Unlock()
	srv.peerWG.Done()
F
Felix Lange 已提交
599
}