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.

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