peer_test.go 8.9 KB

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