github.com/sunjiahui/go-ethereum@v1.10.31/p2p/dial.go (about)

     1  // Copyright 2015 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
    18  
    19  import (
    20  	"context"
    21  	crand "crypto/rand"
    22  	"encoding/binary"
    23  	"errors"
    24  	"fmt"
    25  	mrand "math/rand"
    26  	"net"
    27  	"sync"
    28  	"time"
    29  
    30  	"github.com/sunjiahui/go-ethereum/common/mclock"
    31  	"github.com/sunjiahui/go-ethereum/log"
    32  	"github.com/sunjiahui/go-ethereum/p2p/enode"
    33  	"github.com/sunjiahui/go-ethereum/p2p/netutil"
    34  )
    35  
    36  const (
    37  	// This is the amount of time spent waiting in between redialing a certain node. The
    38  	// limit is a bit higher than inboundThrottleTime to prevent failing dials in small
    39  	// private networks.
    40  	dialHistoryExpiration = inboundThrottleTime + 5*time.Second
    41  
    42  	// Config for the "Looking for peers" message.
    43  	dialStatsLogInterval = 10 * time.Second // printed at most this often
    44  	dialStatsPeerLimit   = 3                // but not if more than this many dialed peers
    45  
    46  	// Endpoint resolution is throttled with bounded backoff.
    47  	initialResolveDelay = 60 * time.Second
    48  	maxResolveDelay     = time.Hour
    49  )
    50  
    51  // NodeDialer is used to connect to nodes in the network, typically by using
    52  // an underlying net.Dialer but also using net.Pipe in tests.
    53  type NodeDialer interface {
    54  	Dial(context.Context, *enode.Node) (net.Conn, error)
    55  }
    56  
    57  type nodeResolver interface {
    58  	Resolve(*enode.Node) *enode.Node
    59  }
    60  
    61  // tcpDialer implements NodeDialer using real TCP connections.
    62  type tcpDialer struct {
    63  	d *net.Dialer
    64  }
    65  
    66  func (t tcpDialer) Dial(ctx context.Context, dest *enode.Node) (net.Conn, error) {
    67  	return t.d.DialContext(ctx, "tcp", nodeAddr(dest).String())
    68  }
    69  
    70  func nodeAddr(n *enode.Node) net.Addr {
    71  	return &net.TCPAddr{IP: n.IP(), Port: n.TCP()}
    72  }
    73  
    74  // checkDial errors:
    75  var (
    76  	errSelf             = errors.New("is self")
    77  	errAlreadyDialing   = errors.New("already dialing")
    78  	errAlreadyConnected = errors.New("already connected")
    79  	errRecentlyDialed   = errors.New("recently dialed")
    80  	errNetRestrict      = errors.New("not contained in netrestrict list")
    81  	errNoPort           = errors.New("node does not provide TCP port")
    82  )
    83  
    84  // dialer creates outbound connections and submits them into Server.
    85  // Two types of peer connections can be created:
    86  //
    87  //   - static dials are pre-configured connections. The dialer attempts
    88  //     keep these nodes connected at all times.
    89  //
    90  //   - dynamic dials are created from node discovery results. The dialer
    91  //     continuously reads candidate nodes from its input iterator and attempts
    92  //     to create peer connections to nodes arriving through the iterator.
    93  type dialScheduler struct {
    94  	dialConfig
    95  	setupFunc   dialSetupFunc
    96  	wg          sync.WaitGroup
    97  	cancel      context.CancelFunc
    98  	ctx         context.Context
    99  	nodesIn     chan *enode.Node
   100  	doneCh      chan *dialTask
   101  	addStaticCh chan *enode.Node
   102  	remStaticCh chan *enode.Node
   103  	addPeerCh   chan *conn
   104  	remPeerCh   chan *conn
   105  
   106  	// Everything below here belongs to loop and
   107  	// should only be accessed by code on the loop goroutine.
   108  	dialing   map[enode.ID]*dialTask // active tasks
   109  	peers     map[enode.ID]struct{}  // all connected peers
   110  	dialPeers int                    // current number of dialed peers
   111  
   112  	// The static map tracks all static dial tasks. The subset of usable static dial tasks
   113  	// (i.e. those passing checkDial) is kept in staticPool. The scheduler prefers
   114  	// launching random static tasks from the pool over launching dynamic dials from the
   115  	// iterator.
   116  	static     map[enode.ID]*dialTask
   117  	staticPool []*dialTask
   118  
   119  	// The dial history keeps recently dialed nodes. Members of history are not dialed.
   120  	history      expHeap
   121  	historyTimer *mclock.Alarm
   122  
   123  	// for logStats
   124  	lastStatsLog     mclock.AbsTime
   125  	doneSinceLastLog int
   126  }
   127  
   128  type dialSetupFunc func(net.Conn, connFlag, *enode.Node) error
   129  
   130  type dialConfig struct {
   131  	self           enode.ID         // our own ID
   132  	maxDialPeers   int              // maximum number of dialed peers
   133  	maxActiveDials int              // maximum number of active dials
   134  	netRestrict    *netutil.Netlist // IP netrestrict list, disabled if nil
   135  	resolver       nodeResolver
   136  	dialer         NodeDialer
   137  	log            log.Logger
   138  	clock          mclock.Clock
   139  	rand           *mrand.Rand
   140  }
   141  
   142  func (cfg dialConfig) withDefaults() dialConfig {
   143  	if cfg.maxActiveDials == 0 {
   144  		cfg.maxActiveDials = defaultMaxPendingPeers
   145  	}
   146  	if cfg.log == nil {
   147  		cfg.log = log.Root()
   148  	}
   149  	if cfg.clock == nil {
   150  		cfg.clock = mclock.System{}
   151  	}
   152  	if cfg.rand == nil {
   153  		seedb := make([]byte, 8)
   154  		crand.Read(seedb)
   155  		seed := int64(binary.BigEndian.Uint64(seedb))
   156  		cfg.rand = mrand.New(mrand.NewSource(seed))
   157  	}
   158  	return cfg
   159  }
   160  
   161  func newDialScheduler(config dialConfig, it enode.Iterator, setupFunc dialSetupFunc) *dialScheduler {
   162  	cfg := config.withDefaults()
   163  	d := &dialScheduler{
   164  		dialConfig:   cfg,
   165  		historyTimer: mclock.NewAlarm(cfg.clock),
   166  		setupFunc:    setupFunc,
   167  		dialing:      make(map[enode.ID]*dialTask),
   168  		static:       make(map[enode.ID]*dialTask),
   169  		peers:        make(map[enode.ID]struct{}),
   170  		doneCh:       make(chan *dialTask),
   171  		nodesIn:      make(chan *enode.Node),
   172  		addStaticCh:  make(chan *enode.Node),
   173  		remStaticCh:  make(chan *enode.Node),
   174  		addPeerCh:    make(chan *conn),
   175  		remPeerCh:    make(chan *conn),
   176  	}
   177  	d.lastStatsLog = d.clock.Now()
   178  	d.ctx, d.cancel = context.WithCancel(context.Background())
   179  	d.wg.Add(2)
   180  	go d.readNodes(it)
   181  	go d.loop(it)
   182  	return d
   183  }
   184  
   185  // stop shuts down the dialer, canceling all current dial tasks.
   186  func (d *dialScheduler) stop() {
   187  	d.cancel()
   188  	d.wg.Wait()
   189  }
   190  
   191  // addStatic adds a static dial candidate.
   192  func (d *dialScheduler) addStatic(n *enode.Node) {
   193  	select {
   194  	case d.addStaticCh <- n:
   195  	case <-d.ctx.Done():
   196  	}
   197  }
   198  
   199  // removeStatic removes a static dial candidate.
   200  func (d *dialScheduler) removeStatic(n *enode.Node) {
   201  	select {
   202  	case d.remStaticCh <- n:
   203  	case <-d.ctx.Done():
   204  	}
   205  }
   206  
   207  // peerAdded updates the peer set.
   208  func (d *dialScheduler) peerAdded(c *conn) {
   209  	select {
   210  	case d.addPeerCh <- c:
   211  	case <-d.ctx.Done():
   212  	}
   213  }
   214  
   215  // peerRemoved updates the peer set.
   216  func (d *dialScheduler) peerRemoved(c *conn) {
   217  	select {
   218  	case d.remPeerCh <- c:
   219  	case <-d.ctx.Done():
   220  	}
   221  }
   222  
   223  // loop is the main loop of the dialer.
   224  func (d *dialScheduler) loop(it enode.Iterator) {
   225  	var (
   226  		nodesCh chan *enode.Node
   227  	)
   228  
   229  loop:
   230  	for {
   231  		// Launch new dials if slots are available.
   232  		slots := d.freeDialSlots()
   233  		slots -= d.startStaticDials(slots)
   234  		if slots > 0 {
   235  			nodesCh = d.nodesIn
   236  		} else {
   237  			nodesCh = nil
   238  		}
   239  		d.rearmHistoryTimer()
   240  		d.logStats()
   241  
   242  		select {
   243  		case node := <-nodesCh:
   244  			if err := d.checkDial(node); err != nil {
   245  				d.log.Trace("Discarding dial candidate", "id", node.ID(), "ip", node.IP(), "reason", err)
   246  			} else {
   247  				d.startDial(newDialTask(node, dynDialedConn))
   248  			}
   249  
   250  		case task := <-d.doneCh:
   251  			id := task.dest.ID()
   252  			delete(d.dialing, id)
   253  			d.updateStaticPool(id)
   254  			d.doneSinceLastLog++
   255  
   256  		case c := <-d.addPeerCh:
   257  			if c.is(dynDialedConn) || c.is(staticDialedConn) {
   258  				d.dialPeers++
   259  			}
   260  			id := c.node.ID()
   261  			d.peers[id] = struct{}{}
   262  			// Remove from static pool because the node is now connected.
   263  			task := d.static[id]
   264  			if task != nil && task.staticPoolIndex >= 0 {
   265  				d.removeFromStaticPool(task.staticPoolIndex)
   266  			}
   267  			// TODO: cancel dials to connected peers
   268  
   269  		case c := <-d.remPeerCh:
   270  			if c.is(dynDialedConn) || c.is(staticDialedConn) {
   271  				d.dialPeers--
   272  			}
   273  			delete(d.peers, c.node.ID())
   274  			d.updateStaticPool(c.node.ID())
   275  
   276  		case node := <-d.addStaticCh:
   277  			id := node.ID()
   278  			_, exists := d.static[id]
   279  			d.log.Trace("Adding static node", "id", id, "ip", node.IP(), "added", !exists)
   280  			if exists {
   281  				continue loop
   282  			}
   283  			task := newDialTask(node, staticDialedConn)
   284  			d.static[id] = task
   285  			if d.checkDial(node) == nil {
   286  				d.addToStaticPool(task)
   287  			}
   288  
   289  		case node := <-d.remStaticCh:
   290  			id := node.ID()
   291  			task := d.static[id]
   292  			d.log.Trace("Removing static node", "id", id, "ok", task != nil)
   293  			if task != nil {
   294  				delete(d.static, id)
   295  				if task.staticPoolIndex >= 0 {
   296  					d.removeFromStaticPool(task.staticPoolIndex)
   297  				}
   298  			}
   299  
   300  		case <-d.historyTimer.C():
   301  			d.expireHistory()
   302  
   303  		case <-d.ctx.Done():
   304  			it.Close()
   305  			break loop
   306  		}
   307  	}
   308  
   309  	d.historyTimer.Stop()
   310  	for range d.dialing {
   311  		<-d.doneCh
   312  	}
   313  	d.wg.Done()
   314  }
   315  
   316  // readNodes runs in its own goroutine and delivers nodes from
   317  // the input iterator to the nodesIn channel.
   318  func (d *dialScheduler) readNodes(it enode.Iterator) {
   319  	defer d.wg.Done()
   320  
   321  	for it.Next() {
   322  		select {
   323  		case d.nodesIn <- it.Node():
   324  		case <-d.ctx.Done():
   325  		}
   326  	}
   327  }
   328  
   329  // logStats prints dialer statistics to the log. The message is suppressed when enough
   330  // peers are connected because users should only see it while their client is starting up
   331  // or comes back online.
   332  func (d *dialScheduler) logStats() {
   333  	now := d.clock.Now()
   334  	if d.lastStatsLog.Add(dialStatsLogInterval) > now {
   335  		return
   336  	}
   337  	if d.dialPeers < dialStatsPeerLimit && d.dialPeers < d.maxDialPeers {
   338  		d.log.Info("Looking for peers", "peercount", len(d.peers), "tried", d.doneSinceLastLog, "static", len(d.static))
   339  	}
   340  	d.doneSinceLastLog = 0
   341  	d.lastStatsLog = now
   342  }
   343  
   344  // rearmHistoryTimer configures d.historyTimer to fire when the
   345  // next item in d.history expires.
   346  func (d *dialScheduler) rearmHistoryTimer() {
   347  	if len(d.history) == 0 {
   348  		return
   349  	}
   350  	d.historyTimer.Schedule(d.history.nextExpiry())
   351  }
   352  
   353  // expireHistory removes expired items from d.history.
   354  func (d *dialScheduler) expireHistory() {
   355  	d.history.expire(d.clock.Now(), func(hkey string) {
   356  		var id enode.ID
   357  		copy(id[:], hkey)
   358  		d.updateStaticPool(id)
   359  	})
   360  }
   361  
   362  // freeDialSlots returns the number of free dial slots. The result can be negative
   363  // when peers are connected while their task is still running.
   364  func (d *dialScheduler) freeDialSlots() int {
   365  	slots := (d.maxDialPeers - d.dialPeers) * 2
   366  	if slots > d.maxActiveDials {
   367  		slots = d.maxActiveDials
   368  	}
   369  	free := slots - len(d.dialing)
   370  	return free
   371  }
   372  
   373  // checkDial returns an error if node n should not be dialed.
   374  func (d *dialScheduler) checkDial(n *enode.Node) error {
   375  	if n.ID() == d.self {
   376  		return errSelf
   377  	}
   378  	if n.IP() != nil && n.TCP() == 0 {
   379  		// This check can trigger if a non-TCP node is found
   380  		// by discovery. If there is no IP, the node is a static
   381  		// node and the actual endpoint will be resolved later in dialTask.
   382  		return errNoPort
   383  	}
   384  	if _, ok := d.dialing[n.ID()]; ok {
   385  		return errAlreadyDialing
   386  	}
   387  	if _, ok := d.peers[n.ID()]; ok {
   388  		return errAlreadyConnected
   389  	}
   390  	if d.netRestrict != nil && !d.netRestrict.Contains(n.IP()) {
   391  		return errNetRestrict
   392  	}
   393  	if d.history.contains(string(n.ID().Bytes())) {
   394  		return errRecentlyDialed
   395  	}
   396  	return nil
   397  }
   398  
   399  // startStaticDials starts n static dial tasks.
   400  func (d *dialScheduler) startStaticDials(n int) (started int) {
   401  	for started = 0; started < n && len(d.staticPool) > 0; started++ {
   402  		idx := d.rand.Intn(len(d.staticPool))
   403  		task := d.staticPool[idx]
   404  		d.startDial(task)
   405  		d.removeFromStaticPool(idx)
   406  	}
   407  	return started
   408  }
   409  
   410  // updateStaticPool attempts to move the given static dial back into staticPool.
   411  func (d *dialScheduler) updateStaticPool(id enode.ID) {
   412  	task, ok := d.static[id]
   413  	if ok && task.staticPoolIndex < 0 && d.checkDial(task.dest) == nil {
   414  		d.addToStaticPool(task)
   415  	}
   416  }
   417  
   418  func (d *dialScheduler) addToStaticPool(task *dialTask) {
   419  	if task.staticPoolIndex >= 0 {
   420  		panic("attempt to add task to staticPool twice")
   421  	}
   422  	d.staticPool = append(d.staticPool, task)
   423  	task.staticPoolIndex = len(d.staticPool) - 1
   424  }
   425  
   426  // removeFromStaticPool removes the task at idx from staticPool. It does that by moving the
   427  // current last element of the pool to idx and then shortening the pool by one.
   428  func (d *dialScheduler) removeFromStaticPool(idx int) {
   429  	task := d.staticPool[idx]
   430  	end := len(d.staticPool) - 1
   431  	d.staticPool[idx] = d.staticPool[end]
   432  	d.staticPool[idx].staticPoolIndex = idx
   433  	d.staticPool[end] = nil
   434  	d.staticPool = d.staticPool[:end]
   435  	task.staticPoolIndex = -1
   436  }
   437  
   438  // startDial runs the given dial task in a separate goroutine.
   439  func (d *dialScheduler) startDial(task *dialTask) {
   440  	d.log.Trace("Starting p2p dial", "id", task.dest.ID(), "ip", task.dest.IP(), "flag", task.flags)
   441  	hkey := string(task.dest.ID().Bytes())
   442  	d.history.add(hkey, d.clock.Now().Add(dialHistoryExpiration))
   443  	d.dialing[task.dest.ID()] = task
   444  	go func() {
   445  		task.run(d)
   446  		d.doneCh <- task
   447  	}()
   448  }
   449  
   450  // A dialTask generated for each node that is dialed.
   451  type dialTask struct {
   452  	staticPoolIndex int
   453  	flags           connFlag
   454  	// These fields are private to the task and should not be
   455  	// accessed by dialScheduler while the task is running.
   456  	dest         *enode.Node
   457  	lastResolved mclock.AbsTime
   458  	resolveDelay time.Duration
   459  }
   460  
   461  func newDialTask(dest *enode.Node, flags connFlag) *dialTask {
   462  	return &dialTask{dest: dest, flags: flags, staticPoolIndex: -1}
   463  }
   464  
   465  type dialError struct {
   466  	error
   467  }
   468  
   469  func (t *dialTask) run(d *dialScheduler) {
   470  	if t.needResolve() && !t.resolve(d) {
   471  		return
   472  	}
   473  
   474  	err := t.dial(d, t.dest)
   475  	if err != nil {
   476  		// For static nodes, resolve one more time if dialing fails.
   477  		if _, ok := err.(*dialError); ok && t.flags&staticDialedConn != 0 {
   478  			if t.resolve(d) {
   479  				t.dial(d, t.dest)
   480  			}
   481  		}
   482  	}
   483  }
   484  
   485  func (t *dialTask) needResolve() bool {
   486  	return t.flags&staticDialedConn != 0 && t.dest.IP() == nil
   487  }
   488  
   489  // resolve attempts to find the current endpoint for the destination
   490  // using discovery.
   491  //
   492  // Resolve operations are throttled with backoff to avoid flooding the
   493  // discovery network with useless queries for nodes that don't exist.
   494  // The backoff delay resets when the node is found.
   495  func (t *dialTask) resolve(d *dialScheduler) bool {
   496  	if d.resolver == nil {
   497  		return false
   498  	}
   499  	if t.resolveDelay == 0 {
   500  		t.resolveDelay = initialResolveDelay
   501  	}
   502  	if t.lastResolved > 0 && time.Duration(d.clock.Now()-t.lastResolved) < t.resolveDelay {
   503  		return false
   504  	}
   505  	resolved := d.resolver.Resolve(t.dest)
   506  	t.lastResolved = d.clock.Now()
   507  	if resolved == nil {
   508  		t.resolveDelay *= 2
   509  		if t.resolveDelay > maxResolveDelay {
   510  			t.resolveDelay = maxResolveDelay
   511  		}
   512  		d.log.Debug("Resolving node failed", "id", t.dest.ID(), "newdelay", t.resolveDelay)
   513  		return false
   514  	}
   515  	// The node was found.
   516  	t.resolveDelay = initialResolveDelay
   517  	t.dest = resolved
   518  	d.log.Debug("Resolved node", "id", t.dest.ID(), "addr", &net.TCPAddr{IP: t.dest.IP(), Port: t.dest.TCP()})
   519  	return true
   520  }
   521  
   522  // dial performs the actual connection attempt.
   523  func (t *dialTask) dial(d *dialScheduler, dest *enode.Node) error {
   524  	fd, err := d.dialer.Dial(d.ctx, t.dest)
   525  	if err != nil {
   526  		d.log.Trace("Dial error", "id", t.dest.ID(), "addr", nodeAddr(t.dest), "conn", t.flags, "err", cleanupDialErr(err))
   527  		return &dialError{err}
   528  	}
   529  	mfd := newMeteredConn(fd, false, &net.TCPAddr{IP: dest.IP(), Port: dest.TCP()})
   530  	return d.setupFunc(mfd, t.flags, dest)
   531  }
   532  
   533  func (t *dialTask) String() string {
   534  	id := t.dest.ID()
   535  	return fmt.Sprintf("%v %x %v:%d", t.flags, id[:8], t.dest.IP(), t.dest.TCP())
   536  }
   537  
   538  func cleanupDialErr(err error) error {
   539  	if netErr, ok := err.(*net.OpError); ok && netErr.Op == "dial" {
   540  		return netErr.Err
   541  	}
   542  	return err
   543  }