You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

751 lines
24 KiB

p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
4 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
4 years ago
  1. package p2p_test
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/fortytw2/leaktest"
  11. "github.com/gogo/protobuf/proto"
  12. gogotypes "github.com/gogo/protobuf/types"
  13. "github.com/stretchr/testify/mock"
  14. "github.com/stretchr/testify/require"
  15. dbm "github.com/tendermint/tm-db"
  16. "github.com/tendermint/tendermint/crypto"
  17. "github.com/tendermint/tendermint/libs/log"
  18. tmsync "github.com/tendermint/tendermint/libs/sync"
  19. "github.com/tendermint/tendermint/p2p"
  20. "github.com/tendermint/tendermint/p2p/mocks"
  21. "github.com/tendermint/tendermint/p2p/p2ptest"
  22. )
  23. func echoReactor(channel *p2p.Channel) {
  24. for {
  25. select {
  26. case envelope := <-channel.In:
  27. value := envelope.Message.(*p2ptest.Message).Value
  28. channel.Out <- p2p.Envelope{
  29. To: envelope.From,
  30. Message: &p2ptest.Message{Value: value},
  31. }
  32. case <-channel.Done():
  33. return
  34. }
  35. }
  36. }
  37. func TestRouter_Network(t *testing.T) {
  38. t.Cleanup(leaktest.Check(t))
  39. // Create a test network and open a channel where all peers run echoReactor.
  40. network := p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: 8})
  41. network.Start(t)
  42. local := network.RandomNode()
  43. peers := network.Peers(local.NodeID)
  44. channels := network.MakeChannels(t, 1, &p2ptest.Message{}, 0)
  45. channel := channels[local.NodeID]
  46. for _, peer := range peers {
  47. go echoReactor(channels[peer.NodeID])
  48. }
  49. // Sending a message to each peer should work.
  50. for _, peer := range peers {
  51. p2ptest.RequireSendReceive(t, channel, peer.NodeID,
  52. &p2ptest.Message{Value: "foo"},
  53. &p2ptest.Message{Value: "foo"},
  54. )
  55. }
  56. // Sending a broadcast should return back a message from all peers.
  57. p2ptest.RequireSend(t, channel, p2p.Envelope{
  58. Broadcast: true,
  59. Message: &p2ptest.Message{Value: "bar"},
  60. })
  61. expect := []p2p.Envelope{}
  62. for _, peer := range peers {
  63. expect = append(expect, p2p.Envelope{
  64. From: peer.NodeID,
  65. Message: &p2ptest.Message{Value: "bar"},
  66. })
  67. }
  68. p2ptest.RequireReceiveUnordered(t, channel, expect)
  69. // We then submit an error for a peer, and watch it get disconnected and
  70. // then reconnected as the router retries it.
  71. peerUpdates := local.MakePeerUpdatesNoRequireEmpty(t)
  72. channel.Error <- p2p.PeerError{
  73. NodeID: peers[0].NodeID,
  74. Err: errors.New("boom"),
  75. }
  76. p2ptest.RequireUpdates(t, peerUpdates, []p2p.PeerUpdate{
  77. {NodeID: peers[0].NodeID, Status: p2p.PeerStatusDown},
  78. {NodeID: peers[0].NodeID, Status: p2p.PeerStatusUp},
  79. })
  80. }
  81. func TestRouter_Channel(t *testing.T) {
  82. t.Cleanup(leaktest.Check(t))
  83. // Set up a router with no transports (so no peers).
  84. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  85. require.NoError(t, err)
  86. defer peerManager.Close()
  87. router, err := p2p.NewRouter(
  88. log.TestingLogger(),
  89. p2p.NopMetrics(),
  90. selfInfo,
  91. selfKey,
  92. peerManager,
  93. nil,
  94. p2p.RouterOptions{},
  95. )
  96. require.NoError(t, err)
  97. require.NoError(t, router.Start())
  98. t.Cleanup(func() {
  99. require.NoError(t, router.Stop())
  100. })
  101. // Opening a channel should work.
  102. channel, err := router.OpenChannel(chID, &p2ptest.Message{}, 0)
  103. require.NoError(t, err)
  104. // Opening the same channel again should fail.
  105. _, err = router.OpenChannel(chID, &p2ptest.Message{}, 0)
  106. require.Error(t, err)
  107. // Opening a different channel should work.
  108. _, err = router.OpenChannel(2, &p2ptest.Message{}, 0)
  109. require.NoError(t, err)
  110. // Closing the channel, then opening it again should be fine.
  111. channel.Close()
  112. time.Sleep(100 * time.Millisecond) // yes yes, but Close() is async...
  113. channel, err = router.OpenChannel(chID, &p2ptest.Message{}, 0)
  114. require.NoError(t, err)
  115. // We should be able to send on the channel, even though there are no peers.
  116. p2ptest.RequireSend(t, channel, p2p.Envelope{
  117. To: p2p.NodeID(strings.Repeat("a", 40)),
  118. Message: &p2ptest.Message{Value: "foo"},
  119. })
  120. // A message to ourselves should be dropped.
  121. p2ptest.RequireSend(t, channel, p2p.Envelope{
  122. To: selfID,
  123. Message: &p2ptest.Message{Value: "self"},
  124. })
  125. p2ptest.RequireEmpty(t, channel)
  126. }
  127. // Channel tests are hairy to mock, so we use an in-memory network instead.
  128. func TestRouter_Channel_SendReceive(t *testing.T) {
  129. t.Cleanup(leaktest.Check(t))
  130. // Create a test network and open a channel on all nodes.
  131. network := p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: 3})
  132. network.Start(t)
  133. ids := network.NodeIDs()
  134. aID, bID, cID := ids[0], ids[1], ids[2]
  135. channels := network.MakeChannels(t, chID, &p2ptest.Message{}, 0)
  136. a, b, c := channels[aID], channels[bID], channels[cID]
  137. otherChannels := network.MakeChannels(t, 9, &p2ptest.Message{}, 0)
  138. // Sending a message a->b should work, and not send anything
  139. // further to a, b, or c.
  140. p2ptest.RequireSend(t, a, p2p.Envelope{To: bID, Message: &p2ptest.Message{Value: "foo"}})
  141. p2ptest.RequireReceive(t, b, p2p.Envelope{From: aID, Message: &p2ptest.Message{Value: "foo"}})
  142. p2ptest.RequireEmpty(t, a, b, c)
  143. // Sending a nil message a->c should be dropped.
  144. p2ptest.RequireSend(t, a, p2p.Envelope{To: bID, Message: nil})
  145. p2ptest.RequireEmpty(t, a, b, c)
  146. // Sending a different message type should be dropped.
  147. p2ptest.RequireSend(t, a, p2p.Envelope{To: bID, Message: &gogotypes.BoolValue{Value: true}})
  148. p2ptest.RequireEmpty(t, a, b, c)
  149. // Sending to an unknown peer should be dropped.
  150. p2ptest.RequireSend(t, a, p2p.Envelope{
  151. To: p2p.NodeID(strings.Repeat("a", 40)),
  152. Message: &p2ptest.Message{Value: "a"},
  153. })
  154. p2ptest.RequireEmpty(t, a, b, c)
  155. // Sending without a recipient should be dropped.
  156. p2ptest.RequireSend(t, a, p2p.Envelope{Message: &p2ptest.Message{Value: "noto"}})
  157. p2ptest.RequireEmpty(t, a, b, c)
  158. // Sending to self should be dropped.
  159. p2ptest.RequireSend(t, a, p2p.Envelope{To: aID, Message: &p2ptest.Message{Value: "self"}})
  160. p2ptest.RequireEmpty(t, a, b, c)
  161. // Removing b and sending to it should be dropped.
  162. network.Remove(t, bID)
  163. p2ptest.RequireSend(t, a, p2p.Envelope{To: bID, Message: &p2ptest.Message{Value: "nob"}})
  164. p2ptest.RequireEmpty(t, a, b, c)
  165. // After all this, sending a message c->a should work.
  166. p2ptest.RequireSend(t, c, p2p.Envelope{To: aID, Message: &p2ptest.Message{Value: "bar"}})
  167. p2ptest.RequireReceive(t, a, p2p.Envelope{From: cID, Message: &p2ptest.Message{Value: "bar"}})
  168. p2ptest.RequireEmpty(t, a, b, c)
  169. // None of these messages should have made it onto the other channels.
  170. for _, other := range otherChannels {
  171. p2ptest.RequireEmpty(t, other)
  172. }
  173. }
  174. func TestRouter_Channel_Broadcast(t *testing.T) {
  175. t.Cleanup(leaktest.Check(t))
  176. // Create a test network and open a channel on all nodes.
  177. network := p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: 4})
  178. network.Start(t)
  179. ids := network.NodeIDs()
  180. aID, bID, cID, dID := ids[0], ids[1], ids[2], ids[3]
  181. channels := network.MakeChannels(t, 1, &p2ptest.Message{}, 0)
  182. a, b, c, d := channels[aID], channels[bID], channels[cID], channels[dID]
  183. // Sending a broadcast from b should work.
  184. p2ptest.RequireSend(t, b, p2p.Envelope{Broadcast: true, Message: &p2ptest.Message{Value: "foo"}})
  185. p2ptest.RequireReceive(t, a, p2p.Envelope{From: bID, Message: &p2ptest.Message{Value: "foo"}})
  186. p2ptest.RequireReceive(t, c, p2p.Envelope{From: bID, Message: &p2ptest.Message{Value: "foo"}})
  187. p2ptest.RequireReceive(t, d, p2p.Envelope{From: bID, Message: &p2ptest.Message{Value: "foo"}})
  188. p2ptest.RequireEmpty(t, a, b, c, d)
  189. // Removing one node from the network shouldn't prevent broadcasts from working.
  190. network.Remove(t, dID)
  191. p2ptest.RequireSend(t, a, p2p.Envelope{Broadcast: true, Message: &p2ptest.Message{Value: "bar"}})
  192. p2ptest.RequireReceive(t, b, p2p.Envelope{From: aID, Message: &p2ptest.Message{Value: "bar"}})
  193. p2ptest.RequireReceive(t, c, p2p.Envelope{From: aID, Message: &p2ptest.Message{Value: "bar"}})
  194. p2ptest.RequireEmpty(t, a, b, c, d)
  195. }
  196. func TestRouter_Channel_Wrapper(t *testing.T) {
  197. t.Cleanup(leaktest.Check(t))
  198. // Create a test network and open a channel on all nodes.
  199. network := p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: 2})
  200. network.Start(t)
  201. ids := network.NodeIDs()
  202. aID, bID := ids[0], ids[1]
  203. channels := network.MakeChannels(t, 1, &wrapperMessage{}, 0)
  204. a, b := channels[aID], channels[bID]
  205. // Since wrapperMessage implements p2p.Wrapper and handles Message, it
  206. // should automatically wrap and unwrap sent messages -- we prepend the
  207. // wrapper actions to the message value to signal this.
  208. p2ptest.RequireSend(t, a, p2p.Envelope{To: bID, Message: &p2ptest.Message{Value: "foo"}})
  209. p2ptest.RequireReceive(t, b, p2p.Envelope{From: aID, Message: &p2ptest.Message{Value: "unwrap:wrap:foo"}})
  210. // If we send a different message that can't be wrapped, it should be dropped.
  211. p2ptest.RequireSend(t, a, p2p.Envelope{To: bID, Message: &gogotypes.BoolValue{Value: true}})
  212. p2ptest.RequireEmpty(t, b)
  213. // If we send the wrapper message itself, it should also be passed through
  214. // since WrapperMessage supports it, and should only be unwrapped at the receiver.
  215. p2ptest.RequireSend(t, a, p2p.Envelope{
  216. To: bID,
  217. Message: &wrapperMessage{Message: p2ptest.Message{Value: "foo"}},
  218. })
  219. p2ptest.RequireReceive(t, b, p2p.Envelope{
  220. From: aID,
  221. Message: &p2ptest.Message{Value: "unwrap:foo"},
  222. })
  223. }
  224. // WrapperMessage prepends the value with "wrap:" and "unwrap:" to test it.
  225. type wrapperMessage struct {
  226. p2ptest.Message
  227. }
  228. var _ p2p.Wrapper = (*wrapperMessage)(nil)
  229. func (w *wrapperMessage) Wrap(inner proto.Message) error {
  230. switch inner := inner.(type) {
  231. case *p2ptest.Message:
  232. w.Message.Value = fmt.Sprintf("wrap:%v", inner.Value)
  233. case *wrapperMessage:
  234. *w = *inner
  235. default:
  236. return fmt.Errorf("invalid message type %T", inner)
  237. }
  238. return nil
  239. }
  240. func (w *wrapperMessage) Unwrap() (proto.Message, error) {
  241. return &p2ptest.Message{Value: fmt.Sprintf("unwrap:%v", w.Message.Value)}, nil
  242. }
  243. func TestRouter_Channel_Error(t *testing.T) {
  244. t.Cleanup(leaktest.Check(t))
  245. // Create a test network and open a channel on all nodes.
  246. network := p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: 3})
  247. network.Start(t)
  248. ids := network.NodeIDs()
  249. aID, bID := ids[0], ids[1]
  250. channels := network.MakeChannels(t, 1, &p2ptest.Message{}, 0)
  251. a := channels[aID]
  252. // Erroring b should cause it to be disconnected. It will reconnect shortly after.
  253. sub := network.Nodes[aID].MakePeerUpdates(t)
  254. p2ptest.RequireError(t, a, p2p.PeerError{NodeID: bID, Err: errors.New("boom")})
  255. p2ptest.RequireUpdates(t, sub, []p2p.PeerUpdate{
  256. {NodeID: bID, Status: p2p.PeerStatusDown},
  257. {NodeID: bID, Status: p2p.PeerStatusUp},
  258. })
  259. }
  260. func TestRouter_AcceptPeers(t *testing.T) {
  261. testcases := map[string]struct {
  262. peerInfo p2p.NodeInfo
  263. peerKey crypto.PubKey
  264. ok bool
  265. }{
  266. "valid handshake": {peerInfo, peerKey.PubKey(), true},
  267. "empty handshake": {p2p.NodeInfo{}, nil, false},
  268. "invalid key": {peerInfo, selfKey.PubKey(), false},
  269. "self handshake": {selfInfo, selfKey.PubKey(), false},
  270. }
  271. for name, tc := range testcases {
  272. tc := tc
  273. t.Run(name, func(t *testing.T) {
  274. t.Cleanup(leaktest.Check(t))
  275. // Set up a mock transport that handshakes.
  276. closer := tmsync.NewCloser()
  277. mockConnection := &mocks.Connection{}
  278. mockConnection.On("String").Maybe().Return("mock")
  279. mockConnection.On("Handshake", mock.Anything, selfInfo, selfKey).
  280. Return(tc.peerInfo, tc.peerKey, nil)
  281. mockConnection.On("Close").Run(func(_ mock.Arguments) { closer.Close() }).Return(nil)
  282. mockConnection.On("RemoteEndpoint").Return(p2p.Endpoint{})
  283. if tc.ok {
  284. // without the sleep after RequireUpdate this method isn't
  285. // always called. Consider making this call optional.
  286. mockConnection.On("ReceiveMessage").Return(chID, nil, io.EOF)
  287. }
  288. mockTransport := &mocks.Transport{}
  289. mockTransport.On("String").Maybe().Return("mock")
  290. mockTransport.On("Protocols").Return([]p2p.Protocol{"mock"})
  291. mockTransport.On("Close").Return(nil)
  292. mockTransport.On("Accept").Once().Return(mockConnection, nil)
  293. mockTransport.On("Accept").Once().Return(nil, io.EOF)
  294. // Set up and start the router.
  295. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  296. require.NoError(t, err)
  297. defer peerManager.Close()
  298. sub := peerManager.Subscribe()
  299. defer sub.Close()
  300. router, err := p2p.NewRouter(
  301. log.TestingLogger(),
  302. p2p.NopMetrics(),
  303. selfInfo,
  304. selfKey,
  305. peerManager,
  306. []p2p.Transport{mockTransport},
  307. p2p.RouterOptions{},
  308. )
  309. require.NoError(t, err)
  310. require.NoError(t, router.Start())
  311. if tc.ok {
  312. p2ptest.RequireUpdate(t, sub, p2p.PeerUpdate{
  313. NodeID: tc.peerInfo.NodeID,
  314. Status: p2p.PeerStatusUp,
  315. })
  316. // force a context switch so that the
  317. // connection is handled.
  318. time.Sleep(time.Millisecond)
  319. sub.Close()
  320. } else {
  321. select {
  322. case <-closer.Done():
  323. case <-time.After(100 * time.Millisecond):
  324. require.Fail(t, "connection not closed")
  325. }
  326. }
  327. require.NoError(t, router.Stop())
  328. mockTransport.AssertExpectations(t)
  329. mockConnection.AssertExpectations(t)
  330. })
  331. }
  332. }
  333. func TestRouter_AcceptPeers_Error(t *testing.T) {
  334. t.Cleanup(leaktest.Check(t))
  335. // Set up a mock transport that returns an error, which should prevent
  336. // the router from calling Accept again.
  337. mockTransport := &mocks.Transport{}
  338. mockTransport.On("String").Maybe().Return("mock")
  339. mockTransport.On("Protocols").Return([]p2p.Protocol{"mock"})
  340. mockTransport.On("Accept").Once().Return(nil, errors.New("boom"))
  341. mockTransport.On("Close").Return(nil)
  342. // Set up and start the router.
  343. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  344. require.NoError(t, err)
  345. defer peerManager.Close()
  346. router, err := p2p.NewRouter(
  347. log.TestingLogger(),
  348. p2p.NopMetrics(),
  349. selfInfo,
  350. selfKey,
  351. peerManager,
  352. []p2p.Transport{mockTransport},
  353. p2p.RouterOptions{},
  354. )
  355. require.NoError(t, err)
  356. require.NoError(t, router.Start())
  357. time.Sleep(time.Second)
  358. require.NoError(t, router.Stop())
  359. mockTransport.AssertExpectations(t)
  360. }
  361. func TestRouter_AcceptPeers_ErrorEOF(t *testing.T) {
  362. t.Cleanup(leaktest.Check(t))
  363. // Set up a mock transport that returns io.EOF once, which should prevent
  364. // the router from calling Accept again.
  365. mockTransport := &mocks.Transport{}
  366. mockTransport.On("String").Maybe().Return("mock")
  367. mockTransport.On("Protocols").Return([]p2p.Protocol{"mock"})
  368. mockTransport.On("Accept").Once().Return(nil, io.EOF)
  369. mockTransport.On("Close").Return(nil)
  370. // Set up and start the router.
  371. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  372. require.NoError(t, err)
  373. defer peerManager.Close()
  374. router, err := p2p.NewRouter(
  375. log.TestingLogger(),
  376. p2p.NopMetrics(),
  377. selfInfo,
  378. selfKey,
  379. peerManager,
  380. []p2p.Transport{mockTransport},
  381. p2p.RouterOptions{},
  382. )
  383. require.NoError(t, err)
  384. require.NoError(t, router.Start())
  385. time.Sleep(time.Second)
  386. require.NoError(t, router.Stop())
  387. mockTransport.AssertExpectations(t)
  388. }
  389. func TestRouter_AcceptPeers_HeadOfLineBlocking(t *testing.T) {
  390. t.Cleanup(leaktest.Check(t))
  391. // Set up a mock transport that returns a connection that blocks during the
  392. // handshake. It should be able to accept several of these in parallel, i.e.
  393. // a single connection can't halt other connections being accepted.
  394. acceptCh := make(chan bool, 3)
  395. closeCh := make(chan time.Time)
  396. mockConnection := &mocks.Connection{}
  397. mockConnection.On("String").Maybe().Return("mock")
  398. mockConnection.On("Handshake", mock.Anything, selfInfo, selfKey).
  399. WaitUntil(closeCh).Return(p2p.NodeInfo{}, nil, io.EOF)
  400. mockConnection.On("Close").Return(nil)
  401. mockConnection.On("RemoteEndpoint").Return(p2p.Endpoint{})
  402. mockTransport := &mocks.Transport{}
  403. mockTransport.On("String").Maybe().Return("mock")
  404. mockTransport.On("Protocols").Return([]p2p.Protocol{"mock"})
  405. mockTransport.On("Close").Return(nil)
  406. mockTransport.On("Accept").Times(3).Run(func(_ mock.Arguments) {
  407. acceptCh <- true
  408. }).Return(mockConnection, nil)
  409. mockTransport.On("Accept").Once().Return(nil, io.EOF)
  410. // Set up and start the router.
  411. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  412. require.NoError(t, err)
  413. defer peerManager.Close()
  414. router, err := p2p.NewRouter(
  415. log.TestingLogger(),
  416. p2p.NopMetrics(),
  417. selfInfo,
  418. selfKey,
  419. peerManager,
  420. []p2p.Transport{mockTransport},
  421. p2p.RouterOptions{},
  422. )
  423. require.NoError(t, err)
  424. require.NoError(t, router.Start())
  425. require.Eventually(t, func() bool {
  426. return len(acceptCh) == 3
  427. }, time.Second, 10*time.Millisecond)
  428. close(closeCh)
  429. time.Sleep(100 * time.Millisecond)
  430. require.NoError(t, router.Stop())
  431. mockTransport.AssertExpectations(t)
  432. mockConnection.AssertExpectations(t)
  433. }
  434. func TestRouter_DialPeers(t *testing.T) {
  435. testcases := map[string]struct {
  436. dialID p2p.NodeID
  437. peerInfo p2p.NodeInfo
  438. peerKey crypto.PubKey
  439. dialErr error
  440. ok bool
  441. }{
  442. "valid dial": {peerInfo.NodeID, peerInfo, peerKey.PubKey(), nil, true},
  443. "empty handshake": {peerInfo.NodeID, p2p.NodeInfo{}, nil, nil, false},
  444. "invalid key": {peerInfo.NodeID, peerInfo, selfKey.PubKey(), nil, false},
  445. "unexpected node ID": {peerInfo.NodeID, selfInfo, selfKey.PubKey(), nil, false},
  446. "dial error": {peerInfo.NodeID, peerInfo, peerKey.PubKey(), errors.New("boom"), false},
  447. }
  448. for name, tc := range testcases {
  449. tc := tc
  450. t.Run(name, func(t *testing.T) {
  451. t.Cleanup(leaktest.Check(t))
  452. address := p2p.NodeAddress{Protocol: "mock", NodeID: tc.dialID}
  453. endpoint := p2p.Endpoint{Protocol: "mock", Path: string(tc.dialID)}
  454. // Set up a mock transport that handshakes.
  455. closer := tmsync.NewCloser()
  456. mockConnection := &mocks.Connection{}
  457. mockConnection.On("String").Maybe().Return("mock")
  458. if tc.dialErr == nil {
  459. mockConnection.On("Handshake", mock.Anything, selfInfo, selfKey).
  460. Return(tc.peerInfo, tc.peerKey, nil)
  461. mockConnection.On("Close").Run(func(_ mock.Arguments) { closer.Close() }).Return(nil)
  462. }
  463. if tc.ok {
  464. // without the sleep after RequireUpdate this method isn't
  465. // always called. Consider making this call optional.
  466. mockConnection.On("ReceiveMessage").Return(chID, nil, io.EOF)
  467. }
  468. mockTransport := &mocks.Transport{}
  469. mockTransport.On("String").Maybe().Return("mock")
  470. mockTransport.On("Protocols").Return([]p2p.Protocol{"mock"})
  471. mockTransport.On("Close").Return(nil)
  472. mockTransport.On("Accept").Maybe().Return(nil, io.EOF)
  473. if tc.dialErr == nil {
  474. mockTransport.On("Dial", mock.Anything, endpoint).Once().Return(mockConnection, nil)
  475. // This handles the retry when a dialed connection gets closed after ReceiveMessage
  476. // returns io.EOF above.
  477. mockTransport.On("Dial", mock.Anything, endpoint).Maybe().Return(nil, io.EOF)
  478. } else {
  479. mockTransport.On("Dial", mock.Anything, endpoint).Once().
  480. Run(func(_ mock.Arguments) { closer.Close() }).
  481. Return(nil, tc.dialErr)
  482. }
  483. // Set up and start the router.
  484. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  485. require.NoError(t, err)
  486. defer peerManager.Close()
  487. added, err := peerManager.Add(address)
  488. require.NoError(t, err)
  489. require.True(t, added)
  490. sub := peerManager.Subscribe()
  491. defer sub.Close()
  492. router, err := p2p.NewRouter(
  493. log.TestingLogger(),
  494. p2p.NopMetrics(),
  495. selfInfo,
  496. selfKey,
  497. peerManager,
  498. []p2p.Transport{mockTransport},
  499. p2p.RouterOptions{},
  500. )
  501. require.NoError(t, err)
  502. require.NoError(t, router.Start())
  503. if tc.ok {
  504. p2ptest.RequireUpdate(t, sub, p2p.PeerUpdate{
  505. NodeID: tc.peerInfo.NodeID,
  506. Status: p2p.PeerStatusUp,
  507. })
  508. // force a context switch so that the
  509. // connection is handled.
  510. time.Sleep(time.Millisecond)
  511. sub.Close()
  512. } else {
  513. select {
  514. case <-closer.Done():
  515. case <-time.After(100 * time.Millisecond):
  516. require.Fail(t, "connection not closed")
  517. }
  518. }
  519. require.NoError(t, router.Stop())
  520. mockTransport.AssertExpectations(t)
  521. mockConnection.AssertExpectations(t)
  522. })
  523. }
  524. }
  525. func TestRouter_DialPeers_Parallel(t *testing.T) {
  526. t.Cleanup(leaktest.Check(t))
  527. a := p2p.NodeAddress{Protocol: "mock", NodeID: p2p.NodeID(strings.Repeat("a", 40))}
  528. b := p2p.NodeAddress{Protocol: "mock", NodeID: p2p.NodeID(strings.Repeat("b", 40))}
  529. c := p2p.NodeAddress{Protocol: "mock", NodeID: p2p.NodeID(strings.Repeat("c", 40))}
  530. // Set up a mock transport that returns a connection that blocks during the
  531. // handshake. It should dial all peers in parallel.
  532. dialCh := make(chan bool, 3)
  533. closeCh := make(chan time.Time)
  534. mockConnection := &mocks.Connection{}
  535. mockConnection.On("String").Maybe().Return("mock")
  536. mockConnection.On("Handshake", mock.Anything, selfInfo, selfKey).
  537. WaitUntil(closeCh).Return(p2p.NodeInfo{}, nil, io.EOF)
  538. mockConnection.On("Close").Return(nil)
  539. mockTransport := &mocks.Transport{}
  540. mockTransport.On("String").Maybe().Return("mock")
  541. mockTransport.On("Protocols").Return([]p2p.Protocol{"mock"})
  542. mockTransport.On("Close").Return(nil)
  543. mockTransport.On("Accept").Once().Return(nil, io.EOF)
  544. for _, address := range []p2p.NodeAddress{a, b, c} {
  545. endpoint := p2p.Endpoint{Protocol: address.Protocol, Path: string(address.NodeID)}
  546. mockTransport.On("Dial", mock.Anything, endpoint).Run(func(_ mock.Arguments) {
  547. dialCh <- true
  548. }).Return(mockConnection, nil)
  549. }
  550. // Set up and start the router.
  551. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  552. require.NoError(t, err)
  553. defer peerManager.Close()
  554. added, err := peerManager.Add(a)
  555. require.NoError(t, err)
  556. require.True(t, added)
  557. added, err = peerManager.Add(b)
  558. require.NoError(t, err)
  559. require.True(t, added)
  560. added, err = peerManager.Add(c)
  561. require.NoError(t, err)
  562. require.True(t, added)
  563. router, err := p2p.NewRouter(
  564. log.TestingLogger(),
  565. p2p.NopMetrics(),
  566. selfInfo,
  567. selfKey,
  568. peerManager,
  569. []p2p.Transport{mockTransport},
  570. p2p.RouterOptions{},
  571. )
  572. require.NoError(t, err)
  573. require.NoError(t, router.Start())
  574. require.Eventually(t, func() bool {
  575. return len(dialCh) == 3
  576. }, time.Second, 10*time.Millisecond)
  577. close(closeCh)
  578. time.Sleep(100 * time.Millisecond)
  579. require.NoError(t, router.Stop())
  580. mockTransport.AssertExpectations(t)
  581. mockConnection.AssertExpectations(t)
  582. }
  583. func TestRouter_EvictPeers(t *testing.T) {
  584. t.Cleanup(leaktest.Check(t))
  585. // Set up a mock transport that we can evict.
  586. closeCh := make(chan time.Time)
  587. closeOnce := sync.Once{}
  588. mockConnection := &mocks.Connection{}
  589. mockConnection.On("String").Maybe().Return("mock")
  590. mockConnection.On("Handshake", mock.Anything, selfInfo, selfKey).
  591. Return(peerInfo, peerKey.PubKey(), nil)
  592. mockConnection.On("ReceiveMessage").WaitUntil(closeCh).Return(chID, nil, io.EOF)
  593. mockConnection.On("RemoteEndpoint").Return(p2p.Endpoint{})
  594. mockConnection.On("Close").Run(func(_ mock.Arguments) {
  595. closeOnce.Do(func() {
  596. close(closeCh)
  597. })
  598. }).Return(nil)
  599. mockTransport := &mocks.Transport{}
  600. mockTransport.On("String").Maybe().Return("mock")
  601. mockTransport.On("Protocols").Return([]p2p.Protocol{"mock"})
  602. mockTransport.On("Close").Return(nil)
  603. mockTransport.On("Accept").Once().Return(mockConnection, nil)
  604. mockTransport.On("Accept").Once().Return(nil, io.EOF)
  605. // Set up and start the router.
  606. peerManager, err := p2p.NewPeerManager(selfID, dbm.NewMemDB(), p2p.PeerManagerOptions{})
  607. require.NoError(t, err)
  608. defer peerManager.Close()
  609. sub := peerManager.Subscribe()
  610. defer sub.Close()
  611. router, err := p2p.NewRouter(
  612. log.TestingLogger(),
  613. p2p.NopMetrics(),
  614. selfInfo,
  615. selfKey,
  616. peerManager,
  617. []p2p.Transport{mockTransport},
  618. p2p.RouterOptions{},
  619. )
  620. require.NoError(t, err)
  621. require.NoError(t, router.Start())
  622. // Wait for the mock peer to connect, then evict it by reporting an error.
  623. p2ptest.RequireUpdate(t, sub, p2p.PeerUpdate{
  624. NodeID: peerInfo.NodeID,
  625. Status: p2p.PeerStatusUp,
  626. })
  627. require.NoError(t, peerManager.Errored(peerInfo.NodeID, errors.New("boom")))
  628. p2ptest.RequireUpdate(t, sub, p2p.PeerUpdate{
  629. NodeID: peerInfo.NodeID,
  630. Status: p2p.PeerStatusDown,
  631. })
  632. sub.Close()
  633. require.NoError(t, router.Stop())
  634. mockTransport.AssertExpectations(t)
  635. mockConnection.AssertExpectations(t)
  636. }