server.go 15.0 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 26 27 28 29
	// This is the maximum number of inbound connection
	// that are allowed to linger between 'accepted' and
	// 'added as peer'.
	maxAcceptConns = 50

F
Felix Lange 已提交
30 31 32 33 34 35 36 37
	// 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 已提交
38 39
)

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

42 43 44 45 46
// 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 已提交
47
type Server struct {
F
Felix Lange 已提交
48 49
	// This field must be set to a valid secp256k1 private key.
	PrivateKey *ecdsa.PrivateKey
50 51 52 53 54

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

F
Felix Lange 已提交
55
	// Name sets the node name of this server.
O
obscuren 已提交
56
	// Use common.MakeName to create a name that follows existing conventions.
F
Felix Lange 已提交
57 58 59 60
	Name string

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

63 64 65
	// Static nodes are used as pre-configured connections which are always
	// maintained and re-connected on disconnects.
	StaticNodes []*discover.Node
66

67 68 69
	// NodeDatabase is the path to the database containing the previously seen
	// live nodes in the network.
	NodeDatabase string
70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
	// 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.
87
	NAT nat.Interface
88 89 90 91 92 93 94 95

	// 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 已提交
96
	// Hooks for testing. These are useful because we can inhibit
97
	// the whole protocol stack.
F
Felix Lange 已提交
98
	setupFunc
F
Felix Lange 已提交
99
	newPeerHook
Z
zelig 已提交
100

F
Felix Lange 已提交
101 102
	ourHandshake *protoHandshake

103 104 105 106 107 108
	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
109

110 111
	ntab     *discover.Table
	listener net.Listener
F
Felix Lange 已提交
112

113 114 115
	quit   chan struct{}
	loopWG sync.WaitGroup // {dial,listen,nat}Loop
	peerWG sync.WaitGroup // active peer goroutines
Z
zelig 已提交
116 117
}

118
type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool) (*conn, error)
F
Felix Lange 已提交
119
type newPeerHook func(*Peer)
Z
zelig 已提交
120

121 122 123 124 125
// 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 已提交
126 127 128 129 130 131 132
		if peer != nil {
			peers = append(peers, peer)
		}
	}
	return
}

133 134 135
// PeerCount returns the number of connected peers.
func (srv *Server) PeerCount() int {
	srv.lock.RLock()
F
Felix Lange 已提交
136 137 138
	n := len(srv.peers)
	srv.lock.RUnlock()
	return n
Z
zelig 已提交
139 140
}

141 142 143 144
// 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) {
145 146 147
	srv.lock.Lock()
	defer srv.lock.Unlock()

148
	srv.staticNodes[node.ID] = node
Z
zelig 已提交
149 150
}

151 152
// Broadcast sends an RLP-encoded message to all connected peers.
// This method is deprecated and will be removed later.
153
func (srv *Server) Broadcast(protocol string, code uint64, data interface{}) error {
154 155 156 157 158 159
	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 已提交
160 161
	var payload []byte
	if data != nil {
162 163 164 165 166
		var err error
		payload, err = rlp.EncodeToBytes(data)
		if err != nil {
			return err
		}
F
Felix Lange 已提交
167
	}
168 169
	srv.lock.RLock()
	defer srv.lock.RUnlock()
170 171

	i, max := 0, int(limit(float64(len(srv.peers))))
172
	for _, peer := range srv.peers {
173 174 175 176
		if i >= max {
			break
		}

Z
zelig 已提交
177
		if peer != nil {
F
Felix Lange 已提交
178 179 180 181 182
			var msg = Msg{Code: code}
			if data != nil {
				msg.Payload = bytes.NewReader(payload)
				msg.Size = uint32(len(payload))
			}
183
			peer.writeProtoMsg(protocol, msg)
184
			i++
Z
zelig 已提交
185 186
		}
	}
187
	return nil
Z
zelig 已提交
188 189
}

190 191 192 193 194 195 196 197
// 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 已提交
198
	glog.V(logger.Info).Infoln("Starting Server")
199

200
	// static fields
F
Felix Lange 已提交
201 202
	if srv.PrivateKey == nil {
		return fmt.Errorf("Server.PrivateKey must be set to a non-nil key")
Z
zelig 已提交
203
	}
204 205 206 207
	if srv.MaxPeers <= 0 {
		return fmt.Errorf("Server.MaxPeers must be > 0")
	}
	srv.quit = make(chan struct{})
F
Felix Lange 已提交
208
	srv.peers = make(map[discover.NodeID]*Peer)
209 210

	// Create the current trust map, and the associated dialing channel
211
	srv.staticNodes = make(map[discover.NodeID]*discover.Node)
212
	for _, node := range srv.StaticNodes {
213
		srv.staticNodes[node.ID] = node
214
	}
215
	srv.staticDial = make(chan *discover.Node)
216

F
Felix Lange 已提交
217 218
	if srv.setupFunc == nil {
		srv.setupFunc = setupConn
219
	}
F
Felix Lange 已提交
220

221
	// node table
222
	ntab, err := discover.ListenUDP(srv.PrivateKey, srv.ListenAddr, srv.NAT, srv.NodeDatabase)
F
Felix Lange 已提交
223 224 225
	if err != nil {
		return err
	}
F
Felix Lange 已提交
226 227
	srv.ntab = ntab

228
	// handshake
229
	srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: ntab.Self().ID}
F
Felix Lange 已提交
230 231 232 233
	for _, p := range srv.Protocols {
		srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
	}

234 235 236 237 238 239
	// listen/dial
	if srv.ListenAddr != "" {
		if err := srv.startListening(); err != nil {
			return err
		}
	}
F
Felix Lange 已提交
240 241 242
	if srv.Dialer == nil {
		srv.Dialer = &net.Dialer{Timeout: defaultDialTimeout}
	}
243
	if !srv.NoDial {
F
Felix Lange 已提交
244
		srv.loopWG.Add(1)
245 246 247
		go srv.dialLoop()
	}
	if srv.NoDial && srv.ListenAddr == "" {
O
obscuren 已提交
248
		glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.")
249
	}
250 251
	// maintain the static peers
	go srv.staticNodesLoop()
252 253 254

	srv.running = true
	return nil
Z
zelig 已提交
255 256
}

257 258 259 260 261
func (srv *Server) startListening() error {
	listener, err := net.Listen("tcp", srv.ListenAddr)
	if err != nil {
		return err
	}
262 263
	laddr := listener.Addr().(*net.TCPAddr)
	srv.ListenAddr = laddr.String()
264
	srv.listener = listener
F
Felix Lange 已提交
265
	srv.loopWG.Add(1)
266
	go srv.listenLoop()
267
	if !laddr.IP.IsLoopback() && srv.NAT != nil {
F
Felix Lange 已提交
268
		srv.loopWG.Add(1)
269 270 271 272
		go func() {
			nat.Map(srv.NAT, srv.quit, "tcp", laddr.Port, laddr.Port, "ethereum p2p")
			srv.loopWG.Done()
		}()
273 274 275 276 277 278 279 280 281 282 283
	}
	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 已提交
284
	}
285 286 287
	srv.running = false
	srv.lock.Unlock()

O
obscuren 已提交
288
	glog.V(logger.Info).Infoln("Stopping Server")
F
Felix Lange 已提交
289
	srv.ntab.Close()
290 291 292 293 294
	if srv.listener != nil {
		// this unblocks listener Accept
		srv.listener.Close()
	}
	close(srv.quit)
F
Felix Lange 已提交
295
	srv.loopWG.Wait()
296

F
Felix Lange 已提交
297 298 299
	// 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.
300
	srv.lock.Lock()
F
Felix Lange 已提交
301 302
	for _, peer := range srv.peers {
		peer.Disconnect(DiscQuitting)
303
	}
304
	srv.lock.Unlock()
F
Felix Lange 已提交
305
	srv.peerWG.Wait()
306
}
Z
zelig 已提交
307

308 309
// Self returns the local node's endpoint information.
func (srv *Server) Self() *discover.Node {
310 311 312 313 314
	srv.lock.RLock()
	defer srv.lock.RUnlock()
	if !srv.running {
		return &discover.Node{IP: net.ParseIP("0.0.0.0")}
	}
315 316 317
	return srv.ntab.Self()
}

318 319
// main loop for adding connections via listening
func (srv *Server) listenLoop() {
F
Felix Lange 已提交
320
	defer srv.loopWG.Done()
321 322 323 324 325 326 327 328 329

	// 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.
	slots := make(chan struct{}, maxAcceptConns)
	for i := 0; i < maxAcceptConns; i++ {
		slots <- struct{}{}
	}

O
obscuren 已提交
330
	glog.V(logger.Info).Infoln("Listening on", srv.listener.Addr())
Z
zelig 已提交
331
	for {
332
		<-slots
F
Felix Lange 已提交
333 334
		conn, err := srv.listener.Accept()
		if err != nil {
335
			return
Z
zelig 已提交
336
		}
O
obscuren 已提交
337
		glog.V(logger.Debug).Infof("Accepted conn %v\n", conn.RemoteAddr())
F
Felix Lange 已提交
338
		srv.peerWG.Add(1)
339 340 341 342
		go func() {
			srv.startPeer(conn, nil)
			slots <- struct{}{}
		}()
Z
zelig 已提交
343 344 345
	}
}

346
// staticNodesLoop is responsible for periodically checking that static
347
// connections are actually live, and requests dialing if not.
348
func (srv *Server) staticNodesLoop() {
349 350 351 352 353 354 355
	// Create a default maintenance ticker, but override it requested
	cycle := staticPeerCheckInterval
	if srv.staticCycle != 0 {
		cycle = srv.staticCycle
	}
	tick := time.NewTicker(cycle)

356 357 358 359 360
	for {
		select {
		case <-srv.quit:
			return

361
		case <-tick.C:
362
			// Collect all the non-connected static nodes
363 364
			needed := []*discover.Node{}
			srv.lock.RLock()
365
			for id, node := range srv.staticNodes {
366 367 368 369 370 371 372 373
				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 {
374
				glog.V(logger.Debug).Infof("Dialing static peer %v", node)
375
				select {
376
				case srv.staticDial <- node:
377 378 379 380 381 382 383 384
				case <-srv.quit:
					return
				}
			}
		}
	}
}

385
func (srv *Server) dialLoop() {
F
Felix Lange 已提交
386 387 388 389 390 391
	var (
		dialed      = make(chan *discover.Node)
		dialing     = make(map[discover.NodeID]bool)
		findresults = make(chan []*discover.Node)
		refresh     = time.NewTimer(0)
	)
F
Felix Lange 已提交
392 393 394
	defer srv.loopWG.Done()
	defer refresh.Stop()

F
Felix Lange 已提交
395 396 397 398 399 400
	// TODO: maybe limit number of active dials
	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.
401 402 403
		srv.lock.RLock()
		ok, _ := srv.checkPeer(dest.ID)
		srv.lock.RUnlock()
F
Felix Lange 已提交
404 405 406
		if !ok || dialing[dest.ID] {
			return
		}
407

F
Felix Lange 已提交
408 409 410 411 412 413 414
		dialing[dest.ID] = true
		srv.peerWG.Add(1)
		go func() {
			srv.dialNode(dest)
			dialed <- dest
		}()
	}
F
Felix Lange 已提交
415

F
Felix Lange 已提交
416
	srv.ntab.Bootstrap(srv.BootstrapNodes)
Z
zelig 已提交
417 418
	for {
		select {
F
Felix Lange 已提交
419
		case <-refresh.C:
420 421
			// Grab some nodes to connect to if we're not at capacity.
			srv.lock.RLock()
F
Felix Lange 已提交
422
			needpeers := len(srv.peers) < srv.MaxPeers
423
			srv.lock.RUnlock()
F
Felix Lange 已提交
424 425 426 427 428 429
			if needpeers {
				go func() {
					var target discover.NodeID
					rand.Read(target[:])
					findresults <- srv.ntab.Lookup(target)
				}()
F
Felix Lange 已提交
430 431 432 433
			} else {
				// Make sure we check again if the peer count falls
				// below MaxPeers.
				refresh.Reset(refreshPeersInterval)
Z
zelig 已提交
434
			}
435
		case dest := <-srv.staticDial:
F
Felix Lange 已提交
436 437 438 439 440 441
			dial(dest)
		case dests := <-findresults:
			for _, dest := range dests {
				dial(dest)
			}
			refresh.Reset(refreshPeersInterval)
F
Felix Lange 已提交
442 443
		case dest := <-dialed:
			delete(dialing, dest.ID)
F
Felix Lange 已提交
444 445 446 447
			if len(dialing) == 0 {
				// Check again immediately after dialing all current candidates.
				refresh.Reset(0)
			}
F
Felix Lange 已提交
448 449
		case <-srv.quit:
			// TODO: maybe wait for active dials
Z
zelig 已提交
450 451 452 453 454
			return
		}
	}
}

F
Felix Lange 已提交
455
func (srv *Server) dialNode(dest *discover.Node) {
456
	addr := &net.TCPAddr{IP: dest.IP, Port: dest.TCPPort}
O
obscuren 已提交
457
	glog.V(logger.Debug).Infof("Dialing %v\n", dest)
458
	conn, err := srv.Dialer.Dial("tcp", addr.String())
Z
zelig 已提交
459
	if err != nil {
460 461 462 463
		// 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 已提交
464
		glog.V(logger.Detail).Infof("dial error: %v", err)
F
Felix Lange 已提交
465
		return
Z
zelig 已提交
466
	}
F
Felix Lange 已提交
467
	srv.startPeer(conn, dest)
Z
zelig 已提交
468 469
}

F
Felix Lange 已提交
470
func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
471
	// TODO: handle/store session token
472 473 474 475 476

	// 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 已提交
477
	fd.SetDeadline(time.Now().Add(handshakeTimeout))
478

479
	// Check capacity, but override for static nodes
480 481
	srv.lock.RLock()
	atcap := len(srv.peers) == srv.MaxPeers
482
	if dest != nil {
483
		if _, ok := srv.staticNodes[dest.ID]; ok {
484 485
			atcap = false
		}
486
	}
487
	srv.lock.RUnlock()
488

489
	conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap)
F
Felix Lange 已提交
490
	if err != nil {
F
Felix Lange 已提交
491
		fd.Close()
O
obscuren 已提交
492
		glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err)
493
		srv.peerWG.Done()
F
Felix Lange 已提交
494 495
		return
	}
F
Felix Lange 已提交
496 497 498 499
	conn.MsgReadWriter = &netWrapper{
		wrapped: conn.MsgReadWriter,
		conn:    fd, rtimeout: frameReadTimeout, wtimeout: frameWriteTimeout,
	}
F
Felix Lange 已提交
500
	p := newPeer(fd, conn, srv.Protocols)
F
Felix Lange 已提交
501
	if ok, reason := srv.addPeer(conn.ID, p); !ok {
O
obscuren 已提交
502
		glog.V(logger.Detail).Infof("Not adding %v (%v)\n", p, reason)
503
		p.politeDisconnect(reason)
504
		srv.peerWG.Done()
F
Felix Lange 已提交
505
		return
Z
zelig 已提交
506
	}
F
Felix Lange 已提交
507 508 509 510
	// The handshakes are done and it passed all checks.
	// Spawn the Peer loops.
	go srv.runPeer(p)
}
511

F
Felix Lange 已提交
512
func (srv *Server) runPeer(p *Peer) {
O
obscuren 已提交
513
	glog.V(logger.Debug).Infof("Added %v\n", p)
514
	srvjslog.LogJson(&logger.P2PConnected{
F
Felix Lange 已提交
515 516 517
		RemoteId:            p.ID().String(),
		RemoteAddress:       p.RemoteAddr().String(),
		RemoteVersionString: p.Name(),
518 519
		NumConnections:      srv.PeerCount(),
	})
F
Felix Lange 已提交
520 521 522
	if srv.newPeerHook != nil {
		srv.newPeerHook(p)
	}
523
	discreason := p.run()
F
Felix Lange 已提交
524
	srv.removePeer(p)
O
obscuren 已提交
525
	glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
526
	srvjslog.LogJson(&logger.P2PDisconnected{
F
Felix Lange 已提交
527
		RemoteId:       p.ID().String(),
528 529
		NumConnections: srv.PeerCount(),
	})
Z
zelig 已提交
530 531
}

F
Felix Lange 已提交
532
func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) {
533 534
	srv.lock.Lock()
	defer srv.lock.Unlock()
F
Felix Lange 已提交
535 536 537 538 539 540 541
	if ok, reason := srv.checkPeer(id); !ok {
		return false, reason
	}
	srv.peers[id] = p
	return true, 0
}

542 543
// 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 已提交
544
func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) {
545
	// First up, figure out if the peer is static
546
	_, static := srv.staticNodes[id]
547 548

	// Make sure the peer passes all required checks
F
Felix Lange 已提交
549 550 551
	switch {
	case !srv.running:
		return false, DiscQuitting
552
	case !static && len(srv.peers) >= srv.MaxPeers:
F
Felix Lange 已提交
553 554 555
		return false, DiscTooManyPeers
	case srv.peers[id] != nil:
		return false, DiscAlreadyConnected
556
	case id == srv.ntab.Self().ID:
F
Felix Lange 已提交
557
		return false, DiscSelf
F
Felix Lange 已提交
558 559
	default:
		return true, 0
F
Felix Lange 已提交
560
	}
Z
zelig 已提交
561 562
}

F
Felix Lange 已提交
563 564
func (srv *Server) removePeer(p *Peer) {
	srv.lock.Lock()
F
Felix Lange 已提交
565
	delete(srv.peers, p.ID())
F
Felix Lange 已提交
566 567
	srv.lock.Unlock()
	srv.peerWG.Done()
F
Felix Lange 已提交
568
}