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.

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