github.com/phillinzzz/newBsc@v1.1.6/p2p/discover/v4_udp.go (about)

     1  // Copyright 2019 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 discover
    18  
    19  import (
    20  	"bytes"
    21  	"container/list"
    22  	"context"
    23  	"crypto/ecdsa"
    24  	crand "crypto/rand"
    25  	"errors"
    26  	"fmt"
    27  	"io"
    28  	"net"
    29  	"sync"
    30  	"time"
    31  
    32  	"github.com/phillinzzz/newBsc/common/gopool"
    33  	"github.com/phillinzzz/newBsc/crypto"
    34  	"github.com/phillinzzz/newBsc/log"
    35  	"github.com/phillinzzz/newBsc/p2p/discover/v4wire"
    36  	"github.com/phillinzzz/newBsc/p2p/enode"
    37  	"github.com/phillinzzz/newBsc/p2p/netutil"
    38  	"github.com/phillinzzz/newBsc/rlp"
    39  )
    40  
    41  // Errors
    42  var (
    43  	errExpired          = errors.New("expired")
    44  	errUnsolicitedReply = errors.New("unsolicited reply")
    45  	errUnknownNode      = errors.New("unknown node")
    46  	errTimeout          = errors.New("RPC timeout")
    47  	errClockWarp        = errors.New("reply deadline too far in the future")
    48  	errClosed           = errors.New("socket closed")
    49  	errLowPort          = errors.New("low port")
    50  )
    51  
    52  const (
    53  	respTimeout    = 500 * time.Millisecond
    54  	expiration     = 20 * time.Second
    55  	bondExpiration = 24 * time.Hour
    56  
    57  	maxFindnodeFailures = 5                // nodes exceeding this limit are dropped
    58  	ntpFailureThreshold = 32               // Continuous timeouts after which to check NTP
    59  	ntpWarningCooldown  = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
    60  	driftThreshold      = 10 * time.Second // Allowed clock drift before warning user
    61  
    62  	// Discovery packets are defined to be no larger than 1280 bytes.
    63  	// Packets larger than this size will be cut at the end and treated
    64  	// as invalid because their hash won't match.
    65  	maxPacketSize = 1280
    66  )
    67  
    68  // UDPv4 implements the v4 wire protocol.
    69  type UDPv4 struct {
    70  	conn        UDPConn
    71  	log         log.Logger
    72  	netrestrict *netutil.Netlist
    73  	priv        *ecdsa.PrivateKey
    74  	localNode   *enode.LocalNode
    75  	db          *enode.DB
    76  	tab         *Table
    77  	closeOnce   sync.Once
    78  	wg          sync.WaitGroup
    79  
    80  	addReplyMatcher chan *replyMatcher
    81  	gotreply        chan reply
    82  	closeCtx        context.Context
    83  	cancelCloseCtx  context.CancelFunc
    84  }
    85  
    86  // replyMatcher represents a pending reply.
    87  //
    88  // Some implementations of the protocol wish to send more than one
    89  // reply packet to findnode. In general, any neighbors packet cannot
    90  // be matched up with a specific findnode packet.
    91  //
    92  // Our implementation handles this by storing a callback function for
    93  // each pending reply. Incoming packets from a node are dispatched
    94  // to all callback functions for that node.
    95  type replyMatcher struct {
    96  	// these fields must match in the reply.
    97  	from  enode.ID
    98  	ip    net.IP
    99  	ptype byte
   100  
   101  	// time when the request must complete
   102  	deadline time.Time
   103  
   104  	// callback is called when a matching reply arrives. If it returns matched == true, the
   105  	// reply was acceptable. The second return value indicates whether the callback should
   106  	// be removed from the pending reply queue. If it returns false, the reply is considered
   107  	// incomplete and the callback will be invoked again for the next matching reply.
   108  	callback replyMatchFunc
   109  
   110  	// errc receives nil when the callback indicates completion or an
   111  	// error if no further reply is received within the timeout.
   112  	errc chan error
   113  
   114  	// reply contains the most recent reply. This field is safe for reading after errc has
   115  	// received a value.
   116  	reply v4wire.Packet
   117  }
   118  
   119  type replyMatchFunc func(v4wire.Packet) (matched bool, requestDone bool)
   120  
   121  // reply is a reply packet from a certain node.
   122  type reply struct {
   123  	from enode.ID
   124  	ip   net.IP
   125  	data v4wire.Packet
   126  	// loop indicates whether there was
   127  	// a matching request by sending on this channel.
   128  	matched chan<- bool
   129  }
   130  
   131  func ListenV4(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) {
   132  	cfg = cfg.withDefaults()
   133  	closeCtx, cancel := context.WithCancel(context.Background())
   134  	t := &UDPv4{
   135  		conn:            c,
   136  		priv:            cfg.PrivateKey,
   137  		netrestrict:     cfg.NetRestrict,
   138  		localNode:       ln,
   139  		db:              ln.Database(),
   140  		gotreply:        make(chan reply),
   141  		addReplyMatcher: make(chan *replyMatcher),
   142  		closeCtx:        closeCtx,
   143  		cancelCloseCtx:  cancel,
   144  		log:             cfg.Log,
   145  	}
   146  
   147  	tab, err := newTable(t, ln.Database(), cfg.Bootnodes, t.log)
   148  	if err != nil {
   149  		return nil, err
   150  	}
   151  	t.tab = tab
   152  	go tab.loop()
   153  
   154  	t.wg.Add(2)
   155  	go t.loop()
   156  	go t.readLoop(cfg.Unhandled)
   157  	return t, nil
   158  }
   159  
   160  // Self returns the local node.
   161  func (t *UDPv4) Self() *enode.Node {
   162  	return t.localNode.Node()
   163  }
   164  
   165  // Close shuts down the socket and aborts any running queries.
   166  func (t *UDPv4) Close() {
   167  	t.closeOnce.Do(func() {
   168  		t.cancelCloseCtx()
   169  		t.conn.Close()
   170  		t.wg.Wait()
   171  		t.tab.close()
   172  	})
   173  }
   174  
   175  // Resolve searches for a specific node with the given ID and tries to get the most recent
   176  // version of the node record for it. It returns n if the node could not be resolved.
   177  func (t *UDPv4) Resolve(n *enode.Node) *enode.Node {
   178  	// Try asking directly. This works if the node is still responding on the endpoint we have.
   179  	if rn, err := t.RequestENR(n); err == nil {
   180  		return rn
   181  	}
   182  	// Check table for the ID, we might have a newer version there.
   183  	if intable := t.tab.getNode(n.ID()); intable != nil && intable.Seq() > n.Seq() {
   184  		n = intable
   185  		if rn, err := t.RequestENR(n); err == nil {
   186  			return rn
   187  		}
   188  	}
   189  	// Otherwise perform a network lookup.
   190  	var key enode.Secp256k1
   191  	if n.Load(&key) != nil {
   192  		return n // no secp256k1 key
   193  	}
   194  	result := t.LookupPubkey((*ecdsa.PublicKey)(&key))
   195  	for _, rn := range result {
   196  		if rn.ID() == n.ID() {
   197  			if rn, err := t.RequestENR(rn); err == nil {
   198  				return rn
   199  			}
   200  		}
   201  	}
   202  	return n
   203  }
   204  
   205  func (t *UDPv4) ourEndpoint() v4wire.Endpoint {
   206  	n := t.Self()
   207  	a := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
   208  	return v4wire.NewEndpoint(a, uint16(n.TCP()))
   209  }
   210  
   211  // Ping sends a ping message to the given node.
   212  func (t *UDPv4) Ping(n *enode.Node) error {
   213  	_, err := t.ping(n)
   214  	return err
   215  }
   216  
   217  // ping sends a ping message to the given node and waits for a reply.
   218  func (t *UDPv4) ping(n *enode.Node) (seq uint64, err error) {
   219  	rm := t.sendPing(n.ID(), &net.UDPAddr{IP: n.IP(), Port: n.UDP()}, nil)
   220  	if err = <-rm.errc; err == nil {
   221  		seq = rm.reply.(*v4wire.Pong).ENRSeq()
   222  	}
   223  	return seq, err
   224  }
   225  
   226  // sendPing sends a ping message to the given node and invokes the callback
   227  // when the reply arrives.
   228  func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) *replyMatcher {
   229  	req := t.makePing(toaddr)
   230  	packet, hash, err := v4wire.Encode(t.priv, req)
   231  	if err != nil {
   232  		errc := make(chan error, 1)
   233  		errc <- err
   234  		return &replyMatcher{errc: errc}
   235  	}
   236  	// Add a matcher for the reply to the pending reply queue. Pongs are matched if they
   237  	// reference the ping we're about to send.
   238  	rm := t.pending(toid, toaddr.IP, v4wire.PongPacket, func(p v4wire.Packet) (matched bool, requestDone bool) {
   239  		matched = bytes.Equal(p.(*v4wire.Pong).ReplyTok, hash)
   240  		if matched && callback != nil {
   241  			callback()
   242  		}
   243  		return matched, matched
   244  	})
   245  	// Send the packet.
   246  	t.localNode.UDPContact(toaddr)
   247  	t.write(toaddr, toid, req.Name(), packet)
   248  	return rm
   249  }
   250  
   251  func (t *UDPv4) makePing(toaddr *net.UDPAddr) *v4wire.Ping {
   252  	seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
   253  	return &v4wire.Ping{
   254  		Version:    4,
   255  		From:       t.ourEndpoint(),
   256  		To:         v4wire.NewEndpoint(toaddr, 0),
   257  		Expiration: uint64(time.Now().Add(expiration).Unix()),
   258  		Rest:       []rlp.RawValue{seq},
   259  	}
   260  }
   261  
   262  // LookupPubkey finds the closest nodes to the given public key.
   263  func (t *UDPv4) LookupPubkey(key *ecdsa.PublicKey) []*enode.Node {
   264  	if t.tab.len() == 0 {
   265  		// All nodes were dropped, refresh. The very first query will hit this
   266  		// case and run the bootstrapping logic.
   267  		<-t.tab.refresh()
   268  	}
   269  	return t.newLookup(t.closeCtx, encodePubkey(key)).run()
   270  }
   271  
   272  // RandomNodes is an iterator yielding nodes from a random walk of the DHT.
   273  func (t *UDPv4) RandomNodes() enode.Iterator {
   274  	return newLookupIterator(t.closeCtx, t.newRandomLookup)
   275  }
   276  
   277  // lookupRandom implements transport.
   278  func (t *UDPv4) lookupRandom() []*enode.Node {
   279  	return t.newRandomLookup(t.closeCtx).run()
   280  }
   281  
   282  // lookupSelf implements transport.
   283  func (t *UDPv4) lookupSelf() []*enode.Node {
   284  	return t.newLookup(t.closeCtx, encodePubkey(&t.priv.PublicKey)).run()
   285  }
   286  
   287  func (t *UDPv4) newRandomLookup(ctx context.Context) *lookup {
   288  	var target encPubkey
   289  	crand.Read(target[:])
   290  	return t.newLookup(ctx, target)
   291  }
   292  
   293  func (t *UDPv4) newLookup(ctx context.Context, targetKey encPubkey) *lookup {
   294  	target := enode.ID(crypto.Keccak256Hash(targetKey[:]))
   295  	ekey := v4wire.Pubkey(targetKey)
   296  	it := newLookup(ctx, t.tab, target, func(n *node) ([]*node, error) {
   297  		return t.findnode(n.ID(), n.addr(), ekey)
   298  	})
   299  	return it
   300  }
   301  
   302  // findnode sends a findnode request to the given node and waits until
   303  // the node has sent up to k neighbors.
   304  func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target v4wire.Pubkey) ([]*node, error) {
   305  	t.ensureBond(toid, toaddr)
   306  
   307  	// Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
   308  	// active until enough nodes have been received.
   309  	nodes := make([]*node, 0, bucketSize)
   310  	nreceived := 0
   311  	rm := t.pending(toid, toaddr.IP, v4wire.NeighborsPacket, func(r v4wire.Packet) (matched bool, requestDone bool) {
   312  		reply := r.(*v4wire.Neighbors)
   313  		for _, rn := range reply.Nodes {
   314  			nreceived++
   315  			n, err := t.nodeFromRPC(toaddr, rn)
   316  			if err != nil {
   317  				t.log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
   318  				continue
   319  			}
   320  			nodes = append(nodes, n)
   321  		}
   322  		return true, nreceived >= bucketSize
   323  	})
   324  	t.send(toaddr, toid, &v4wire.Findnode{
   325  		Target:     target,
   326  		Expiration: uint64(time.Now().Add(expiration).Unix()),
   327  	})
   328  	// Ensure that callers don't see a timeout if the node actually responded. Since
   329  	// findnode can receive more than one neighbors response, the reply matcher will be
   330  	// active until the remote node sends enough nodes. If the remote end doesn't have
   331  	// enough nodes the reply matcher will time out waiting for the second reply, but
   332  	// there's no need for an error in that case.
   333  	err := <-rm.errc
   334  	if err == errTimeout && rm.reply != nil {
   335  		err = nil
   336  	}
   337  	return nodes, err
   338  }
   339  
   340  // RequestENR sends enrRequest to the given node and waits for a response.
   341  func (t *UDPv4) RequestENR(n *enode.Node) (*enode.Node, error) {
   342  	addr := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
   343  	t.ensureBond(n.ID(), addr)
   344  
   345  	req := &v4wire.ENRRequest{
   346  		Expiration: uint64(time.Now().Add(expiration).Unix()),
   347  	}
   348  	packet, hash, err := v4wire.Encode(t.priv, req)
   349  	if err != nil {
   350  		return nil, err
   351  	}
   352  
   353  	// Add a matcher for the reply to the pending reply queue. Responses are matched if
   354  	// they reference the request we're about to send.
   355  	rm := t.pending(n.ID(), addr.IP, v4wire.ENRResponsePacket, func(r v4wire.Packet) (matched bool, requestDone bool) {
   356  		matched = bytes.Equal(r.(*v4wire.ENRResponse).ReplyTok, hash)
   357  		return matched, matched
   358  	})
   359  	// Send the packet and wait for the reply.
   360  	t.write(addr, n.ID(), req.Name(), packet)
   361  	if err := <-rm.errc; err != nil {
   362  		return nil, err
   363  	}
   364  	// Verify the response record.
   365  	respN, err := enode.New(enode.ValidSchemes, &rm.reply.(*v4wire.ENRResponse).Record)
   366  	if err != nil {
   367  		return nil, err
   368  	}
   369  	if respN.ID() != n.ID() {
   370  		return nil, fmt.Errorf("invalid ID in response record")
   371  	}
   372  	if respN.Seq() < n.Seq() {
   373  		return n, nil // response record is older
   374  	}
   375  	if err := netutil.CheckRelayIP(addr.IP, respN.IP()); err != nil {
   376  		return nil, fmt.Errorf("invalid IP in response record: %v", err)
   377  	}
   378  	return respN, nil
   379  }
   380  
   381  // pending adds a reply matcher to the pending reply queue.
   382  // see the documentation of type replyMatcher for a detailed explanation.
   383  func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) *replyMatcher {
   384  	ch := make(chan error, 1)
   385  	p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch}
   386  	select {
   387  	case t.addReplyMatcher <- p:
   388  		// loop will handle it
   389  	case <-t.closeCtx.Done():
   390  		ch <- errClosed
   391  	}
   392  	return p
   393  }
   394  
   395  // handleReply dispatches a reply packet, invoking reply matchers. It returns
   396  // whether any matcher considered the packet acceptable.
   397  func (t *UDPv4) handleReply(from enode.ID, fromIP net.IP, req v4wire.Packet) bool {
   398  	matched := make(chan bool, 1)
   399  	select {
   400  	case t.gotreply <- reply{from, fromIP, req, matched}:
   401  		// loop will handle it
   402  		return <-matched
   403  	case <-t.closeCtx.Done():
   404  		return false
   405  	}
   406  }
   407  
   408  // loop runs in its own goroutine. it keeps track of
   409  // the refresh timer and the pending reply queue.
   410  func (t *UDPv4) loop() {
   411  	defer t.wg.Done()
   412  
   413  	var (
   414  		plist        = list.New()
   415  		timeout      = time.NewTimer(0)
   416  		nextTimeout  *replyMatcher // head of plist when timeout was last reset
   417  		contTimeouts = 0           // number of continuous timeouts to do NTP checks
   418  		ntpWarnTime  = time.Unix(0, 0)
   419  	)
   420  	<-timeout.C // ignore first timeout
   421  	defer timeout.Stop()
   422  
   423  	resetTimeout := func() {
   424  		if plist.Front() == nil || nextTimeout == plist.Front().Value {
   425  			return
   426  		}
   427  		// Start the timer so it fires when the next pending reply has expired.
   428  		now := time.Now()
   429  		for el := plist.Front(); el != nil; el = el.Next() {
   430  			nextTimeout = el.Value.(*replyMatcher)
   431  			if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
   432  				timeout.Reset(dist)
   433  				return
   434  			}
   435  			// Remove pending replies whose deadline is too far in the
   436  			// future. These can occur if the system clock jumped
   437  			// backwards after the deadline was assigned.
   438  			nextTimeout.errc <- errClockWarp
   439  			plist.Remove(el)
   440  		}
   441  		nextTimeout = nil
   442  		timeout.Stop()
   443  	}
   444  
   445  	for {
   446  		resetTimeout()
   447  
   448  		select {
   449  		case <-t.closeCtx.Done():
   450  			for el := plist.Front(); el != nil; el = el.Next() {
   451  				el.Value.(*replyMatcher).errc <- errClosed
   452  			}
   453  			return
   454  
   455  		case p := <-t.addReplyMatcher:
   456  			p.deadline = time.Now().Add(respTimeout)
   457  			plist.PushBack(p)
   458  
   459  		case r := <-t.gotreply:
   460  			var matched bool // whether any replyMatcher considered the reply acceptable.
   461  			for el := plist.Front(); el != nil; el = el.Next() {
   462  				p := el.Value.(*replyMatcher)
   463  				if p.from == r.from && p.ptype == r.data.Kind() && p.ip.Equal(r.ip) {
   464  					ok, requestDone := p.callback(r.data)
   465  					matched = matched || ok
   466  					p.reply = r.data
   467  					// Remove the matcher if callback indicates that all replies have been received.
   468  					if requestDone {
   469  						p.errc <- nil
   470  						plist.Remove(el)
   471  					}
   472  					// Reset the continuous timeout counter (time drift detection)
   473  					contTimeouts = 0
   474  				}
   475  			}
   476  			r.matched <- matched
   477  
   478  		case now := <-timeout.C:
   479  			nextTimeout = nil
   480  
   481  			// Notify and remove callbacks whose deadline is in the past.
   482  			for el := plist.Front(); el != nil; el = el.Next() {
   483  				p := el.Value.(*replyMatcher)
   484  				if now.After(p.deadline) || now.Equal(p.deadline) {
   485  					p.errc <- errTimeout
   486  					plist.Remove(el)
   487  					contTimeouts++
   488  				}
   489  			}
   490  			// If we've accumulated too many timeouts, do an NTP time sync check
   491  			if contTimeouts > ntpFailureThreshold {
   492  				if time.Since(ntpWarnTime) >= ntpWarningCooldown {
   493  					ntpWarnTime = time.Now()
   494  					gopool.Submit(func() {
   495  						checkClockDrift()
   496  					})
   497  				}
   498  				contTimeouts = 0
   499  			}
   500  		}
   501  	}
   502  }
   503  
   504  func (t *UDPv4) send(toaddr *net.UDPAddr, toid enode.ID, req v4wire.Packet) ([]byte, error) {
   505  	packet, hash, err := v4wire.Encode(t.priv, req)
   506  	if err != nil {
   507  		return hash, err
   508  	}
   509  	return hash, t.write(toaddr, toid, req.Name(), packet)
   510  }
   511  
   512  func (t *UDPv4) write(toaddr *net.UDPAddr, toid enode.ID, what string, packet []byte) error {
   513  	_, err := t.conn.WriteToUDP(packet, toaddr)
   514  	t.log.Trace(">> "+what, "id", toid, "addr", toaddr, "err", err)
   515  	return err
   516  }
   517  
   518  // readLoop runs in its own goroutine. it handles incoming UDP packets.
   519  func (t *UDPv4) readLoop(unhandled chan<- ReadPacket) {
   520  	defer t.wg.Done()
   521  	if unhandled != nil {
   522  		defer close(unhandled)
   523  	}
   524  
   525  	buf := make([]byte, maxPacketSize)
   526  	for {
   527  		nbytes, from, err := t.conn.ReadFromUDP(buf)
   528  		if netutil.IsTemporaryError(err) {
   529  			// Ignore temporary read errors.
   530  			t.log.Debug("Temporary UDP read error", "err", err)
   531  			continue
   532  		} else if err != nil {
   533  			// Shut down the loop for permament errors.
   534  			if err != io.EOF {
   535  				t.log.Debug("UDP read error", "err", err)
   536  			}
   537  			return
   538  		}
   539  		if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil {
   540  			select {
   541  			case unhandled <- ReadPacket{buf[:nbytes], from}:
   542  			default:
   543  			}
   544  		}
   545  	}
   546  }
   547  
   548  func (t *UDPv4) handlePacket(from *net.UDPAddr, buf []byte) error {
   549  	rawpacket, fromKey, hash, err := v4wire.Decode(buf)
   550  	if err != nil {
   551  		t.log.Debug("Bad discv4 packet", "addr", from, "err", err)
   552  		return err
   553  	}
   554  	packet := t.wrapPacket(rawpacket)
   555  	fromID := fromKey.ID()
   556  	if err == nil && packet.preverify != nil {
   557  		err = packet.preverify(packet, from, fromID, fromKey)
   558  	}
   559  	t.log.Trace("<< "+packet.Name(), "id", fromID, "addr", from, "err", err)
   560  	if err == nil && packet.handle != nil {
   561  		packet.handle(packet, from, fromID, hash)
   562  	}
   563  	return err
   564  }
   565  
   566  // checkBond checks if the given node has a recent enough endpoint proof.
   567  func (t *UDPv4) checkBond(id enode.ID, ip net.IP) bool {
   568  	return time.Since(t.db.LastPongReceived(id, ip)) < bondExpiration
   569  }
   570  
   571  // ensureBond solicits a ping from a node if we haven't seen a ping from it for a while.
   572  // This ensures there is a valid endpoint proof on the remote end.
   573  func (t *UDPv4) ensureBond(toid enode.ID, toaddr *net.UDPAddr) {
   574  	tooOld := time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration
   575  	if tooOld || t.db.FindFails(toid, toaddr.IP) > maxFindnodeFailures {
   576  		rm := t.sendPing(toid, toaddr, nil)
   577  		<-rm.errc
   578  		// Wait for them to ping back and process our pong.
   579  		time.Sleep(respTimeout)
   580  	}
   581  }
   582  
   583  func (t *UDPv4) nodeFromRPC(sender *net.UDPAddr, rn v4wire.Node) (*node, error) {
   584  	if rn.UDP <= 1024 {
   585  		return nil, errLowPort
   586  	}
   587  	if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
   588  		return nil, err
   589  	}
   590  	if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) {
   591  		return nil, errors.New("not contained in netrestrict whitelist")
   592  	}
   593  	key, err := v4wire.DecodePubkey(crypto.S256(), rn.ID)
   594  	if err != nil {
   595  		return nil, err
   596  	}
   597  	n := wrapNode(enode.NewV4(key, rn.IP, int(rn.TCP), int(rn.UDP)))
   598  	err = n.ValidateComplete()
   599  	return n, err
   600  }
   601  
   602  func nodeToRPC(n *node) v4wire.Node {
   603  	var key ecdsa.PublicKey
   604  	var ekey v4wire.Pubkey
   605  	if err := n.Load((*enode.Secp256k1)(&key)); err == nil {
   606  		ekey = v4wire.EncodePubkey(&key)
   607  	}
   608  	return v4wire.Node{ID: ekey, IP: n.IP(), UDP: uint16(n.UDP()), TCP: uint16(n.TCP())}
   609  }
   610  
   611  // wrapPacket returns the handler functions applicable to a packet.
   612  func (t *UDPv4) wrapPacket(p v4wire.Packet) *packetHandlerV4 {
   613  	var h packetHandlerV4
   614  	h.Packet = p
   615  	switch p.(type) {
   616  	case *v4wire.Ping:
   617  		h.preverify = t.verifyPing
   618  		h.handle = t.handlePing
   619  	case *v4wire.Pong:
   620  		h.preverify = t.verifyPong
   621  	case *v4wire.Findnode:
   622  		h.preverify = t.verifyFindnode
   623  		h.handle = t.handleFindnode
   624  	case *v4wire.Neighbors:
   625  		h.preverify = t.verifyNeighbors
   626  	case *v4wire.ENRRequest:
   627  		h.preverify = t.verifyENRRequest
   628  		h.handle = t.handleENRRequest
   629  	case *v4wire.ENRResponse:
   630  		h.preverify = t.verifyENRResponse
   631  	}
   632  	return &h
   633  }
   634  
   635  // packetHandlerV4 wraps a packet with handler functions.
   636  type packetHandlerV4 struct {
   637  	v4wire.Packet
   638  	senderKey *ecdsa.PublicKey // used for ping
   639  
   640  	// preverify checks whether the packet is valid and should be handled at all.
   641  	preverify func(p *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error
   642  	// handle handles the packet.
   643  	handle func(req *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte)
   644  }
   645  
   646  // PING/v4
   647  
   648  func (t *UDPv4) verifyPing(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
   649  	req := h.Packet.(*v4wire.Ping)
   650  
   651  	senderKey, err := v4wire.DecodePubkey(crypto.S256(), fromKey)
   652  	if err != nil {
   653  		return err
   654  	}
   655  	if v4wire.Expired(req.Expiration) {
   656  		return errExpired
   657  	}
   658  	h.senderKey = senderKey
   659  	return nil
   660  }
   661  
   662  func (t *UDPv4) handlePing(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
   663  	req := h.Packet.(*v4wire.Ping)
   664  
   665  	// Reply.
   666  	seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
   667  	t.send(from, fromID, &v4wire.Pong{
   668  		To:         v4wire.NewEndpoint(from, req.From.TCP),
   669  		ReplyTok:   mac,
   670  		Expiration: uint64(time.Now().Add(expiration).Unix()),
   671  		Rest:       []rlp.RawValue{seq},
   672  	})
   673  
   674  	// Ping back if our last pong on file is too far in the past.
   675  	n := wrapNode(enode.NewV4(h.senderKey, from.IP, int(req.From.TCP), from.Port))
   676  	if time.Since(t.db.LastPongReceived(n.ID(), from.IP)) > bondExpiration {
   677  		t.sendPing(fromID, from, func() {
   678  			t.tab.addVerifiedNode(n)
   679  		})
   680  	} else {
   681  		t.tab.addVerifiedNode(n)
   682  	}
   683  
   684  	// Update node database and endpoint predictor.
   685  	t.db.UpdateLastPingReceived(n.ID(), from.IP, time.Now())
   686  	t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
   687  }
   688  
   689  // PONG/v4
   690  
   691  func (t *UDPv4) verifyPong(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
   692  	req := h.Packet.(*v4wire.Pong)
   693  
   694  	if v4wire.Expired(req.Expiration) {
   695  		return errExpired
   696  	}
   697  	if !t.handleReply(fromID, from.IP, req) {
   698  		return errUnsolicitedReply
   699  	}
   700  	t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
   701  	t.db.UpdateLastPongReceived(fromID, from.IP, time.Now())
   702  	return nil
   703  }
   704  
   705  // FINDNODE/v4
   706  
   707  func (t *UDPv4) verifyFindnode(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
   708  	req := h.Packet.(*v4wire.Findnode)
   709  
   710  	if v4wire.Expired(req.Expiration) {
   711  		return errExpired
   712  	}
   713  	if !t.checkBond(fromID, from.IP) {
   714  		// No endpoint proof pong exists, we don't process the packet. This prevents an
   715  		// attack vector where the discovery protocol could be used to amplify traffic in a
   716  		// DDOS attack. A malicious actor would send a findnode request with the IP address
   717  		// and UDP port of the target as the source address. The recipient of the findnode
   718  		// packet would then send a neighbors packet (which is a much bigger packet than
   719  		// findnode) to the victim.
   720  		return errUnknownNode
   721  	}
   722  	return nil
   723  }
   724  
   725  func (t *UDPv4) handleFindnode(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
   726  	req := h.Packet.(*v4wire.Findnode)
   727  
   728  	// Determine closest nodes.
   729  	target := enode.ID(crypto.Keccak256Hash(req.Target[:]))
   730  	closest := t.tab.findnodeByID(target, bucketSize, true).entries
   731  
   732  	// Send neighbors in chunks with at most maxNeighbors per packet
   733  	// to stay below the packet size limit.
   734  	p := v4wire.Neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
   735  	var sent bool
   736  	for _, n := range closest {
   737  		if netutil.CheckRelayIP(from.IP, n.IP()) == nil {
   738  			p.Nodes = append(p.Nodes, nodeToRPC(n))
   739  		}
   740  		if len(p.Nodes) == v4wire.MaxNeighbors {
   741  			t.send(from, fromID, &p)
   742  			p.Nodes = p.Nodes[:0]
   743  			sent = true
   744  		}
   745  	}
   746  	if len(p.Nodes) > 0 || !sent {
   747  		t.send(from, fromID, &p)
   748  	}
   749  }
   750  
   751  // NEIGHBORS/v4
   752  
   753  func (t *UDPv4) verifyNeighbors(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
   754  	req := h.Packet.(*v4wire.Neighbors)
   755  
   756  	if v4wire.Expired(req.Expiration) {
   757  		return errExpired
   758  	}
   759  	if !t.handleReply(fromID, from.IP, h.Packet) {
   760  		return errUnsolicitedReply
   761  	}
   762  	return nil
   763  }
   764  
   765  // ENRREQUEST/v4
   766  
   767  func (t *UDPv4) verifyENRRequest(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
   768  	req := h.Packet.(*v4wire.ENRRequest)
   769  
   770  	if v4wire.Expired(req.Expiration) {
   771  		return errExpired
   772  	}
   773  	if !t.checkBond(fromID, from.IP) {
   774  		return errUnknownNode
   775  	}
   776  	return nil
   777  }
   778  
   779  func (t *UDPv4) handleENRRequest(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
   780  	t.send(from, fromID, &v4wire.ENRResponse{
   781  		ReplyTok: mac,
   782  		Record:   *t.localNode.Node().Record(),
   783  	})
   784  }
   785  
   786  // ENRRESPONSE/v4
   787  
   788  func (t *UDPv4) verifyENRResponse(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
   789  	if !t.handleReply(fromID, from.IP, h.Packet) {
   790  		return errUnsolicitedReply
   791  	}
   792  	return nil
   793  }