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.

532 lines
17 KiB

  1. package pex
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "github.com/tendermint/tendermint/internal/p2p"
  8. "github.com/tendermint/tendermint/internal/p2p/conn"
  9. "github.com/tendermint/tendermint/libs/log"
  10. tmmath "github.com/tendermint/tendermint/libs/math"
  11. "github.com/tendermint/tendermint/libs/service"
  12. protop2p "github.com/tendermint/tendermint/proto/tendermint/p2p"
  13. )
  14. var (
  15. _ service.Service = (*ReactorV2)(nil)
  16. _ p2p.Wrapper = (*protop2p.PexMessage)(nil)
  17. )
  18. // TODO: Consolidate with params file.
  19. // See https://github.com/tendermint/tendermint/issues/6371
  20. const (
  21. // the minimum time one peer can send another request to the same peer
  22. minReceiveRequestInterval = 100 * time.Millisecond
  23. // the maximum amount of addresses that can be included in a response
  24. maxAddresses uint16 = 100
  25. // allocated time to resolve a node address into a set of endpoints
  26. resolveTimeout = 3 * time.Second
  27. // How long to wait when there are no peers available before trying again
  28. noAvailablePeersWaitPeriod = 1 * time.Second
  29. // indicates the ping rate of the pex reactor when the peer store is full.
  30. // The reactor should still look to add new peers in order to flush out low
  31. // scoring peers that are still in the peer store
  32. fullCapacityInterval = 10 * time.Minute
  33. )
  34. // TODO: We should decide whether we want channel descriptors to be housed
  35. // within each reactor (as they are now) or, considering that the reactor doesn't
  36. // really need to care about the channel descriptors, if they should be housed
  37. // in the node module.
  38. func ChannelDescriptor() conn.ChannelDescriptor {
  39. return conn.ChannelDescriptor{
  40. ID: PexChannel,
  41. Priority: 1,
  42. SendQueueCapacity: 10,
  43. RecvMessageCapacity: maxMsgSize,
  44. MaxSendBytes: 200,
  45. }
  46. }
  47. // ReactorV2 is a PEX reactor for the new P2P stack. The legacy reactor
  48. // is Reactor.
  49. //
  50. // FIXME: Rename this when Reactor is removed, and consider moving to p2p/.
  51. //
  52. // The peer exchange or PEX reactor supports the peer manager by sending
  53. // requests to other peers for addresses that can be given to the peer manager
  54. // and at the same time advertises addresses to peers that need more.
  55. //
  56. // The reactor is able to tweak the intensity of it's search by decreasing or
  57. // increasing the interval between each request. It tracks connected peers via
  58. // a linked list, sending a request to the node at the front of the list and
  59. // adding it to the back of the list once a response is received.
  60. type ReactorV2 struct {
  61. service.BaseService
  62. peerManager *p2p.PeerManager
  63. pexCh *p2p.Channel
  64. peerUpdates *p2p.PeerUpdates
  65. closeCh chan struct{}
  66. // list of available peers to loop through and send peer requests to
  67. availablePeers map[p2p.NodeID]struct{}
  68. mtx sync.RWMutex
  69. // requestsSent keeps track of which peers the PEX reactor has sent requests
  70. // to. This prevents the sending of spurious responses.
  71. // NOTE: If a node never responds, they will remain in this map until a
  72. // peer down status update is sent
  73. requestsSent map[p2p.NodeID]struct{}
  74. // lastReceivedRequests keeps track of when peers send a request to prevent
  75. // peers from sending requests too often (as defined by
  76. // minReceiveRequestInterval).
  77. lastReceivedRequests map[p2p.NodeID]time.Time
  78. // the time when another request will be sent
  79. nextRequestTime time.Time
  80. // keep track of how many new peers to existing peers we have received to
  81. // extrapolate the size of the network
  82. newPeers uint32
  83. totalPeers uint32
  84. // discoveryRatio is the inverse ratio of new peers to old peers squared.
  85. // This is multiplied by the minimum duration to calculate how long to wait
  86. // between each request.
  87. discoveryRatio float32
  88. }
  89. // NewReactor returns a reference to a new reactor.
  90. func NewReactorV2(
  91. logger log.Logger,
  92. peerManager *p2p.PeerManager,
  93. pexCh *p2p.Channel,
  94. peerUpdates *p2p.PeerUpdates,
  95. ) *ReactorV2 {
  96. r := &ReactorV2{
  97. peerManager: peerManager,
  98. pexCh: pexCh,
  99. peerUpdates: peerUpdates,
  100. closeCh: make(chan struct{}),
  101. availablePeers: make(map[p2p.NodeID]struct{}),
  102. requestsSent: make(map[p2p.NodeID]struct{}),
  103. lastReceivedRequests: make(map[p2p.NodeID]time.Time),
  104. }
  105. r.BaseService = *service.NewBaseService(logger, "PEX", r)
  106. return r
  107. }
  108. // OnStart starts separate go routines for each p2p Channel and listens for
  109. // envelopes on each. In addition, it also listens for peer updates and handles
  110. // messages on that p2p channel accordingly. The caller must be sure to execute
  111. // OnStop to ensure the outbound p2p Channels are closed.
  112. func (r *ReactorV2) OnStart() error {
  113. go r.processPexCh()
  114. go r.processPeerUpdates()
  115. return nil
  116. }
  117. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  118. // blocking until they all exit.
  119. func (r *ReactorV2) OnStop() {
  120. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  121. // p2p Channels should execute Close().
  122. close(r.closeCh)
  123. // Wait for all p2p Channels to be closed before returning. This ensures we
  124. // can easily reason about synchronization of all p2p Channels and ensure no
  125. // panics will occur.
  126. <-r.pexCh.Done()
  127. <-r.peerUpdates.Done()
  128. }
  129. // processPexCh implements a blocking event loop where we listen for p2p
  130. // Envelope messages from the pexCh.
  131. func (r *ReactorV2) processPexCh() {
  132. defer r.pexCh.Close()
  133. for {
  134. select {
  135. case <-r.closeCh:
  136. r.Logger.Debug("stopped listening on PEX channel; closing...")
  137. return
  138. // outbound requests for new peers
  139. case <-r.waitUntilNextRequest():
  140. r.sendRequestForPeers()
  141. // inbound requests for new peers or responses to requests sent by this
  142. // reactor
  143. case envelope := <-r.pexCh.In:
  144. if err := r.handleMessage(r.pexCh.ID, envelope); err != nil {
  145. r.Logger.Error("failed to process message", "ch_id", r.pexCh.ID, "envelope", envelope, "err", err)
  146. r.pexCh.Error <- p2p.PeerError{
  147. NodeID: envelope.From,
  148. Err: err,
  149. }
  150. }
  151. }
  152. }
  153. }
  154. // processPeerUpdates initiates a blocking process where we listen for and handle
  155. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  156. // close the p2p PeerUpdatesCh gracefully.
  157. func (r *ReactorV2) processPeerUpdates() {
  158. defer r.peerUpdates.Close()
  159. for {
  160. select {
  161. case peerUpdate := <-r.peerUpdates.Updates():
  162. r.processPeerUpdate(peerUpdate)
  163. case <-r.closeCh:
  164. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  165. return
  166. }
  167. }
  168. }
  169. // handlePexMessage handles envelopes sent from peers on the PexChannel.
  170. func (r *ReactorV2) handlePexMessage(envelope p2p.Envelope) error {
  171. logger := r.Logger.With("peer", envelope.From)
  172. switch msg := envelope.Message.(type) {
  173. case *protop2p.PexRequest:
  174. // Check if the peer hasn't sent a prior request too close to this one
  175. // in time.
  176. if err := r.markPeerRequest(envelope.From); err != nil {
  177. return err
  178. }
  179. // parse and send the legacy PEX addresses
  180. pexAddresses := r.resolve(r.peerManager.Advertise(envelope.From, maxAddresses))
  181. r.pexCh.Out <- p2p.Envelope{
  182. To: envelope.From,
  183. Message: &protop2p.PexResponse{Addresses: pexAddresses},
  184. }
  185. case *protop2p.PexResponse:
  186. // check if the response matches a request that was made to that peer
  187. if err := r.markPeerResponse(envelope.From); err != nil {
  188. return err
  189. }
  190. // check the size of the response
  191. if len(msg.Addresses) > int(maxAddresses) {
  192. return fmt.Errorf("peer sent too many addresses (max: %d, got: %d)",
  193. maxAddresses,
  194. len(msg.Addresses),
  195. )
  196. }
  197. for _, pexAddress := range msg.Addresses {
  198. // no protocol is prefixed so we assume the default (mconn)
  199. peerAddress, err := p2p.ParseNodeAddress(
  200. fmt.Sprintf("%s@%s:%d", pexAddress.ID, pexAddress.IP, pexAddress.Port))
  201. if err != nil {
  202. continue
  203. }
  204. added, err := r.peerManager.Add(peerAddress)
  205. if err != nil {
  206. logger.Error("failed to add PEX address", "address", peerAddress, "err", err)
  207. }
  208. if added {
  209. r.newPeers++
  210. logger.Debug("added PEX address", "address", peerAddress)
  211. }
  212. r.totalPeers++
  213. }
  214. // V2 PEX MESSAGES
  215. case *protop2p.PexRequestV2:
  216. // check if the peer hasn't sent a prior request too close to this one
  217. // in time
  218. if err := r.markPeerRequest(envelope.From); err != nil {
  219. return err
  220. }
  221. // request peers from the peer manager and parse the NodeAddresses into
  222. // URL strings
  223. nodeAddresses := r.peerManager.Advertise(envelope.From, maxAddresses)
  224. pexAddressesV2 := make([]protop2p.PexAddressV2, len(nodeAddresses))
  225. for idx, addr := range nodeAddresses {
  226. pexAddressesV2[idx] = protop2p.PexAddressV2{
  227. URL: addr.String(),
  228. }
  229. }
  230. r.pexCh.Out <- p2p.Envelope{
  231. To: envelope.From,
  232. Message: &protop2p.PexResponseV2{Addresses: pexAddressesV2},
  233. }
  234. case *protop2p.PexResponseV2:
  235. // check if the response matches a request that was made to that peer
  236. if err := r.markPeerResponse(envelope.From); err != nil {
  237. return err
  238. }
  239. // check the size of the response
  240. if len(msg.Addresses) > int(maxAddresses) {
  241. return fmt.Errorf("peer sent too many addresses (max: %d, got: %d)",
  242. maxAddresses,
  243. len(msg.Addresses),
  244. )
  245. }
  246. for _, pexAddress := range msg.Addresses {
  247. peerAddress, err := p2p.ParseNodeAddress(pexAddress.URL)
  248. if err != nil {
  249. continue
  250. }
  251. added, err := r.peerManager.Add(peerAddress)
  252. if err != nil {
  253. logger.Error("failed to add V2 PEX address", "address", peerAddress, "err", err)
  254. }
  255. if added {
  256. r.newPeers++
  257. logger.Debug("added V2 PEX address", "address", peerAddress)
  258. }
  259. r.totalPeers++
  260. }
  261. default:
  262. return fmt.Errorf("received unknown message: %T", msg)
  263. }
  264. return nil
  265. }
  266. // resolve resolves a set of peer addresses into PEX addresses.
  267. //
  268. // FIXME: This is necessary because the current PEX protocol only supports
  269. // IP/port pairs, while the P2P stack uses NodeAddress URLs. The PEX protocol
  270. // should really use URLs too, to exchange DNS names instead of IPs and allow
  271. // different transport protocols (e.g. QUIC and MemoryTransport).
  272. //
  273. // FIXME: We may want to cache and parallelize this, but for now we'll just rely
  274. // on the operating system to cache it for us.
  275. func (r *ReactorV2) resolve(addresses []p2p.NodeAddress) []protop2p.PexAddress {
  276. limit := len(addresses)
  277. pexAddresses := make([]protop2p.PexAddress, 0, limit)
  278. for _, address := range addresses {
  279. ctx, cancel := context.WithTimeout(context.Background(), resolveTimeout)
  280. endpoints, err := address.Resolve(ctx)
  281. r.Logger.Debug("resolved node address", "endpoints", endpoints)
  282. cancel()
  283. if err != nil {
  284. r.Logger.Debug("failed to resolve address", "address", address, "err", err)
  285. continue
  286. }
  287. for _, endpoint := range endpoints {
  288. r.Logger.Debug("checking endpint", "IP", endpoint.IP, "Port", endpoint.Port)
  289. if len(pexAddresses) >= limit {
  290. return pexAddresses
  291. } else if endpoint.IP != nil {
  292. r.Logger.Debug("appending pex address")
  293. // PEX currently only supports IP-networked transports (as
  294. // opposed to e.g. p2p.MemoryTransport).
  295. //
  296. // FIXME: as the PEX address contains no information about the
  297. // protocol, we jam this into the ID. We won't need to this once
  298. // we support URLs
  299. pexAddresses = append(pexAddresses, protop2p.PexAddress{
  300. ID: string(address.NodeID),
  301. IP: endpoint.IP.String(),
  302. Port: uint32(endpoint.Port),
  303. })
  304. }
  305. }
  306. }
  307. return pexAddresses
  308. }
  309. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  310. // It will handle errors and any possible panics gracefully. A caller can handle
  311. // any error returned by sending a PeerError on the respective channel.
  312. func (r *ReactorV2) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  313. defer func() {
  314. if e := recover(); e != nil {
  315. err = fmt.Errorf("panic in processing message: %v", e)
  316. }
  317. }()
  318. r.Logger.Debug("received PEX message", "peer", envelope.From)
  319. switch chID {
  320. case p2p.ChannelID(PexChannel):
  321. err = r.handlePexMessage(envelope)
  322. default:
  323. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  324. }
  325. return err
  326. }
  327. // processPeerUpdate processes a PeerUpdate. For added peers, PeerStatusUp, we
  328. // send a request for addresses.
  329. func (r *ReactorV2) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  330. r.Logger.Debug("received PEX peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  331. r.mtx.Lock()
  332. defer r.mtx.Unlock()
  333. switch peerUpdate.Status {
  334. case p2p.PeerStatusUp:
  335. r.availablePeers[peerUpdate.NodeID] = struct{}{}
  336. case p2p.PeerStatusDown:
  337. delete(r.availablePeers, peerUpdate.NodeID)
  338. delete(r.requestsSent, peerUpdate.NodeID)
  339. delete(r.lastReceivedRequests, peerUpdate.NodeID)
  340. default:
  341. }
  342. }
  343. func (r *ReactorV2) waitUntilNextRequest() <-chan time.Time {
  344. return time.After(time.Until(r.nextRequestTime))
  345. }
  346. // sendRequestForPeers pops the first peerID off the list and sends the
  347. // peer a request for more peer addresses. The function then moves the
  348. // peer into the requestsSent bucket and calculates when the next request
  349. // time should be
  350. func (r *ReactorV2) sendRequestForPeers() {
  351. r.mtx.Lock()
  352. defer r.mtx.Unlock()
  353. if len(r.availablePeers) == 0 {
  354. // no peers are available
  355. r.Logger.Debug("no available peers to send request to, waiting...")
  356. r.nextRequestTime = time.Now().Add(noAvailablePeersWaitPeriod)
  357. return
  358. }
  359. var peerID p2p.NodeID
  360. // use range to get a random peer.
  361. for peerID = range r.availablePeers {
  362. break
  363. }
  364. // The node accommodates for both pex systems
  365. if r.isLegacyPeer(peerID) {
  366. r.pexCh.Out <- p2p.Envelope{
  367. To: peerID,
  368. Message: &protop2p.PexRequest{},
  369. }
  370. } else {
  371. r.pexCh.Out <- p2p.Envelope{
  372. To: peerID,
  373. Message: &protop2p.PexRequestV2{},
  374. }
  375. }
  376. // remove the peer from the abvailable peers list and mark it in the requestsSent map
  377. delete(r.availablePeers, peerID)
  378. r.requestsSent[peerID] = struct{}{}
  379. r.calculateNextRequestTime()
  380. r.Logger.Debug("peer request sent", "next_request_time", r.nextRequestTime)
  381. }
  382. // calculateNextRequestTime implements something of a proportional controller
  383. // to estimate how often the reactor should be requesting new peer addresses.
  384. // The dependent variable in this calculation is the ratio of new peers to
  385. // all peers that the reactor receives. The interval is thus calculated as the
  386. // inverse squared. In the beginning, all peers should be new peers.
  387. // We expect this ratio to be near 1 and thus the interval to be as short
  388. // as possible. As the node becomes more familiar with the network the ratio of
  389. // new nodes will plummet to a very small number, meaning the interval expands
  390. // to its upper bound.
  391. // CONTRACT: Must use a write lock as nextRequestTime is updated
  392. func (r *ReactorV2) calculateNextRequestTime() {
  393. // check if the peer store is full. If so then there is no need
  394. // to send peer requests too often
  395. if ratio := r.peerManager.PeerRatio(); ratio >= 0.95 {
  396. r.Logger.Debug("peer manager near full ratio, sleeping...",
  397. "sleep_period", fullCapacityInterval, "ratio", ratio)
  398. r.nextRequestTime = time.Now().Add(fullCapacityInterval)
  399. return
  400. }
  401. // baseTime represents the shortest interval that we can send peer requests
  402. // in. For example if we have 10 peers and we can't send a message to the
  403. // same peer every 500ms, then we can send a request every 50ms. In practice
  404. // we use a safety margin of 2, ergo 100ms
  405. peers := tmmath.MinInt(len(r.availablePeers), 50)
  406. baseTime := minReceiveRequestInterval
  407. if peers > 0 {
  408. baseTime = minReceiveRequestInterval * 2 / time.Duration(peers)
  409. }
  410. if r.totalPeers > 0 || r.discoveryRatio == 0 {
  411. // find the ratio of new peers. NOTE: We add 1 to both sides to avoid
  412. // divide by zero problems
  413. ratio := float32(r.totalPeers+1) / float32(r.newPeers+1)
  414. // square the ratio in order to get non linear time intervals
  415. // NOTE: The longest possible interval for a network with 100 or more peers
  416. // where a node is connected to 50 of them is 2 minutes.
  417. r.discoveryRatio = ratio * ratio
  418. r.newPeers = 0
  419. r.totalPeers = 0
  420. }
  421. // NOTE: As ratio is always >= 1, discovery ratio is >= 1. Therefore we don't need to worry
  422. // about the next request time being less than the minimum time
  423. r.nextRequestTime = time.Now().Add(baseTime * time.Duration(r.discoveryRatio))
  424. }
  425. func (r *ReactorV2) markPeerRequest(peer p2p.NodeID) error {
  426. r.mtx.Lock()
  427. defer r.mtx.Unlock()
  428. if lastRequestTime, ok := r.lastReceivedRequests[peer]; ok {
  429. if time.Now().Before(lastRequestTime.Add(minReceiveRequestInterval)) {
  430. return fmt.Errorf("peer sent a request too close after a prior one. Minimum interval: %v",
  431. minReceiveRequestInterval)
  432. }
  433. }
  434. r.lastReceivedRequests[peer] = time.Now()
  435. return nil
  436. }
  437. func (r *ReactorV2) markPeerResponse(peer p2p.NodeID) error {
  438. r.mtx.Lock()
  439. defer r.mtx.Unlock()
  440. // check if a request to this peer was sent
  441. if _, ok := r.requestsSent[peer]; !ok {
  442. return fmt.Errorf("peer sent a PEX response when none was requested (%v)", peer)
  443. }
  444. delete(r.requestsSent, peer)
  445. // attach to the back of the list so that the peer can be used again for
  446. // future requests
  447. r.availablePeers[peer] = struct{}{}
  448. return nil
  449. }
  450. // all addresses must use a MCONN protocol for the peer to be considered part of the
  451. // legacy p2p pex system
  452. func (r *ReactorV2) isLegacyPeer(peer p2p.NodeID) bool {
  453. for _, addr := range r.peerManager.Addresses(peer) {
  454. if addr.Protocol != p2p.MConnProtocol {
  455. return false
  456. }
  457. }
  458. return true
  459. }