protocol_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. // Copyright 2017 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 protocols
  17. import (
  18. "context"
  19. "errors"
  20. "fmt"
  21. "testing"
  22. "time"
  23. "github.com/ethereum/go-ethereum/p2p"
  24. "github.com/ethereum/go-ethereum/p2p/discover"
  25. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  26. p2ptest "github.com/ethereum/go-ethereum/p2p/testing"
  27. )
  28. // handshake message type
  29. type hs0 struct {
  30. C uint
  31. }
  32. // message to kill/drop the peer with nodeID
  33. type kill struct {
  34. C discover.NodeID
  35. }
  36. // message to drop connection
  37. type drop struct {
  38. }
  39. /// protoHandshake represents module-independent aspects of the protocol and is
  40. // the first message peers send and receive as part the initial exchange
  41. type protoHandshake struct {
  42. Version uint // local and remote peer should have identical version
  43. NetworkID string // local and remote peer should have identical network id
  44. }
  45. // checkProtoHandshake verifies local and remote protoHandshakes match
  46. func checkProtoHandshake(testVersion uint, testNetworkID string) func(interface{}) error {
  47. return func(rhs interface{}) error {
  48. remote := rhs.(*protoHandshake)
  49. if remote.NetworkID != testNetworkID {
  50. return fmt.Errorf("%s (!= %s)", remote.NetworkID, testNetworkID)
  51. }
  52. if remote.Version != testVersion {
  53. return fmt.Errorf("%d (!= %d)", remote.Version, testVersion)
  54. }
  55. return nil
  56. }
  57. }
  58. // newProtocol sets up a protocol
  59. // the run function here demonstrates a typical protocol using peerPool, handshake
  60. // and messages registered to handlers
  61. func newProtocol(pp *p2ptest.TestPeerPool) func(*p2p.Peer, p2p.MsgReadWriter) error {
  62. spec := &Spec{
  63. Name: "test",
  64. Version: 42,
  65. MaxMsgSize: 10 * 1024,
  66. Messages: []interface{}{
  67. protoHandshake{},
  68. hs0{},
  69. kill{},
  70. drop{},
  71. },
  72. }
  73. return func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  74. peer := NewPeer(p, rw, spec)
  75. // initiate one-off protohandshake and check validity
  76. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  77. defer cancel()
  78. phs := &protoHandshake{42, "420"}
  79. hsCheck := checkProtoHandshake(phs.Version, phs.NetworkID)
  80. _, err := peer.Handshake(ctx, phs, hsCheck)
  81. if err != nil {
  82. return err
  83. }
  84. lhs := &hs0{42}
  85. // module handshake demonstrating a simple repeatable exchange of same-type message
  86. hs, err := peer.Handshake(ctx, lhs, nil)
  87. if err != nil {
  88. return err
  89. }
  90. if rmhs := hs.(*hs0); rmhs.C > lhs.C {
  91. return fmt.Errorf("handshake mismatch remote %v > local %v", rmhs.C, lhs.C)
  92. }
  93. handle := func(msg interface{}) error {
  94. switch msg := msg.(type) {
  95. case *protoHandshake:
  96. return errors.New("duplicate handshake")
  97. case *hs0:
  98. rhs := msg
  99. if rhs.C > lhs.C {
  100. return fmt.Errorf("handshake mismatch remote %v > local %v", rhs.C, lhs.C)
  101. }
  102. lhs.C += rhs.C
  103. return peer.Send(lhs)
  104. case *kill:
  105. // demonstrates use of peerPool, killing another peer connection as a response to a message
  106. id := msg.C
  107. pp.Get(id).Drop(errors.New("killed"))
  108. return nil
  109. case *drop:
  110. // for testing we can trigger self induced disconnect upon receiving drop message
  111. return errors.New("dropped")
  112. default:
  113. return fmt.Errorf("unknown message type: %T", msg)
  114. }
  115. }
  116. pp.Add(peer)
  117. defer pp.Remove(peer)
  118. return peer.Run(handle)
  119. }
  120. }
  121. func protocolTester(t *testing.T, pp *p2ptest.TestPeerPool) *p2ptest.ProtocolTester {
  122. conf := adapters.RandomNodeConfig()
  123. return p2ptest.NewProtocolTester(t, conf.ID, 2, newProtocol(pp))
  124. }
  125. func protoHandshakeExchange(id discover.NodeID, proto *protoHandshake) []p2ptest.Exchange {
  126. return []p2ptest.Exchange{
  127. {
  128. Expects: []p2ptest.Expect{
  129. {
  130. Code: 0,
  131. Msg: &protoHandshake{42, "420"},
  132. Peer: id,
  133. },
  134. },
  135. },
  136. {
  137. Triggers: []p2ptest.Trigger{
  138. {
  139. Code: 0,
  140. Msg: proto,
  141. Peer: id,
  142. },
  143. },
  144. },
  145. }
  146. }
  147. func runProtoHandshake(t *testing.T, proto *protoHandshake, errs ...error) {
  148. pp := p2ptest.NewTestPeerPool()
  149. s := protocolTester(t, pp)
  150. // TODO: make this more than one handshake
  151. id := s.IDs[0]
  152. if err := s.TestExchanges(protoHandshakeExchange(id, proto)...); err != nil {
  153. t.Fatal(err)
  154. }
  155. var disconnects []*p2ptest.Disconnect
  156. for i, err := range errs {
  157. disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.IDs[i], Error: err})
  158. }
  159. if err := s.TestDisconnected(disconnects...); err != nil {
  160. t.Fatal(err)
  161. }
  162. }
  163. func TestProtoHandshakeVersionMismatch(t *testing.T) {
  164. runProtoHandshake(t, &protoHandshake{41, "420"}, errorf(ErrHandshake, errorf(ErrHandler, "(msg code 0): 41 (!= 42)").Error()))
  165. }
  166. func TestProtoHandshakeNetworkIDMismatch(t *testing.T) {
  167. runProtoHandshake(t, &protoHandshake{42, "421"}, errorf(ErrHandshake, errorf(ErrHandler, "(msg code 0): 421 (!= 420)").Error()))
  168. }
  169. func TestProtoHandshakeSuccess(t *testing.T) {
  170. runProtoHandshake(t, &protoHandshake{42, "420"})
  171. }
  172. func moduleHandshakeExchange(id discover.NodeID, resp uint) []p2ptest.Exchange {
  173. return []p2ptest.Exchange{
  174. {
  175. Expects: []p2ptest.Expect{
  176. {
  177. Code: 1,
  178. Msg: &hs0{42},
  179. Peer: id,
  180. },
  181. },
  182. },
  183. {
  184. Triggers: []p2ptest.Trigger{
  185. {
  186. Code: 1,
  187. Msg: &hs0{resp},
  188. Peer: id,
  189. },
  190. },
  191. },
  192. }
  193. }
  194. func runModuleHandshake(t *testing.T, resp uint, errs ...error) {
  195. pp := p2ptest.NewTestPeerPool()
  196. s := protocolTester(t, pp)
  197. id := s.IDs[0]
  198. if err := s.TestExchanges(protoHandshakeExchange(id, &protoHandshake{42, "420"})...); err != nil {
  199. t.Fatal(err)
  200. }
  201. if err := s.TestExchanges(moduleHandshakeExchange(id, resp)...); err != nil {
  202. t.Fatal(err)
  203. }
  204. var disconnects []*p2ptest.Disconnect
  205. for i, err := range errs {
  206. disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.IDs[i], Error: err})
  207. }
  208. if err := s.TestDisconnected(disconnects...); err != nil {
  209. t.Fatal(err)
  210. }
  211. }
  212. func TestModuleHandshakeError(t *testing.T) {
  213. runModuleHandshake(t, 43, fmt.Errorf("handshake mismatch remote 43 > local 42"))
  214. }
  215. func TestModuleHandshakeSuccess(t *testing.T) {
  216. runModuleHandshake(t, 42)
  217. }
  218. // testing complex interactions over multiple peers, relaying, dropping
  219. func testMultiPeerSetup(a, b discover.NodeID) []p2ptest.Exchange {
  220. return []p2ptest.Exchange{
  221. {
  222. Label: "primary handshake",
  223. Expects: []p2ptest.Expect{
  224. {
  225. Code: 0,
  226. Msg: &protoHandshake{42, "420"},
  227. Peer: a,
  228. },
  229. {
  230. Code: 0,
  231. Msg: &protoHandshake{42, "420"},
  232. Peer: b,
  233. },
  234. },
  235. },
  236. {
  237. Label: "module handshake",
  238. Triggers: []p2ptest.Trigger{
  239. {
  240. Code: 0,
  241. Msg: &protoHandshake{42, "420"},
  242. Peer: a,
  243. },
  244. {
  245. Code: 0,
  246. Msg: &protoHandshake{42, "420"},
  247. Peer: b,
  248. },
  249. },
  250. Expects: []p2ptest.Expect{
  251. {
  252. Code: 1,
  253. Msg: &hs0{42},
  254. Peer: a,
  255. },
  256. {
  257. Code: 1,
  258. Msg: &hs0{42},
  259. Peer: b,
  260. },
  261. },
  262. },
  263. {Label: "alternative module handshake", Triggers: []p2ptest.Trigger{{Code: 1, Msg: &hs0{41}, Peer: a},
  264. {Code: 1, Msg: &hs0{41}, Peer: b}}},
  265. {Label: "repeated module handshake", Triggers: []p2ptest.Trigger{{Code: 1, Msg: &hs0{1}, Peer: a}}},
  266. {Label: "receiving repeated module handshake", Expects: []p2ptest.Expect{{Code: 1, Msg: &hs0{43}, Peer: a}}}}
  267. }
  268. func runMultiplePeers(t *testing.T, peer int, errs ...error) {
  269. pp := p2ptest.NewTestPeerPool()
  270. s := protocolTester(t, pp)
  271. if err := s.TestExchanges(testMultiPeerSetup(s.IDs[0], s.IDs[1])...); err != nil {
  272. t.Fatal(err)
  273. }
  274. // after some exchanges of messages, we can test state changes
  275. // here this is simply demonstrated by the peerPool
  276. // after the handshake negotiations peers must be added to the pool
  277. // time.Sleep(1)
  278. tick := time.NewTicker(10 * time.Millisecond)
  279. timeout := time.NewTimer(1 * time.Second)
  280. WAIT:
  281. for {
  282. select {
  283. case <-tick.C:
  284. if pp.Has(s.IDs[0]) {
  285. break WAIT
  286. }
  287. case <-timeout.C:
  288. t.Fatal("timeout")
  289. }
  290. }
  291. if !pp.Has(s.IDs[1]) {
  292. t.Fatalf("missing peer test-1: %v (%v)", pp, s.IDs)
  293. }
  294. // peer 0 sends kill request for peer with index <peer>
  295. err := s.TestExchanges(p2ptest.Exchange{
  296. Triggers: []p2ptest.Trigger{
  297. {
  298. Code: 2,
  299. Msg: &kill{s.IDs[peer]},
  300. Peer: s.IDs[0],
  301. },
  302. },
  303. })
  304. if err != nil {
  305. t.Fatal(err)
  306. }
  307. // the peer not killed sends a drop request
  308. err = s.TestExchanges(p2ptest.Exchange{
  309. Triggers: []p2ptest.Trigger{
  310. {
  311. Code: 3,
  312. Msg: &drop{},
  313. Peer: s.IDs[(peer+1)%2],
  314. },
  315. },
  316. })
  317. if err != nil {
  318. t.Fatal(err)
  319. }
  320. // check the actual discconnect errors on the individual peers
  321. var disconnects []*p2ptest.Disconnect
  322. for i, err := range errs {
  323. disconnects = append(disconnects, &p2ptest.Disconnect{Peer: s.IDs[i], Error: err})
  324. }
  325. if err := s.TestDisconnected(disconnects...); err != nil {
  326. t.Fatal(err)
  327. }
  328. // test if disconnected peers have been removed from peerPool
  329. if pp.Has(s.IDs[peer]) {
  330. t.Fatalf("peer test-%v not dropped: %v (%v)", peer, pp, s.IDs)
  331. }
  332. }
  333. func TestMultiplePeersDropSelf(t *testing.T) {
  334. runMultiplePeers(t, 0,
  335. fmt.Errorf("subprotocol error"),
  336. fmt.Errorf("Message handler error: (msg code 3): dropped"),
  337. )
  338. }
  339. func TestMultiplePeersDropOther(t *testing.T) {
  340. runMultiplePeers(t, 1,
  341. fmt.Errorf("Message handler error: (msg code 3): dropped"),
  342. fmt.Errorf("subprotocol error"),
  343. )
  344. }