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.

627 lines
17 KiB

p2p: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
6 years ago
  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. "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 _, sw := range switches {
  88. err := sw.Start() // start switch and reactors
  89. require.Nil(t, err)
  90. }
  91. assertPeersWithTimeout(t, switches, 10*time.Millisecond, 10*time.Second, N-1)
  92. // stop them
  93. for _, s := range switches {
  94. s.Stop()
  95. }
  96. }
  97. func TestPEXReactorReceive(t *testing.T) {
  98. r, book := createReactor(&PEXReactorConfig{})
  99. defer teardownReactor(book)
  100. peer := p2p.CreateRandomPeer(false)
  101. // we have to send a request to receive responses
  102. r.RequestAddrs(peer)
  103. size := book.Size()
  104. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  105. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  106. r.Receive(PexChannel, peer, msg)
  107. assert.Equal(t, size+1, book.Size())
  108. msg = cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  109. r.Receive(PexChannel, peer, msg) // should not panic.
  110. }
  111. func TestPEXReactorRequestMessageAbuse(t *testing.T) {
  112. r, book := createReactor(&PEXReactorConfig{})
  113. defer teardownReactor(book)
  114. sw := createSwitchAndAddReactors(r)
  115. sw.SetAddrBook(book)
  116. peer := newMockPeer()
  117. p2p.AddPeerToSwitch(sw, peer)
  118. assert.True(t, sw.Peers().Has(peer.ID()))
  119. id := string(peer.ID())
  120. msg := cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  121. // first time creates the entry
  122. r.Receive(PexChannel, peer, msg)
  123. assert.True(t, r.lastReceivedRequests.Has(id))
  124. assert.True(t, sw.Peers().Has(peer.ID()))
  125. // next time sets the last time value
  126. r.Receive(PexChannel, peer, msg)
  127. assert.True(t, r.lastReceivedRequests.Has(id))
  128. assert.True(t, sw.Peers().Has(peer.ID()))
  129. // third time is too many too soon - peer is removed
  130. r.Receive(PexChannel, peer, msg)
  131. assert.False(t, r.lastReceivedRequests.Has(id))
  132. assert.False(t, sw.Peers().Has(peer.ID()))
  133. }
  134. func TestPEXReactorAddrsMessageAbuse(t *testing.T) {
  135. r, book := createReactor(&PEXReactorConfig{})
  136. defer teardownReactor(book)
  137. sw := createSwitchAndAddReactors(r)
  138. sw.SetAddrBook(book)
  139. peer := newMockPeer()
  140. p2p.AddPeerToSwitch(sw, peer)
  141. assert.True(t, sw.Peers().Has(peer.ID()))
  142. id := string(peer.ID())
  143. // request addrs from the peer
  144. r.RequestAddrs(peer)
  145. assert.True(t, r.requestsSent.Has(id))
  146. assert.True(t, sw.Peers().Has(peer.ID()))
  147. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  148. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  149. // receive some addrs. should clear the request
  150. r.Receive(PexChannel, peer, msg)
  151. assert.False(t, r.requestsSent.Has(id))
  152. assert.True(t, sw.Peers().Has(peer.ID()))
  153. // receiving more addrs causes a disconnect
  154. r.Receive(PexChannel, peer, msg)
  155. assert.False(t, sw.Peers().Has(peer.ID()))
  156. }
  157. func TestCheckSeeds(t *testing.T) {
  158. // directory to store address books
  159. dir, err := ioutil.TempDir("", "pex_reactor")
  160. require.Nil(t, err)
  161. defer os.RemoveAll(dir) // nolint: errcheck
  162. // 1. test creating peer with no seeds works
  163. peer := testCreateDefaultPeer(dir, 0)
  164. require.Nil(t, peer.Start())
  165. peer.Stop()
  166. // 2. create seed
  167. seed := testCreateSeed(dir, 1, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  168. // 3. test create peer with online seed works
  169. peer = testCreatePeerWithSeed(dir, 2, seed)
  170. require.Nil(t, peer.Start())
  171. peer.Stop()
  172. // 4. test create peer with all seeds having unresolvable DNS fails
  173. badPeerConfig := &PEXReactorConfig{
  174. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  175. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657"},
  176. }
  177. peer = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  178. require.Error(t, peer.Start())
  179. peer.Stop()
  180. // 5. test create peer with one good seed address succeeds
  181. badPeerConfig = &PEXReactorConfig{
  182. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  183. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657",
  184. seed.NodeInfo().NetAddress().String()},
  185. }
  186. peer = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  187. require.Nil(t, peer.Start())
  188. peer.Stop()
  189. }
  190. func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
  191. // directory to store address books
  192. dir, err := ioutil.TempDir("", "pex_reactor")
  193. require.Nil(t, err)
  194. defer os.RemoveAll(dir) // nolint: errcheck
  195. // 1. create seed
  196. seed := testCreateSeed(dir, 0, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  197. require.Nil(t, seed.Start())
  198. defer seed.Stop()
  199. // 2. create usual peer with only seed configured.
  200. peer := testCreatePeerWithSeed(dir, 1, seed)
  201. require.Nil(t, peer.Start())
  202. defer peer.Stop()
  203. // 3. check that the peer connects to seed immediately
  204. assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1)
  205. }
  206. func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) {
  207. // directory to store address books
  208. dir, err := ioutil.TempDir("", "pex_reactor")
  209. require.Nil(t, err)
  210. defer os.RemoveAll(dir) // nolint: errcheck
  211. // 1. create peer
  212. peer := testCreateDefaultPeer(dir, 1)
  213. require.Nil(t, peer.Start())
  214. defer peer.Stop()
  215. // 2. Create seed which knows about the peer
  216. seed := testCreateSeed(dir, 2, []*p2p.NetAddress{peer.NodeInfo().NetAddress()}, []*p2p.NetAddress{peer.NodeInfo().NetAddress()})
  217. require.Nil(t, seed.Start())
  218. defer seed.Stop()
  219. // 3. create another peer with only seed configured.
  220. secondPeer := testCreatePeerWithSeed(dir, 3, seed)
  221. require.Nil(t, secondPeer.Start())
  222. defer secondPeer.Stop()
  223. // 4. check that the second peer connects to seed immediately
  224. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 3*time.Second, 1)
  225. // 5. check that the second peer connects to the first peer immediately
  226. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 1*time.Second, 2)
  227. }
  228. func TestPEXReactorCrawlStatus(t *testing.T) {
  229. pexR, book := createReactor(&PEXReactorConfig{SeedMode: true})
  230. defer teardownReactor(book)
  231. // Seed/Crawler mode uses data from the Switch
  232. sw := createSwitchAndAddReactors(pexR)
  233. sw.SetAddrBook(book)
  234. // Create a peer, add it to the peer set and the addrbook.
  235. peer := p2p.CreateRandomPeer(false)
  236. p2p.AddPeerToSwitch(pexR.Switch, peer)
  237. addr1 := peer.NodeInfo().NetAddress()
  238. pexR.book.AddAddress(addr1, addr1)
  239. // Add a non-connected address to the book.
  240. _, addr2 := p2p.CreateRoutableAddr()
  241. pexR.book.AddAddress(addr2, addr1)
  242. // Get some peerInfos to crawl
  243. peerInfos := pexR.getPeersToCrawl()
  244. // Make sure it has the proper number of elements
  245. assert.Equal(t, 2, len(peerInfos))
  246. // TODO: test
  247. }
  248. // connect a peer to a seed, wait a bit, then stop it.
  249. // this should give it time to request addrs and for the seed
  250. // to call FlushStop, and allows us to test calling Stop concurrently
  251. // with FlushStop. Before a fix, this non-deterministically reproduced
  252. // https://github.com/tendermint/tendermint/issues/3231.
  253. func TestPEXReactorSeedModeFlushStop(t *testing.T) {
  254. N := 2
  255. switches := make([]*p2p.Switch, N)
  256. // directory to store address books
  257. dir, err := ioutil.TempDir("", "pex_reactor")
  258. require.Nil(t, err)
  259. defer os.RemoveAll(dir) // nolint: errcheck
  260. books := make([]*addrBook, N)
  261. logger := log.TestingLogger()
  262. // create switches
  263. for i := 0; i < N; i++ {
  264. switches[i] = p2p.MakeSwitch(cfg, i, "testing", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch {
  265. books[i] = NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", i)), false)
  266. books[i].SetLogger(logger.With("pex", i))
  267. sw.SetAddrBook(books[i])
  268. sw.SetLogger(logger.With("pex", i))
  269. config := &PEXReactorConfig{}
  270. if i == 0 {
  271. // first one is a seed node
  272. config = &PEXReactorConfig{SeedMode: true}
  273. }
  274. r := NewPEXReactor(books[i], config)
  275. r.SetLogger(logger.With("pex", i))
  276. r.SetEnsurePeersPeriod(250 * time.Millisecond)
  277. sw.AddReactor("pex", r)
  278. return sw
  279. })
  280. }
  281. for _, sw := range switches {
  282. err := sw.Start() // start switch and reactors
  283. require.Nil(t, err)
  284. }
  285. reactor := switches[0].Reactors()["pex"].(*PEXReactor)
  286. peerID := switches[1].NodeInfo().ID()
  287. err = switches[1].DialPeerWithAddress(switches[0].NodeInfo().NetAddress(), false)
  288. assert.NoError(t, err)
  289. // sleep up to a second while waiting for the peer to send us a message.
  290. // this isn't perfect since it's possible the peer sends us a msg and we FlushStop
  291. // before this loop catches it. but non-deterministically it works pretty well.
  292. for i := 0; i < 1000; i++ {
  293. v := reactor.lastReceivedRequests.Get(string(peerID))
  294. if v != nil {
  295. break
  296. }
  297. time.Sleep(time.Millisecond)
  298. }
  299. // by now the FlushStop should have happened. Try stopping the peer.
  300. // it should be safe to do this.
  301. peers := switches[0].Peers().List()
  302. for _, peer := range peers {
  303. peer.Stop()
  304. }
  305. // stop the switches
  306. for _, s := range switches {
  307. s.Stop()
  308. }
  309. }
  310. func TestPEXReactorDoesNotAddPrivatePeersToAddrBook(t *testing.T) {
  311. peer := p2p.CreateRandomPeer(false)
  312. pexR, book := createReactor(&PEXReactorConfig{})
  313. book.AddPrivateIDs([]string{string(peer.NodeInfo().ID())})
  314. defer teardownReactor(book)
  315. // we have to send a request to receive responses
  316. pexR.RequestAddrs(peer)
  317. size := book.Size()
  318. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  319. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  320. pexR.Receive(PexChannel, peer, msg)
  321. assert.Equal(t, size, book.Size())
  322. pexR.AddPeer(peer)
  323. assert.Equal(t, size, book.Size())
  324. }
  325. func TestPEXReactorDialPeer(t *testing.T) {
  326. pexR, book := createReactor(&PEXReactorConfig{})
  327. defer teardownReactor(book)
  328. sw := createSwitchAndAddReactors(pexR)
  329. sw.SetAddrBook(book)
  330. peer := newMockPeer()
  331. addr := peer.NodeInfo().NetAddress()
  332. assert.Equal(t, 0, pexR.AttemptsToDial(addr))
  333. // 1st unsuccessful attempt
  334. pexR.dialPeer(addr)
  335. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  336. // 2nd unsuccessful attempt
  337. pexR.dialPeer(addr)
  338. // must be skipped because it is too early
  339. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  340. if !testing.Short() {
  341. time.Sleep(3 * time.Second)
  342. // 3rd attempt
  343. pexR.dialPeer(addr)
  344. assert.Equal(t, 2, pexR.AttemptsToDial(addr))
  345. }
  346. }
  347. type mockPeer struct {
  348. *cmn.BaseService
  349. pubKey crypto.PubKey
  350. addr *p2p.NetAddress
  351. outbound, persistent bool
  352. }
  353. func newMockPeer() mockPeer {
  354. _, netAddr := p2p.CreateRoutableAddr()
  355. mp := mockPeer{
  356. addr: netAddr,
  357. pubKey: ed25519.GenPrivKey().PubKey(),
  358. }
  359. mp.BaseService = cmn.NewBaseService(nil, "MockPeer", mp)
  360. mp.Start()
  361. return mp
  362. }
  363. func (mp mockPeer) FlushStop() { mp.Stop() }
  364. func (mp mockPeer) ID() p2p.ID { return mp.addr.ID }
  365. func (mp mockPeer) IsOutbound() bool { return mp.outbound }
  366. func (mp mockPeer) IsPersistent() bool { return mp.persistent }
  367. func (mp mockPeer) NodeInfo() p2p.NodeInfo {
  368. return p2p.DefaultNodeInfo{
  369. ID_: mp.addr.ID,
  370. ListenAddr: mp.addr.DialString(),
  371. }
  372. }
  373. func (mockPeer) RemoteIP() net.IP { return net.ParseIP("127.0.0.1") }
  374. func (mockPeer) Status() conn.ConnectionStatus { return conn.ConnectionStatus{} }
  375. func (mockPeer) Send(byte, []byte) bool { return false }
  376. func (mockPeer) TrySend(byte, []byte) bool { return false }
  377. func (mockPeer) Set(string, interface{}) {}
  378. func (mockPeer) Get(string) interface{} { return nil }
  379. func (mockPeer) OriginalAddr() *p2p.NetAddress { return nil }
  380. func (mockPeer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8800} }
  381. func (mockPeer) CloseConn() error { return nil }
  382. func assertPeersWithTimeout(
  383. t *testing.T,
  384. switches []*p2p.Switch,
  385. checkPeriod, timeout time.Duration,
  386. nPeers int,
  387. ) {
  388. var (
  389. ticker = time.NewTicker(checkPeriod)
  390. remaining = timeout
  391. )
  392. for {
  393. select {
  394. case <-ticker.C:
  395. // check peers are connected
  396. allGood := true
  397. for _, s := range switches {
  398. outbound, inbound, _ := s.NumPeers()
  399. if outbound+inbound < nPeers {
  400. allGood = false
  401. break
  402. }
  403. }
  404. remaining -= checkPeriod
  405. if remaining < 0 {
  406. remaining = 0
  407. }
  408. if allGood {
  409. return
  410. }
  411. case <-time.After(remaining):
  412. numPeersStr := ""
  413. for i, s := range switches {
  414. outbound, inbound, _ := s.NumPeers()
  415. numPeersStr += fmt.Sprintf("%d => {outbound: %d, inbound: %d}, ", i, outbound, inbound)
  416. }
  417. t.Errorf(
  418. "expected all switches to be connected to at least %d peer(s) (switches: %s)",
  419. nPeers, numPeersStr,
  420. )
  421. return
  422. }
  423. }
  424. }
  425. // Creates a peer with the provided config
  426. func testCreatePeerWithConfig(dir string, id int, config *PEXReactorConfig) *p2p.Switch {
  427. peer := p2p.MakeSwitch(
  428. cfg,
  429. id,
  430. "127.0.0.1",
  431. "123.123.123",
  432. func(i int, sw *p2p.Switch) *p2p.Switch {
  433. book := NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", id)), false)
  434. book.SetLogger(log.TestingLogger())
  435. sw.SetAddrBook(book)
  436. sw.SetLogger(log.TestingLogger())
  437. r := NewPEXReactor(
  438. book,
  439. config,
  440. )
  441. r.SetLogger(log.TestingLogger())
  442. sw.AddReactor("pex", r)
  443. return sw
  444. },
  445. )
  446. return peer
  447. }
  448. // Creates a peer with the default config
  449. func testCreateDefaultPeer(dir string, id int) *p2p.Switch {
  450. return testCreatePeerWithConfig(dir, id, &PEXReactorConfig{})
  451. }
  452. // Creates a seed which knows about the provided addresses / source address pairs.
  453. // Starting and stopping the seed is left to the caller
  454. func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*p2p.NetAddress) *p2p.Switch {
  455. seed := p2p.MakeSwitch(
  456. cfg,
  457. id,
  458. "127.0.0.1",
  459. "123.123.123",
  460. func(i int, sw *p2p.Switch) *p2p.Switch {
  461. book := NewAddrBook(filepath.Join(dir, "addrbookSeed.json"), false)
  462. book.SetLogger(log.TestingLogger())
  463. for j := 0; j < len(knownAddrs); j++ {
  464. book.AddAddress(knownAddrs[j], srcAddrs[j])
  465. book.MarkGood(knownAddrs[j])
  466. }
  467. sw.SetAddrBook(book)
  468. sw.SetLogger(log.TestingLogger())
  469. r := NewPEXReactor(book, &PEXReactorConfig{})
  470. r.SetLogger(log.TestingLogger())
  471. sw.AddReactor("pex", r)
  472. return sw
  473. },
  474. )
  475. return seed
  476. }
  477. // Creates a peer which knows about the provided seed.
  478. // Starting and stopping the peer is left to the caller
  479. func testCreatePeerWithSeed(dir string, id int, seed *p2p.Switch) *p2p.Switch {
  480. conf := &PEXReactorConfig{
  481. Seeds: []string{seed.NodeInfo().NetAddress().String()},
  482. }
  483. return testCreatePeerWithConfig(dir, id, conf)
  484. }
  485. func createReactor(conf *PEXReactorConfig) (r *PEXReactor, book *addrBook) {
  486. // directory to store address book
  487. dir, err := ioutil.TempDir("", "pex_reactor")
  488. if err != nil {
  489. panic(err)
  490. }
  491. book = NewAddrBook(filepath.Join(dir, "addrbook.json"), true)
  492. book.SetLogger(log.TestingLogger())
  493. r = NewPEXReactor(book, conf)
  494. r.SetLogger(log.TestingLogger())
  495. return
  496. }
  497. func teardownReactor(book *addrBook) {
  498. err := os.RemoveAll(filepath.Dir(book.FilePath()))
  499. if err != nil {
  500. panic(err)
  501. }
  502. }
  503. func createSwitchAndAddReactors(reactors ...p2p.Reactor) *p2p.Switch {
  504. sw := p2p.MakeSwitch(cfg, 0, "127.0.0.1", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch { return sw })
  505. sw.SetLogger(log.TestingLogger())
  506. for _, r := range reactors {
  507. sw.AddReactor(r.String(), r)
  508. r.SetSwitch(sw)
  509. }
  510. return sw
  511. }