discv5tests.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // Copyright 2020 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package v5test
  17. import (
  18. "bytes"
  19. "net"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/internal/utesting"
  23. "github.com/ethereum/go-ethereum/p2p/discover/v5wire"
  24. "github.com/ethereum/go-ethereum/p2p/enode"
  25. "github.com/ethereum/go-ethereum/p2p/netutil"
  26. )
  27. // Suite is the discv5 test suite.
  28. type Suite struct {
  29. Dest *enode.Node
  30. Listen1, Listen2 string // listening addresses
  31. }
  32. func (s *Suite) listen1(log logger) (*conn, net.PacketConn) {
  33. c := newConn(s.Dest, log)
  34. l := c.listen(s.Listen1)
  35. return c, l
  36. }
  37. func (s *Suite) listen2(log logger) (*conn, net.PacketConn, net.PacketConn) {
  38. c := newConn(s.Dest, log)
  39. l1, l2 := c.listen(s.Listen1), c.listen(s.Listen2)
  40. return c, l1, l2
  41. }
  42. func (s *Suite) AllTests() []utesting.Test {
  43. return []utesting.Test{
  44. {Name: "Ping", Fn: s.TestPing},
  45. {Name: "PingLargeRequestID", Fn: s.TestPingLargeRequestID},
  46. {Name: "PingMultiIP", Fn: s.TestPingMultiIP},
  47. {Name: "PingHandshakeInterrupted", Fn: s.TestPingHandshakeInterrupted},
  48. {Name: "TalkRequest", Fn: s.TestTalkRequest},
  49. {Name: "FindnodeZeroDistance", Fn: s.TestFindnodeZeroDistance},
  50. {Name: "FindnodeResults", Fn: s.TestFindnodeResults},
  51. }
  52. }
  53. // This test sends PING and expects a PONG response.
  54. func (s *Suite) TestPing(t *utesting.T) {
  55. conn, l1 := s.listen1(t)
  56. defer conn.close()
  57. ping := &v5wire.Ping{ReqID: conn.nextReqID()}
  58. switch resp := conn.reqresp(l1, ping).(type) {
  59. case *v5wire.Pong:
  60. checkPong(t, resp, ping, l1)
  61. default:
  62. t.Fatal("expected PONG, got", resp.Name())
  63. }
  64. }
  65. func checkPong(t *utesting.T, pong *v5wire.Pong, ping *v5wire.Ping, c net.PacketConn) {
  66. if !bytes.Equal(pong.ReqID, ping.ReqID) {
  67. t.Fatalf("wrong request ID %x in PONG, want %x", pong.ReqID, ping.ReqID)
  68. }
  69. if !pong.ToIP.Equal(laddr(c).IP) {
  70. t.Fatalf("wrong destination IP %v in PONG, want %v", pong.ToIP, laddr(c).IP)
  71. }
  72. if int(pong.ToPort) != laddr(c).Port {
  73. t.Fatalf("wrong destination port %v in PONG, want %v", pong.ToPort, laddr(c).Port)
  74. }
  75. }
  76. // This test sends PING with a 9-byte request ID, which isn't allowed by the spec.
  77. // The remote node should not respond.
  78. func (s *Suite) TestPingLargeRequestID(t *utesting.T) {
  79. conn, l1 := s.listen1(t)
  80. defer conn.close()
  81. ping := &v5wire.Ping{ReqID: make([]byte, 9)}
  82. switch resp := conn.reqresp(l1, ping).(type) {
  83. case *v5wire.Pong:
  84. t.Errorf("PONG response with unknown request ID %x", resp.ReqID)
  85. case *readError:
  86. if resp.err == v5wire.ErrInvalidReqID {
  87. t.Error("response with oversized request ID")
  88. } else if !netutil.IsTimeout(resp.err) {
  89. t.Error(resp)
  90. }
  91. }
  92. }
  93. // In this test, a session is established from one IP as usual. The session is then reused
  94. // on another IP, which shouldn't work. The remote node should respond with WHOAREYOU for
  95. // the attempt from a different IP.
  96. func (s *Suite) TestPingMultiIP(t *utesting.T) {
  97. conn, l1, l2 := s.listen2(t)
  98. defer conn.close()
  99. // Create the session on l1.
  100. ping := &v5wire.Ping{ReqID: conn.nextReqID()}
  101. resp := conn.reqresp(l1, ping)
  102. if resp.Kind() != v5wire.PongMsg {
  103. t.Fatal("expected PONG, got", resp)
  104. }
  105. checkPong(t, resp.(*v5wire.Pong), ping, l1)
  106. // Send on l2. This reuses the session because there is only one codec.
  107. ping2 := &v5wire.Ping{ReqID: conn.nextReqID()}
  108. conn.write(l2, ping2, nil)
  109. switch resp := conn.read(l2).(type) {
  110. case *v5wire.Pong:
  111. t.Fatalf("remote responded to PING from %v for session on IP %v", laddr(l2).IP, laddr(l1).IP)
  112. case *v5wire.Whoareyou:
  113. t.Logf("got WHOAREYOU for new session as expected")
  114. resp.Node = s.Dest
  115. conn.write(l2, ping2, resp)
  116. default:
  117. t.Fatal("expected WHOAREYOU, got", resp)
  118. }
  119. // Catch the PONG on l2.
  120. switch resp := conn.read(l2).(type) {
  121. case *v5wire.Pong:
  122. checkPong(t, resp, ping2, l2)
  123. default:
  124. t.Fatal("expected PONG, got", resp)
  125. }
  126. // Try on l1 again.
  127. ping3 := &v5wire.Ping{ReqID: conn.nextReqID()}
  128. conn.write(l1, ping3, nil)
  129. switch resp := conn.read(l1).(type) {
  130. case *v5wire.Pong:
  131. t.Fatalf("remote responded to PING from %v for session on IP %v", laddr(l1).IP, laddr(l2).IP)
  132. case *v5wire.Whoareyou:
  133. t.Logf("got WHOAREYOU for new session as expected")
  134. default:
  135. t.Fatal("expected WHOAREYOU, got", resp)
  136. }
  137. }
  138. // This test starts a handshake, but doesn't finish it and sends a second ordinary message
  139. // packet instead of a handshake message packet. The remote node should respond with
  140. // another WHOAREYOU challenge for the second packet.
  141. func (s *Suite) TestPingHandshakeInterrupted(t *utesting.T) {
  142. conn, l1 := s.listen1(t)
  143. defer conn.close()
  144. // First PING triggers challenge.
  145. ping := &v5wire.Ping{ReqID: conn.nextReqID()}
  146. conn.write(l1, ping, nil)
  147. switch resp := conn.read(l1).(type) {
  148. case *v5wire.Whoareyou:
  149. t.Logf("got WHOAREYOU for PING")
  150. default:
  151. t.Fatal("expected WHOAREYOU, got", resp)
  152. }
  153. // Send second PING.
  154. ping2 := &v5wire.Ping{ReqID: conn.nextReqID()}
  155. switch resp := conn.reqresp(l1, ping2).(type) {
  156. case *v5wire.Pong:
  157. checkPong(t, resp, ping2, l1)
  158. default:
  159. t.Fatal("expected WHOAREYOU, got", resp)
  160. }
  161. }
  162. // This test sends TALKREQ and expects an empty TALKRESP response.
  163. func (s *Suite) TestTalkRequest(t *utesting.T) {
  164. conn, l1 := s.listen1(t)
  165. defer conn.close()
  166. // Non-empty request ID.
  167. id := conn.nextReqID()
  168. resp := conn.reqresp(l1, &v5wire.TalkRequest{ReqID: id, Protocol: "test-protocol"})
  169. switch resp := resp.(type) {
  170. case *v5wire.TalkResponse:
  171. if !bytes.Equal(resp.ReqID, id) {
  172. t.Fatalf("wrong request ID %x in TALKRESP, want %x", resp.ReqID, id)
  173. }
  174. if len(resp.Message) > 0 {
  175. t.Fatalf("non-empty message %x in TALKRESP", resp.Message)
  176. }
  177. default:
  178. t.Fatal("expected TALKRESP, got", resp.Name())
  179. }
  180. // Empty request ID.
  181. resp = conn.reqresp(l1, &v5wire.TalkRequest{Protocol: "test-protocol"})
  182. switch resp := resp.(type) {
  183. case *v5wire.TalkResponse:
  184. if len(resp.ReqID) > 0 {
  185. t.Fatalf("wrong request ID %x in TALKRESP, want empty byte array", resp.ReqID)
  186. }
  187. if len(resp.Message) > 0 {
  188. t.Fatalf("non-empty message %x in TALKRESP", resp.Message)
  189. }
  190. default:
  191. t.Fatal("expected TALKRESP, got", resp.Name())
  192. }
  193. }
  194. // This test checks that the remote node returns itself for FINDNODE with distance zero.
  195. func (s *Suite) TestFindnodeZeroDistance(t *utesting.T) {
  196. conn, l1 := s.listen1(t)
  197. defer conn.close()
  198. nodes, err := conn.findnode(l1, []uint{0})
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. if len(nodes) != 1 {
  203. t.Fatalf("remote returned more than one node for FINDNODE [0]")
  204. }
  205. if nodes[0].ID() != conn.remote.ID() {
  206. t.Errorf("ID of response node is %v, want %v", nodes[0].ID(), conn.remote.ID())
  207. }
  208. }
  209. // In this test, multiple nodes ping the node under test. After waiting for them to be
  210. // accepted into the remote table, the test checks that they are returned by FINDNODE.
  211. func (s *Suite) TestFindnodeResults(t *utesting.T) {
  212. // Create bystanders.
  213. nodes := make([]*bystander, 5)
  214. added := make(chan enode.ID, len(nodes))
  215. for i := range nodes {
  216. nodes[i] = newBystander(t, s, added)
  217. defer nodes[i].close()
  218. }
  219. // Get them added to the remote table.
  220. timeout := 60 * time.Second
  221. timeoutCh := time.After(timeout)
  222. for count := 0; count < len(nodes); {
  223. select {
  224. case id := <-added:
  225. t.Logf("bystander node %v added to remote table", id)
  226. count++
  227. case <-timeoutCh:
  228. t.Errorf("remote added %d bystander nodes in %v, need %d to continue", count, timeout, len(nodes))
  229. t.Logf("this can happen if the node has a non-empty table from previous runs")
  230. return
  231. }
  232. }
  233. t.Logf("all %d bystander nodes were added", len(nodes))
  234. // Collect our nodes by distance.
  235. var dists []uint
  236. expect := make(map[enode.ID]*enode.Node)
  237. for _, bn := range nodes {
  238. n := bn.conn.localNode.Node()
  239. expect[n.ID()] = n
  240. d := uint(enode.LogDist(n.ID(), s.Dest.ID()))
  241. if !containsUint(dists, d) {
  242. dists = append(dists, d)
  243. }
  244. }
  245. // Send FINDNODE for all distances.
  246. conn, l1 := s.listen1(t)
  247. defer conn.close()
  248. foundNodes, err := conn.findnode(l1, dists)
  249. if err != nil {
  250. t.Fatal(err)
  251. }
  252. t.Logf("remote returned %d nodes for distance list %v", len(foundNodes), dists)
  253. for _, n := range foundNodes {
  254. delete(expect, n.ID())
  255. }
  256. if len(expect) > 0 {
  257. t.Errorf("missing %d nodes in FINDNODE result", len(expect))
  258. t.Logf("this can happen if the test is run multiple times in quick succession")
  259. t.Logf("and the remote node hasn't removed dead nodes from previous runs yet")
  260. } else {
  261. t.Logf("all %d expected nodes were returned", len(nodes))
  262. }
  263. }
  264. // A bystander is a node whose only purpose is filling a spot in the remote table.
  265. type bystander struct {
  266. dest *enode.Node
  267. conn *conn
  268. l net.PacketConn
  269. addedCh chan enode.ID
  270. done sync.WaitGroup
  271. }
  272. func newBystander(t *utesting.T, s *Suite, added chan enode.ID) *bystander {
  273. conn, l := s.listen1(t)
  274. conn.setEndpoint(l) // bystander nodes need IP/port to get pinged
  275. bn := &bystander{
  276. conn: conn,
  277. l: l,
  278. dest: s.Dest,
  279. addedCh: added,
  280. }
  281. bn.done.Add(1)
  282. go bn.loop()
  283. return bn
  284. }
  285. // id returns the node ID of the bystander.
  286. func (bn *bystander) id() enode.ID {
  287. return bn.conn.localNode.ID()
  288. }
  289. // close shuts down loop.
  290. func (bn *bystander) close() {
  291. bn.conn.close()
  292. bn.done.Wait()
  293. }
  294. // loop answers packets from the remote node until quit.
  295. func (bn *bystander) loop() {
  296. defer bn.done.Done()
  297. var (
  298. lastPing time.Time
  299. wasAdded bool
  300. )
  301. for {
  302. // Ping the remote node.
  303. if !wasAdded && time.Since(lastPing) > 10*time.Second {
  304. bn.conn.reqresp(bn.l, &v5wire.Ping{
  305. ReqID: bn.conn.nextReqID(),
  306. ENRSeq: bn.dest.Seq(),
  307. })
  308. lastPing = time.Now()
  309. }
  310. // Answer packets.
  311. switch p := bn.conn.read(bn.l).(type) {
  312. case *v5wire.Ping:
  313. bn.conn.write(bn.l, &v5wire.Pong{
  314. ReqID: p.ReqID,
  315. ENRSeq: bn.conn.localNode.Seq(),
  316. ToIP: bn.dest.IP(),
  317. ToPort: uint16(bn.dest.UDP()),
  318. }, nil)
  319. wasAdded = true
  320. bn.notifyAdded()
  321. case *v5wire.Findnode:
  322. bn.conn.write(bn.l, &v5wire.Nodes{ReqID: p.ReqID, Total: 1}, nil)
  323. wasAdded = true
  324. bn.notifyAdded()
  325. case *v5wire.TalkRequest:
  326. bn.conn.write(bn.l, &v5wire.TalkResponse{ReqID: p.ReqID}, nil)
  327. case *readError:
  328. if !netutil.IsTemporaryError(p.err) {
  329. bn.conn.logf("shutting down: %v", p.err)
  330. return
  331. }
  332. }
  333. }
  334. }
  335. func (bn *bystander) notifyAdded() {
  336. if bn.addedCh != nil {
  337. bn.addedCh <- bn.id()
  338. bn.addedCh = nil
  339. }
  340. }