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.

595 lines
16 KiB

p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
  1. package pex
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. "github.com/tendermint/tendermint/config"
  12. "github.com/tendermint/tendermint/libs/log"
  13. "github.com/tendermint/tendermint/p2p"
  14. "github.com/tendermint/tendermint/p2p/mock"
  15. )
  16. var (
  17. cfg *config.P2PConfig
  18. )
  19. func init() {
  20. cfg = config.DefaultP2PConfig()
  21. cfg.PexReactor = true
  22. cfg.AllowDuplicateIP = true
  23. }
  24. func TestPEXReactorBasic(t *testing.T) {
  25. r, book := createReactor(&PEXReactorConfig{})
  26. defer teardownReactor(book)
  27. assert.NotNil(t, r)
  28. assert.NotEmpty(t, r.GetChannels())
  29. }
  30. func TestPEXReactorAddRemovePeer(t *testing.T) {
  31. r, book := createReactor(&PEXReactorConfig{})
  32. defer teardownReactor(book)
  33. size := book.Size()
  34. peer := p2p.CreateRandomPeer(false)
  35. r.AddPeer(peer)
  36. assert.Equal(t, size+1, book.Size())
  37. r.RemovePeer(peer, "peer not available")
  38. outboundPeer := p2p.CreateRandomPeer(true)
  39. r.AddPeer(outboundPeer)
  40. assert.Equal(t, size+1, book.Size(), "outbound peers should not be added to the address book")
  41. r.RemovePeer(outboundPeer, "peer not available")
  42. }
  43. // --- FAIL: TestPEXReactorRunning (11.10s)
  44. // pex_reactor_test.go:411: expected all switches to be connected to at
  45. // least one peer (switches: 0 => {outbound: 1, inbound: 0}, 1 =>
  46. // {outbound: 0, inbound: 1}, 2 => {outbound: 0, inbound: 0}, )
  47. //
  48. // EXPLANATION: peers are getting rejected because in switch#addPeer we check
  49. // if any peer (who we already connected to) has the same IP. Even though local
  50. // peers have different IP addresses, they all have the same underlying remote
  51. // IP: 127.0.0.1.
  52. //
  53. func TestPEXReactorRunning(t *testing.T) {
  54. N := 3
  55. switches := make([]*p2p.Switch, N)
  56. // directory to store address books
  57. dir, err := ioutil.TempDir("", "pex_reactor")
  58. require.Nil(t, err)
  59. defer os.RemoveAll(dir) // nolint: errcheck
  60. books := make([]*addrBook, N)
  61. logger := log.TestingLogger()
  62. // create switches
  63. for i := 0; i < N; i++ {
  64. switches[i] = p2p.MakeSwitch(cfg, i, "testing", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch {
  65. books[i] = NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", i)), false)
  66. books[i].SetLogger(logger.With("pex", i))
  67. sw.SetAddrBook(books[i])
  68. sw.SetLogger(logger.With("pex", i))
  69. r := NewPEXReactor(books[i], &PEXReactorConfig{})
  70. r.SetLogger(logger.With("pex", i))
  71. r.SetEnsurePeersPeriod(250 * time.Millisecond)
  72. sw.AddReactor("pex", r)
  73. return sw
  74. })
  75. }
  76. addOtherNodeAddrToAddrBook := func(switchIndex, otherSwitchIndex int) {
  77. addr := switches[otherSwitchIndex].NetAddress()
  78. books[switchIndex].AddAddress(addr, addr)
  79. }
  80. addOtherNodeAddrToAddrBook(0, 1)
  81. addOtherNodeAddrToAddrBook(1, 0)
  82. addOtherNodeAddrToAddrBook(2, 1)
  83. for _, sw := range switches {
  84. err := sw.Start() // start switch and reactors
  85. require.Nil(t, err)
  86. }
  87. assertPeersWithTimeout(t, switches, 10*time.Millisecond, 10*time.Second, N-1)
  88. // stop them
  89. for _, s := range switches {
  90. s.Stop()
  91. }
  92. }
  93. func TestPEXReactorReceive(t *testing.T) {
  94. r, book := createReactor(&PEXReactorConfig{})
  95. defer teardownReactor(book)
  96. peer := p2p.CreateRandomPeer(false)
  97. // we have to send a request to receive responses
  98. r.RequestAddrs(peer)
  99. size := book.Size()
  100. addrs := []*p2p.NetAddress{peer.SocketAddr()}
  101. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  102. r.Receive(PexChannel, peer, msg)
  103. assert.Equal(t, size+1, book.Size())
  104. msg = cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  105. r.Receive(PexChannel, peer, msg) // should not panic.
  106. }
  107. func TestPEXReactorRequestMessageAbuse(t *testing.T) {
  108. r, book := createReactor(&PEXReactorConfig{})
  109. defer teardownReactor(book)
  110. sw := createSwitchAndAddReactors(r)
  111. sw.SetAddrBook(book)
  112. peer := mock.NewPeer(nil)
  113. p2p.AddPeerToSwitch(sw, peer)
  114. assert.True(t, sw.Peers().Has(peer.ID()))
  115. id := string(peer.ID())
  116. msg := cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  117. // first time creates the entry
  118. r.Receive(PexChannel, peer, msg)
  119. assert.True(t, r.lastReceivedRequests.Has(id))
  120. assert.True(t, sw.Peers().Has(peer.ID()))
  121. // next time sets the last time value
  122. r.Receive(PexChannel, peer, msg)
  123. assert.True(t, r.lastReceivedRequests.Has(id))
  124. assert.True(t, sw.Peers().Has(peer.ID()))
  125. // third time is too many too soon - peer is removed
  126. r.Receive(PexChannel, peer, msg)
  127. assert.False(t, r.lastReceivedRequests.Has(id))
  128. assert.False(t, sw.Peers().Has(peer.ID()))
  129. }
  130. func TestPEXReactorAddrsMessageAbuse(t *testing.T) {
  131. r, book := createReactor(&PEXReactorConfig{})
  132. defer teardownReactor(book)
  133. sw := createSwitchAndAddReactors(r)
  134. sw.SetAddrBook(book)
  135. peer := mock.NewPeer(nil)
  136. p2p.AddPeerToSwitch(sw, peer)
  137. assert.True(t, sw.Peers().Has(peer.ID()))
  138. id := string(peer.ID())
  139. // request addrs from the peer
  140. r.RequestAddrs(peer)
  141. assert.True(t, r.requestsSent.Has(id))
  142. assert.True(t, sw.Peers().Has(peer.ID()))
  143. addrs := []*p2p.NetAddress{peer.SocketAddr()}
  144. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  145. // receive some addrs. should clear the request
  146. r.Receive(PexChannel, peer, msg)
  147. assert.False(t, r.requestsSent.Has(id))
  148. assert.True(t, sw.Peers().Has(peer.ID()))
  149. // receiving more addrs causes a disconnect
  150. r.Receive(PexChannel, peer, msg)
  151. assert.False(t, sw.Peers().Has(peer.ID()))
  152. }
  153. func TestCheckSeeds(t *testing.T) {
  154. // directory to store address books
  155. dir, err := ioutil.TempDir("", "pex_reactor")
  156. require.Nil(t, err)
  157. defer os.RemoveAll(dir) // nolint: errcheck
  158. // 1. test creating peer with no seeds works
  159. peerSwitch := testCreateDefaultPeer(dir, 0)
  160. require.Nil(t, peerSwitch.Start())
  161. peerSwitch.Stop()
  162. // 2. create seed
  163. seed := testCreateSeed(dir, 1, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  164. // 3. test create peer with online seed works
  165. peerSwitch = testCreatePeerWithSeed(dir, 2, seed)
  166. require.Nil(t, peerSwitch.Start())
  167. peerSwitch.Stop()
  168. // 4. test create peer with all seeds having unresolvable DNS fails
  169. badPeerConfig := &PEXReactorConfig{
  170. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  171. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657"},
  172. }
  173. peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  174. require.Error(t, peerSwitch.Start())
  175. peerSwitch.Stop()
  176. // 5. test create peer with one good seed address succeeds
  177. badPeerConfig = &PEXReactorConfig{
  178. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  179. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657",
  180. seed.NetAddress().String()},
  181. }
  182. peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  183. require.Nil(t, peerSwitch.Start())
  184. peerSwitch.Stop()
  185. }
  186. func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
  187. // directory to store address books
  188. dir, err := ioutil.TempDir("", "pex_reactor")
  189. require.Nil(t, err)
  190. defer os.RemoveAll(dir) // nolint: errcheck
  191. // 1. create seed
  192. seed := testCreateSeed(dir, 0, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  193. require.Nil(t, seed.Start())
  194. defer seed.Stop()
  195. // 2. create usual peer with only seed configured.
  196. peer := testCreatePeerWithSeed(dir, 1, seed)
  197. require.Nil(t, peer.Start())
  198. defer peer.Stop()
  199. // 3. check that the peer connects to seed immediately
  200. assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1)
  201. }
  202. func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) {
  203. // directory to store address books
  204. dir, err := ioutil.TempDir("", "pex_reactor")
  205. require.Nil(t, err)
  206. defer os.RemoveAll(dir) // nolint: errcheck
  207. // 1. create peer
  208. peerSwitch := testCreateDefaultPeer(dir, 1)
  209. require.Nil(t, peerSwitch.Start())
  210. defer peerSwitch.Stop()
  211. // 2. Create seed which knows about the peer
  212. peerAddr := peerSwitch.NetAddress()
  213. seed := testCreateSeed(dir, 2, []*p2p.NetAddress{peerAddr}, []*p2p.NetAddress{peerAddr})
  214. require.Nil(t, seed.Start())
  215. defer seed.Stop()
  216. // 3. create another peer with only seed configured.
  217. secondPeer := testCreatePeerWithSeed(dir, 3, seed)
  218. require.Nil(t, secondPeer.Start())
  219. defer secondPeer.Stop()
  220. // 4. check that the second peer connects to seed immediately
  221. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 3*time.Second, 1)
  222. // 5. check that the second peer connects to the first peer immediately
  223. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 1*time.Second, 2)
  224. }
  225. func TestPEXReactorSeedMode(t *testing.T) {
  226. // directory to store address books
  227. dir, err := ioutil.TempDir("", "pex_reactor")
  228. require.Nil(t, err)
  229. defer os.RemoveAll(dir) // nolint: errcheck
  230. pexR, book := createReactor(&PEXReactorConfig{SeedMode: true, SeedDisconnectWaitPeriod: 10 * time.Millisecond})
  231. defer teardownReactor(book)
  232. sw := createSwitchAndAddReactors(pexR)
  233. sw.SetAddrBook(book)
  234. err = sw.Start()
  235. require.NoError(t, err)
  236. defer sw.Stop()
  237. assert.Zero(t, sw.Peers().Size())
  238. peerSwitch := testCreateDefaultPeer(dir, 1)
  239. require.NoError(t, peerSwitch.Start())
  240. defer peerSwitch.Stop()
  241. // 1. Test crawlPeers dials the peer
  242. pexR.crawlPeers([]*p2p.NetAddress{peerSwitch.NetAddress()})
  243. assert.Equal(t, 1, sw.Peers().Size())
  244. assert.True(t, sw.Peers().Has(peerSwitch.NodeInfo().ID()))
  245. // 2. attemptDisconnects should not disconnect because of wait period
  246. pexR.attemptDisconnects()
  247. assert.Equal(t, 1, sw.Peers().Size())
  248. time.Sleep(100 * time.Millisecond)
  249. // 3. attemptDisconnects should disconnect after wait period
  250. pexR.attemptDisconnects()
  251. assert.Equal(t, 0, sw.Peers().Size())
  252. }
  253. // connect a peer to a seed, wait a bit, then stop it.
  254. // this should give it time to request addrs and for the seed
  255. // to call FlushStop, and allows us to test calling Stop concurrently
  256. // with FlushStop. Before a fix, this non-deterministically reproduced
  257. // https://github.com/tendermint/tendermint/issues/3231.
  258. func TestPEXReactorSeedModeFlushStop(t *testing.T) {
  259. N := 2
  260. switches := make([]*p2p.Switch, N)
  261. // directory to store address books
  262. dir, err := ioutil.TempDir("", "pex_reactor")
  263. require.Nil(t, err)
  264. defer os.RemoveAll(dir) // nolint: errcheck
  265. books := make([]*addrBook, N)
  266. logger := log.TestingLogger()
  267. // create switches
  268. for i := 0; i < N; i++ {
  269. switches[i] = p2p.MakeSwitch(cfg, i, "testing", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch {
  270. books[i] = NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", i)), false)
  271. books[i].SetLogger(logger.With("pex", i))
  272. sw.SetAddrBook(books[i])
  273. sw.SetLogger(logger.With("pex", i))
  274. config := &PEXReactorConfig{}
  275. if i == 0 {
  276. // first one is a seed node
  277. config = &PEXReactorConfig{SeedMode: true}
  278. }
  279. r := NewPEXReactor(books[i], config)
  280. r.SetLogger(logger.With("pex", i))
  281. r.SetEnsurePeersPeriod(250 * time.Millisecond)
  282. sw.AddReactor("pex", r)
  283. return sw
  284. })
  285. }
  286. for _, sw := range switches {
  287. err := sw.Start() // start switch and reactors
  288. require.Nil(t, err)
  289. }
  290. reactor := switches[0].Reactors()["pex"].(*PEXReactor)
  291. peerID := switches[1].NodeInfo().ID()
  292. err = switches[1].DialPeerWithAddress(switches[0].NetAddress(), false)
  293. assert.NoError(t, err)
  294. // sleep up to a second while waiting for the peer to send us a message.
  295. // this isn't perfect since it's possible the peer sends us a msg and we FlushStop
  296. // before this loop catches it. but non-deterministically it works pretty well.
  297. for i := 0; i < 1000; i++ {
  298. v := reactor.lastReceivedRequests.Get(string(peerID))
  299. if v != nil {
  300. break
  301. }
  302. time.Sleep(time.Millisecond)
  303. }
  304. // by now the FlushStop should have happened. Try stopping the peer.
  305. // it should be safe to do this.
  306. peers := switches[0].Peers().List()
  307. for _, peer := range peers {
  308. peer.Stop()
  309. }
  310. // stop the switches
  311. for _, s := range switches {
  312. s.Stop()
  313. }
  314. }
  315. func TestPEXReactorDoesNotAddPrivatePeersToAddrBook(t *testing.T) {
  316. peer := p2p.CreateRandomPeer(false)
  317. pexR, book := createReactor(&PEXReactorConfig{})
  318. book.AddPrivateIDs([]string{string(peer.NodeInfo().ID())})
  319. defer teardownReactor(book)
  320. // we have to send a request to receive responses
  321. pexR.RequestAddrs(peer)
  322. size := book.Size()
  323. addrs := []*p2p.NetAddress{peer.SocketAddr()}
  324. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  325. pexR.Receive(PexChannel, peer, msg)
  326. assert.Equal(t, size, book.Size())
  327. pexR.AddPeer(peer)
  328. assert.Equal(t, size, book.Size())
  329. }
  330. func TestPEXReactorDialPeer(t *testing.T) {
  331. pexR, book := createReactor(&PEXReactorConfig{})
  332. defer teardownReactor(book)
  333. sw := createSwitchAndAddReactors(pexR)
  334. sw.SetAddrBook(book)
  335. peer := mock.NewPeer(nil)
  336. addr := peer.SocketAddr()
  337. assert.Equal(t, 0, pexR.AttemptsToDial(addr))
  338. // 1st unsuccessful attempt
  339. pexR.dialPeer(addr)
  340. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  341. // 2nd unsuccessful attempt
  342. pexR.dialPeer(addr)
  343. // must be skipped because it is too early
  344. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  345. if !testing.Short() {
  346. time.Sleep(3 * time.Second)
  347. // 3rd attempt
  348. pexR.dialPeer(addr)
  349. assert.Equal(t, 2, pexR.AttemptsToDial(addr))
  350. }
  351. }
  352. func assertPeersWithTimeout(
  353. t *testing.T,
  354. switches []*p2p.Switch,
  355. checkPeriod, timeout time.Duration,
  356. nPeers int,
  357. ) {
  358. var (
  359. ticker = time.NewTicker(checkPeriod)
  360. remaining = timeout
  361. )
  362. for {
  363. select {
  364. case <-ticker.C:
  365. // check peers are connected
  366. allGood := true
  367. for _, s := range switches {
  368. outbound, inbound, _ := s.NumPeers()
  369. if outbound+inbound < nPeers {
  370. allGood = false
  371. break
  372. }
  373. }
  374. remaining -= checkPeriod
  375. if remaining < 0 {
  376. remaining = 0
  377. }
  378. if allGood {
  379. return
  380. }
  381. case <-time.After(remaining):
  382. numPeersStr := ""
  383. for i, s := range switches {
  384. outbound, inbound, _ := s.NumPeers()
  385. numPeersStr += fmt.Sprintf("%d => {outbound: %d, inbound: %d}, ", i, outbound, inbound)
  386. }
  387. t.Errorf(
  388. "expected all switches to be connected to at least %d peer(s) (switches: %s)",
  389. nPeers, numPeersStr,
  390. )
  391. return
  392. }
  393. }
  394. }
  395. // Creates a peer with the provided config
  396. func testCreatePeerWithConfig(dir string, id int, config *PEXReactorConfig) *p2p.Switch {
  397. peer := p2p.MakeSwitch(
  398. cfg,
  399. id,
  400. "127.0.0.1",
  401. "123.123.123",
  402. func(i int, sw *p2p.Switch) *p2p.Switch {
  403. book := NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", id)), false)
  404. book.SetLogger(log.TestingLogger())
  405. sw.SetAddrBook(book)
  406. sw.SetLogger(log.TestingLogger())
  407. r := NewPEXReactor(
  408. book,
  409. config,
  410. )
  411. r.SetLogger(log.TestingLogger())
  412. sw.AddReactor("pex", r)
  413. return sw
  414. },
  415. )
  416. return peer
  417. }
  418. // Creates a peer with the default config
  419. func testCreateDefaultPeer(dir string, id int) *p2p.Switch {
  420. return testCreatePeerWithConfig(dir, id, &PEXReactorConfig{})
  421. }
  422. // Creates a seed which knows about the provided addresses / source address pairs.
  423. // Starting and stopping the seed is left to the caller
  424. func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*p2p.NetAddress) *p2p.Switch {
  425. seed := p2p.MakeSwitch(
  426. cfg,
  427. id,
  428. "127.0.0.1",
  429. "123.123.123",
  430. func(i int, sw *p2p.Switch) *p2p.Switch {
  431. book := NewAddrBook(filepath.Join(dir, "addrbookSeed.json"), false)
  432. book.SetLogger(log.TestingLogger())
  433. for j := 0; j < len(knownAddrs); j++ {
  434. book.AddAddress(knownAddrs[j], srcAddrs[j])
  435. book.MarkGood(knownAddrs[j])
  436. }
  437. sw.SetAddrBook(book)
  438. sw.SetLogger(log.TestingLogger())
  439. r := NewPEXReactor(book, &PEXReactorConfig{})
  440. r.SetLogger(log.TestingLogger())
  441. sw.AddReactor("pex", r)
  442. return sw
  443. },
  444. )
  445. return seed
  446. }
  447. // Creates a peer which knows about the provided seed.
  448. // Starting and stopping the peer is left to the caller
  449. func testCreatePeerWithSeed(dir string, id int, seed *p2p.Switch) *p2p.Switch {
  450. conf := &PEXReactorConfig{
  451. Seeds: []string{seed.NetAddress().String()},
  452. }
  453. return testCreatePeerWithConfig(dir, id, conf)
  454. }
  455. func createReactor(conf *PEXReactorConfig) (r *PEXReactor, book *addrBook) {
  456. // directory to store address book
  457. dir, err := ioutil.TempDir("", "pex_reactor")
  458. if err != nil {
  459. panic(err)
  460. }
  461. book = NewAddrBook(filepath.Join(dir, "addrbook.json"), true)
  462. book.SetLogger(log.TestingLogger())
  463. r = NewPEXReactor(book, conf)
  464. r.SetLogger(log.TestingLogger())
  465. return
  466. }
  467. func teardownReactor(book *addrBook) {
  468. err := os.RemoveAll(filepath.Dir(book.FilePath()))
  469. if err != nil {
  470. panic(err)
  471. }
  472. }
  473. func createSwitchAndAddReactors(reactors ...p2p.Reactor) *p2p.Switch {
  474. sw := p2p.MakeSwitch(cfg, 0, "127.0.0.1", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch { return sw })
  475. sw.SetLogger(log.TestingLogger())
  476. for _, r := range reactors {
  477. sw.AddReactor(r.String(), r)
  478. r.SetSwitch(sw)
  479. }
  480. return sw
  481. }