v4_udp_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. return
  258. }
  259. for i, n := range p.Nodes {
  260. if n.ID.ID() != want[i].ID() {
  261. t.Errorf("result mismatch at %d:\n got: %v\n want: %v", i, n, expected.entries[i])
  262. }
  263. if !live[n.ID.ID()] {
  264. t.Errorf("result includes dead node %v", n.ID.ID())
  265. }
  266. }
  267. })
  268. }
  269. // Receive replies.
  270. want := expected.entries
  271. if len(want) > v4wire.MaxNeighbors {
  272. waitNeighbors(want[:v4wire.MaxNeighbors])
  273. want = want[v4wire.MaxNeighbors:]
  274. }
  275. waitNeighbors(want)
  276. }
  277. func TestUDPv4_findnodeMultiReply(t *testing.T) {
  278. test := newUDPTest(t)
  279. defer test.close()
  280. rid := enode.PubkeyToIDV4(&test.remotekey.PublicKey)
  281. test.table.db.UpdateLastPingReceived(rid, test.remoteaddr.IP, time.Now())
  282. // queue a pending findnode request
  283. resultc, errc := make(chan []*node), make(chan error)
  284. go func() {
  285. rid := encodePubkey(&test.remotekey.PublicKey).id()
  286. ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget)
  287. if err != nil && len(ns) == 0 {
  288. errc <- err
  289. } else {
  290. resultc <- ns
  291. }
  292. }()
  293. // wait for the findnode to be sent.
  294. // after it is sent, the transport is waiting for a reply
  295. test.waitPacketOut(func(p *v4wire.Findnode, to *net.UDPAddr, hash []byte) {
  296. if p.Target != testTarget {
  297. t.Errorf("wrong target: got %v, want %v", p.Target, testTarget)
  298. }
  299. })
  300. // send the reply as two packets.
  301. list := []*node{
  302. wrapNode(enode.MustParse("enode://ba85011c70bcc5c04d8607d3a0ed29aa6179c092cbdda10d5d32684fb33ed01bd94f588ca8f91ac48318087dcb02eaf36773a7a453f0eedd6742af668097b29c@10.0.1.16:30303?discport=30304")),
  303. wrapNode(enode.MustParse("enode://81fa361d25f157cd421c60dcc28d8dac5ef6a89476633339c5df30287474520caca09627da18543d9079b5b288698b542d56167aa5c09111e55acdbbdf2ef799@10.0.1.16:30303")),
  304. wrapNode(enode.MustParse("enode://9bffefd833d53fac8e652415f4973bee289e8b1a5c6c4cbe70abf817ce8a64cee11b823b66a987f51aaa9fba0d6a91b3e6bf0d5a5d1042de8e9eeea057b217f8@10.0.1.36:30301?discport=17")),
  305. wrapNode(enode.MustParse("enode://1b5b4aa662d7cb44a7221bfba67302590b643028197a7d5214790f3bac7aaa4a3241be9e83c09cf1f6c69d007c634faae3dc1b1221793e8446c0b3a09de65960@10.0.1.16:30303")),
  306. }
  307. rpclist := make([]v4wire.Node, len(list))
  308. for i := range list {
  309. rpclist[i] = nodeToRPC(list[i])
  310. }
  311. test.packetIn(nil, &v4wire.Neighbors{Expiration: futureExp, Nodes: rpclist[:2]})
  312. test.packetIn(nil, &v4wire.Neighbors{Expiration: futureExp, Nodes: rpclist[2:]})
  313. // check that the sent neighbors are all returned by findnode
  314. select {
  315. case result := <-resultc:
  316. want := append(list[:2], list[3:]...)
  317. if !reflect.DeepEqual(result, want) {
  318. t.Errorf("neighbors mismatch:\n got: %v\n want: %v", result, want)
  319. }
  320. case err := <-errc:
  321. t.Errorf("findnode error: %v", err)
  322. case <-time.After(5 * time.Second):
  323. t.Error("findnode did not return within 5 seconds")
  324. }
  325. }
  326. // This test checks that reply matching of pong verifies the ping hash.
  327. func TestUDPv4_pingMatch(t *testing.T) {
  328. test := newUDPTest(t)
  329. defer test.close()
  330. randToken := make([]byte, 32)
  331. crand.Read(randToken)
  332. test.packetIn(nil, &v4wire.Ping{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp})
  333. test.waitPacketOut(func(*v4wire.Pong, *net.UDPAddr, []byte) {})
  334. test.waitPacketOut(func(*v4wire.Ping, *net.UDPAddr, []byte) {})
  335. test.packetIn(errUnsolicitedReply, &v4wire.Pong{ReplyTok: randToken, To: testLocalAnnounced, Expiration: futureExp})
  336. }
  337. // This test checks that reply matching of pong verifies the sender IP address.
  338. func TestUDPv4_pingMatchIP(t *testing.T) {
  339. test := newUDPTest(t)
  340. defer test.close()
  341. test.packetIn(nil, &v4wire.Ping{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp})
  342. test.waitPacketOut(func(*v4wire.Pong, *net.UDPAddr, []byte) {})
  343. test.waitPacketOut(func(p *v4wire.Ping, to *net.UDPAddr, hash []byte) {
  344. wrongAddr := &net.UDPAddr{IP: net.IP{33, 44, 1, 2}, Port: 30000}
  345. test.packetInFrom(errUnsolicitedReply, test.remotekey, wrongAddr, &v4wire.Pong{
  346. ReplyTok: hash,
  347. To: testLocalAnnounced,
  348. Expiration: futureExp,
  349. })
  350. })
  351. }
  352. func TestUDPv4_successfulPing(t *testing.T) {
  353. test := newUDPTest(t)
  354. added := make(chan *node, 1)
  355. test.table.nodeAddedHook = func(n *node) { added <- n }
  356. defer test.close()
  357. // The remote side sends a ping packet to initiate the exchange.
  358. go test.packetIn(nil, &v4wire.Ping{From: testRemote, To: testLocalAnnounced, Version: 4, Expiration: futureExp})
  359. // The ping is replied to.
  360. test.waitPacketOut(func(p *v4wire.Pong, to *net.UDPAddr, hash []byte) {
  361. pinghash := test.sent[0][:32]
  362. if !bytes.Equal(p.ReplyTok, pinghash) {
  363. t.Errorf("got pong.ReplyTok %x, want %x", p.ReplyTok, pinghash)
  364. }
  365. wantTo := v4wire.Endpoint{
  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. // Remote is unknown, the table pings back.
  376. test.waitPacketOut(func(p *v4wire.Ping, to *net.UDPAddr, hash []byte) {
  377. if !reflect.DeepEqual(p.From, test.udp.ourEndpoint()) {
  378. t.Errorf("got ping.From %#v, want %#v", p.From, test.udp.ourEndpoint())
  379. }
  380. wantTo := v4wire.Endpoint{
  381. // The mirrored UDP address is the UDP packet sender.
  382. IP: test.remoteaddr.IP,
  383. UDP: uint16(test.remoteaddr.Port),
  384. TCP: 0,
  385. }
  386. if !reflect.DeepEqual(p.To, wantTo) {
  387. t.Errorf("got ping.To %v, want %v", p.To, wantTo)
  388. }
  389. test.packetIn(nil, &v4wire.Pong{ReplyTok: hash, Expiration: futureExp})
  390. })
  391. // The node should be added to the table shortly after getting the
  392. // pong packet.
  393. select {
  394. case n := <-added:
  395. rid := encodePubkey(&test.remotekey.PublicKey).id()
  396. if n.ID() != rid {
  397. t.Errorf("node has wrong ID: got %v, want %v", n.ID(), rid)
  398. }
  399. if !n.IP().Equal(test.remoteaddr.IP) {
  400. t.Errorf("node has wrong IP: got %v, want: %v", n.IP(), test.remoteaddr.IP)
  401. }
  402. if n.UDP() != test.remoteaddr.Port {
  403. t.Errorf("node has wrong UDP port: got %v, want: %v", n.UDP(), test.remoteaddr.Port)
  404. }
  405. if n.TCP() != int(testRemote.TCP) {
  406. t.Errorf("node has wrong TCP port: got %v, want: %v", n.TCP(), testRemote.TCP)
  407. }
  408. case <-time.After(2 * time.Second):
  409. t.Errorf("node was not added within 2 seconds")
  410. }
  411. }
  412. // This test checks that EIP-868 requests work.
  413. func TestUDPv4_EIP868(t *testing.T) {
  414. test := newUDPTest(t)
  415. defer test.close()
  416. test.udp.localNode.Set(enr.WithEntry("foo", "bar"))
  417. wantNode := test.udp.localNode.Node()
  418. // ENR requests aren't allowed before endpoint proof.
  419. test.packetIn(errUnknownNode, &v4wire.ENRRequest{Expiration: futureExp})
  420. // Perform endpoint proof and check for sequence number in packet tail.
  421. test.packetIn(nil, &v4wire.Ping{Expiration: futureExp})
  422. test.waitPacketOut(func(p *v4wire.Pong, addr *net.UDPAddr, hash []byte) {
  423. if p.ENRSeq != wantNode.Seq() {
  424. t.Errorf("wrong sequence number in pong: %d, want %d", p.ENRSeq, wantNode.Seq())
  425. }
  426. })
  427. test.waitPacketOut(func(p *v4wire.Ping, addr *net.UDPAddr, hash []byte) {
  428. if p.ENRSeq != wantNode.Seq() {
  429. t.Errorf("wrong sequence number in ping: %d, want %d", p.ENRSeq, wantNode.Seq())
  430. }
  431. test.packetIn(nil, &v4wire.Pong{Expiration: futureExp, ReplyTok: hash})
  432. })
  433. // Request should work now.
  434. test.packetIn(nil, &v4wire.ENRRequest{Expiration: futureExp})
  435. test.waitPacketOut(func(p *v4wire.ENRResponse, addr *net.UDPAddr, hash []byte) {
  436. n, err := enode.New(enode.ValidSchemes, &p.Record)
  437. if err != nil {
  438. t.Fatalf("invalid record: %v", err)
  439. }
  440. if !reflect.DeepEqual(n, wantNode) {
  441. t.Fatalf("wrong node in ENRResponse: %v", n)
  442. }
  443. })
  444. }
  445. // This test verifies that a small network of nodes can boot up into a healthy state.
  446. func TestUDPv4_smallNetConvergence(t *testing.T) {
  447. t.Parallel()
  448. // Start the network.
  449. nodes := make([]*UDPv4, 4)
  450. for i := range nodes {
  451. var cfg Config
  452. if i > 0 {
  453. bn := nodes[0].Self()
  454. cfg.Bootnodes = []*enode.Node{bn}
  455. }
  456. nodes[i] = startLocalhostV4(t, cfg)
  457. defer nodes[i].Close()
  458. }
  459. // Run through the iterator on all nodes until
  460. // they have all found each other.
  461. status := make(chan error, len(nodes))
  462. for i := range nodes {
  463. node := nodes[i]
  464. go func() {
  465. found := make(map[enode.ID]bool, len(nodes))
  466. it := node.RandomNodes()
  467. for it.Next() {
  468. found[it.Node().ID()] = true
  469. if len(found) == len(nodes) {
  470. status <- nil
  471. return
  472. }
  473. }
  474. status <- fmt.Errorf("node %s didn't find all nodes", node.Self().ID().TerminalString())
  475. }()
  476. }
  477. // Wait for all status reports.
  478. timeout := time.NewTimer(30 * time.Second)
  479. defer timeout.Stop()
  480. for received := 0; received < len(nodes); {
  481. select {
  482. case <-timeout.C:
  483. for _, node := range nodes {
  484. node.Close()
  485. }
  486. case err := <-status:
  487. received++
  488. if err != nil {
  489. t.Error("ERROR:", err)
  490. return
  491. }
  492. }
  493. }
  494. }
  495. func startLocalhostV4(t *testing.T, cfg Config) *UDPv4 {
  496. t.Helper()
  497. cfg.PrivateKey = newkey()
  498. db, _ := enode.OpenDB("")
  499. ln := enode.NewLocalNode(db, cfg.PrivateKey)
  500. // Prefix logs with node ID.
  501. lprefix := fmt.Sprintf("(%s)", ln.ID().TerminalString())
  502. lfmt := log.TerminalFormat(false)
  503. cfg.Log = testlog.Logger(t, log.LvlTrace)
  504. cfg.Log.SetHandler(log.FuncHandler(func(r *log.Record) error {
  505. t.Logf("%s %s", lprefix, lfmt.Format(r))
  506. return nil
  507. }))
  508. // Listen.
  509. socket, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IP{127, 0, 0, 1}})
  510. if err != nil {
  511. t.Fatal(err)
  512. }
  513. realaddr := socket.LocalAddr().(*net.UDPAddr)
  514. ln.SetStaticIP(realaddr.IP)
  515. ln.SetFallbackUDP(realaddr.Port)
  516. udp, err := ListenV4(socket, ln, cfg)
  517. if err != nil {
  518. t.Fatal(err)
  519. }
  520. return udp
  521. }
  522. // dgramPipe is a fake UDP socket. It queues all sent datagrams.
  523. type dgramPipe struct {
  524. mu *sync.Mutex
  525. cond *sync.Cond
  526. closing chan struct{}
  527. closed bool
  528. queue []dgram
  529. }
  530. type dgram struct {
  531. to net.UDPAddr
  532. data []byte
  533. }
  534. func newpipe() *dgramPipe {
  535. mu := new(sync.Mutex)
  536. return &dgramPipe{
  537. closing: make(chan struct{}),
  538. cond: &sync.Cond{L: mu},
  539. mu: mu,
  540. }
  541. }
  542. // WriteToUDP queues a datagram.
  543. func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) {
  544. msg := make([]byte, len(b))
  545. copy(msg, b)
  546. c.mu.Lock()
  547. defer c.mu.Unlock()
  548. if c.closed {
  549. return 0, errors.New("closed")
  550. }
  551. c.queue = append(c.queue, dgram{*to, b})
  552. c.cond.Signal()
  553. return len(b), nil
  554. }
  555. // ReadFromUDP just hangs until the pipe is closed.
  556. func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
  557. <-c.closing
  558. return 0, nil, io.EOF
  559. }
  560. func (c *dgramPipe) Close() error {
  561. c.mu.Lock()
  562. defer c.mu.Unlock()
  563. if !c.closed {
  564. close(c.closing)
  565. c.closed = true
  566. }
  567. c.cond.Broadcast()
  568. return nil
  569. }
  570. func (c *dgramPipe) LocalAddr() net.Addr {
  571. return &net.UDPAddr{IP: testLocal.IP, Port: int(testLocal.UDP)}
  572. }
  573. func (c *dgramPipe) receive() (dgram, error) {
  574. c.mu.Lock()
  575. defer c.mu.Unlock()
  576. var timedOut bool
  577. timer := time.AfterFunc(3*time.Second, func() {
  578. c.mu.Lock()
  579. timedOut = true
  580. c.mu.Unlock()
  581. c.cond.Broadcast()
  582. })
  583. defer timer.Stop()
  584. for len(c.queue) == 0 && !c.closed && !timedOut {
  585. c.cond.Wait()
  586. }
  587. if c.closed {
  588. return dgram{}, errClosed
  589. }
  590. if timedOut {
  591. return dgram{}, errTimeout
  592. }
  593. p := c.queue[0]
  594. copy(c.queue, c.queue[1:])
  595. c.queue = c.queue[:len(c.queue)-1]
  596. return p, nil
  597. }