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.

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