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.

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