peer_test.go 9.9 KB

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