peer_test.go 9.0 KB

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