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.

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