peer_test.go 8.9 KB

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