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