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.

457 lines
12 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 TestPEXReactorUsesSeedsIfNeeded(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. create seed
  164. seed := p2p.MakeSwitch(
  165. cfg,
  166. 0,
  167. "127.0.0.1",
  168. "123.123.123",
  169. func(i int, sw *p2p.Switch) *p2p.Switch {
  170. book := NewAddrBook(filepath.Join(dir, "addrbook0.json"), false)
  171. book.SetLogger(log.TestingLogger())
  172. sw.SetAddrBook(book)
  173. sw.SetLogger(log.TestingLogger())
  174. r := NewPEXReactor(book, &PEXReactorConfig{})
  175. r.SetLogger(log.TestingLogger())
  176. sw.AddReactor("pex", r)
  177. return sw
  178. },
  179. )
  180. seed.AddListener(
  181. p2p.NewDefaultListener("tcp://"+seed.NodeInfo().ListenAddr, "", false, log.TestingLogger()),
  182. )
  183. require.Nil(t, seed.Start())
  184. defer seed.Stop()
  185. // 2. create usual peer with only seed configured.
  186. peer := p2p.MakeSwitch(
  187. cfg,
  188. 1,
  189. "127.0.0.1",
  190. "123.123.123",
  191. func(i int, sw *p2p.Switch) *p2p.Switch {
  192. book := NewAddrBook(filepath.Join(dir, "addrbook1.json"), false)
  193. book.SetLogger(log.TestingLogger())
  194. sw.SetAddrBook(book)
  195. sw.SetLogger(log.TestingLogger())
  196. r := NewPEXReactor(
  197. book,
  198. &PEXReactorConfig{
  199. Seeds: []string{seed.NodeInfo().NetAddress().String()},
  200. },
  201. )
  202. r.SetLogger(log.TestingLogger())
  203. sw.AddReactor("pex", r)
  204. return sw
  205. },
  206. )
  207. require.Nil(t, peer.Start())
  208. defer peer.Stop()
  209. // 3. check that the peer connects to seed immediately
  210. assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1)
  211. }
  212. func TestPEXReactorCrawlStatus(t *testing.T) {
  213. pexR, book := createReactor(&PEXReactorConfig{SeedMode: true})
  214. defer teardownReactor(book)
  215. // Seed/Crawler mode uses data from the Switch
  216. sw := createSwitchAndAddReactors(pexR)
  217. sw.SetAddrBook(book)
  218. // Create a peer, add it to the peer set and the addrbook.
  219. peer := p2p.CreateRandomPeer(false)
  220. p2p.AddPeerToSwitch(pexR.Switch, peer)
  221. addr1 := peer.NodeInfo().NetAddress()
  222. pexR.book.AddAddress(addr1, addr1)
  223. // Add a non-connected address to the book.
  224. _, addr2 := p2p.CreateRoutableAddr()
  225. pexR.book.AddAddress(addr2, addr1)
  226. // Get some peerInfos to crawl
  227. peerInfos := pexR.getPeersToCrawl()
  228. // Make sure it has the proper number of elements
  229. assert.Equal(t, 2, len(peerInfos))
  230. // TODO: test
  231. }
  232. func TestPEXReactorDoesNotAddPrivatePeersToAddrBook(t *testing.T) {
  233. peer := p2p.CreateRandomPeer(false)
  234. pexR, book := createReactor(&PEXReactorConfig{})
  235. book.AddPrivateIDs([]string{string(peer.NodeInfo().ID)})
  236. defer teardownReactor(book)
  237. // we have to send a request to receive responses
  238. pexR.RequestAddrs(peer)
  239. size := book.Size()
  240. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  241. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  242. pexR.Receive(PexChannel, peer, msg)
  243. assert.Equal(t, size, book.Size())
  244. pexR.AddPeer(peer)
  245. assert.Equal(t, size, book.Size())
  246. }
  247. func TestPEXReactorDialPeer(t *testing.T) {
  248. pexR, book := createReactor(&PEXReactorConfig{})
  249. defer teardownReactor(book)
  250. sw := createSwitchAndAddReactors(pexR)
  251. sw.SetAddrBook(book)
  252. peer := newMockPeer()
  253. addr := peer.NodeInfo().NetAddress()
  254. assert.Equal(t, 0, pexR.AttemptsToDial(addr))
  255. // 1st unsuccessful attempt
  256. pexR.dialPeer(addr)
  257. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  258. // 2nd unsuccessful attempt
  259. pexR.dialPeer(addr)
  260. // must be skipped because it is too early
  261. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  262. if !testing.Short() {
  263. time.Sleep(3 * time.Second)
  264. // 3rd attempt
  265. pexR.dialPeer(addr)
  266. assert.Equal(t, 2, pexR.AttemptsToDial(addr))
  267. }
  268. }
  269. type mockPeer struct {
  270. *cmn.BaseService
  271. pubKey crypto.PubKey
  272. addr *p2p.NetAddress
  273. outbound, persistent bool
  274. }
  275. func newMockPeer() mockPeer {
  276. _, netAddr := p2p.CreateRoutableAddr()
  277. mp := mockPeer{
  278. addr: netAddr,
  279. pubKey: ed25519.GenPrivKey().PubKey(),
  280. }
  281. mp.BaseService = cmn.NewBaseService(nil, "MockPeer", mp)
  282. mp.Start()
  283. return mp
  284. }
  285. func (mp mockPeer) ID() p2p.ID { return mp.addr.ID }
  286. func (mp mockPeer) IsOutbound() bool { return mp.outbound }
  287. func (mp mockPeer) IsPersistent() bool { return mp.persistent }
  288. func (mp mockPeer) NodeInfo() p2p.NodeInfo {
  289. return p2p.NodeInfo{
  290. ID: mp.addr.ID,
  291. ListenAddr: mp.addr.DialString(),
  292. }
  293. }
  294. func (mockPeer) RemoteIP() net.IP { return net.ParseIP("127.0.0.1") }
  295. func (mockPeer) Status() conn.ConnectionStatus { return conn.ConnectionStatus{} }
  296. func (mockPeer) Send(byte, []byte) bool { return false }
  297. func (mockPeer) TrySend(byte, []byte) bool { return false }
  298. func (mockPeer) Set(string, interface{}) {}
  299. func (mockPeer) Get(string) interface{} { return nil }
  300. func (mockPeer) OriginalAddr() *p2p.NetAddress { return nil }
  301. func assertPeersWithTimeout(
  302. t *testing.T,
  303. switches []*p2p.Switch,
  304. checkPeriod, timeout time.Duration,
  305. nPeers int,
  306. ) {
  307. var (
  308. ticker = time.NewTicker(checkPeriod)
  309. remaining = timeout
  310. )
  311. for {
  312. select {
  313. case <-ticker.C:
  314. // check peers are connected
  315. allGood := true
  316. for _, s := range switches {
  317. outbound, inbound, _ := s.NumPeers()
  318. if outbound+inbound < nPeers {
  319. allGood = false
  320. }
  321. }
  322. remaining -= checkPeriod
  323. if remaining < 0 {
  324. remaining = 0
  325. }
  326. if allGood {
  327. return
  328. }
  329. case <-time.After(remaining):
  330. numPeersStr := ""
  331. for i, s := range switches {
  332. outbound, inbound, _ := s.NumPeers()
  333. numPeersStr += fmt.Sprintf("%d => {outbound: %d, inbound: %d}, ", i, outbound, inbound)
  334. }
  335. t.Errorf(
  336. "expected all switches to be connected to at least one peer (switches: %s)",
  337. numPeersStr,
  338. )
  339. return
  340. }
  341. }
  342. }
  343. func createReactor(conf *PEXReactorConfig) (r *PEXReactor, book *addrBook) {
  344. // directory to store address book
  345. dir, err := ioutil.TempDir("", "pex_reactor")
  346. if err != nil {
  347. panic(err)
  348. }
  349. book = NewAddrBook(filepath.Join(dir, "addrbook.json"), true)
  350. book.SetLogger(log.TestingLogger())
  351. r = NewPEXReactor(book, conf)
  352. r.SetLogger(log.TestingLogger())
  353. return
  354. }
  355. func teardownReactor(book *addrBook) {
  356. err := os.RemoveAll(filepath.Dir(book.FilePath()))
  357. if err != nil {
  358. panic(err)
  359. }
  360. }
  361. func createSwitchAndAddReactors(reactors ...p2p.Reactor) *p2p.Switch {
  362. sw := p2p.MakeSwitch(cfg, 0, "127.0.0.1", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch { return sw })
  363. sw.SetLogger(log.TestingLogger())
  364. for _, r := range reactors {
  365. sw.AddReactor(r.String(), r)
  366. r.SetSwitch(sw)
  367. }
  368. return sw
  369. }