udp_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. "errors"
  22. "fmt"
  23. "io"
  24. logpkg "log"
  25. "math/rand"
  26. "net"
  27. "os"
  28. "path/filepath"
  29. "reflect"
  30. "runtime"
  31. "sync"
  32. "testing"
  33. "time"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/logger"
  36. )
  37. func init() {
  38. logger.AddLogSystem(logger.NewStdLogSystem(os.Stdout, logpkg.LstdFlags, logger.ErrorLevel))
  39. }
  40. // shared test variables
  41. var (
  42. futureExp = uint64(time.Now().Add(10 * time.Hour).Unix())
  43. testTarget = NodeID{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}
  44. testRemote = rpcEndpoint{IP: net.ParseIP("1.1.1.1").To4(), UDP: 1, TCP: 2}
  45. testLocalAnnounced = rpcEndpoint{IP: net.ParseIP("2.2.2.2").To4(), UDP: 3, TCP: 4}
  46. testLocal = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6}
  47. )
  48. type udpTest struct {
  49. t *testing.T
  50. pipe *dgramPipe
  51. table *Table
  52. udp *udp
  53. sent [][]byte
  54. localkey, remotekey *ecdsa.PrivateKey
  55. remoteaddr *net.UDPAddr
  56. }
  57. func newUDPTest(t *testing.T) *udpTest {
  58. test := &udpTest{
  59. t: t,
  60. pipe: newpipe(),
  61. localkey: newkey(),
  62. remotekey: newkey(),
  63. remoteaddr: &net.UDPAddr{IP: net.IP{1, 2, 3, 4}, Port: 30303},
  64. }
  65. test.table, test.udp, _ = newUDP(test.localkey, test.pipe, nil, "")
  66. return test
  67. }
  68. // handles a packet as if it had been sent to the transport.
  69. func (test *udpTest) packetIn(wantError error, ptype byte, data packet) error {
  70. enc, err := encodePacket(test.remotekey, ptype, data)
  71. if err != nil {
  72. return test.errorf("packet (%d) encode error: %v", err)
  73. }
  74. test.sent = append(test.sent, enc)
  75. if err = test.udp.handlePacket(test.remoteaddr, enc); err != wantError {
  76. return test.errorf("error mismatch: got %q, want %q", err, wantError)
  77. }
  78. return nil
  79. }
  80. // waits for a packet to be sent by the transport.
  81. // validate should have type func(*udpTest, X) error, where X is a packet type.
  82. func (test *udpTest) waitPacketOut(validate interface{}) error {
  83. dgram := test.pipe.waitPacketOut()
  84. p, _, _, err := decodePacket(dgram)
  85. if err != nil {
  86. return test.errorf("sent packet decode error: %v", err)
  87. }
  88. fn := reflect.ValueOf(validate)
  89. exptype := fn.Type().In(0)
  90. if reflect.TypeOf(p) != exptype {
  91. return test.errorf("sent packet type mismatch, got: %v, want: %v", reflect.TypeOf(p), exptype)
  92. }
  93. fn.Call([]reflect.Value{reflect.ValueOf(p)})
  94. return nil
  95. }
  96. func (test *udpTest) errorf(format string, args ...interface{}) error {
  97. _, file, line, ok := runtime.Caller(2) // errorf + waitPacketOut
  98. if ok {
  99. file = filepath.Base(file)
  100. } else {
  101. file = "???"
  102. line = 1
  103. }
  104. err := fmt.Errorf(format, args...)
  105. fmt.Printf("\t%s:%d: %v\n", file, line, err)
  106. test.t.Fail()
  107. return err
  108. }
  109. func TestUDP_packetErrors(t *testing.T) {
  110. test := newUDPTest(t)
  111. defer test.table.Close()
  112. test.packetIn(errExpired, pingPacket, &ping{From: testRemote, To: testLocalAnnounced, Version: Version})
  113. test.packetIn(errUnsolicitedReply, pongPacket, &pong{ReplyTok: []byte{}, Expiration: futureExp})
  114. test.packetIn(errUnknownNode, findnodePacket, &findnode{Expiration: futureExp})
  115. test.packetIn(errUnsolicitedReply, neighborsPacket, &neighbors{Expiration: futureExp})
  116. }
  117. func TestUDP_pingTimeout(t *testing.T) {
  118. t.Parallel()
  119. test := newUDPTest(t)
  120. defer test.table.Close()
  121. toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222}
  122. toid := NodeID{1, 2, 3, 4}
  123. if err := test.udp.ping(toid, toaddr); err != errTimeout {
  124. t.Error("expected timeout error, got", err)
  125. }
  126. }
  127. func TestUDP_responseTimeouts(t *testing.T) {
  128. t.Parallel()
  129. test := newUDPTest(t)
  130. defer test.table.Close()
  131. rand.Seed(time.Now().UnixNano())
  132. randomDuration := func(max time.Duration) time.Duration {
  133. return time.Duration(rand.Int63n(int64(max)))
  134. }
  135. var (
  136. nReqs = 200
  137. nTimeouts = 0 // number of requests with ptype > 128
  138. nilErr = make(chan error, nReqs) // for requests that get a reply
  139. timeoutErr = make(chan error, nReqs) // for requests that time out
  140. )
  141. for i := 0; i < nReqs; i++ {
  142. // Create a matcher for a random request in udp.loop. Requests
  143. // with ptype <= 128 will not get a reply and should time out.
  144. // For all other requests, a reply is scheduled to arrive
  145. // within the timeout window.
  146. p := &pending{
  147. ptype: byte(rand.Intn(255)),
  148. callback: func(interface{}) bool { return true },
  149. }
  150. binary.BigEndian.PutUint64(p.from[:], uint64(i))
  151. if p.ptype <= 128 {
  152. p.errc = timeoutErr
  153. test.udp.addpending <- p
  154. nTimeouts++
  155. } else {
  156. p.errc = nilErr
  157. test.udp.addpending <- p
  158. time.AfterFunc(randomDuration(60*time.Millisecond), func() {
  159. if !test.udp.handleReply(p.from, p.ptype, nil) {
  160. t.Logf("not matched: %v", p)
  161. }
  162. })
  163. }
  164. time.Sleep(randomDuration(30 * time.Millisecond))
  165. }
  166. // Check that all timeouts were delivered and that the rest got nil errors.
  167. // The replies must be delivered.
  168. var (
  169. recvDeadline = time.After(20 * time.Second)
  170. nTimeoutsRecv, nNil = 0, 0
  171. )
  172. for i := 0; i < nReqs; i++ {
  173. select {
  174. case err := <-timeoutErr:
  175. if err != errTimeout {
  176. t.Fatalf("got non-timeout error on timeoutErr %d: %v", i, err)
  177. }
  178. nTimeoutsRecv++
  179. case err := <-nilErr:
  180. if err != nil {
  181. t.Fatalf("got non-nil error on nilErr %d: %v", i, err)
  182. }
  183. nNil++
  184. case <-recvDeadline:
  185. t.Fatalf("exceeded recv deadline")
  186. }
  187. }
  188. if nTimeoutsRecv != nTimeouts {
  189. t.Errorf("wrong number of timeout errors received: got %d, want %d", nTimeoutsRecv, nTimeouts)
  190. }
  191. if nNil != nReqs-nTimeouts {
  192. t.Errorf("wrong number of successful replies: got %d, want %d", nNil, nReqs-nTimeouts)
  193. }
  194. }
  195. func TestUDP_findnodeTimeout(t *testing.T) {
  196. t.Parallel()
  197. test := newUDPTest(t)
  198. defer test.table.Close()
  199. toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222}
  200. toid := NodeID{1, 2, 3, 4}
  201. target := NodeID{4, 5, 6, 7}
  202. result, err := test.udp.findnode(toid, toaddr, target)
  203. if err != errTimeout {
  204. t.Error("expected timeout error, got", err)
  205. }
  206. if len(result) > 0 {
  207. t.Error("expected empty result, got", result)
  208. }
  209. }
  210. func TestUDP_findnode(t *testing.T) {
  211. test := newUDPTest(t)
  212. defer test.table.Close()
  213. // put a few nodes into the table. their exact
  214. // distribution shouldn't matter much, altough we need to
  215. // take care not to overflow any bucket.
  216. targetHash := crypto.Sha3Hash(testTarget[:])
  217. nodes := &nodesByDistance{target: targetHash}
  218. for i := 0; i < bucketSize; i++ {
  219. nodes.push(nodeAtDistance(test.table.self.sha, i+2), bucketSize)
  220. }
  221. test.table.stuff(nodes.entries)
  222. // ensure there's a bond with the test node,
  223. // findnode won't be accepted otherwise.
  224. test.table.db.updateNode(NewNode(
  225. PubkeyID(&test.remotekey.PublicKey),
  226. test.remoteaddr.IP,
  227. uint16(test.remoteaddr.Port),
  228. 99,
  229. ))
  230. // check that closest neighbors are returned.
  231. test.packetIn(nil, findnodePacket, &findnode{Target: testTarget, Expiration: futureExp})
  232. expected := test.table.closest(targetHash, bucketSize)
  233. waitNeighbors := func(want []*Node) {
  234. test.waitPacketOut(func(p *neighbors) {
  235. if len(p.Nodes) != len(want) {
  236. t.Errorf("wrong number of results: got %d, want %d", len(p.Nodes), bucketSize)
  237. }
  238. for i := range p.Nodes {
  239. if p.Nodes[i].ID != want[i].ID {
  240. t.Errorf("result mismatch at %d:\n got: %v\n want: %v", i, p.Nodes[i], expected.entries[i])
  241. }
  242. }
  243. })
  244. }
  245. waitNeighbors(expected.entries[:maxNeighbors])
  246. waitNeighbors(expected.entries[maxNeighbors:])
  247. }
  248. func TestUDP_findnodeMultiReply(t *testing.T) {
  249. test := newUDPTest(t)
  250. defer test.table.Close()
  251. // queue a pending findnode request
  252. resultc, errc := make(chan []*Node), make(chan error)
  253. go func() {
  254. rid := PubkeyID(&test.remotekey.PublicKey)
  255. ns, err := test.udp.findnode(rid, test.remoteaddr, testTarget)
  256. if err != nil && len(ns) == 0 {
  257. errc <- err
  258. } else {
  259. resultc <- ns
  260. }
  261. }()
  262. // wait for the findnode to be sent.
  263. // after it is sent, the transport is waiting for a reply
  264. test.waitPacketOut(func(p *findnode) {
  265. if p.Target != testTarget {
  266. t.Errorf("wrong target: got %v, want %v", p.Target, testTarget)
  267. }
  268. })
  269. // send the reply as two packets.
  270. list := []*Node{
  271. MustParseNode("enode://ba85011c70bcc5c04d8607d3a0ed29aa6179c092cbdda10d5d32684fb33ed01bd94f588ca8f91ac48318087dcb02eaf36773a7a453f0eedd6742af668097b29c@10.0.1.16:30303?discport=30304"),
  272. MustParseNode("enode://81fa361d25f157cd421c60dcc28d8dac5ef6a89476633339c5df30287474520caca09627da18543d9079b5b288698b542d56167aa5c09111e55acdbbdf2ef799@10.0.1.16:30303"),
  273. MustParseNode("enode://9bffefd833d53fac8e652415f4973bee289e8b1a5c6c4cbe70abf817ce8a64cee11b823b66a987f51aaa9fba0d6a91b3e6bf0d5a5d1042de8e9eeea057b217f8@10.0.1.36:30301?discport=17"),
  274. MustParseNode("enode://1b5b4aa662d7cb44a7221bfba67302590b643028197a7d5214790f3bac7aaa4a3241be9e83c09cf1f6c69d007c634faae3dc1b1221793e8446c0b3a09de65960@10.0.1.16:30303"),
  275. }
  276. rpclist := make([]rpcNode, len(list))
  277. for i := range list {
  278. rpclist[i] = nodeToRPC(list[i])
  279. }
  280. test.packetIn(nil, neighborsPacket, &neighbors{Expiration: futureExp, Nodes: rpclist[:2]})
  281. test.packetIn(nil, neighborsPacket, &neighbors{Expiration: futureExp, Nodes: rpclist[2:]})
  282. // check that the sent neighbors are all returned by findnode
  283. select {
  284. case result := <-resultc:
  285. if !reflect.DeepEqual(result, list) {
  286. t.Errorf("neighbors mismatch:\n got: %v\n want: %v", result, list)
  287. }
  288. case err := <-errc:
  289. t.Errorf("findnode error: %v", err)
  290. case <-time.After(5 * time.Second):
  291. t.Error("findnode did not return within 5 seconds")
  292. }
  293. }
  294. func TestUDP_successfulPing(t *testing.T) {
  295. test := newUDPTest(t)
  296. added := make(chan *Node, 1)
  297. test.table.nodeAddedHook = func(n *Node) { added <- n }
  298. defer test.table.Close()
  299. // The remote side sends a ping packet to initiate the exchange.
  300. go test.packetIn(nil, pingPacket, &ping{From: testRemote, To: testLocalAnnounced, Version: Version, Expiration: futureExp})
  301. // the ping is replied to.
  302. test.waitPacketOut(func(p *pong) {
  303. pinghash := test.sent[0][:macSize]
  304. if !bytes.Equal(p.ReplyTok, pinghash) {
  305. t.Errorf("got pong.ReplyTok %x, want %x", p.ReplyTok, pinghash)
  306. }
  307. wantTo := rpcEndpoint{
  308. // The mirrored UDP address is the UDP packet sender
  309. IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port),
  310. // The mirrored TCP port is the one from the ping packet
  311. TCP: testRemote.TCP,
  312. }
  313. if !reflect.DeepEqual(p.To, wantTo) {
  314. t.Errorf("got pong.To %v, want %v", p.To, wantTo)
  315. }
  316. })
  317. // remote is unknown, the table pings back.
  318. test.waitPacketOut(func(p *ping) error {
  319. if !reflect.DeepEqual(p.From, test.udp.ourEndpoint) {
  320. t.Errorf("got ping.From %v, want %v", p.From, test.udp.ourEndpoint)
  321. }
  322. wantTo := rpcEndpoint{
  323. // The mirrored UDP address is the UDP packet sender.
  324. IP: test.remoteaddr.IP, UDP: uint16(test.remoteaddr.Port),
  325. TCP: 0,
  326. }
  327. if !reflect.DeepEqual(p.To, wantTo) {
  328. t.Errorf("got ping.To %v, want %v", p.To, wantTo)
  329. }
  330. return nil
  331. })
  332. test.packetIn(nil, pongPacket, &pong{Expiration: futureExp})
  333. // the node should be added to the table shortly after getting the
  334. // pong packet.
  335. select {
  336. case n := <-added:
  337. rid := PubkeyID(&test.remotekey.PublicKey)
  338. if n.ID != rid {
  339. t.Errorf("node has wrong ID: got %v, want %v", n.ID, rid)
  340. }
  341. if !bytes.Equal(n.IP, test.remoteaddr.IP) {
  342. t.Errorf("node has wrong IP: got %v, want: %v", n.IP, test.remoteaddr.IP)
  343. }
  344. if int(n.UDP) != test.remoteaddr.Port {
  345. t.Errorf("node has wrong UDP port: got %v, want: %v", n.UDP, test.remoteaddr.Port)
  346. }
  347. if n.TCP != testRemote.TCP {
  348. t.Errorf("node has wrong TCP port: got %v, want: %v", n.TCP, testRemote.TCP)
  349. }
  350. case <-time.After(2 * time.Second):
  351. t.Errorf("node was not added within 2 seconds")
  352. }
  353. }
  354. // dgramPipe is a fake UDP socket. It queues all sent datagrams.
  355. type dgramPipe struct {
  356. mu *sync.Mutex
  357. cond *sync.Cond
  358. closing chan struct{}
  359. closed bool
  360. queue [][]byte
  361. }
  362. func newpipe() *dgramPipe {
  363. mu := new(sync.Mutex)
  364. return &dgramPipe{
  365. closing: make(chan struct{}),
  366. cond: &sync.Cond{L: mu},
  367. mu: mu,
  368. }
  369. }
  370. // WriteToUDP queues a datagram.
  371. func (c *dgramPipe) WriteToUDP(b []byte, to *net.UDPAddr) (n int, err error) {
  372. msg := make([]byte, len(b))
  373. copy(msg, b)
  374. c.mu.Lock()
  375. defer c.mu.Unlock()
  376. if c.closed {
  377. return 0, errors.New("closed")
  378. }
  379. c.queue = append(c.queue, msg)
  380. c.cond.Signal()
  381. return len(b), nil
  382. }
  383. // ReadFromUDP just hangs until the pipe is closed.
  384. func (c *dgramPipe) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
  385. <-c.closing
  386. return 0, nil, io.EOF
  387. }
  388. func (c *dgramPipe) Close() error {
  389. c.mu.Lock()
  390. defer c.mu.Unlock()
  391. if !c.closed {
  392. close(c.closing)
  393. c.closed = true
  394. }
  395. return nil
  396. }
  397. func (c *dgramPipe) LocalAddr() net.Addr {
  398. return &net.UDPAddr{IP: testLocal.IP, Port: int(testLocal.UDP)}
  399. }
  400. func (c *dgramPipe) waitPacketOut() []byte {
  401. c.mu.Lock()
  402. defer c.mu.Unlock()
  403. for len(c.queue) == 0 {
  404. c.cond.Wait()
  405. }
  406. p := c.queue[0]
  407. copy(c.queue, c.queue[1:])
  408. c.queue = c.queue[:len(c.queue)-1]
  409. return p
  410. }