github.com/luckypickle/go-ethereum-vet@v1.14.2/p2p/server.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package p2p implements the Ethereum p2p network protocols.
    18  package p2p
    19  
    20  import (
    21  	"crypto/ecdsa"
    22  	"errors"
    23  	"fmt"
    24  	"net"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/luckypickle/go-ethereum-vet/common"
    30  	"github.com/luckypickle/go-ethereum-vet/common/mclock"
    31  	"github.com/luckypickle/go-ethereum-vet/event"
    32  	"github.com/luckypickle/go-ethereum-vet/log"
    33  	"github.com/luckypickle/go-ethereum-vet/p2p/discover"
    34  	"github.com/luckypickle/go-ethereum-vet/p2p/discv5"
    35  	"github.com/luckypickle/go-ethereum-vet/p2p/nat"
    36  	"github.com/luckypickle/go-ethereum-vet/p2p/netutil"
    37  )
    38  
    39  const (
    40  	defaultDialTimeout = 15 * time.Second
    41  
    42  	// Connectivity defaults.
    43  	maxActiveDialTasks     = 16
    44  	defaultMaxPendingPeers = 50
    45  	defaultDialRatio       = 3
    46  
    47  	// Maximum time allowed for reading a complete message.
    48  	// This is effectively the amount of time a connection can be idle.
    49  	frameReadTimeout = 30 * time.Second
    50  
    51  	// Maximum amount of time allowed for writing a complete message.
    52  	frameWriteTimeout = 20 * time.Second
    53  )
    54  
    55  var errServerStopped = errors.New("server stopped")
    56  
    57  // Config holds Server options.
    58  type Config struct {
    59  	// This field must be set to a valid secp256k1 private key.
    60  	PrivateKey *ecdsa.PrivateKey `toml:"-"`
    61  
    62  	// MaxPeers is the maximum number of peers that can be
    63  	// connected. It must be greater than zero.
    64  	MaxPeers int
    65  
    66  	// MaxPendingPeers is the maximum number of peers that can be pending in the
    67  	// handshake phase, counted separately for inbound and outbound connections.
    68  	// Zero defaults to preset values.
    69  	MaxPendingPeers int `toml:",omitempty"`
    70  
    71  	// DialRatio controls the ratio of inbound to dialed connections.
    72  	// Example: a DialRatio of 2 allows 1/2 of connections to be dialed.
    73  	// Setting DialRatio to zero defaults it to 3.
    74  	DialRatio int `toml:",omitempty"`
    75  
    76  	// NoDiscovery can be used to disable the peer discovery mechanism.
    77  	// Disabling is useful for protocol debugging (manual topology).
    78  	NoDiscovery bool
    79  
    80  	// DiscoveryV5 specifies whether the the new topic-discovery based V5 discovery
    81  	// protocol should be started or not.
    82  	DiscoveryV5 bool `toml:",omitempty"`
    83  
    84  	// Name sets the node name of this server.
    85  	// Use common.MakeName to create a name that follows existing conventions.
    86  	Name string `toml:"-"`
    87  
    88  	// BootstrapNodes are used to establish connectivity
    89  	// with the rest of the network.
    90  	BootstrapNodes []*discover.Node
    91  
    92  	// BootstrapNodesV5 are used to establish connectivity
    93  	// with the rest of the network using the V5 discovery
    94  	// protocol.
    95  	BootstrapNodesV5 []*discv5.Node `toml:",omitempty"`
    96  
    97  	// Static nodes are used as pre-configured connections which are always
    98  	// maintained and re-connected on disconnects.
    99  	StaticNodes []*discover.Node
   100  
   101  	// Trusted nodes are used as pre-configured connections which are always
   102  	// allowed to connect, even above the peer limit.
   103  	TrustedNodes []*discover.Node
   104  
   105  	// Connectivity can be restricted to certain IP networks.
   106  	// If this option is set to a non-nil value, only hosts which match one of the
   107  	// IP networks contained in the list are considered.
   108  	NetRestrict *netutil.Netlist `toml:",omitempty"`
   109  
   110  	// NodeDatabase is the path to the database containing the previously seen
   111  	// live nodes in the network.
   112  	NodeDatabase string `toml:",omitempty"`
   113  
   114  	// Protocols should contain the protocols supported
   115  	// by the server. Matching protocols are launched for
   116  	// each peer.
   117  	Protocols []Protocol `toml:"-"`
   118  
   119  	// If ListenAddr is set to a non-nil address, the server
   120  	// will listen for incoming connections.
   121  	//
   122  	// If the port is zero, the operating system will pick a port. The
   123  	// ListenAddr field will be updated with the actual address when
   124  	// the server is started.
   125  	ListenAddr string
   126  
   127  	// If set to a non-nil value, the given NAT port mapper
   128  	// is used to make the listening port available to the
   129  	// Internet.
   130  	NAT nat.Interface `toml:",omitempty"`
   131  
   132  	// If Dialer is set to a non-nil value, the given Dialer
   133  	// is used to dial outbound peer connections.
   134  	Dialer NodeDialer `toml:"-"`
   135  
   136  	// If NoDial is true, the server will not dial any peers.
   137  	NoDial bool `toml:",omitempty"`
   138  
   139  	// If EnableMsgEvents is set then the server will emit PeerEvents
   140  	// whenever a message is sent to or received from a peer
   141  	EnableMsgEvents bool
   142  
   143  	// Logger is a custom logger to use with the p2p.Server.
   144  	Logger log.Logger `toml:",omitempty"`
   145  }
   146  
   147  // Server manages all peer connections.
   148  type Server struct {
   149  	// Config fields may not be modified while the server is running.
   150  	Config
   151  
   152  	// Hooks for testing. These are useful because we can inhibit
   153  	// the whole protocol stack.
   154  	newTransport func(net.Conn) transport
   155  	newPeerHook  func(*Peer)
   156  
   157  	lock    sync.Mutex // protects running
   158  	running bool
   159  
   160  	ntab         discoverTable
   161  	listener     net.Listener
   162  	ourHandshake *protoHandshake
   163  	lastLookup   time.Time
   164  	DiscV5       *discv5.Network
   165  
   166  	// These are for Peers, PeerCount (and nothing else).
   167  	peerOp     chan peerOpFunc
   168  	peerOpDone chan struct{}
   169  
   170  	quit          chan struct{}
   171  	addstatic     chan *discover.Node
   172  	removestatic  chan *discover.Node
   173  	addtrusted    chan *discover.Node
   174  	removetrusted chan *discover.Node
   175  	posthandshake chan *conn
   176  	addpeer       chan *conn
   177  	delpeer       chan peerDrop
   178  	loopWG        sync.WaitGroup // loop, listenLoop
   179  	peerFeed      event.Feed
   180  	log           log.Logger
   181  }
   182  
   183  type peerOpFunc func(map[discover.NodeID]*Peer)
   184  
   185  type peerDrop struct {
   186  	*Peer
   187  	err       error
   188  	requested bool // true if signaled by the peer
   189  }
   190  
   191  type connFlag int32
   192  
   193  const (
   194  	dynDialedConn connFlag = 1 << iota
   195  	staticDialedConn
   196  	inboundConn
   197  	trustedConn
   198  )
   199  
   200  // conn wraps a network connection with information gathered
   201  // during the two handshakes.
   202  type conn struct {
   203  	fd net.Conn
   204  	transport
   205  	flags connFlag
   206  	cont  chan error      // The run loop uses cont to signal errors to SetupConn.
   207  	id    discover.NodeID // valid after the encryption handshake
   208  	caps  []Cap           // valid after the protocol handshake
   209  	name  string          // valid after the protocol handshake
   210  }
   211  
   212  type transport interface {
   213  	// The two handshakes.
   214  	doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error)
   215  	doProtoHandshake(our *protoHandshake) (*protoHandshake, error)
   216  	// The MsgReadWriter can only be used after the encryption
   217  	// handshake has completed. The code uses conn.id to track this
   218  	// by setting it to a non-nil value after the encryption handshake.
   219  	MsgReadWriter
   220  	// transports must provide Close because we use MsgPipe in some of
   221  	// the tests. Closing the actual network connection doesn't do
   222  	// anything in those tests because NsgPipe doesn't use it.
   223  	close(err error)
   224  }
   225  
   226  func (c *conn) String() string {
   227  	s := c.flags.String()
   228  	if (c.id != discover.NodeID{}) {
   229  		s += " " + c.id.String()
   230  	}
   231  	s += " " + c.fd.RemoteAddr().String()
   232  	return s
   233  }
   234  
   235  func (f connFlag) String() string {
   236  	s := ""
   237  	if f&trustedConn != 0 {
   238  		s += "-trusted"
   239  	}
   240  	if f&dynDialedConn != 0 {
   241  		s += "-dyndial"
   242  	}
   243  	if f&staticDialedConn != 0 {
   244  		s += "-staticdial"
   245  	}
   246  	if f&inboundConn != 0 {
   247  		s += "-inbound"
   248  	}
   249  	if s != "" {
   250  		s = s[1:]
   251  	}
   252  	return s
   253  }
   254  
   255  func (c *conn) is(f connFlag) bool {
   256  	flags := connFlag(atomic.LoadInt32((*int32)(&c.flags)))
   257  	return flags&f != 0
   258  }
   259  
   260  func (c *conn) set(f connFlag, val bool) {
   261  	for {
   262  		oldFlags := connFlag(atomic.LoadInt32((*int32)(&c.flags)))
   263  		flags := oldFlags
   264  		if val {
   265  			flags |= f
   266  		} else {
   267  			flags &= ^f
   268  		}
   269  		if atomic.CompareAndSwapInt32((*int32)(&c.flags), int32(oldFlags), int32(flags)) {
   270  			return
   271  		}
   272  	}
   273  }
   274  
   275  // Peers returns all connected peers.
   276  func (srv *Server) Peers() []*Peer {
   277  	var ps []*Peer
   278  	select {
   279  	// Note: We'd love to put this function into a variable but
   280  	// that seems to cause a weird compiler error in some
   281  	// environments.
   282  	case srv.peerOp <- func(peers map[discover.NodeID]*Peer) {
   283  		for _, p := range peers {
   284  			ps = append(ps, p)
   285  		}
   286  	}:
   287  		<-srv.peerOpDone
   288  	case <-srv.quit:
   289  	}
   290  	return ps
   291  }
   292  
   293  // PeerCount returns the number of connected peers.
   294  func (srv *Server) PeerCount() int {
   295  	var count int
   296  	select {
   297  	case srv.peerOp <- func(ps map[discover.NodeID]*Peer) { count = len(ps) }:
   298  		<-srv.peerOpDone
   299  	case <-srv.quit:
   300  	}
   301  	return count
   302  }
   303  
   304  // AddPeer connects to the given node and maintains the connection until the
   305  // server is shut down. If the connection fails for any reason, the server will
   306  // attempt to reconnect the peer.
   307  func (srv *Server) AddPeer(node *discover.Node) {
   308  	select {
   309  	case srv.addstatic <- node:
   310  	case <-srv.quit:
   311  	}
   312  }
   313  
   314  // RemovePeer disconnects from the given node
   315  func (srv *Server) RemovePeer(node *discover.Node) {
   316  	select {
   317  	case srv.removestatic <- node:
   318  	case <-srv.quit:
   319  	}
   320  }
   321  
   322  // AddTrustedPeer adds the given node to a reserved whitelist which allows the
   323  // node to always connect, even if the slot are full.
   324  func (srv *Server) AddTrustedPeer(node *discover.Node) {
   325  	select {
   326  	case srv.addtrusted <- node:
   327  	case <-srv.quit:
   328  	}
   329  }
   330  
   331  // RemoveTrustedPeer removes the given node from the trusted peer set.
   332  func (srv *Server) RemoveTrustedPeer(node *discover.Node) {
   333  	select {
   334  	case srv.removetrusted <- node:
   335  	case <-srv.quit:
   336  	}
   337  }
   338  
   339  // SubscribePeers subscribes the given channel to peer events
   340  func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription {
   341  	return srv.peerFeed.Subscribe(ch)
   342  }
   343  
   344  // Self returns the local node's endpoint information.
   345  func (srv *Server) Self() *discover.Node {
   346  	srv.lock.Lock()
   347  	defer srv.lock.Unlock()
   348  
   349  	if !srv.running {
   350  		return &discover.Node{IP: net.ParseIP("0.0.0.0")}
   351  	}
   352  	return srv.makeSelf(srv.listener, srv.ntab)
   353  }
   354  
   355  func (srv *Server) makeSelf(listener net.Listener, ntab discoverTable) *discover.Node {
   356  	// If the server's not running, return an empty node.
   357  	// If the node is running but discovery is off, manually assemble the node infos.
   358  	if ntab == nil {
   359  		// Inbound connections disabled, use zero address.
   360  		if listener == nil {
   361  			return &discover.Node{IP: net.ParseIP("0.0.0.0"), ID: discover.PubkeyID(&srv.PrivateKey.PublicKey)}
   362  		}
   363  		// Otherwise inject the listener address too
   364  		addr := listener.Addr().(*net.TCPAddr)
   365  		return &discover.Node{
   366  			ID:  discover.PubkeyID(&srv.PrivateKey.PublicKey),
   367  			IP:  addr.IP,
   368  			TCP: uint16(addr.Port),
   369  		}
   370  	}
   371  	// Otherwise return the discovery node.
   372  	return ntab.Self()
   373  }
   374  
   375  // Stop terminates the server and all active peer connections.
   376  // It blocks until all active connections have been closed.
   377  func (srv *Server) Stop() {
   378  	srv.lock.Lock()
   379  	if !srv.running {
   380  		srv.lock.Unlock()
   381  		return
   382  	}
   383  	srv.running = false
   384  	if srv.listener != nil {
   385  		// this unblocks listener Accept
   386  		srv.listener.Close()
   387  	}
   388  	close(srv.quit)
   389  	srv.lock.Unlock()
   390  	srv.loopWG.Wait()
   391  }
   392  
   393  // sharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns
   394  // messages that were found unprocessable and sent to the unhandled channel by the primary listener.
   395  type sharedUDPConn struct {
   396  	*net.UDPConn
   397  	unhandled chan discover.ReadPacket
   398  }
   399  
   400  // ReadFromUDP implements discv5.conn
   401  func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
   402  	packet, ok := <-s.unhandled
   403  	if !ok {
   404  		return 0, nil, fmt.Errorf("Connection was closed")
   405  	}
   406  	l := len(packet.Data)
   407  	if l > len(b) {
   408  		l = len(b)
   409  	}
   410  	copy(b[:l], packet.Data[:l])
   411  	return l, packet.Addr, nil
   412  }
   413  
   414  // Close implements discv5.conn
   415  func (s *sharedUDPConn) Close() error {
   416  	return nil
   417  }
   418  
   419  // Start starts running the server.
   420  // Servers can not be re-used after stopping.
   421  func (srv *Server) Start() (err error) {
   422  	srv.lock.Lock()
   423  	defer srv.lock.Unlock()
   424  	if srv.running {
   425  		return errors.New("server already running")
   426  	}
   427  	srv.running = true
   428  	srv.log = srv.Config.Logger
   429  	if srv.log == nil {
   430  		srv.log = log.New()
   431  	}
   432  	srv.log.Info("Starting P2P networking")
   433  
   434  	// static fields
   435  	if srv.PrivateKey == nil {
   436  		return fmt.Errorf("Server.PrivateKey must be set to a non-nil key")
   437  	}
   438  	if srv.newTransport == nil {
   439  		srv.newTransport = newRLPX
   440  	}
   441  	if srv.Dialer == nil {
   442  		srv.Dialer = TCPDialer{&net.Dialer{Timeout: defaultDialTimeout}}
   443  	}
   444  	srv.quit = make(chan struct{})
   445  	srv.addpeer = make(chan *conn)
   446  	srv.delpeer = make(chan peerDrop)
   447  	srv.posthandshake = make(chan *conn)
   448  	srv.addstatic = make(chan *discover.Node)
   449  	srv.removestatic = make(chan *discover.Node)
   450  	srv.addtrusted = make(chan *discover.Node)
   451  	srv.removetrusted = make(chan *discover.Node)
   452  	srv.peerOp = make(chan peerOpFunc)
   453  	srv.peerOpDone = make(chan struct{})
   454  
   455  	var (
   456  		conn      *net.UDPConn
   457  		sconn     *sharedUDPConn
   458  		realaddr  *net.UDPAddr
   459  		unhandled chan discover.ReadPacket
   460  	)
   461  
   462  	if !srv.NoDiscovery || srv.DiscoveryV5 {
   463  		addr, err := net.ResolveUDPAddr("udp", srv.ListenAddr)
   464  		if err != nil {
   465  			return err
   466  		}
   467  		conn, err = net.ListenUDP("udp", addr)
   468  		if err != nil {
   469  			return err
   470  		}
   471  		realaddr = conn.LocalAddr().(*net.UDPAddr)
   472  		if srv.NAT != nil {
   473  			if !realaddr.IP.IsLoopback() {
   474  				go nat.Map(srv.NAT, srv.quit, "udp", realaddr.Port, realaddr.Port, "ethereum discovery")
   475  			}
   476  			// TODO: react to external IP changes over time.
   477  			if ext, err := srv.NAT.ExternalIP(); err == nil {
   478  				realaddr = &net.UDPAddr{IP: ext, Port: realaddr.Port}
   479  			}
   480  		}
   481  	}
   482  
   483  	if !srv.NoDiscovery && srv.DiscoveryV5 {
   484  		unhandled = make(chan discover.ReadPacket, 100)
   485  		sconn = &sharedUDPConn{conn, unhandled}
   486  	}
   487  
   488  	// node table
   489  	if !srv.NoDiscovery {
   490  		cfg := discover.Config{
   491  			PrivateKey:   srv.PrivateKey,
   492  			AnnounceAddr: realaddr,
   493  			NodeDBPath:   srv.NodeDatabase,
   494  			NetRestrict:  srv.NetRestrict,
   495  			Bootnodes:    srv.BootstrapNodes,
   496  			Unhandled:    unhandled,
   497  		}
   498  		ntab, err := discover.ListenUDP(conn, cfg)
   499  		if err != nil {
   500  			return err
   501  		}
   502  		srv.ntab = ntab
   503  	}
   504  
   505  	if srv.DiscoveryV5 {
   506  		var (
   507  			ntab *discv5.Network
   508  			err  error
   509  		)
   510  		if sconn != nil {
   511  			ntab, err = discv5.ListenUDP(srv.PrivateKey, sconn, realaddr, "", srv.NetRestrict) //srv.NodeDatabase)
   512  		} else {
   513  			ntab, err = discv5.ListenUDP(srv.PrivateKey, conn, realaddr, "", srv.NetRestrict) //srv.NodeDatabase)
   514  		}
   515  		if err != nil {
   516  			return err
   517  		}
   518  		if err := ntab.SetFallbackNodes(srv.BootstrapNodesV5); err != nil {
   519  			return err
   520  		}
   521  		srv.DiscV5 = ntab
   522  	}
   523  
   524  	dynPeers := srv.maxDialedConns()
   525  	dialer := newDialState(srv.StaticNodes, srv.BootstrapNodes, srv.ntab, dynPeers, srv.NetRestrict)
   526  
   527  	// handshake
   528  	srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: discover.PubkeyID(&srv.PrivateKey.PublicKey)}
   529  	for _, p := range srv.Protocols {
   530  		srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
   531  	}
   532  	// listen/dial
   533  	if srv.ListenAddr != "" {
   534  		if err := srv.startListening(); err != nil {
   535  			return err
   536  		}
   537  	}
   538  	if srv.NoDial && srv.ListenAddr == "" {
   539  		srv.log.Warn("P2P server will be useless, neither dialing nor listening")
   540  	}
   541  
   542  	srv.loopWG.Add(1)
   543  	go srv.run(dialer)
   544  	srv.running = true
   545  	return nil
   546  }
   547  
   548  func (srv *Server) startListening() error {
   549  	// Launch the TCP listener.
   550  	listener, err := net.Listen("tcp", srv.ListenAddr)
   551  	if err != nil {
   552  		return err
   553  	}
   554  	laddr := listener.Addr().(*net.TCPAddr)
   555  	srv.ListenAddr = laddr.String()
   556  	srv.listener = listener
   557  	srv.loopWG.Add(1)
   558  	go srv.listenLoop()
   559  	// Map the TCP listening port if NAT is configured.
   560  	if !laddr.IP.IsLoopback() && srv.NAT != nil {
   561  		srv.loopWG.Add(1)
   562  		go func() {
   563  			nat.Map(srv.NAT, srv.quit, "tcp", laddr.Port, laddr.Port, "ethereum p2p")
   564  			srv.loopWG.Done()
   565  		}()
   566  	}
   567  	return nil
   568  }
   569  
   570  type dialer interface {
   571  	newTasks(running int, peers map[discover.NodeID]*Peer, now time.Time) []task
   572  	taskDone(task, time.Time)
   573  	addStatic(*discover.Node)
   574  	removeStatic(*discover.Node)
   575  }
   576  
   577  func (srv *Server) run(dialstate dialer) {
   578  	defer srv.loopWG.Done()
   579  	var (
   580  		peers        = make(map[discover.NodeID]*Peer)
   581  		inboundCount = 0
   582  		trusted      = make(map[discover.NodeID]bool, len(srv.TrustedNodes))
   583  		taskdone     = make(chan task, maxActiveDialTasks)
   584  		runningTasks []task
   585  		queuedTasks  []task // tasks that can't run yet
   586  	)
   587  	// Put trusted nodes into a map to speed up checks.
   588  	// Trusted peers are loaded on startup or added via AddTrustedPeer RPC.
   589  	for _, n := range srv.TrustedNodes {
   590  		trusted[n.ID] = true
   591  	}
   592  
   593  	// removes t from runningTasks
   594  	delTask := func(t task) {
   595  		for i := range runningTasks {
   596  			if runningTasks[i] == t {
   597  				runningTasks = append(runningTasks[:i], runningTasks[i+1:]...)
   598  				break
   599  			}
   600  		}
   601  	}
   602  	// starts until max number of active tasks is satisfied
   603  	startTasks := func(ts []task) (rest []task) {
   604  		i := 0
   605  		for ; len(runningTasks) < maxActiveDialTasks && i < len(ts); i++ {
   606  			t := ts[i]
   607  			srv.log.Trace("New dial task", "task", t)
   608  			go func() { t.Do(srv); taskdone <- t }()
   609  			runningTasks = append(runningTasks, t)
   610  		}
   611  		return ts[i:]
   612  	}
   613  	scheduleTasks := func() {
   614  		// Start from queue first.
   615  		queuedTasks = append(queuedTasks[:0], startTasks(queuedTasks)...)
   616  		// Query dialer for new tasks and start as many as possible now.
   617  		if len(runningTasks) < maxActiveDialTasks {
   618  			nt := dialstate.newTasks(len(runningTasks)+len(queuedTasks), peers, time.Now())
   619  			queuedTasks = append(queuedTasks, startTasks(nt)...)
   620  		}
   621  	}
   622  
   623  running:
   624  	for {
   625  		scheduleTasks()
   626  
   627  		select {
   628  		case <-srv.quit:
   629  			// The server was stopped. Run the cleanup logic.
   630  			break running
   631  		case n := <-srv.addstatic:
   632  			// This channel is used by AddPeer to add to the
   633  			// ephemeral static peer list. Add it to the dialer,
   634  			// it will keep the node connected.
   635  			srv.log.Trace("Adding static node", "node", n)
   636  			dialstate.addStatic(n)
   637  		case n := <-srv.removestatic:
   638  			// This channel is used by RemovePeer to send a
   639  			// disconnect request to a peer and begin the
   640  			// stop keeping the node connected.
   641  			srv.log.Trace("Removing static node", "node", n)
   642  			dialstate.removeStatic(n)
   643  			if p, ok := peers[n.ID]; ok {
   644  				p.Disconnect(DiscRequested)
   645  			}
   646  		case n := <-srv.addtrusted:
   647  			// This channel is used by AddTrustedPeer to add an enode
   648  			// to the trusted node set.
   649  			srv.log.Trace("Adding trusted node", "node", n)
   650  			trusted[n.ID] = true
   651  			// Mark any already-connected peer as trusted
   652  			if p, ok := peers[n.ID]; ok {
   653  				p.rw.set(trustedConn, true)
   654  			}
   655  		case n := <-srv.removetrusted:
   656  			// This channel is used by RemoveTrustedPeer to remove an enode
   657  			// from the trusted node set.
   658  			srv.log.Trace("Removing trusted node", "node", n)
   659  			if _, ok := trusted[n.ID]; ok {
   660  				delete(trusted, n.ID)
   661  			}
   662  			// Unmark any already-connected peer as trusted
   663  			if p, ok := peers[n.ID]; ok {
   664  				p.rw.set(trustedConn, false)
   665  			}
   666  		case op := <-srv.peerOp:
   667  			// This channel is used by Peers and PeerCount.
   668  			op(peers)
   669  			srv.peerOpDone <- struct{}{}
   670  		case t := <-taskdone:
   671  			// A task got done. Tell dialstate about it so it
   672  			// can update its state and remove it from the active
   673  			// tasks list.
   674  			srv.log.Trace("Dial task done", "task", t)
   675  			dialstate.taskDone(t, time.Now())
   676  			delTask(t)
   677  		case c := <-srv.posthandshake:
   678  			// A connection has passed the encryption handshake so
   679  			// the remote identity is known (but hasn't been verified yet).
   680  			if trusted[c.id] {
   681  				// Ensure that the trusted flag is set before checking against MaxPeers.
   682  				c.flags |= trustedConn
   683  			}
   684  			// TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them.
   685  			select {
   686  			case c.cont <- srv.encHandshakeChecks(peers, inboundCount, c):
   687  			case <-srv.quit:
   688  				break running
   689  			}
   690  		case c := <-srv.addpeer:
   691  			// At this point the connection is past the protocol handshake.
   692  			// Its capabilities are known and the remote identity is verified.
   693  			err := srv.protoHandshakeChecks(peers, inboundCount, c)
   694  			if err == nil {
   695  				// The handshakes are done and it passed all checks.
   696  				p := newPeer(c, srv.Protocols)
   697  				// If message events are enabled, pass the peerFeed
   698  				// to the peer
   699  				if srv.EnableMsgEvents {
   700  					p.events = &srv.peerFeed
   701  				}
   702  				name := truncateName(c.name)
   703  				srv.log.Debug("Adding p2p peer", "name", name, "addr", c.fd.RemoteAddr(), "peers", len(peers)+1)
   704  				go srv.runPeer(p)
   705  				peers[c.id] = p
   706  				if p.Inbound() {
   707  					inboundCount++
   708  				}
   709  			}
   710  			// The dialer logic relies on the assumption that
   711  			// dial tasks complete after the peer has been added or
   712  			// discarded. Unblock the task last.
   713  			select {
   714  			case c.cont <- err:
   715  			case <-srv.quit:
   716  				break running
   717  			}
   718  		case pd := <-srv.delpeer:
   719  			// A peer disconnected.
   720  			d := common.PrettyDuration(mclock.Now() - pd.created)
   721  			pd.log.Debug("Removing p2p peer", "duration", d, "peers", len(peers)-1, "req", pd.requested, "err", pd.err)
   722  			delete(peers, pd.ID())
   723  			if pd.Inbound() {
   724  				inboundCount--
   725  			}
   726  		}
   727  	}
   728  
   729  	srv.log.Trace("P2P networking is spinning down")
   730  
   731  	// Terminate discovery. If there is a running lookup it will terminate soon.
   732  	if srv.ntab != nil {
   733  		srv.ntab.Close()
   734  	}
   735  	if srv.DiscV5 != nil {
   736  		srv.DiscV5.Close()
   737  	}
   738  	// Disconnect all peers.
   739  	for _, p := range peers {
   740  		p.Disconnect(DiscQuitting)
   741  	}
   742  	// Wait for peers to shut down. Pending connections and tasks are
   743  	// not handled here and will terminate soon-ish because srv.quit
   744  	// is closed.
   745  	for len(peers) > 0 {
   746  		p := <-srv.delpeer
   747  		p.log.Trace("<-delpeer (spindown)", "remainingTasks", len(runningTasks))
   748  		delete(peers, p.ID())
   749  	}
   750  }
   751  
   752  func (srv *Server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, inboundCount int, c *conn) error {
   753  	// Drop connections with no matching protocols.
   754  	if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
   755  		return DiscUselessPeer
   756  	}
   757  	// Repeat the encryption handshake checks because the
   758  	// peer set might have changed between the handshakes.
   759  	return srv.encHandshakeChecks(peers, inboundCount, c)
   760  }
   761  
   762  func (srv *Server) encHandshakeChecks(peers map[discover.NodeID]*Peer, inboundCount int, c *conn) error {
   763  	switch {
   764  	case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers:
   765  		return DiscTooManyPeers
   766  	case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns():
   767  		return DiscTooManyPeers
   768  	case peers[c.id] != nil:
   769  		return DiscAlreadyConnected
   770  	case c.id == srv.Self().ID:
   771  		return DiscSelf
   772  	default:
   773  		return nil
   774  	}
   775  }
   776  
   777  func (srv *Server) maxInboundConns() int {
   778  	return srv.MaxPeers - srv.maxDialedConns()
   779  }
   780  
   781  func (srv *Server) maxDialedConns() int {
   782  	if srv.NoDiscovery || srv.NoDial {
   783  		return 0
   784  	}
   785  	r := srv.DialRatio
   786  	if r == 0 {
   787  		r = defaultDialRatio
   788  	}
   789  	return srv.MaxPeers / r
   790  }
   791  
   792  type tempError interface {
   793  	Temporary() bool
   794  }
   795  
   796  // listenLoop runs in its own goroutine and accepts
   797  // inbound connections.
   798  func (srv *Server) listenLoop() {
   799  	defer srv.loopWG.Done()
   800  	srv.log.Info("RLPx listener up", "self", srv.makeSelf(srv.listener, srv.ntab))
   801  
   802  	tokens := defaultMaxPendingPeers
   803  	if srv.MaxPendingPeers > 0 {
   804  		tokens = srv.MaxPendingPeers
   805  	}
   806  	slots := make(chan struct{}, tokens)
   807  	for i := 0; i < tokens; i++ {
   808  		slots <- struct{}{}
   809  	}
   810  
   811  	for {
   812  		// Wait for a handshake slot before accepting.
   813  		<-slots
   814  
   815  		var (
   816  			fd  net.Conn
   817  			err error
   818  		)
   819  		for {
   820  			fd, err = srv.listener.Accept()
   821  			if tempErr, ok := err.(tempError); ok && tempErr.Temporary() {
   822  				srv.log.Debug("Temporary read error", "err", err)
   823  				continue
   824  			} else if err != nil {
   825  				srv.log.Debug("Read error", "err", err)
   826  				return
   827  			}
   828  			break
   829  		}
   830  
   831  		// Reject connections that do not match NetRestrict.
   832  		if srv.NetRestrict != nil {
   833  			if tcp, ok := fd.RemoteAddr().(*net.TCPAddr); ok && !srv.NetRestrict.Contains(tcp.IP) {
   834  				srv.log.Debug("Rejected conn (not whitelisted in NetRestrict)", "addr", fd.RemoteAddr())
   835  				fd.Close()
   836  				slots <- struct{}{}
   837  				continue
   838  			}
   839  		}
   840  
   841  		fd = newMeteredConn(fd, true)
   842  		srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr())
   843  		go func() {
   844  			srv.SetupConn(fd, inboundConn, nil)
   845  			slots <- struct{}{}
   846  		}()
   847  	}
   848  }
   849  
   850  // SetupConn runs the handshakes and attempts to add the connection
   851  // as a peer. It returns when the connection has been added as a peer
   852  // or the handshakes have failed.
   853  func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node) error {
   854  	self := srv.Self()
   855  	if self == nil {
   856  		return errors.New("shutdown")
   857  	}
   858  	c := &conn{fd: fd, transport: srv.newTransport(fd), flags: flags, cont: make(chan error)}
   859  	err := srv.setupConn(c, flags, dialDest)
   860  	if err != nil {
   861  		c.close(err)
   862  		srv.log.Trace("Setting up connection failed", "id", c.id, "err", err)
   863  	}
   864  	return err
   865  }
   866  
   867  func (srv *Server) setupConn(c *conn, flags connFlag, dialDest *discover.Node) error {
   868  	// Prevent leftover pending conns from entering the handshake.
   869  	srv.lock.Lock()
   870  	running := srv.running
   871  	srv.lock.Unlock()
   872  	if !running {
   873  		return errServerStopped
   874  	}
   875  	// Run the encryption handshake.
   876  	var err error
   877  	if c.id, err = c.doEncHandshake(srv.PrivateKey, dialDest); err != nil {
   878  		srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
   879  		return err
   880  	}
   881  	clog := srv.log.New("id", c.id, "addr", c.fd.RemoteAddr(), "conn", c.flags)
   882  	// For dialed connections, check that the remote public key matches.
   883  	if dialDest != nil && c.id != dialDest.ID {
   884  		clog.Trace("Dialed identity mismatch", "want", c, dialDest.ID)
   885  		return DiscUnexpectedIdentity
   886  	}
   887  	err = srv.checkpoint(c, srv.posthandshake)
   888  	if err != nil {
   889  		clog.Trace("Rejected peer before protocol handshake", "err", err)
   890  		return err
   891  	}
   892  	// Run the protocol handshake
   893  	phs, err := c.doProtoHandshake(srv.ourHandshake)
   894  	if err != nil {
   895  		clog.Trace("Failed proto handshake", "err", err)
   896  		return err
   897  	}
   898  	if phs.ID != c.id {
   899  		clog.Trace("Wrong devp2p handshake identity", "err", phs.ID)
   900  		return DiscUnexpectedIdentity
   901  	}
   902  	c.caps, c.name = phs.Caps, phs.Name
   903  	err = srv.checkpoint(c, srv.addpeer)
   904  	if err != nil {
   905  		clog.Trace("Rejected peer", "err", err)
   906  		return err
   907  	}
   908  	// If the checks completed successfully, runPeer has now been
   909  	// launched by run.
   910  	clog.Trace("connection set up", "inbound", dialDest == nil)
   911  	return nil
   912  }
   913  
   914  func truncateName(s string) string {
   915  	if len(s) > 20 {
   916  		return s[:20] + "..."
   917  	}
   918  	return s
   919  }
   920  
   921  // checkpoint sends the conn to run, which performs the
   922  // post-handshake checks for the stage (posthandshake, addpeer).
   923  func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
   924  	select {
   925  	case stage <- c:
   926  	case <-srv.quit:
   927  		return errServerStopped
   928  	}
   929  	select {
   930  	case err := <-c.cont:
   931  		return err
   932  	case <-srv.quit:
   933  		return errServerStopped
   934  	}
   935  }
   936  
   937  // runPeer runs in its own goroutine for each peer.
   938  // it waits until the Peer logic returns and removes
   939  // the peer.
   940  func (srv *Server) runPeer(p *Peer) {
   941  	if srv.newPeerHook != nil {
   942  		srv.newPeerHook(p)
   943  	}
   944  
   945  	// broadcast peer add
   946  	srv.peerFeed.Send(&PeerEvent{
   947  		Type: PeerEventTypeAdd,
   948  		Peer: p.ID(),
   949  	})
   950  
   951  	// run the protocol
   952  	remoteRequested, err := p.run()
   953  
   954  	// broadcast peer drop
   955  	srv.peerFeed.Send(&PeerEvent{
   956  		Type:  PeerEventTypeDrop,
   957  		Peer:  p.ID(),
   958  		Error: err.Error(),
   959  	})
   960  
   961  	// Note: run waits for existing peers to be sent on srv.delpeer
   962  	// before returning, so this send should not select on srv.quit.
   963  	srv.delpeer <- peerDrop{p, err, remoteRequested}
   964  }
   965  
   966  // NodeInfo represents a short summary of the information known about the host.
   967  type NodeInfo struct {
   968  	ID    string `json:"id"`    // Unique node identifier (also the encryption key)
   969  	Name  string `json:"name"`  // Name of the node, including client type, version, OS, custom data
   970  	Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
   971  	IP    string `json:"ip"`    // IP address of the node
   972  	Ports struct {
   973  		Discovery int `json:"discovery"` // UDP listening port for discovery protocol
   974  		Listener  int `json:"listener"`  // TCP listening port for RLPx
   975  	} `json:"ports"`
   976  	ListenAddr string                 `json:"listenAddr"`
   977  	Protocols  map[string]interface{} `json:"protocols"`
   978  }
   979  
   980  // NodeInfo gathers and returns a collection of metadata known about the host.
   981  func (srv *Server) NodeInfo() *NodeInfo {
   982  	node := srv.Self()
   983  
   984  	// Gather and assemble the generic node infos
   985  	info := &NodeInfo{
   986  		Name:       srv.Name,
   987  		Enode:      node.String(),
   988  		ID:         node.ID.String(),
   989  		IP:         node.IP.String(),
   990  		ListenAddr: srv.ListenAddr,
   991  		Protocols:  make(map[string]interface{}),
   992  	}
   993  	info.Ports.Discovery = int(node.UDP)
   994  	info.Ports.Listener = int(node.TCP)
   995  
   996  	// Gather all the running protocol infos (only once per protocol type)
   997  	for _, proto := range srv.Protocols {
   998  		if _, ok := info.Protocols[proto.Name]; !ok {
   999  			nodeInfo := interface{}("unknown")
  1000  			if query := proto.NodeInfo; query != nil {
  1001  				nodeInfo = proto.NodeInfo()
  1002  			}
  1003  			info.Protocols[proto.Name] = nodeInfo
  1004  		}
  1005  	}
  1006  	return info
  1007  }
  1008  
  1009  // PeersInfo returns an array of metadata objects describing connected peers.
  1010  func (srv *Server) PeersInfo() []*PeerInfo {
  1011  	// Gather all the generic and sub-protocol specific infos
  1012  	infos := make([]*PeerInfo, 0, srv.PeerCount())
  1013  	for _, peer := range srv.Peers() {
  1014  		if peer != nil {
  1015  			infos = append(infos, peer.Info())
  1016  		}
  1017  	}
  1018  	// Sort the result array alphabetically by node identifier
  1019  	for i := 0; i < len(infos); i++ {
  1020  		for j := i + 1; j < len(infos); j++ {
  1021  			if infos[i].ID > infos[j].ID {
  1022  				infos[i], infos[j] = infos[j], infos[i]
  1023  			}
  1024  		}
  1025  	}
  1026  	return infos
  1027  }