github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/p2p/discover/v4_udp_test.go (about)

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