v4_udp_test.go 24 KB

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