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.

557 lines
15 KiB

  1. package pex
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. crypto "github.com/tendermint/tendermint/crypto"
  13. "github.com/tendermint/tendermint/crypto/ed25519"
  14. cmn "github.com/tendermint/tendermint/libs/common"
  15. "github.com/tendermint/tendermint/libs/log"
  16. "github.com/tendermint/tendermint/config"
  17. "github.com/tendermint/tendermint/p2p"
  18. "github.com/tendermint/tendermint/p2p/conn"
  19. )
  20. var (
  21. cfg *config.P2PConfig
  22. )
  23. func init() {
  24. cfg = config.DefaultP2PConfig()
  25. cfg.PexReactor = true
  26. cfg.AllowDuplicateIP = true
  27. }
  28. func TestPEXReactorBasic(t *testing.T) {
  29. r, book := createReactor(&PEXReactorConfig{})
  30. defer teardownReactor(book)
  31. assert.NotNil(t, r)
  32. assert.NotEmpty(t, r.GetChannels())
  33. }
  34. func TestPEXReactorAddRemovePeer(t *testing.T) {
  35. r, book := createReactor(&PEXReactorConfig{})
  36. defer teardownReactor(book)
  37. size := book.Size()
  38. peer := p2p.CreateRandomPeer(false)
  39. r.AddPeer(peer)
  40. assert.Equal(t, size+1, book.Size())
  41. r.RemovePeer(peer, "peer not available")
  42. outboundPeer := p2p.CreateRandomPeer(true)
  43. r.AddPeer(outboundPeer)
  44. assert.Equal(t, size+1, book.Size(), "outbound peers should not be added to the address book")
  45. r.RemovePeer(outboundPeer, "peer not available")
  46. }
  47. // --- FAIL: TestPEXReactorRunning (11.10s)
  48. // pex_reactor_test.go:411: expected all switches to be connected to at
  49. // least one peer (switches: 0 => {outbound: 1, inbound: 0}, 1 =>
  50. // {outbound: 0, inbound: 1}, 2 => {outbound: 0, inbound: 0}, )
  51. //
  52. // EXPLANATION: peers are getting rejected because in switch#addPeer we check
  53. // if any peer (who we already connected to) has the same IP. Even though local
  54. // peers have different IP addresses, they all have the same underlying remote
  55. // IP: 127.0.0.1.
  56. //
  57. func TestPEXReactorRunning(t *testing.T) {
  58. N := 3
  59. switches := make([]*p2p.Switch, N)
  60. // directory to store address books
  61. dir, err := ioutil.TempDir("", "pex_reactor")
  62. require.Nil(t, err)
  63. defer os.RemoveAll(dir) // nolint: errcheck
  64. books := make([]*addrBook, N)
  65. logger := log.TestingLogger()
  66. // create switches
  67. for i := 0; i < N; i++ {
  68. switches[i] = p2p.MakeSwitch(cfg, i, "testing", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch {
  69. books[i] = NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", i)), false)
  70. books[i].SetLogger(logger.With("pex", i))
  71. sw.SetAddrBook(books[i])
  72. sw.SetLogger(logger.With("pex", i))
  73. r := NewPEXReactor(books[i], &PEXReactorConfig{})
  74. r.SetLogger(logger.With("pex", i))
  75. r.SetEnsurePeersPeriod(250 * time.Millisecond)
  76. sw.AddReactor("pex", r)
  77. return sw
  78. })
  79. }
  80. addOtherNodeAddrToAddrBook := func(switchIndex, otherSwitchIndex int) {
  81. addr := switches[otherSwitchIndex].NodeInfo().NetAddress()
  82. books[switchIndex].AddAddress(addr, addr)
  83. }
  84. addOtherNodeAddrToAddrBook(0, 1)
  85. addOtherNodeAddrToAddrBook(1, 0)
  86. addOtherNodeAddrToAddrBook(2, 1)
  87. for i, sw := range switches {
  88. sw.AddListener(p2p.NewDefaultListener("tcp://"+sw.NodeInfo().ListenAddr, "", false, logger.With("pex", i)))
  89. err := sw.Start() // start switch and reactors
  90. require.Nil(t, err)
  91. }
  92. assertPeersWithTimeout(t, switches, 10*time.Millisecond, 10*time.Second, N-1)
  93. // stop them
  94. for _, s := range switches {
  95. s.Stop()
  96. }
  97. }
  98. func TestPEXReactorReceive(t *testing.T) {
  99. r, book := createReactor(&PEXReactorConfig{})
  100. defer teardownReactor(book)
  101. peer := p2p.CreateRandomPeer(false)
  102. // we have to send a request to receive responses
  103. r.RequestAddrs(peer)
  104. size := book.Size()
  105. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  106. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  107. r.Receive(PexChannel, peer, msg)
  108. assert.Equal(t, size+1, book.Size())
  109. msg = cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  110. r.Receive(PexChannel, peer, msg) // should not panic.
  111. }
  112. func TestPEXReactorRequestMessageAbuse(t *testing.T) {
  113. r, book := createReactor(&PEXReactorConfig{})
  114. defer teardownReactor(book)
  115. sw := createSwitchAndAddReactors(r)
  116. sw.SetAddrBook(book)
  117. peer := newMockPeer()
  118. p2p.AddPeerToSwitch(sw, peer)
  119. assert.True(t, sw.Peers().Has(peer.ID()))
  120. id := string(peer.ID())
  121. msg := cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  122. // first time creates the entry
  123. r.Receive(PexChannel, peer, msg)
  124. assert.True(t, r.lastReceivedRequests.Has(id))
  125. assert.True(t, sw.Peers().Has(peer.ID()))
  126. // next time sets the last time value
  127. r.Receive(PexChannel, peer, msg)
  128. assert.True(t, r.lastReceivedRequests.Has(id))
  129. assert.True(t, sw.Peers().Has(peer.ID()))
  130. // third time is too many too soon - peer is removed
  131. r.Receive(PexChannel, peer, msg)
  132. assert.False(t, r.lastReceivedRequests.Has(id))
  133. assert.False(t, sw.Peers().Has(peer.ID()))
  134. }
  135. func TestPEXReactorAddrsMessageAbuse(t *testing.T) {
  136. r, book := createReactor(&PEXReactorConfig{})
  137. defer teardownReactor(book)
  138. sw := createSwitchAndAddReactors(r)
  139. sw.SetAddrBook(book)
  140. peer := newMockPeer()
  141. p2p.AddPeerToSwitch(sw, peer)
  142. assert.True(t, sw.Peers().Has(peer.ID()))
  143. id := string(peer.ID())
  144. // request addrs from the peer
  145. r.RequestAddrs(peer)
  146. assert.True(t, r.requestsSent.Has(id))
  147. assert.True(t, sw.Peers().Has(peer.ID()))
  148. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  149. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  150. // receive some addrs. should clear the request
  151. r.Receive(PexChannel, peer, msg)
  152. assert.False(t, r.requestsSent.Has(id))
  153. assert.True(t, sw.Peers().Has(peer.ID()))
  154. // receiving more addrs causes a disconnect
  155. r.Receive(PexChannel, peer, msg)
  156. assert.False(t, sw.Peers().Has(peer.ID()))
  157. }
  158. func TestCheckSeeds(t *testing.T) {
  159. // directory to store address books
  160. dir, err := ioutil.TempDir("", "pex_reactor")
  161. require.Nil(t, err)
  162. defer os.RemoveAll(dir) // nolint: errcheck
  163. // 1. test creating peer with no seeds works
  164. peer := testCreateDefaultPeer(dir, 0)
  165. require.Nil(t, peer.Start())
  166. peer.Stop()
  167. // 2. create seed
  168. seed := testCreateSeed(dir, 1, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  169. // 3. test create peer with online seed works
  170. peer = testCreatePeerWithSeed(dir, 2, seed)
  171. require.Nil(t, peer.Start())
  172. peer.Stop()
  173. // 4. test create peer with all seeds having unresolvable DNS fails
  174. badPeerConfig := &PEXReactorConfig{
  175. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  176. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657"},
  177. }
  178. peer = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  179. require.Error(t, peer.Start())
  180. peer.Stop()
  181. // 5. test create peer with one good seed address succeeds
  182. badPeerConfig = &PEXReactorConfig{
  183. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  184. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657",
  185. seed.NodeInfo().NetAddress().String()},
  186. }
  187. peer = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  188. require.Nil(t, peer.Start())
  189. peer.Stop()
  190. }
  191. func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
  192. // directory to store address books
  193. dir, err := ioutil.TempDir("", "pex_reactor")
  194. require.Nil(t, err)
  195. defer os.RemoveAll(dir) // nolint: errcheck
  196. // 1. create seed
  197. seed := testCreateSeed(dir, 0, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  198. require.Nil(t, seed.Start())
  199. defer seed.Stop()
  200. // 2. create usual peer with only seed configured.
  201. peer := testCreatePeerWithSeed(dir, 1, seed)
  202. require.Nil(t, peer.Start())
  203. defer peer.Stop()
  204. // 3. check that the peer connects to seed immediately
  205. assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1)
  206. }
  207. func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) {
  208. // directory to store address books
  209. dir, err := ioutil.TempDir("", "pex_reactor")
  210. require.Nil(t, err)
  211. defer os.RemoveAll(dir) // nolint: errcheck
  212. // 1. create peer
  213. peer := testCreateDefaultPeer(dir, 1)
  214. require.Nil(t, peer.Start())
  215. defer peer.Stop()
  216. // 2. Create seed which knows about the peer
  217. seed := testCreateSeed(dir, 2, []*p2p.NetAddress{peer.NodeInfo().NetAddress()}, []*p2p.NetAddress{peer.NodeInfo().NetAddress()})
  218. require.Nil(t, seed.Start())
  219. defer seed.Stop()
  220. // 3. create another peer with only seed configured.
  221. secondPeer := testCreatePeerWithSeed(dir, 3, seed)
  222. require.Nil(t, secondPeer.Start())
  223. defer secondPeer.Stop()
  224. // 4. check that the second peer connects to seed immediately
  225. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 3*time.Second, 1)
  226. // 5. check that the second peer connects to the first peer immediately
  227. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 1*time.Second, 2)
  228. }
  229. func TestPEXReactorCrawlStatus(t *testing.T) {
  230. pexR, book := createReactor(&PEXReactorConfig{SeedMode: true})
  231. defer teardownReactor(book)
  232. // Seed/Crawler mode uses data from the Switch
  233. sw := createSwitchAndAddReactors(pexR)
  234. sw.SetAddrBook(book)
  235. // Create a peer, add it to the peer set and the addrbook.
  236. peer := p2p.CreateRandomPeer(false)
  237. p2p.AddPeerToSwitch(pexR.Switch, peer)
  238. addr1 := peer.NodeInfo().NetAddress()
  239. pexR.book.AddAddress(addr1, addr1)
  240. // Add a non-connected address to the book.
  241. _, addr2 := p2p.CreateRoutableAddr()
  242. pexR.book.AddAddress(addr2, addr1)
  243. // Get some peerInfos to crawl
  244. peerInfos := pexR.getPeersToCrawl()
  245. // Make sure it has the proper number of elements
  246. assert.Equal(t, 2, len(peerInfos))
  247. // TODO: test
  248. }
  249. func TestPEXReactorDoesNotAddPrivatePeersToAddrBook(t *testing.T) {
  250. peer := p2p.CreateRandomPeer(false)
  251. pexR, book := createReactor(&PEXReactorConfig{})
  252. book.AddPrivateIDs([]string{string(peer.NodeInfo().ID)})
  253. defer teardownReactor(book)
  254. // we have to send a request to receive responses
  255. pexR.RequestAddrs(peer)
  256. size := book.Size()
  257. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  258. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  259. pexR.Receive(PexChannel, peer, msg)
  260. assert.Equal(t, size, book.Size())
  261. pexR.AddPeer(peer)
  262. assert.Equal(t, size, book.Size())
  263. }
  264. func TestPEXReactorDialPeer(t *testing.T) {
  265. pexR, book := createReactor(&PEXReactorConfig{})
  266. defer teardownReactor(book)
  267. sw := createSwitchAndAddReactors(pexR)
  268. sw.SetAddrBook(book)
  269. peer := newMockPeer()
  270. addr := peer.NodeInfo().NetAddress()
  271. assert.Equal(t, 0, pexR.AttemptsToDial(addr))
  272. // 1st unsuccessful attempt
  273. pexR.dialPeer(addr)
  274. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  275. // 2nd unsuccessful attempt
  276. pexR.dialPeer(addr)
  277. // must be skipped because it is too early
  278. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  279. if !testing.Short() {
  280. time.Sleep(3 * time.Second)
  281. // 3rd attempt
  282. pexR.dialPeer(addr)
  283. assert.Equal(t, 2, pexR.AttemptsToDial(addr))
  284. }
  285. }
  286. type mockPeer struct {
  287. *cmn.BaseService
  288. pubKey crypto.PubKey
  289. addr *p2p.NetAddress
  290. outbound, persistent bool
  291. }
  292. func newMockPeer() mockPeer {
  293. _, netAddr := p2p.CreateRoutableAddr()
  294. mp := mockPeer{
  295. addr: netAddr,
  296. pubKey: ed25519.GenPrivKey().PubKey(),
  297. }
  298. mp.BaseService = cmn.NewBaseService(nil, "MockPeer", mp)
  299. mp.Start()
  300. return mp
  301. }
  302. func (mp mockPeer) ID() p2p.ID { return mp.addr.ID }
  303. func (mp mockPeer) IsOutbound() bool { return mp.outbound }
  304. func (mp mockPeer) IsPersistent() bool { return mp.persistent }
  305. func (mp mockPeer) NodeInfo() p2p.NodeInfo {
  306. return p2p.NodeInfo{
  307. ID: mp.addr.ID,
  308. ListenAddr: mp.addr.DialString(),
  309. }
  310. }
  311. func (mockPeer) RemoteIP() net.IP { return net.ParseIP("127.0.0.1") }
  312. func (mockPeer) Status() conn.ConnectionStatus { return conn.ConnectionStatus{} }
  313. func (mockPeer) Send(byte, []byte) bool { return false }
  314. func (mockPeer) TrySend(byte, []byte) bool { return false }
  315. func (mockPeer) Set(string, interface{}) {}
  316. func (mockPeer) Get(string) interface{} { return nil }
  317. func (mockPeer) OriginalAddr() *p2p.NetAddress { return nil }
  318. func assertPeersWithTimeout(
  319. t *testing.T,
  320. switches []*p2p.Switch,
  321. checkPeriod, timeout time.Duration,
  322. nPeers int,
  323. ) {
  324. var (
  325. ticker = time.NewTicker(checkPeriod)
  326. remaining = timeout
  327. )
  328. for {
  329. select {
  330. case <-ticker.C:
  331. // check peers are connected
  332. allGood := true
  333. for _, s := range switches {
  334. outbound, inbound, _ := s.NumPeers()
  335. if outbound+inbound < nPeers {
  336. allGood = false
  337. break
  338. }
  339. }
  340. remaining -= checkPeriod
  341. if remaining < 0 {
  342. remaining = 0
  343. }
  344. if allGood {
  345. return
  346. }
  347. case <-time.After(remaining):
  348. numPeersStr := ""
  349. for i, s := range switches {
  350. outbound, inbound, _ := s.NumPeers()
  351. numPeersStr += fmt.Sprintf("%d => {outbound: %d, inbound: %d}, ", i, outbound, inbound)
  352. }
  353. t.Errorf(
  354. "expected all switches to be connected to at least %d peer(s) (switches: %s)",
  355. nPeers, numPeersStr,
  356. )
  357. return
  358. }
  359. }
  360. }
  361. // Creates a peer with the provided config
  362. func testCreatePeerWithConfig(dir string, id int, config *PEXReactorConfig) *p2p.Switch {
  363. peer := p2p.MakeSwitch(
  364. cfg,
  365. id,
  366. "127.0.0.1",
  367. "123.123.123",
  368. func(i int, sw *p2p.Switch) *p2p.Switch {
  369. book := NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", id)), false)
  370. book.SetLogger(log.TestingLogger())
  371. sw.SetAddrBook(book)
  372. sw.SetLogger(log.TestingLogger())
  373. r := NewPEXReactor(
  374. book,
  375. config,
  376. )
  377. r.SetLogger(log.TestingLogger())
  378. sw.AddReactor("pex", r)
  379. return sw
  380. },
  381. )
  382. peer.AddListener(
  383. p2p.NewDefaultListener("tcp://"+peer.NodeInfo().ListenAddr, "", false, log.TestingLogger()),
  384. )
  385. return peer
  386. }
  387. // Creates a peer with the default config
  388. func testCreateDefaultPeer(dir string, id int) *p2p.Switch {
  389. return testCreatePeerWithConfig(dir, id, &PEXReactorConfig{})
  390. }
  391. // Creates a seed which knows about the provided addresses / source address pairs.
  392. // Starting and stopping the seed is left to the caller
  393. func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*p2p.NetAddress) *p2p.Switch {
  394. seed := p2p.MakeSwitch(
  395. cfg,
  396. id,
  397. "127.0.0.1",
  398. "123.123.123",
  399. func(i int, sw *p2p.Switch) *p2p.Switch {
  400. book := NewAddrBook(filepath.Join(dir, "addrbookSeed.json"), false)
  401. book.SetLogger(log.TestingLogger())
  402. for j := 0; j < len(knownAddrs); j++ {
  403. book.AddAddress(knownAddrs[j], srcAddrs[j])
  404. book.MarkGood(knownAddrs[j])
  405. }
  406. sw.SetAddrBook(book)
  407. sw.SetLogger(log.TestingLogger())
  408. r := NewPEXReactor(book, &PEXReactorConfig{})
  409. r.SetLogger(log.TestingLogger())
  410. sw.AddReactor("pex", r)
  411. return sw
  412. },
  413. )
  414. seed.AddListener(
  415. p2p.NewDefaultListener("tcp://"+seed.NodeInfo().ListenAddr, "", false, log.TestingLogger()),
  416. )
  417. return seed
  418. }
  419. // Creates a peer which knows about the provided seed.
  420. // Starting and stopping the peer is left to the caller
  421. func testCreatePeerWithSeed(dir string, id int, seed *p2p.Switch) *p2p.Switch {
  422. conf := &PEXReactorConfig{
  423. Seeds: []string{seed.NodeInfo().NetAddress().String()},
  424. }
  425. return testCreatePeerWithConfig(dir, id, conf)
  426. }
  427. func createReactor(conf *PEXReactorConfig) (r *PEXReactor, book *addrBook) {
  428. // directory to store address book
  429. dir, err := ioutil.TempDir("", "pex_reactor")
  430. if err != nil {
  431. panic(err)
  432. }
  433. book = NewAddrBook(filepath.Join(dir, "addrbook.json"), true)
  434. book.SetLogger(log.TestingLogger())
  435. r = NewPEXReactor(book, conf)
  436. r.SetLogger(log.TestingLogger())
  437. return
  438. }
  439. func teardownReactor(book *addrBook) {
  440. err := os.RemoveAll(filepath.Dir(book.FilePath()))
  441. if err != nil {
  442. panic(err)
  443. }
  444. }
  445. func createSwitchAndAddReactors(reactors ...p2p.Reactor) *p2p.Switch {
  446. sw := p2p.MakeSwitch(cfg, 0, "127.0.0.1", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch { return sw })
  447. sw.SetLogger(log.TestingLogger())
  448. for _, r := range reactors {
  449. sw.AddReactor(r.String(), r)
  450. r.SetSwitch(sw)
  451. }
  452. return sw
  453. }