v4_udp_test.go 20 KB

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