udp_test.go 21 KB

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