gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/p2p/discover/v4_udp_test.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  	"crypto/ecdsa"
    22  	crand "crypto/rand"
    23  	"encoding/binary"
    24  	"encoding/hex"
    25  	"errors"
    26  	"io"
    27  	"math/rand"
    28  	"net"
    29  	"reflect"
    30  	"sync"
    31  	"testing"
    32  	"time"
    33  
    34  	"github.com/davecgh/go-spew/spew"
    35  	"github.com/ethereum/go-ethereum/common"
    36  	"github.com/ethereum/go-ethereum/crypto"
    37  	"github.com/ethereum/go-ethereum/internal/testlog"
    38  	"github.com/ethereum/go-ethereum/log"
    39  	"github.com/ethereum/go-ethereum/p2p/enode"
    40  	"github.com/ethereum/go-ethereum/p2p/enr"
    41  	"github.com/ethereum/go-ethereum/rlp"
    42  )
    43  
    44  // shared test variables
    45  var (
    46  	futureExp          = uint64(time.Now().Add(10 * time.Hour).Unix())
    47  	testTarget         = encPubkey{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}
    48  	testRemote         = rpcEndpoint{IP: net.ParseIP("1.1.1.1").To4(), UDP: 1, TCP: 2}
    49  	testLocalAnnounced = rpcEndpoint{IP: net.ParseIP("2.2.2.2").To4(), UDP: 3, TCP: 4}
    50  	testLocal          = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6}
    51  )
    52  
    53  type udpTest struct {
    54  	t                   *testing.T
    55  	pipe                *dgramPipe
    56  	table               *Table
    57  	db                  *enode.DB
    58  	udp                 *UDPv4
    59  	sent                [][]byte
    60  	localkey, remotekey *ecdsa.PrivateKey
    61  	remoteaddr          *net.UDPAddr
    62  }
    63  
    64  func newUDPTest(t *testing.T) *udpTest {
    65  	test := &udpTest{
    66  		t:          t,
    67  		pipe:       newpipe(),
    68  		localkey:   newkey(),
    69  		remotekey:  newkey(),
    70  		remoteaddr: &net.UDPAddr{IP: net.IP{10, 0, 1, 99}, Port: 30303},
    71  	}
    72  
    73  	test.db, _ = enode.OpenDB("")
    74  	ln := enode.NewLocalNode(test.db, test.localkey)
    75  	test.udp, _ = ListenV4(test.pipe, ln, Config{
    76  		PrivateKey: test.localkey,
    77  		Log:        testlog.Logger(t, log.LvlTrace),
    78  	})
    79  	test.table = test.udp.tab
    80  	// Wait for initial refresh so the table doesn't send unexpected findnode.
    81  	<-test.table.initDone
    82  	return test
    83  }
    84  
    85  func (test *udpTest) close() {
    86  	test.udp.Close()
    87  	test.db.Close()
    88  }
    89  
    90  // handles a packet as if it had been sent to the transport.
    91  func (test *udpTest) packetIn(wantError error, data packetV4) {
    92  	test.t.Helper()
    93  
    94  	test.packetInFrom(wantError, test.remotekey, test.remoteaddr, data)
    95  }
    96  
    97  // handles a packet as if it had been sent to the transport by the key/endpoint.
    98  func (test *udpTest) packetInFrom(wantError error, key *ecdsa.PrivateKey, addr *net.UDPAddr, data packetV4) {
    99  	test.t.Helper()
   100  
   101  	enc, _, err := test.udp.encode(key, data)
   102  	if err != nil {
   103  		test.t.Errorf("%s encode error: %v", data.name(), err)
   104  	}
   105  	test.sent = append(test.sent, enc)
   106  	if err = test.udp.handlePacket(addr, enc); err != wantError {
   107  		test.t.Errorf("error mismatch: got %q, want %q", err, wantError)
   108  	}
   109  }
   110  
   111  // waits for a packet to be sent by the transport.
   112  // validate should have type func(X, *net.UDPAddr, []byte), where X is a packet type.
   113  func (test *udpTest) waitPacketOut(validate interface{}) (closed bool) {
   114  	test.t.Helper()
   115  
   116  	dgram, err := test.pipe.receive()
   117  	if err == errClosed {
   118  		return true
   119  	} else if err != nil {
   120  		test.t.Error("packet receive error:", err)
   121  		return false
   122  	}
   123  	p, _, hash, err := decodeV4(dgram.data)
   124  	if err != nil {
   125  		test.t.Errorf("sent packet decode error: %v", err)
   126  		return false
   127  	}
   128  	fn := reflect.ValueOf(validate)
   129  	exptype := fn.Type().In(0)
   130  	if !reflect.TypeOf(p).AssignableTo(exptype) {
   131  		test.t.Errorf("sent packet type mismatch, got: %v, want: %v", reflect.TypeOf(p), exptype)
   132  		return false
   133  	}
   134  	fn.Call([]reflect.Value{reflect.ValueOf(p), reflect.ValueOf(&dgram.to), reflect.ValueOf(hash)})
   135  	return false
   136  }
   137  
   138  func TestUDPv4_packetErrors(t *testing.T) {
   139  	test := newUDPTest(t)
   140  	defer test.close()
   141  
   142  	test.packetIn(errExpired, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4})
   143  	test.packetIn(errUnsolicitedReply, &pongV4{ReplyTok: []byte{}, Expiration: futureExp})
   144  	test.packetIn(errUnknownNode, &findnodeV4{Expiration: futureExp})
   145  	test.packetIn(errUnsolicitedReply, &neighborsV4{Expiration: futureExp})
   146  }
   147  
   148  func TestUDPv4_pingTimeout(t *testing.T) {
   149  	t.Parallel()
   150  	test := newUDPTest(t)
   151  	defer test.close()
   152  
   153  	key := newkey()
   154  	toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222}
   155  	node := enode.NewV4(&key.PublicKey, toaddr.IP, 0, toaddr.Port)
   156  	if _, err := test.udp.ping(node); err != errTimeout {
   157  		t.Error("expected timeout error, got", err)
   158  	}
   159  }
   160  
   161  type testPacket byte
   162  
   163  func (req testPacket) kind() byte   { return byte(req) }
   164  func (req testPacket) name() string { return "" }
   165  func (req testPacket) preverify(*UDPv4, *net.UDPAddr, enode.ID, encPubkey) error {
   166  	return nil
   167  }
   168  func (req testPacket) handle(*UDPv4, *net.UDPAddr, enode.ID, []byte) {
   169  }
   170  
   171  func TestUDPv4_responseTimeouts(t *testing.T) {
   172  	t.Parallel()
   173  	test := newUDPTest(t)
   174  	defer test.close()
   175  
   176  	rand.Seed(time.Now().UnixNano())
   177  	randomDuration := func(max time.Duration) time.Duration {
   178  		return time.Duration(rand.Int63n(int64(max)))
   179  	}
   180  
   181  	var (
   182  		nReqs      = 200
   183  		nTimeouts  = 0                       // number of requests with ptype > 128
   184  		nilErr     = make(chan error, nReqs) // for requests that get a reply
   185  		timeoutErr = make(chan error, nReqs) // for requests that time out
   186  	)
   187  	for i := 0; i < nReqs; i++ {
   188  		// Create a matcher for a random request in udp.loop. Requests
   189  		// with ptype <= 128 will not get a reply and should time out.
   190  		// For all other requests, a reply is scheduled to arrive
   191  		// within the timeout window.
   192  		p := &replyMatcher{
   193  			ptype:    byte(rand.Intn(255)),
   194  			callback: func(interface{}) (bool, bool) { return true, true },
   195  		}
   196  		binary.BigEndian.PutUint64(p.from[:], uint64(i))
   197  		if p.ptype <= 128 {
   198  			p.errc = timeoutErr
   199  			test.udp.addReplyMatcher <- p
   200  			nTimeouts++
   201  		} else {
   202  			p.errc = nilErr
   203  			test.udp.addReplyMatcher <- p
   204  			time.AfterFunc(randomDuration(60*time.Millisecond), func() {
   205  				if !test.udp.handleReply(p.from, p.ip, testPacket(p.ptype)) {
   206  					t.Logf("not matched: %v", p)
   207  				}
   208  			})
   209  		}
   210  		time.Sleep(randomDuration(30 * time.Millisecond))
   211  	}
   212  
   213  	// Check that all timeouts were delivered and that the rest got nil errors.
   214  	// The replies must be delivered.
   215  	var (
   216  		recvDeadline        = time.After(20 * time.Second)
   217  		nTimeoutsRecv, nNil = 0, 0
   218  	)
   219  	for i := 0; i < nReqs; i++ {
   220  		select {
   221  		case err := <-timeoutErr:
   222  			if err != errTimeout {
   223  				t.Fatalf("got non-timeout error on timeoutErr %d: %v", i, err)
   224  			}
   225  			nTimeoutsRecv++
   226  		case err := <-nilErr:
   227  			if err != nil {
   228  				t.Fatalf("got non-nil error on nilErr %d: %v", i, err)
   229  			}
   230  			nNil++
   231  		case <-recvDeadline:
   232  			t.Fatalf("exceeded recv deadline")
   233  		}
   234  	}
   235  	if nTimeoutsRecv != nTimeouts {
   236  		t.Errorf("wrong number of timeout errors received: got %d, want %d", nTimeoutsRecv, nTimeouts)
   237  	}
   238  	if nNil != nReqs-nTimeouts {
   239  		t.Errorf("wrong number of successful replies: got %d, want %d", nNil, nReqs-nTimeouts)
   240  	}
   241  }
   242  
   243  func TestUDPv4_findnodeTimeout(t *testing.T) {
   244  	t.Parallel()
   245  	test := newUDPTest(t)
   246  	defer test.close()
   247  
   248  	toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222}
   249  	toid := enode.ID{1, 2, 3, 4}
   250  	target := encPubkey{4, 5, 6, 7}
   251  	result, err := test.udp.findnode(toid, toaddr, target)
   252  	if err != errTimeout {
   253  		t.Error("expected timeout error, got", err)
   254  	}
   255  	if len(result) > 0 {
   256  		t.Error("expected empty result, got", result)
   257  	}
   258  }
   259  
   260  func TestUDPv4_findnode(t *testing.T) {
   261  	test := newUDPTest(t)
   262  	defer test.close()
   263  
   264  	// put a few nodes into the table. their exact
   265  	// distribution shouldn't matter much, although we need to
   266  	// take care not to overflow any bucket.
   267  	nodes := &nodesByDistance{target: testTarget.id()}
   268  	live := make(map[enode.ID]bool)
   269  	numCandidates := 2 * bucketSize
   270  	for i := 0; i < numCandidates; i++ {
   271  		key := newkey()
   272  		ip := net.IP{10, 13, 0, byte(i)}
   273  		n := wrapNode(enode.NewV4(&key.PublicKey, ip, 0, 2000))
   274  		// Ensure half of table content isn't verified live yet.
   275  		if i > numCandidates/2 {
   276  			n.livenessChecks = 1
   277  			live[n.ID()] = true
   278  		}
   279  		nodes.push(n, numCandidates)
   280  	}
   281  	fillTable(test.table, nodes.entries)
   282  
   283  	// ensure there's a bond with the test node,
   284  	// findnode won't be accepted otherwise.
   285  	remoteID := encodePubkey(&test.remotekey.PublicKey).id()
   286  	test.table.db.UpdateLastPongReceived(remoteID, test.remoteaddr.IP, time.Now())
   287  
   288  	// check that closest neighbors are returned.
   289  	expected := test.table.closest(testTarget.id(), bucketSize, true)
   290  	test.packetIn(nil, &findnodeV4{Target: testTarget, Expiration: futureExp})
   291  	waitNeighbors := func(want []*node) {
   292  		test.waitPacketOut(func(p *neighborsV4, to *net.UDPAddr, hash []byte) {
   293  			if len(p.Nodes) != len(want) {
   294  				t.Errorf("wrong number of results: got %d, want %d", len(p.Nodes), bucketSize)
   295  			}
   296  			for i, n := range p.Nodes {
   297  				if n.ID.id() != want[i].ID() {
   298  					t.Errorf("result mismatch at %d:\n  got:  %v\n  want: %v", i, n, expected.entries[i])
   299  				}
   300  				if !live[n.ID.id()] {
   301  					t.Errorf("result includes dead node %v", n.ID.id())
   302  				}
   303  			}
   304  		})
   305  	}
   306  	// Receive replies.
   307  	want := expected.entries
   308  	if len(want) > maxNeighbors {
   309  		waitNeighbors(want[:maxNeighbors])
   310  		want = want[maxNeighbors:]
   311  	}
   312  	waitNeighbors(want)
   313  }
   314  
   315  func TestUDPv4_findnodeMultiReply(t *testing.T) {
   316  	test := newUDPTest(t)
   317  	defer test.close()
   318  
   319  	rid := enode.PubkeyToIDV4(&test.remotekey.PublicKey)
   320  	test.table.db.UpdateLastPingReceived(rid, test.remoteaddr.IP, time.Now())
   321  
   322  	// queue a pending findnode request
   323  	resultc, errc := make(chan []*node), make(chan error)
   324  	go func() {
   325  		rid := encodePubkey(&test.remotekey.PublicKey).id()
   326  		ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget)
   327  		if err != nil && len(ns) == 0 {
   328  			errc <- err
   329  		} else {
   330  			resultc <- ns
   331  		}
   332  	}()
   333  
   334  	// wait for the findnode to be sent.
   335  	// after it is sent, the transport is waiting for a reply
   336  	test.waitPacketOut(func(p *findnodeV4, to *net.UDPAddr, hash []byte) {
   337  		if p.Target != testTarget {
   338  			t.Errorf("wrong target: got %v, want %v", p.Target, testTarget)
   339  		}
   340  	})
   341  
   342  	// send the reply as two packets.
   343  	list := []*node{
   344  		wrapNode(enode.MustParse("enode://ba85011c70bcc5c04d8607d3a0ed29aa6179c092cbdda10d5d32684fb33ed01bd94f588ca8f91ac48318087dcb02eaf36773a7a453f0eedd6742af668097b29c@10.0.1.16:30303?discport=30304")),
   345  		wrapNode(enode.MustParse("enode://81fa361d25f157cd421c60dcc28d8dac5ef6a89476633339c5df30287474520caca09627da18543d9079b5b288698b542d56167aa5c09111e55acdbbdf2ef799@10.0.1.16:30303")),
   346  		wrapNode(enode.MustParse("enode://9bffefd833d53fac8e652415f4973bee289e8b1a5c6c4cbe70abf817ce8a64cee11b823b66a987f51aaa9fba0d6a91b3e6bf0d5a5d1042de8e9eeea057b217f8@10.0.1.36:30301?discport=17")),
   347  		wrapNode(enode.MustParse("enode://1b5b4aa662d7cb44a7221bfba67302590b643028197a7d5214790f3bac7aaa4a3241be9e83c09cf1f6c69d007c634faae3dc1b1221793e8446c0b3a09de65960@10.0.1.16:30303")),
   348  	}
   349  	rpclist := make([]rpcNode, len(list))
   350  	for i := range list {
   351  		rpclist[i] = nodeToRPC(list[i])
   352  	}
   353  	test.packetIn(nil, &neighborsV4{Expiration: futureExp, Nodes: rpclist[:2]})
   354  	test.packetIn(nil, &neighborsV4{Expiration: futureExp, Nodes: rpclist[2:]})
   355  
   356  	// check that the sent neighbors are all returned by findnode
   357  	select {
   358  	case result := <-resultc:
   359  		want := append(list[:2], list[3:]...)
   360  		if !reflect.DeepEqual(result, want) {
   361  			t.Errorf("neighbors mismatch:\n  got:  %v\n  want: %v", result, want)
   362  		}
   363  	case err := <-errc:
   364  		t.Errorf("findnode error: %v", err)
   365  	case <-time.After(5 * time.Second):
   366  		t.Error("findnode did not return within 5 seconds")
   367  	}
   368  }
   369  
   370  // This test checks that reply matching of pong verifies the ping hash.
   371  func TestUDPv4_pingMatch(t *testing.T) {
   372  	test := newUDPTest(t)
   373  	defer test.close()
   374  
   375  	randToken := make([]byte, 32)
   376  	crand.Read(randToken)
   377  
   378  	test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp})
   379  	test.waitPacketOut(func(*pongV4, *net.UDPAddr, []byte) {})
   380  	test.waitPacketOut(func(*pingV4, *net.UDPAddr, []byte) {})
   381  	test.packetIn(errUnsolicitedReply, &pongV4{ReplyTok: randToken, To: testLocalAnnounced, Expiration: futureExp})
   382  }
   383  
   384  // This test checks that reply matching of pong verifies the sender IP address.
   385  func TestUDPv4_pingMatchIP(t *testing.T) {
   386  	test := newUDPTest(t)
   387  	defer test.close()
   388  
   389  	test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp})
   390  	test.waitPacketOut(func(*pongV4, *net.UDPAddr, []byte) {})
   391  
   392  	test.waitPacketOut(func(p *pingV4, to *net.UDPAddr, hash []byte) {
   393  		wrongAddr := &net.UDPAddr{IP: net.IP{33, 44, 1, 2}, Port: 30000}
   394  		test.packetInFrom(errUnsolicitedReply, test.remotekey, wrongAddr, &pongV4{
   395  			ReplyTok:   hash,
   396  			To:         testLocalAnnounced,
   397  			Expiration: futureExp,
   398  		})
   399  	})
   400  }
   401  
   402  func TestUDPv4_successfulPing(t *testing.T) {
   403  	test := newUDPTest(t)
   404  	added := make(chan *node, 1)
   405  	test.table.nodeAddedHook = func(n *node) { added <- n }
   406  	defer test.close()
   407  
   408  	// The remote side sends a ping packet to initiate the exchange.
   409  	go test.packetIn(nil, &pingV4{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp})
   410  
   411  	// The ping is replied to.
   412  	test.waitPacketOut(func(p *pongV4, to *net.UDPAddr, hash []byte) {
   413  		pinghash := test.sent[0][:macSize]
   414  		if !bytes.Equal(p.ReplyTok, pinghash) {
   415  			t.Errorf("got pong.ReplyTok %x, want %x", p.ReplyTok, pinghash)
   416  		}
   417  		wantTo := rpcEndpoint{
   418  			// The mirrored UDP address is the UDP packet sender
   419  			IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port),
   420  			// The mirrored TCP port is the one from the ping packet
   421  			TCP: testRemote.TCP,
   422  		}
   423  		if !reflect.DeepEqual(p.To, wantTo) {
   424  			t.Errorf("got pong.To %v, want %v", p.To, wantTo)
   425  		}
   426  	})
   427  
   428  	// Remote is unknown, the table pings back.
   429  	test.waitPacketOut(func(p *pingV4, to *net.UDPAddr, hash []byte) {
   430  		if !reflect.DeepEqual(p.From, test.udp.ourEndpoint()) {
   431  			t.Errorf("got ping.From %#v, want %#v", p.From, test.udp.ourEndpoint())
   432  		}
   433  		wantTo := rpcEndpoint{
   434  			// The mirrored UDP address is the UDP packet sender.
   435  			IP:  test.remoteaddr.IP,
   436  			UDP: uint16(test.remoteaddr.Port),
   437  			TCP: 0,
   438  		}
   439  		if !reflect.DeepEqual(p.To, wantTo) {
   440  			t.Errorf("got ping.To %v, want %v", p.To, wantTo)
   441  		}
   442  		test.packetIn(nil, &pongV4{ReplyTok: hash, Expiration: futureExp})
   443  	})
   444  
   445  	// The node should be added to the table shortly after getting the
   446  	// pong packet.
   447  	select {
   448  	case n := <-added:
   449  		rid := encodePubkey(&test.remotekey.PublicKey).id()
   450  		if n.ID() != rid {
   451  			t.Errorf("node has wrong ID: got %v, want %v", n.ID(), rid)
   452  		}
   453  		if !n.IP().Equal(test.remoteaddr.IP) {
   454  			t.Errorf("node has wrong IP: got %v, want: %v", n.IP(), test.remoteaddr.IP)
   455  		}
   456  		if n.UDP() != test.remoteaddr.Port {
   457  			t.Errorf("node has wrong UDP port: got %v, want: %v", n.UDP(), test.remoteaddr.Port)
   458  		}
   459  		if n.TCP() != int(testRemote.TCP) {
   460  			t.Errorf("node has wrong TCP port: got %v, want: %v", n.TCP(), testRemote.TCP)
   461  		}
   462  	case <-time.After(2 * time.Second):
   463  		t.Errorf("node was not added within 2 seconds")
   464  	}
   465  }
   466  
   467  // This test checks that EIP-868 requests work.
   468  func TestUDPv4_EIP868(t *testing.T) {
   469  	test := newUDPTest(t)
   470  	defer test.close()
   471  
   472  	test.udp.localNode.Set(enr.WithEntry("foo", "bar"))
   473  	wantNode := test.udp.localNode.Node()
   474  
   475  	// ENR requests aren't allowed before endpoint proof.
   476  	test.packetIn(errUnknownNode, &enrRequestV4{Expiration: futureExp})
   477  
   478  	// Perform endpoint proof and check for sequence number in packet tail.
   479  	test.packetIn(nil, &pingV4{Expiration: futureExp})
   480  	test.waitPacketOut(func(p *pongV4, addr *net.UDPAddr, hash []byte) {
   481  		if seq := seqFromTail(p.Rest); seq != wantNode.Seq() {
   482  			t.Errorf("wrong sequence number in pong: %d, want %d", seq, wantNode.Seq())
   483  		}
   484  	})
   485  	test.waitPacketOut(func(p *pingV4, addr *net.UDPAddr, hash []byte) {
   486  		if seq := seqFromTail(p.Rest); seq != wantNode.Seq() {
   487  			t.Errorf("wrong sequence number in ping: %d, want %d", seq, wantNode.Seq())
   488  		}
   489  		test.packetIn(nil, &pongV4{Expiration: futureExp, ReplyTok: hash})
   490  	})
   491  
   492  	// Request should work now.
   493  	test.packetIn(nil, &enrRequestV4{Expiration: futureExp})
   494  	test.waitPacketOut(func(p *enrResponseV4, addr *net.UDPAddr, hash []byte) {
   495  		n, err := enode.New(enode.ValidSchemes, &p.Record)
   496  		if err != nil {
   497  			t.Fatalf("invalid record: %v", err)
   498  		}
   499  		if !reflect.DeepEqual(n, wantNode) {
   500  			t.Fatalf("wrong node in enrResponse: %v", n)
   501  		}
   502  	})
   503  }
   504  
   505  // EIP-8 test vectors.
   506  var testPackets = []struct {
   507  	input      string
   508  	wantPacket interface{}
   509  }{
   510  	{
   511  		input: "71dbda3a79554728d4f94411e42ee1f8b0d561c10e1e5f5893367948c6a7d70bb87b235fa28a77070271b6c164a2dce8c7e13a5739b53b5e96f2e5acb0e458a02902f5965d55ecbeb2ebb6cabb8b2b232896a36b737666c55265ad0a68412f250001ea04cb847f000001820cfa8215a8d790000000000000000000000000000000018208ae820d058443b9a355",
   512  		wantPacket: &pingV4{
   513  			Version:    4,
   514  			From:       rpcEndpoint{net.ParseIP("127.0.0.1").To4(), 3322, 5544},
   515  			To:         rpcEndpoint{net.ParseIP("::1"), 2222, 3333},
   516  			Expiration: 1136239445,
   517  			Rest:       []rlp.RawValue{},
   518  		},
   519  	},
   520  	{
   521  		input: "e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663aaa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000000000000000000000018208ae820d058443b9a3550102",
   522  		wantPacket: &pingV4{
   523  			Version:    4,
   524  			From:       rpcEndpoint{net.ParseIP("127.0.0.1").To4(), 3322, 5544},
   525  			To:         rpcEndpoint{net.ParseIP("::1"), 2222, 3333},
   526  			Expiration: 1136239445,
   527  			Rest:       []rlp.RawValue{{0x01}, {0x02}},
   528  		},
   529  	},
   530  	{
   531  		input: "577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba76023fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee1917084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c76d922dc3",
   532  		wantPacket: &pingV4{
   533  			Version:    555,
   534  			From:       rpcEndpoint{net.ParseIP("2001:db8:3c4d:15::abcd:ef12"), 3322, 5544},
   535  			To:         rpcEndpoint{net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 2222, 33338},
   536  			Expiration: 1136239445,
   537  			Rest:       []rlp.RawValue{{0xC5, 0x01, 0x02, 0x03, 0x04, 0x05}},
   538  		},
   539  	},
   540  	{
   541  		input: "09b2428d83348d27cdf7064ad9024f526cebc19e4958f0fdad87c15eb598dd61d08423e0bf66b2069869e1724125f820d851c136684082774f870e614d95a2855d000f05d1648b2d5945470bc187c2d2216fbe870f43ed0909009882e176a46b0102f846d79020010db885a308d313198a2e037073488208ae82823aa0fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c9548443b9a355c6010203c2040506a0c969a58f6f9095004c0177a6b47f451530cab38966a25cca5cb58f055542124e",
   542  		wantPacket: &pongV4{
   543  			To:         rpcEndpoint{net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 2222, 33338},
   544  			ReplyTok:   common.Hex2Bytes("fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c954"),
   545  			Expiration: 1136239445,
   546  			Rest:       []rlp.RawValue{{0xC6, 0x01, 0x02, 0x03, 0xC2, 0x04, 0x05}, {0x06}},
   547  		},
   548  	},
   549  	{
   550  		input: "c7c44041b9f7c7e41934417ebac9a8e1a4c6298f74553f2fcfdcae6ed6fe53163eb3d2b52e39fe91831b8a927bf4fc222c3902202027e5e9eb812195f95d20061ef5cd31d502e47ecb61183f74a504fe04c51e73df81f25c4d506b26db4517490103f84eb840ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f8443b9a35582999983999999280dc62cc8255c73471e0a61da0c89acdc0e035e260add7fc0c04ad9ebf3919644c91cb247affc82b69bd2ca235c71eab8e49737c937a2c396",
   551  		wantPacket: &findnodeV4{
   552  			Target:     hexEncPubkey("ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f"),
   553  			Expiration: 1136239445,
   554  			Rest:       []rlp.RawValue{{0x82, 0x99, 0x99}, {0x83, 0x99, 0x99, 0x99}},
   555  		},
   556  	},
   557  	{
   558  		input: "c679fc8fe0b8b12f06577f2e802d34f6fa257e6137a995f6f4cbfc9ee50ed3710faf6e66f932c4c8d81d64343f429651328758b47d3dbc02c4042f0fff6946a50f4a49037a72bb550f3a7872363a83e1b9ee6469856c24eb4ef80b7535bcf99c0004f9015bf90150f84d846321163782115c82115db8403155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32f84984010203040101b840312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069dbf8599020010db83c4d001500000000abcdef12820d05820d05b84038643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aacf8599020010db885a308d313198a2e037073488203e78203e8b8408dcab8618c3253b558d459da53bd8fa68935a719aff8b811197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df738443b9a355010203b525a138aa34383fec3d2719a0",
   559  		wantPacket: &neighborsV4{
   560  			Nodes: []rpcNode{
   561  				{
   562  					ID:  hexEncPubkey("3155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32"),
   563  					IP:  net.ParseIP("99.33.22.55").To4(),
   564  					UDP: 4444,
   565  					TCP: 4445,
   566  				},
   567  				{
   568  					ID:  hexEncPubkey("312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069db"),
   569  					IP:  net.ParseIP("1.2.3.4").To4(),
   570  					UDP: 1,
   571  					TCP: 1,
   572  				},
   573  				{
   574  					ID:  hexEncPubkey("38643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aac"),
   575  					IP:  net.ParseIP("2001:db8:3c4d:15::abcd:ef12"),
   576  					UDP: 3333,
   577  					TCP: 3333,
   578  				},
   579  				{
   580  					ID:  hexEncPubkey("8dcab8618c3253b558d459da53bd8fa68935a719aff8b811197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df73"),
   581  					IP:  net.ParseIP("2001:db8:85a3:8d3:1319:8a2e:370:7348"),
   582  					UDP: 999,
   583  					TCP: 1000,
   584  				},
   585  			},
   586  			Expiration: 1136239445,
   587  			Rest:       []rlp.RawValue{{0x01}, {0x02}, {0x03}},
   588  		},
   589  	},
   590  }
   591  
   592  func TestUDPv4_forwardCompatibility(t *testing.T) {
   593  	testkey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   594  	wantNodeKey := encodePubkey(&testkey.PublicKey)
   595  
   596  	for _, test := range testPackets {
   597  		input, err := hex.DecodeString(test.input)
   598  		if err != nil {
   599  			t.Fatalf("invalid hex: %s", test.input)
   600  		}
   601  		packet, nodekey, _, err := decodeV4(input)
   602  		if err != nil {
   603  			t.Errorf("did not accept packet %s\n%v", test.input, err)
   604  			continue
   605  		}
   606  		if !reflect.DeepEqual(packet, test.wantPacket) {
   607  			t.Errorf("got %s\nwant %s", spew.Sdump(packet), spew.Sdump(test.wantPacket))
   608  		}
   609  		if nodekey != wantNodeKey {
   610  			t.Errorf("got id %v\nwant id %v", nodekey, wantNodeKey)
   611  		}
   612  	}
   613  }
   614  
   615  // dgramPipe is a fake UDP socket. It queues all sent datagrams.
   616  type dgramPipe struct {
   617  	mu      *sync.Mutex
   618  	cond    *sync.Cond
   619  	closing chan struct{}
   620  	closed  bool
   621  	queue   []dgram
   622  }
   623  
   624  type dgram struct {
   625  	to   net.UDPAddr
   626  	data []byte
   627  }
   628  
   629  func newpipe() *dgramPipe {
   630  	mu := new(sync.Mutex)
   631  	return &dgramPipe{
   632  		closing: make(chan struct{}),
   633  		cond:    &sync.Cond{L: mu},
   634  		mu:      mu,
   635  	}
   636  }
   637  
   638  // WriteToUDP queues a datagram.
   639  func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) {
   640  	msg := make([]byte, len(b))
   641  	copy(msg, b)
   642  	c.mu.Lock()
   643  	defer c.mu.Unlock()
   644  	if c.closed {
   645  		return 0, errors.New("closed")
   646  	}
   647  	c.queue = append(c.queue, dgram{*to, b})
   648  	c.cond.Signal()
   649  	return len(b), nil
   650  }
   651  
   652  // ReadFromUDP just hangs until the pipe is closed.
   653  func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
   654  	<-c.closing
   655  	return 0, nil, io.EOF
   656  }
   657  
   658  func (c *dgramPipe) Close() error {
   659  	c.mu.Lock()
   660  	defer c.mu.Unlock()
   661  	if !c.closed {
   662  		close(c.closing)
   663  		c.closed = true
   664  	}
   665  	c.cond.Broadcast()
   666  	return nil
   667  }
   668  
   669  func (c *dgramPipe) LocalAddr() net.Addr {
   670  	return &net.UDPAddr{IP: testLocal.IP, Port: int(testLocal.UDP)}
   671  }
   672  
   673  func (c *dgramPipe) receive() (dgram, error) {
   674  	c.mu.Lock()
   675  	defer c.mu.Unlock()
   676  
   677  	var timedOut bool
   678  	timer := time.AfterFunc(3*time.Second, func() {
   679  		c.mu.Lock()
   680  		timedOut = true
   681  		c.mu.Unlock()
   682  		c.cond.Broadcast()
   683  	})
   684  	defer timer.Stop()
   685  
   686  	for len(c.queue) == 0 && !c.closed && !timedOut {
   687  		c.cond.Wait()
   688  	}
   689  	if c.closed {
   690  		return dgram{}, errClosed
   691  	}
   692  	if timedOut {
   693  		return dgram{}, errTimeout
   694  	}
   695  	p := c.queue[0]
   696  	copy(c.queue, c.queue[1:])
   697  	c.queue = c.queue[:len(c.queue)-1]
   698  	return p, nil
   699  }