peer_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright 2014 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 p2p
  17. import (
  18. "encoding/binary"
  19. "errors"
  20. "fmt"
  21. "math/rand"
  22. "net"
  23. "reflect"
  24. "strconv"
  25. "strings"
  26. "testing"
  27. "time"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/p2p/enode"
  30. "github.com/ethereum/go-ethereum/p2p/enr"
  31. )
  32. var discard = Protocol{
  33. Name: "discard",
  34. Length: 1,
  35. Run: func(p *Peer, rw MsgReadWriter) error {
  36. for {
  37. msg, err := rw.ReadMsg()
  38. if err != nil {
  39. return err
  40. }
  41. fmt.Printf("discarding %d\n", msg.Code)
  42. if err = msg.Discard(); err != nil {
  43. return err
  44. }
  45. }
  46. },
  47. }
  48. // uintID encodes i into a node ID.
  49. func uintID(i uint16) enode.ID {
  50. var id enode.ID
  51. binary.BigEndian.PutUint16(id[:], i)
  52. return id
  53. }
  54. // newNode creates a node record with the given address.
  55. func newNode(id enode.ID, addr string) *enode.Node {
  56. var r enr.Record
  57. if addr != "" {
  58. // Set the port if present.
  59. if strings.Contains(addr, ":") {
  60. hs, ps, err := net.SplitHostPort(addr)
  61. if err != nil {
  62. panic(fmt.Errorf("invalid address %q", addr))
  63. }
  64. port, err := strconv.Atoi(ps)
  65. if err != nil {
  66. panic(fmt.Errorf("invalid port in %q", addr))
  67. }
  68. r.Set(enr.TCP(port))
  69. r.Set(enr.UDP(port))
  70. addr = hs
  71. }
  72. // Set the IP.
  73. ip := net.ParseIP(addr)
  74. if ip == nil {
  75. panic(fmt.Errorf("invalid IP %q", addr))
  76. }
  77. r.Set(enr.IP(ip))
  78. }
  79. return enode.SignNull(&r, id)
  80. }
  81. func testPeer(protos []Protocol) (func(), *conn, *Peer, <-chan error) {
  82. var (
  83. fd1, fd2 = net.Pipe()
  84. key1, key2 = newkey(), newkey()
  85. t1 = newTestTransport(&key2.PublicKey, fd1, nil)
  86. t2 = newTestTransport(&key1.PublicKey, fd2, &key1.PublicKey)
  87. )
  88. c1 := &conn{fd: fd1, node: newNode(uintID(1), ""), transport: t1}
  89. c2 := &conn{fd: fd2, node: newNode(uintID(2), ""), transport: t2}
  90. for _, p := range protos {
  91. c1.caps = append(c1.caps, p.cap())
  92. c2.caps = append(c2.caps, p.cap())
  93. }
  94. peer := newPeer(log.Root(), c1, protos)
  95. errc := make(chan error, 1)
  96. go func() {
  97. _, err := peer.run()
  98. errc <- err
  99. }()
  100. closer := func() { c2.close(errors.New("close func called")) }
  101. return closer, c2, peer, errc
  102. }
  103. func TestPeerProtoReadMsg(t *testing.T) {
  104. proto := Protocol{
  105. Name: "a",
  106. Length: 5,
  107. Run: func(peer *Peer, rw MsgReadWriter) error {
  108. if err := ExpectMsg(rw, 2, []uint{1}); err != nil {
  109. t.Error(err)
  110. }
  111. if err := ExpectMsg(rw, 3, []uint{2}); err != nil {
  112. t.Error(err)
  113. }
  114. if err := ExpectMsg(rw, 4, []uint{3}); err != nil {
  115. t.Error(err)
  116. }
  117. return nil
  118. },
  119. }
  120. closer, rw, _, errc := testPeer([]Protocol{proto})
  121. defer closer()
  122. Send(rw, baseProtocolLength+2, []uint{1})
  123. Send(rw, baseProtocolLength+3, []uint{2})
  124. Send(rw, baseProtocolLength+4, []uint{3})
  125. select {
  126. case err := <-errc:
  127. if err != errProtocolReturned {
  128. t.Errorf("peer returned error: %v", err)
  129. }
  130. case <-time.After(2 * time.Second):
  131. t.Errorf("receive timeout")
  132. }
  133. }
  134. func TestPeerProtoEncodeMsg(t *testing.T) {
  135. proto := Protocol{
  136. Name: "a",
  137. Length: 2,
  138. Run: func(peer *Peer, rw MsgReadWriter) error {
  139. if err := SendItems(rw, 2); err == nil {
  140. t.Error("expected error for out-of-range msg code, got nil")
  141. }
  142. if err := SendItems(rw, 1, "foo", "bar"); err != nil {
  143. t.Errorf("write error: %v", err)
  144. }
  145. return nil
  146. },
  147. }
  148. closer, rw, _, _ := testPeer([]Protocol{proto})
  149. defer closer()
  150. if err := ExpectMsg(rw, 17, []string{"foo", "bar"}); err != nil {
  151. t.Error(err)
  152. }
  153. }
  154. func TestPeerPing(t *testing.T) {
  155. closer, rw, _, _ := testPeer(nil)
  156. defer closer()
  157. if err := SendItems(rw, pingMsg); err != nil {
  158. t.Fatal(err)
  159. }
  160. if err := ExpectMsg(rw, pongMsg, nil); err != nil {
  161. t.Error(err)
  162. }
  163. }
  164. // This test checks that a disconnect message sent by a peer is returned
  165. // as the error from Peer.run.
  166. func TestPeerDisconnect(t *testing.T) {
  167. closer, rw, _, disc := testPeer(nil)
  168. defer closer()
  169. if err := SendItems(rw, discMsg, DiscQuitting); err != nil {
  170. t.Fatal(err)
  171. }
  172. select {
  173. case reason := <-disc:
  174. if reason != DiscQuitting {
  175. t.Errorf("run returned wrong reason: got %v, want %v", reason, DiscQuitting)
  176. }
  177. case <-time.After(500 * time.Millisecond):
  178. t.Error("peer did not return")
  179. }
  180. }
  181. // This test is supposed to verify that Peer can reliably handle
  182. // multiple causes of disconnection occurring at the same time.
  183. func TestPeerDisconnectRace(t *testing.T) {
  184. maybe := func() bool { return rand.Intn(2) == 1 }
  185. for i := 0; i < 1000; i++ {
  186. protoclose := make(chan error)
  187. protodisc := make(chan DiscReason)
  188. closer, rw, p, disc := testPeer([]Protocol{
  189. {
  190. Name: "closereq",
  191. Run: func(p *Peer, rw MsgReadWriter) error { return <-protoclose },
  192. Length: 1,
  193. },
  194. {
  195. Name: "disconnect",
  196. Run: func(p *Peer, rw MsgReadWriter) error { p.Disconnect(<-protodisc); return nil },
  197. Length: 1,
  198. },
  199. })
  200. // Simulate incoming messages.
  201. go SendItems(rw, baseProtocolLength+1)
  202. go SendItems(rw, baseProtocolLength+2)
  203. // Close the network connection.
  204. go closer()
  205. // Make protocol "closereq" return.
  206. protoclose <- errors.New("protocol closed")
  207. // Make protocol "disconnect" call peer.Disconnect
  208. protodisc <- DiscAlreadyConnected
  209. // In some cases, simulate something else calling peer.Disconnect.
  210. if maybe() {
  211. go p.Disconnect(DiscInvalidIdentity)
  212. }
  213. // In some cases, simulate remote requesting a disconnect.
  214. if maybe() {
  215. go SendItems(rw, discMsg, DiscQuitting)
  216. }
  217. select {
  218. case <-disc:
  219. case <-time.After(2 * time.Second):
  220. // Peer.run should return quickly. If it doesn't the Peer
  221. // goroutines are probably deadlocked. Call panic in order to
  222. // show the stacks.
  223. panic("Peer.run took to long to return.")
  224. }
  225. }
  226. }
  227. func TestNewPeer(t *testing.T) {
  228. name := "nodename"
  229. caps := []Cap{{"foo", 2}, {"bar", 3}}
  230. id := randomID()
  231. p := NewPeer(id, name, caps)
  232. if p.ID() != id {
  233. t.Errorf("ID mismatch: got %v, expected %v", p.ID(), id)
  234. }
  235. if p.Name() != name {
  236. t.Errorf("Name mismatch: got %v, expected %v", p.Name(), name)
  237. }
  238. if !reflect.DeepEqual(p.Caps(), caps) {
  239. t.Errorf("Caps mismatch: got %v, expected %v", p.Caps(), caps)
  240. }
  241. p.Disconnect(DiscAlreadyConnected) // Should not hang
  242. }
  243. func TestMatchProtocols(t *testing.T) {
  244. tests := []struct {
  245. Remote []Cap
  246. Local []Protocol
  247. Match map[string]protoRW
  248. }{
  249. {
  250. // No remote capabilities
  251. Local: []Protocol{{Name: "a"}},
  252. },
  253. {
  254. // No local protocols
  255. Remote: []Cap{{Name: "a"}},
  256. },
  257. {
  258. // No mutual protocols
  259. Remote: []Cap{{Name: "a"}},
  260. Local: []Protocol{{Name: "b"}},
  261. },
  262. {
  263. // Some matches, some differences
  264. Remote: []Cap{{Name: "local"}, {Name: "match1"}, {Name: "match2"}},
  265. Local: []Protocol{{Name: "match1"}, {Name: "match2"}, {Name: "remote"}},
  266. Match: map[string]protoRW{"match1": {Protocol: Protocol{Name: "match1"}}, "match2": {Protocol: Protocol{Name: "match2"}}},
  267. },
  268. {
  269. // Various alphabetical ordering
  270. Remote: []Cap{{Name: "aa"}, {Name: "ab"}, {Name: "bb"}, {Name: "ba"}},
  271. Local: []Protocol{{Name: "ba"}, {Name: "bb"}, {Name: "ab"}, {Name: "aa"}},
  272. Match: map[string]protoRW{"aa": {Protocol: Protocol{Name: "aa"}}, "ab": {Protocol: Protocol{Name: "ab"}}, "ba": {Protocol: Protocol{Name: "ba"}}, "bb": {Protocol: Protocol{Name: "bb"}}},
  273. },
  274. {
  275. // No mutual versions
  276. Remote: []Cap{{Version: 1}},
  277. Local: []Protocol{{Version: 2}},
  278. },
  279. {
  280. // Multiple versions, single common
  281. Remote: []Cap{{Version: 1}, {Version: 2}},
  282. Local: []Protocol{{Version: 2}, {Version: 3}},
  283. Match: map[string]protoRW{"": {Protocol: Protocol{Version: 2}}},
  284. },
  285. {
  286. // Multiple versions, multiple common
  287. Remote: []Cap{{Version: 1}, {Version: 2}, {Version: 3}, {Version: 4}},
  288. Local: []Protocol{{Version: 2}, {Version: 3}},
  289. Match: map[string]protoRW{"": {Protocol: Protocol{Version: 3}}},
  290. },
  291. {
  292. // Various version orderings
  293. Remote: []Cap{{Version: 4}, {Version: 1}, {Version: 3}, {Version: 2}},
  294. Local: []Protocol{{Version: 2}, {Version: 3}, {Version: 1}},
  295. Match: map[string]protoRW{"": {Protocol: Protocol{Version: 3}}},
  296. },
  297. {
  298. // Versions overriding sub-protocol lengths
  299. Remote: []Cap{{Version: 1}, {Version: 2}, {Version: 3}, {Name: "a"}},
  300. Local: []Protocol{{Version: 1, Length: 1}, {Version: 2, Length: 2}, {Version: 3, Length: 3}, {Name: "a"}},
  301. Match: map[string]protoRW{"": {Protocol: Protocol{Version: 3}}, "a": {Protocol: Protocol{Name: "a"}, offset: 3}},
  302. },
  303. }
  304. for i, tt := range tests {
  305. result := matchProtocols(tt.Local, tt.Remote, nil)
  306. if len(result) != len(tt.Match) {
  307. t.Errorf("test %d: negotiation mismatch: have %v, want %v", i, len(result), len(tt.Match))
  308. continue
  309. }
  310. // Make sure all negotiated protocols are needed and correct
  311. for name, proto := range result {
  312. match, ok := tt.Match[name]
  313. if !ok {
  314. t.Errorf("test %d, proto '%s': negotiated but shouldn't have", i, name)
  315. continue
  316. }
  317. if proto.Name != match.Name {
  318. t.Errorf("test %d, proto '%s': name mismatch: have %v, want %v", i, name, proto.Name, match.Name)
  319. }
  320. if proto.Version != match.Version {
  321. t.Errorf("test %d, proto '%s': version mismatch: have %v, want %v", i, name, proto.Version, match.Version)
  322. }
  323. if proto.offset-baseProtocolLength != match.offset {
  324. t.Errorf("test %d, proto '%s': offset mismatch: have %v, want %v", i, name, proto.offset-baseProtocolLength, match.offset)
  325. }
  326. }
  327. // Make sure no protocols missed negotiation
  328. for name := range tt.Match {
  329. if _, ok := result[name]; !ok {
  330. t.Errorf("test %d, proto '%s': not negotiated, should have", i, name)
  331. continue
  332. }
  333. }
  334. }
  335. }