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.

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