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.

540 lines
17 KiB

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