github.com/daeglee/go-ethereum@v0.0.0-20190504220456-cad3e8d18e9b/p2p/discover/udp.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 discover
    18  
    19  import (
    20  	"bytes"
    21  	"container/list"
    22  	"crypto/ecdsa"
    23  	"errors"
    24  	"fmt"
    25  	"net"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"github.com/ethereum/go-ethereum/p2p/enode"
    32  	"github.com/ethereum/go-ethereum/p2p/netutil"
    33  	"github.com/ethereum/go-ethereum/rlp"
    34  )
    35  
    36  // Errors
    37  var (
    38  	errPacketTooSmall   = errors.New("too small")
    39  	errBadHash          = errors.New("bad hash")
    40  	errExpired          = errors.New("expired")
    41  	errUnsolicitedReply = errors.New("unsolicited reply")
    42  	errUnknownNode      = errors.New("unknown node")
    43  	errTimeout          = errors.New("RPC timeout")
    44  	errClockWarp        = errors.New("reply deadline too far in the future")
    45  	errClosed           = errors.New("socket closed")
    46  )
    47  
    48  // Timeouts
    49  const (
    50  	respTimeout    = 500 * time.Millisecond
    51  	expiration     = 20 * time.Second
    52  	bondExpiration = 24 * time.Hour
    53  
    54  	ntpFailureThreshold = 32               // Continuous timeouts after which to check NTP
    55  	ntpWarningCooldown  = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
    56  	driftThreshold      = 10 * time.Second // Allowed clock drift before warning user
    57  
    58  	// Discovery packets are defined to be no larger than 1280 bytes.
    59  	// Packets larger than this size will be cut at the end and treated
    60  	// as invalid because their hash won't match.
    61  	maxPacketSize = 1280
    62  )
    63  
    64  // RPC packet types
    65  const (
    66  	pingPacket = iota + 1 // zero is 'reserved'
    67  	pongPacket
    68  	findnodePacket
    69  	neighborsPacket
    70  )
    71  
    72  // RPC request structures
    73  type (
    74  	ping struct {
    75  		senderKey *ecdsa.PublicKey // filled in by preverify
    76  
    77  		Version    uint
    78  		From, To   rpcEndpoint
    79  		Expiration uint64
    80  		// Ignore additional fields (for forward compatibility).
    81  		Rest []rlp.RawValue `rlp:"tail"`
    82  	}
    83  
    84  	// pong is the reply to ping.
    85  	pong struct {
    86  		// This field should mirror the UDP envelope address
    87  		// of the ping packet, which provides a way to discover the
    88  		// the external address (after NAT).
    89  		To rpcEndpoint
    90  
    91  		ReplyTok   []byte // This contains the hash of the ping packet.
    92  		Expiration uint64 // Absolute timestamp at which the packet becomes invalid.
    93  		// Ignore additional fields (for forward compatibility).
    94  		Rest []rlp.RawValue `rlp:"tail"`
    95  	}
    96  
    97  	// findnode is a query for nodes close to the given target.
    98  	findnode struct {
    99  		Target     encPubkey
   100  		Expiration uint64
   101  		// Ignore additional fields (for forward compatibility).
   102  		Rest []rlp.RawValue `rlp:"tail"`
   103  	}
   104  
   105  	// reply to findnode
   106  	neighbors struct {
   107  		Nodes      []rpcNode
   108  		Expiration uint64
   109  		// Ignore additional fields (for forward compatibility).
   110  		Rest []rlp.RawValue `rlp:"tail"`
   111  	}
   112  
   113  	rpcNode struct {
   114  		IP  net.IP // len 4 for IPv4 or 16 for IPv6
   115  		UDP uint16 // for discovery protocol
   116  		TCP uint16 // for RLPx protocol
   117  		ID  encPubkey
   118  	}
   119  
   120  	rpcEndpoint struct {
   121  		IP  net.IP // len 4 for IPv4 or 16 for IPv6
   122  		UDP uint16 // for discovery protocol
   123  		TCP uint16 // for RLPx protocol
   124  	}
   125  )
   126  
   127  func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint {
   128  	ip := net.IP{}
   129  	if ip4 := addr.IP.To4(); ip4 != nil {
   130  		ip = ip4
   131  	} else if ip6 := addr.IP.To16(); ip6 != nil {
   132  		ip = ip6
   133  	}
   134  	return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort}
   135  }
   136  
   137  func (t *udp) nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*node, error) {
   138  	if rn.UDP <= 1024 {
   139  		return nil, errors.New("low port")
   140  	}
   141  	if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
   142  		return nil, err
   143  	}
   144  	if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) {
   145  		return nil, errors.New("not contained in netrestrict whitelist")
   146  	}
   147  	key, err := decodePubkey(rn.ID)
   148  	if err != nil {
   149  		return nil, err
   150  	}
   151  	n := wrapNode(enode.NewV4(key, rn.IP, int(rn.TCP), int(rn.UDP)))
   152  	err = n.ValidateComplete()
   153  	return n, err
   154  }
   155  
   156  func nodeToRPC(n *node) rpcNode {
   157  	var key ecdsa.PublicKey
   158  	var ekey encPubkey
   159  	if err := n.Load((*enode.Secp256k1)(&key)); err == nil {
   160  		ekey = encodePubkey(&key)
   161  	}
   162  	return rpcNode{ID: ekey, IP: n.IP(), UDP: uint16(n.UDP()), TCP: uint16(n.TCP())}
   163  }
   164  
   165  // packet is implemented by all protocol messages.
   166  type packet interface {
   167  	// preverify checks whether the packet is valid and should be handled at all.
   168  	preverify(t *udp, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error
   169  	// handle handles the packet.
   170  	handle(t *udp, from *net.UDPAddr, fromID enode.ID, mac []byte)
   171  	// name returns the name of the packet for logging purposes.
   172  	name() string
   173  }
   174  
   175  type conn interface {
   176  	ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error)
   177  	WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error)
   178  	Close() error
   179  	LocalAddr() net.Addr
   180  }
   181  
   182  // udp implements the discovery v4 UDP wire protocol.
   183  type udp struct {
   184  	conn        conn
   185  	netrestrict *netutil.Netlist
   186  	priv        *ecdsa.PrivateKey
   187  	localNode   *enode.LocalNode
   188  	db          *enode.DB
   189  	tab         *Table
   190  	wg          sync.WaitGroup
   191  
   192  	addReplyMatcher chan *replyMatcher
   193  	gotreply        chan reply
   194  	closing         chan struct{}
   195  }
   196  
   197  // pending represents a pending reply.
   198  //
   199  // Some implementations of the protocol wish to send more than one
   200  // reply packet to findnode. In general, any neighbors packet cannot
   201  // be matched up with a specific findnode packet.
   202  //
   203  // Our implementation handles this by storing a callback function for
   204  // each pending reply. Incoming packets from a node are dispatched
   205  // to all callback functions for that node.
   206  type replyMatcher struct {
   207  	// these fields must match in the reply.
   208  	from  enode.ID
   209  	ip    net.IP
   210  	ptype byte
   211  
   212  	// time when the request must complete
   213  	deadline time.Time
   214  
   215  	// callback is called when a matching reply arrives. If it returns matched == true, the
   216  	// reply was acceptable. The second return value indicates whether the callback should
   217  	// be removed from the pending reply queue. If it returns false, the reply is considered
   218  	// incomplete and the callback will be invoked again for the next matching reply.
   219  	callback replyMatchFunc
   220  
   221  	// errc receives nil when the callback indicates completion or an
   222  	// error if no further reply is received within the timeout.
   223  	errc chan<- error
   224  }
   225  
   226  type replyMatchFunc func(interface{}) (matched bool, requestDone bool)
   227  
   228  type reply struct {
   229  	from  enode.ID
   230  	ip    net.IP
   231  	ptype byte
   232  	data  packet
   233  
   234  	// loop indicates whether there was
   235  	// a matching request by sending on this channel.
   236  	matched chan<- bool
   237  }
   238  
   239  // ReadPacket is sent to the unhandled channel when it could not be processed
   240  type ReadPacket struct {
   241  	Data []byte
   242  	Addr *net.UDPAddr
   243  }
   244  
   245  // Config holds Table-related settings.
   246  type Config struct {
   247  	// These settings are required and configure the UDP listener:
   248  	PrivateKey *ecdsa.PrivateKey
   249  
   250  	// These settings are optional:
   251  	NetRestrict *netutil.Netlist  // network whitelist
   252  	Bootnodes   []*enode.Node     // list of bootstrap nodes
   253  	Unhandled   chan<- ReadPacket // unhandled packets are sent on this channel
   254  }
   255  
   256  // ListenUDP returns a new table that listens for UDP packets on laddr.
   257  func ListenUDP(c conn, ln *enode.LocalNode, cfg Config) (*Table, error) {
   258  	tab, _, err := newUDP(c, ln, cfg)
   259  	if err != nil {
   260  		return nil, err
   261  	}
   262  	return tab, nil
   263  }
   264  
   265  func newUDP(c conn, ln *enode.LocalNode, cfg Config) (*Table, *udp, error) {
   266  	udp := &udp{
   267  		conn:            c,
   268  		priv:            cfg.PrivateKey,
   269  		netrestrict:     cfg.NetRestrict,
   270  		localNode:       ln,
   271  		db:              ln.Database(),
   272  		closing:         make(chan struct{}),
   273  		gotreply:        make(chan reply),
   274  		addReplyMatcher: make(chan *replyMatcher),
   275  	}
   276  	tab, err := newTable(udp, ln.Database(), cfg.Bootnodes)
   277  	if err != nil {
   278  		return nil, nil, err
   279  	}
   280  	udp.tab = tab
   281  
   282  	udp.wg.Add(2)
   283  	go udp.loop()
   284  	go udp.readLoop(cfg.Unhandled)
   285  	return udp.tab, udp, nil
   286  }
   287  
   288  func (t *udp) self() *enode.Node {
   289  	return t.localNode.Node()
   290  }
   291  
   292  func (t *udp) close() {
   293  	close(t.closing)
   294  	t.conn.Close()
   295  	t.wg.Wait()
   296  }
   297  
   298  func (t *udp) ourEndpoint() rpcEndpoint {
   299  	n := t.self()
   300  	a := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
   301  	return makeEndpoint(a, uint16(n.TCP()))
   302  }
   303  
   304  // ping sends a ping message to the given node and waits for a reply.
   305  func (t *udp) ping(toid enode.ID, toaddr *net.UDPAddr) error {
   306  	return <-t.sendPing(toid, toaddr, nil)
   307  }
   308  
   309  // sendPing sends a ping message to the given node and invokes the callback
   310  // when the reply arrives.
   311  func (t *udp) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) <-chan error {
   312  	req := &ping{
   313  		Version:    4,
   314  		From:       t.ourEndpoint(),
   315  		To:         makeEndpoint(toaddr, 0), // TODO: maybe use known TCP port from DB
   316  		Expiration: uint64(time.Now().Add(expiration).Unix()),
   317  	}
   318  	packet, hash, err := encodePacket(t.priv, pingPacket, req)
   319  	if err != nil {
   320  		errc := make(chan error, 1)
   321  		errc <- err
   322  		return errc
   323  	}
   324  	// Add a matcher for the reply to the pending reply queue. Pongs are matched if they
   325  	// reference the ping we're about to send.
   326  	errc := t.pending(toid, toaddr.IP, pongPacket, func(p interface{}) (matched bool, requestDone bool) {
   327  		matched = bytes.Equal(p.(*pong).ReplyTok, hash)
   328  		if matched && callback != nil {
   329  			callback()
   330  		}
   331  		return matched, matched
   332  	})
   333  	// Send the packet.
   334  	t.localNode.UDPContact(toaddr)
   335  	t.write(toaddr, toid, req.name(), packet)
   336  	return errc
   337  }
   338  
   339  // findnode sends a findnode request to the given node and waits until
   340  // the node has sent up to k neighbors.
   341  func (t *udp) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) ([]*node, error) {
   342  	// If we haven't seen a ping from the destination node for a while, it won't remember
   343  	// our endpoint proof and reject findnode. Solicit a ping first.
   344  	if time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration {
   345  		t.ping(toid, toaddr)
   346  		// Wait for them to ping back and process our pong.
   347  		time.Sleep(respTimeout)
   348  	}
   349  
   350  	// Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
   351  	// active until enough nodes have been received.
   352  	nodes := make([]*node, 0, bucketSize)
   353  	nreceived := 0
   354  	errc := t.pending(toid, toaddr.IP, neighborsPacket, func(r interface{}) (matched bool, requestDone bool) {
   355  		reply := r.(*neighbors)
   356  		for _, rn := range reply.Nodes {
   357  			nreceived++
   358  			n, err := t.nodeFromRPC(toaddr, rn)
   359  			if err != nil {
   360  				log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
   361  				continue
   362  			}
   363  			nodes = append(nodes, n)
   364  		}
   365  		return true, nreceived >= bucketSize
   366  	})
   367  	t.send(toaddr, toid, findnodePacket, &findnode{
   368  		Target:     target,
   369  		Expiration: uint64(time.Now().Add(expiration).Unix()),
   370  	})
   371  	return nodes, <-errc
   372  }
   373  
   374  // pending adds a reply matcher to the pending reply queue.
   375  // see the documentation of type replyMatcher for a detailed explanation.
   376  func (t *udp) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) <-chan error {
   377  	ch := make(chan error, 1)
   378  	p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch}
   379  	select {
   380  	case t.addReplyMatcher <- p:
   381  		// loop will handle it
   382  	case <-t.closing:
   383  		ch <- errClosed
   384  	}
   385  	return ch
   386  }
   387  
   388  // handleReply dispatches a reply packet, invoking reply matchers. It returns
   389  // whether any matcher considered the packet acceptable.
   390  func (t *udp) handleReply(from enode.ID, fromIP net.IP, ptype byte, req packet) bool {
   391  	matched := make(chan bool, 1)
   392  	select {
   393  	case t.gotreply <- reply{from, fromIP, ptype, req, matched}:
   394  		// loop will handle it
   395  		return <-matched
   396  	case <-t.closing:
   397  		return false
   398  	}
   399  }
   400  
   401  // loop runs in its own goroutine. it keeps track of
   402  // the refresh timer and the pending reply queue.
   403  func (t *udp) loop() {
   404  	defer t.wg.Done()
   405  
   406  	var (
   407  		plist        = list.New()
   408  		timeout      = time.NewTimer(0)
   409  		nextTimeout  *replyMatcher // head of plist when timeout was last reset
   410  		contTimeouts = 0           // number of continuous timeouts to do NTP checks
   411  		ntpWarnTime  = time.Unix(0, 0)
   412  	)
   413  	<-timeout.C // ignore first timeout
   414  	defer timeout.Stop()
   415  
   416  	resetTimeout := func() {
   417  		if plist.Front() == nil || nextTimeout == plist.Front().Value {
   418  			return
   419  		}
   420  		// Start the timer so it fires when the next pending reply has expired.
   421  		now := time.Now()
   422  		for el := plist.Front(); el != nil; el = el.Next() {
   423  			nextTimeout = el.Value.(*replyMatcher)
   424  			if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
   425  				timeout.Reset(dist)
   426  				return
   427  			}
   428  			// Remove pending replies whose deadline is too far in the
   429  			// future. These can occur if the system clock jumped
   430  			// backwards after the deadline was assigned.
   431  			nextTimeout.errc <- errClockWarp
   432  			plist.Remove(el)
   433  		}
   434  		nextTimeout = nil
   435  		timeout.Stop()
   436  	}
   437  
   438  	for {
   439  		resetTimeout()
   440  
   441  		select {
   442  		case <-t.closing:
   443  			for el := plist.Front(); el != nil; el = el.Next() {
   444  				el.Value.(*replyMatcher).errc <- errClosed
   445  			}
   446  			return
   447  
   448  		case p := <-t.addReplyMatcher:
   449  			p.deadline = time.Now().Add(respTimeout)
   450  			plist.PushBack(p)
   451  
   452  		case r := <-t.gotreply:
   453  			var matched bool // whether any replyMatcher considered the reply acceptable.
   454  			for el := plist.Front(); el != nil; el = el.Next() {
   455  				p := el.Value.(*replyMatcher)
   456  				if p.from == r.from && p.ptype == r.ptype && p.ip.Equal(r.ip) {
   457  					ok, requestDone := p.callback(r.data)
   458  					matched = matched || ok
   459  					// Remove the matcher if callback indicates that all replies have been received.
   460  					if requestDone {
   461  						p.errc <- nil
   462  						plist.Remove(el)
   463  					}
   464  					// Reset the continuous timeout counter (time drift detection)
   465  					contTimeouts = 0
   466  				}
   467  			}
   468  			r.matched <- matched
   469  
   470  		case now := <-timeout.C:
   471  			nextTimeout = nil
   472  
   473  			// Notify and remove callbacks whose deadline is in the past.
   474  			for el := plist.Front(); el != nil; el = el.Next() {
   475  				p := el.Value.(*replyMatcher)
   476  				if now.After(p.deadline) || now.Equal(p.deadline) {
   477  					p.errc <- errTimeout
   478  					plist.Remove(el)
   479  					contTimeouts++
   480  				}
   481  			}
   482  			// If we've accumulated too many timeouts, do an NTP time sync check
   483  			if contTimeouts > ntpFailureThreshold {
   484  				if time.Since(ntpWarnTime) >= ntpWarningCooldown {
   485  					ntpWarnTime = time.Now()
   486  					go checkClockDrift()
   487  				}
   488  				contTimeouts = 0
   489  			}
   490  		}
   491  	}
   492  }
   493  
   494  const (
   495  	macSize  = 256 / 8
   496  	sigSize  = 520 / 8
   497  	headSize = macSize + sigSize // space of packet frame data
   498  )
   499  
   500  var (
   501  	headSpace = make([]byte, headSize)
   502  
   503  	// Neighbors replies are sent across multiple packets to
   504  	// stay below the packet size limit. We compute the maximum number
   505  	// of entries by stuffing a packet until it grows too large.
   506  	maxNeighbors int
   507  )
   508  
   509  func init() {
   510  	p := neighbors{Expiration: ^uint64(0)}
   511  	maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
   512  	for n := 0; ; n++ {
   513  		p.Nodes = append(p.Nodes, maxSizeNode)
   514  		size, _, err := rlp.EncodeToReader(p)
   515  		if err != nil {
   516  			// If this ever happens, it will be caught by the unit tests.
   517  			panic("cannot encode: " + err.Error())
   518  		}
   519  		if headSize+size+1 >= maxPacketSize {
   520  			maxNeighbors = n
   521  			break
   522  		}
   523  	}
   524  }
   525  
   526  func (t *udp) send(toaddr *net.UDPAddr, toid enode.ID, ptype byte, req packet) ([]byte, error) {
   527  	packet, hash, err := encodePacket(t.priv, ptype, req)
   528  	if err != nil {
   529  		return hash, err
   530  	}
   531  	return hash, t.write(toaddr, toid, req.name(), packet)
   532  }
   533  
   534  func (t *udp) write(toaddr *net.UDPAddr, toid enode.ID, what string, packet []byte) error {
   535  	_, err := t.conn.WriteToUDP(packet, toaddr)
   536  	log.Trace(">> "+what, "id", toid, "addr", toaddr, "err", err)
   537  	return err
   538  }
   539  
   540  func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (packet, hash []byte, err error) {
   541  	b := new(bytes.Buffer)
   542  	b.Write(headSpace)
   543  	b.WriteByte(ptype)
   544  	if err := rlp.Encode(b, req); err != nil {
   545  		log.Error("Can't encode discv4 packet", "err", err)
   546  		return nil, nil, err
   547  	}
   548  	packet = b.Bytes()
   549  	sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
   550  	if err != nil {
   551  		log.Error("Can't sign discv4 packet", "err", err)
   552  		return nil, nil, err
   553  	}
   554  	copy(packet[macSize:], sig)
   555  	// add the hash to the front. Note: this doesn't protect the
   556  	// packet in any way. Our public key will be part of this hash in
   557  	// The future.
   558  	hash = crypto.Keccak256(packet[macSize:])
   559  	copy(packet, hash)
   560  	return packet, hash, nil
   561  }
   562  
   563  // readLoop runs in its own goroutine. it handles incoming UDP packets.
   564  func (t *udp) readLoop(unhandled chan<- ReadPacket) {
   565  	defer t.wg.Done()
   566  	if unhandled != nil {
   567  		defer close(unhandled)
   568  	}
   569  
   570  	buf := make([]byte, maxPacketSize)
   571  	for {
   572  		nbytes, from, err := t.conn.ReadFromUDP(buf)
   573  		if netutil.IsTemporaryError(err) {
   574  			// Ignore temporary read errors.
   575  			log.Debug("Temporary UDP read error", "err", err)
   576  			continue
   577  		} else if err != nil {
   578  			// Shut down the loop for permament errors.
   579  			log.Debug("UDP read error", "err", err)
   580  			return
   581  		}
   582  		if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil {
   583  			select {
   584  			case unhandled <- ReadPacket{buf[:nbytes], from}:
   585  			default:
   586  			}
   587  		}
   588  	}
   589  }
   590  
   591  func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error {
   592  	packet, fromKey, hash, err := decodePacket(buf)
   593  	if err != nil {
   594  		log.Debug("Bad discv4 packet", "addr", from, "err", err)
   595  		return err
   596  	}
   597  	fromID := fromKey.id()
   598  	if err == nil {
   599  		err = packet.preverify(t, from, fromID, fromKey)
   600  	}
   601  	log.Trace("<< "+packet.name(), "id", fromID, "addr", from, "err", err)
   602  	if err == nil {
   603  		packet.handle(t, from, fromID, hash)
   604  	}
   605  	return err
   606  }
   607  
   608  func decodePacket(buf []byte) (packet, encPubkey, []byte, error) {
   609  	if len(buf) < headSize+1 {
   610  		return nil, encPubkey{}, nil, errPacketTooSmall
   611  	}
   612  	hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
   613  	shouldhash := crypto.Keccak256(buf[macSize:])
   614  	if !bytes.Equal(hash, shouldhash) {
   615  		return nil, encPubkey{}, nil, errBadHash
   616  	}
   617  	fromKey, err := recoverNodeKey(crypto.Keccak256(buf[headSize:]), sig)
   618  	if err != nil {
   619  		return nil, fromKey, hash, err
   620  	}
   621  
   622  	var req packet
   623  	switch ptype := sigdata[0]; ptype {
   624  	case pingPacket:
   625  		req = new(ping)
   626  	case pongPacket:
   627  		req = new(pong)
   628  	case findnodePacket:
   629  		req = new(findnode)
   630  	case neighborsPacket:
   631  		req = new(neighbors)
   632  	default:
   633  		return nil, fromKey, hash, fmt.Errorf("unknown type: %d", ptype)
   634  	}
   635  	s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0)
   636  	err = s.Decode(req)
   637  	return req, fromKey, hash, err
   638  }
   639  
   640  // Packet Handlers
   641  
   642  func (req *ping) preverify(t *udp, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
   643  	if expired(req.Expiration) {
   644  		return errExpired
   645  	}
   646  	key, err := decodePubkey(fromKey)
   647  	if err != nil {
   648  		return errors.New("invalid public key")
   649  	}
   650  	req.senderKey = key
   651  	return nil
   652  }
   653  
   654  func (req *ping) handle(t *udp, from *net.UDPAddr, fromID enode.ID, mac []byte) {
   655  	// Reply.
   656  	t.send(from, fromID, pongPacket, &pong{
   657  		To:         makeEndpoint(from, req.From.TCP),
   658  		ReplyTok:   mac,
   659  		Expiration: uint64(time.Now().Add(expiration).Unix()),
   660  	})
   661  
   662  	// Ping back if our last pong on file is too far in the past.
   663  	n := wrapNode(enode.NewV4(req.senderKey, from.IP, int(req.From.TCP), from.Port))
   664  	if time.Since(t.db.LastPongReceived(n.ID(), from.IP)) > bondExpiration {
   665  		t.sendPing(fromID, from, func() {
   666  			t.tab.addVerifiedNode(n)
   667  		})
   668  	} else {
   669  		t.tab.addVerifiedNode(n)
   670  	}
   671  
   672  	// Update node database and endpoint predictor.
   673  	t.db.UpdateLastPingReceived(n.ID(), from.IP, time.Now())
   674  	t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
   675  }
   676  
   677  func (req *ping) name() string { return "PING/v4" }
   678  
   679  func (req *pong) preverify(t *udp, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
   680  	if expired(req.Expiration) {
   681  		return errExpired
   682  	}
   683  	if !t.handleReply(fromID, from.IP, pongPacket, req) {
   684  		return errUnsolicitedReply
   685  	}
   686  	return nil
   687  }
   688  
   689  func (req *pong) handle(t *udp, from *net.UDPAddr, fromID enode.ID, mac []byte) {
   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  }
   693  
   694  func (req *pong) name() string { return "PONG/v4" }
   695  
   696  func (req *findnode) preverify(t *udp, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
   697  	if expired(req.Expiration) {
   698  		return errExpired
   699  	}
   700  	if time.Since(t.db.LastPongReceived(fromID, from.IP)) > bondExpiration {
   701  		// No endpoint proof pong exists, we don't process the packet. This prevents an
   702  		// attack vector where the discovery protocol could be used to amplify traffic in a
   703  		// DDOS attack. A malicious actor would send a findnode request with the IP address
   704  		// and UDP port of the target as the source address. The recipient of the findnode
   705  		// packet would then send a neighbors packet (which is a much bigger packet than
   706  		// findnode) to the victim.
   707  		return errUnknownNode
   708  	}
   709  	return nil
   710  }
   711  
   712  func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID enode.ID, mac []byte) {
   713  	// Determine closest nodes.
   714  	target := enode.ID(crypto.Keccak256Hash(req.Target[:]))
   715  	t.tab.mutex.Lock()
   716  	closest := t.tab.closest(target, bucketSize).entries
   717  	t.tab.mutex.Unlock()
   718  
   719  	// Send neighbors in chunks with at most maxNeighbors per packet
   720  	// to stay below the packet size limit.
   721  	p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
   722  	var sent bool
   723  	for _, n := range closest {
   724  		if netutil.CheckRelayIP(from.IP, n.IP()) == nil {
   725  			p.Nodes = append(p.Nodes, nodeToRPC(n))
   726  		}
   727  		if len(p.Nodes) == maxNeighbors {
   728  			t.send(from, fromID, neighborsPacket, &p)
   729  			p.Nodes = p.Nodes[:0]
   730  			sent = true
   731  		}
   732  	}
   733  	if len(p.Nodes) > 0 || !sent {
   734  		t.send(from, fromID, neighborsPacket, &p)
   735  	}
   736  }
   737  
   738  func (req *findnode) name() string { return "FINDNODE/v4" }
   739  
   740  func (req *neighbors) preverify(t *udp, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
   741  	if expired(req.Expiration) {
   742  		return errExpired
   743  	}
   744  	if !t.handleReply(fromID, from.IP, neighborsPacket, req) {
   745  		return errUnsolicitedReply
   746  	}
   747  	return nil
   748  }
   749  
   750  func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID enode.ID, mac []byte) {
   751  }
   752  
   753  func (req *neighbors) name() string { return "NEIGHBORS/v4" }
   754  
   755  func expired(ts uint64) bool {
   756  	return time.Unix(int64(ts), 0).Before(time.Now())
   757  }