gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/p2p/discover/udp.go (about)

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