github.com/core-coin/go-core/v2@v2.1.9/p2p/discover/v4_udp.go (about)

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