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