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.

444 lines
14 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 = (*Reactor)(nil)
  18. _ p2p.Wrapper = (*protop2p.PexMessage)(nil)
  19. )
  20. const (
  21. // PexChannel is a channel for PEX messages
  22. PexChannel = 0x00
  23. // over-estimate of max NetAddress size
  24. // hexID (40) + IP (16) + Port (2) + Name (100) ...
  25. // NOTE: dont use massive DNS name ..
  26. maxAddressSize = 256
  27. // max addresses returned by GetSelection
  28. // NOTE: this must match "maxMsgSize"
  29. maxGetSelection = 250
  30. // NOTE: amplification factor!
  31. // small request results in up to maxMsgSize response
  32. maxMsgSize = maxAddressSize * maxGetSelection
  33. // the minimum time one peer can send another request to the same peer
  34. minReceiveRequestInterval = 100 * time.Millisecond
  35. // the maximum amount of addresses that can be included in a response
  36. maxAddresses uint16 = 100
  37. // How long to wait when there are no peers available before trying again
  38. noAvailablePeersWaitPeriod = 1 * time.Second
  39. // indicates the ping rate of the pex reactor when the peer store is full.
  40. // The reactor should still look to add new peers in order to flush out low
  41. // scoring peers that are still in the peer store
  42. fullCapacityInterval = 10 * time.Minute
  43. )
  44. // TODO: We should decide whether we want channel descriptors to be housed
  45. // within each reactor (as they are now) or, considering that the reactor doesn't
  46. // really need to care about the channel descriptors, if they should be housed
  47. // in the node module.
  48. func ChannelDescriptor() *conn.ChannelDescriptor {
  49. return &conn.ChannelDescriptor{
  50. ID: PexChannel,
  51. MessageType: new(protop2p.PexMessage),
  52. Priority: 1,
  53. SendQueueCapacity: 10,
  54. RecvMessageCapacity: maxMsgSize,
  55. RecvBufferCapacity: 128,
  56. }
  57. }
  58. // The peer exchange or PEX reactor supports the peer manager by sending
  59. // requests to other peers for addresses that can be given to the peer manager
  60. // and at the same time advertises addresses to peers that need more.
  61. //
  62. // The reactor is able to tweak the intensity of it's search by decreasing or
  63. // increasing the interval between each request. It tracks connected peers via
  64. // a linked list, sending a request to the node at the front of the list and
  65. // adding it to the back of the list once a response is received.
  66. type Reactor struct {
  67. service.BaseService
  68. logger log.Logger
  69. peerManager *p2p.PeerManager
  70. pexCh *p2p.Channel
  71. peerUpdates *p2p.PeerUpdates
  72. // list of available peers to loop through and send peer requests to
  73. availablePeers map[types.NodeID]struct{}
  74. mtx sync.RWMutex
  75. // requestsSent keeps track of which peers the PEX reactor has sent requests
  76. // to. This prevents the sending of spurious responses.
  77. // NOTE: If a node never responds, they will remain in this map until a
  78. // peer down status update is sent
  79. requestsSent map[types.NodeID]struct{}
  80. // lastReceivedRequests keeps track of when peers send a request to prevent
  81. // peers from sending requests too often (as defined by
  82. // minReceiveRequestInterval).
  83. lastReceivedRequests map[types.NodeID]time.Time
  84. // keep track of how many new peers to existing peers we have received to
  85. // extrapolate the size of the network
  86. newPeers uint32
  87. totalPeers uint32
  88. // discoveryRatio is the inverse ratio of new peers to old peers squared.
  89. // This is multiplied by the minimum duration to calculate how long to wait
  90. // between each request.
  91. discoveryRatio float32
  92. }
  93. // NewReactor returns a reference to a new reactor.
  94. func NewReactor(
  95. ctx context.Context,
  96. logger log.Logger,
  97. peerManager *p2p.PeerManager,
  98. channelCreator p2p.ChannelCreator,
  99. peerUpdates *p2p.PeerUpdates,
  100. ) (*Reactor, error) {
  101. channel, err := channelCreator(ctx, ChannelDescriptor())
  102. if err != nil {
  103. return nil, err
  104. }
  105. r := &Reactor{
  106. logger: logger,
  107. peerManager: peerManager,
  108. pexCh: channel,
  109. peerUpdates: peerUpdates,
  110. availablePeers: make(map[types.NodeID]struct{}),
  111. requestsSent: make(map[types.NodeID]struct{}),
  112. lastReceivedRequests: make(map[types.NodeID]time.Time),
  113. }
  114. r.BaseService = *service.NewBaseService(logger, "PEX", r)
  115. return r, nil
  116. }
  117. // OnStart starts separate go routines for each p2p Channel and listens for
  118. // envelopes on each. In addition, it also listens for peer updates and handles
  119. // messages on that p2p channel accordingly. The caller must be sure to execute
  120. // OnStop to ensure the outbound p2p Channels are closed.
  121. func (r *Reactor) OnStart(ctx context.Context) error {
  122. go r.processPexCh(ctx)
  123. go r.processPeerUpdates(ctx)
  124. return nil
  125. }
  126. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  127. // blocking until they all exit.
  128. func (r *Reactor) OnStop() {}
  129. // processPexCh implements a blocking event loop where we listen for p2p
  130. // Envelope messages from the pexCh.
  131. func (r *Reactor) processPexCh(ctx context.Context) {
  132. timer := time.NewTimer(0)
  133. defer timer.Stop()
  134. var (
  135. duration = r.calculateNextRequestTime()
  136. err error
  137. )
  138. incoming := make(chan *p2p.Envelope)
  139. go func() {
  140. defer close(incoming)
  141. iter := r.pexCh.Receive(ctx)
  142. for iter.Next(ctx) {
  143. select {
  144. case <-ctx.Done():
  145. return
  146. case incoming <- iter.Envelope():
  147. }
  148. }
  149. }()
  150. for {
  151. timer.Reset(duration)
  152. select {
  153. case <-ctx.Done():
  154. r.logger.Debug("stopped listening on PEX channel; closing...")
  155. return
  156. // outbound requests for new peers
  157. case <-timer.C:
  158. duration, err = r.sendRequestForPeers(ctx)
  159. if err != nil {
  160. return
  161. }
  162. // inbound requests for new peers or responses to requests sent by this
  163. // reactor
  164. case envelope := <-incoming:
  165. duration, err = r.handleMessage(ctx, r.pexCh.ID, envelope)
  166. if err != nil {
  167. r.logger.Error("failed to process message", "ch_id", r.pexCh.ID, "envelope", envelope, "err", err)
  168. if serr := r.pexCh.SendError(ctx, p2p.PeerError{
  169. NodeID: envelope.From,
  170. Err: err,
  171. }); serr != nil {
  172. return
  173. }
  174. }
  175. }
  176. }
  177. }
  178. // processPeerUpdates initiates a blocking process where we listen for and handle
  179. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  180. // close the p2p PeerUpdatesCh gracefully.
  181. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  182. for {
  183. select {
  184. case <-ctx.Done():
  185. r.logger.Debug("stopped listening on peer updates channel; closing...")
  186. return
  187. case peerUpdate := <-r.peerUpdates.Updates():
  188. r.processPeerUpdate(peerUpdate)
  189. }
  190. }
  191. }
  192. // handlePexMessage handles envelopes sent from peers on the PexChannel.
  193. func (r *Reactor) handlePexMessage(ctx context.Context, envelope *p2p.Envelope) (time.Duration, error) {
  194. logger := r.logger.With("peer", envelope.From)
  195. switch msg := envelope.Message.(type) {
  196. case *protop2p.PexRequest:
  197. // check if the peer hasn't sent a prior request too close to this one
  198. // in time
  199. if err := r.markPeerRequest(envelope.From); err != nil {
  200. return time.Minute, err
  201. }
  202. // request peers from the peer manager and parse the NodeAddresses into
  203. // URL strings
  204. nodeAddresses := r.peerManager.Advertise(envelope.From, maxAddresses)
  205. pexAddresses := make([]protop2p.PexAddress, len(nodeAddresses))
  206. for idx, addr := range nodeAddresses {
  207. pexAddresses[idx] = protop2p.PexAddress{
  208. URL: addr.String(),
  209. }
  210. }
  211. if err := r.pexCh.Send(ctx, p2p.Envelope{
  212. To: envelope.From,
  213. Message: &protop2p.PexResponse{Addresses: pexAddresses},
  214. }); err != nil {
  215. return 0, err
  216. }
  217. return time.Second, nil
  218. case *protop2p.PexResponse:
  219. // check if the response matches a request that was made to that peer
  220. if err := r.markPeerResponse(envelope.From); err != nil {
  221. return time.Minute, err
  222. }
  223. // check the size of the response
  224. if len(msg.Addresses) > int(maxAddresses) {
  225. return 10 * time.Minute, fmt.Errorf("peer sent too many addresses (max: %d, got: %d)",
  226. maxAddresses,
  227. len(msg.Addresses),
  228. )
  229. }
  230. for _, pexAddress := range msg.Addresses {
  231. peerAddress, err := p2p.ParseNodeAddress(pexAddress.URL)
  232. if err != nil {
  233. continue
  234. }
  235. added, err := r.peerManager.Add(peerAddress)
  236. if err != nil {
  237. logger.Error("failed to add PEX address", "address", peerAddress, "err", err)
  238. }
  239. if added {
  240. r.newPeers++
  241. logger.Debug("added PEX address", "address", peerAddress)
  242. }
  243. r.totalPeers++
  244. }
  245. return 10 * time.Minute, nil
  246. default:
  247. return time.Second, fmt.Errorf("received unknown message: %T", msg)
  248. }
  249. }
  250. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  251. // It will handle errors and any possible panics gracefully. A caller can handle
  252. // any error returned by sending a PeerError on the respective channel.
  253. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (duration time.Duration, err error) {
  254. defer func() {
  255. if e := recover(); e != nil {
  256. err = fmt.Errorf("panic in processing message: %v", e)
  257. r.logger.Error(
  258. "recovering from processing message panic",
  259. "err", err,
  260. "stack", string(debug.Stack()),
  261. )
  262. }
  263. }()
  264. r.logger.Debug("received PEX message", "peer", envelope.From)
  265. switch chID {
  266. case p2p.ChannelID(PexChannel):
  267. duration, err = r.handlePexMessage(ctx, envelope)
  268. default:
  269. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  270. }
  271. return
  272. }
  273. // processPeerUpdate processes a PeerUpdate. For added peers, PeerStatusUp, we
  274. // send a request for addresses.
  275. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  276. r.logger.Debug("received PEX peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  277. r.mtx.Lock()
  278. defer r.mtx.Unlock()
  279. switch peerUpdate.Status {
  280. case p2p.PeerStatusUp:
  281. r.availablePeers[peerUpdate.NodeID] = struct{}{}
  282. case p2p.PeerStatusDown:
  283. delete(r.availablePeers, peerUpdate.NodeID)
  284. delete(r.requestsSent, peerUpdate.NodeID)
  285. delete(r.lastReceivedRequests, peerUpdate.NodeID)
  286. default:
  287. }
  288. }
  289. // sendRequestForPeers pops the first peerID off the list and sends the
  290. // peer a request for more peer addresses. The function then moves the
  291. // peer into the requestsSent bucket and calculates when the next request
  292. // time should be
  293. func (r *Reactor) sendRequestForPeers(ctx context.Context) (time.Duration, error) {
  294. r.mtx.Lock()
  295. defer r.mtx.Unlock()
  296. if len(r.availablePeers) == 0 {
  297. // no peers are available
  298. r.logger.Debug("no available peers to send request to, waiting...")
  299. return noAvailablePeersWaitPeriod, nil
  300. }
  301. var peerID types.NodeID
  302. // use range to get a random peer.
  303. for peerID = range r.availablePeers {
  304. break
  305. }
  306. // send out the pex request
  307. if err := r.pexCh.Send(ctx, p2p.Envelope{
  308. To: peerID,
  309. Message: &protop2p.PexRequest{},
  310. }); err != nil {
  311. return 0, err
  312. }
  313. // remove the peer from the abvailable peers list and mark it in the requestsSent map
  314. delete(r.availablePeers, peerID)
  315. r.requestsSent[peerID] = struct{}{}
  316. dur := r.calculateNextRequestTime()
  317. r.logger.Debug("peer request sent", "next_request_time", dur)
  318. return dur, nil
  319. }
  320. // calculateNextRequestTime implements something of a proportional controller
  321. // to estimate how often the reactor should be requesting new peer addresses.
  322. // The dependent variable in this calculation is the ratio of new peers to
  323. // all peers that the reactor receives. The interval is thus calculated as the
  324. // inverse squared. In the beginning, all peers should be new peers.
  325. // We expect this ratio to be near 1 and thus the interval to be as short
  326. // as possible. As the node becomes more familiar with the network the ratio of
  327. // new nodes will plummet to a very small number, meaning the interval expands
  328. // to its upper bound.
  329. // CONTRACT: Must use a write lock as nextRequestTime is updated
  330. func (r *Reactor) calculateNextRequestTime() time.Duration {
  331. // check if the peer store is full. If so then there is no need
  332. // to send peer requests too often
  333. if ratio := r.peerManager.PeerRatio(); ratio >= 0.95 {
  334. r.logger.Debug("peer manager near full ratio, sleeping...",
  335. "sleep_period", fullCapacityInterval, "ratio", ratio)
  336. return fullCapacityInterval
  337. }
  338. // baseTime represents the shortest interval that we can send peer requests
  339. // in. For example if we have 10 peers and we can't send a message to the
  340. // same peer every 500ms, then we can send a request every 50ms. In practice
  341. // we use a safety margin of 2, ergo 100ms
  342. peers := tmmath.MinInt(len(r.availablePeers), 50)
  343. baseTime := minReceiveRequestInterval
  344. if peers > 0 {
  345. baseTime = minReceiveRequestInterval * 2 / time.Duration(peers)
  346. }
  347. if r.totalPeers > 0 || r.discoveryRatio == 0 {
  348. // find the ratio of new peers. NOTE: We add 1 to both sides to avoid
  349. // divide by zero problems
  350. ratio := float32(r.totalPeers+1) / float32(r.newPeers+1)
  351. // square the ratio in order to get non linear time intervals
  352. // NOTE: The longest possible interval for a network with 100 or more peers
  353. // where a node is connected to 50 of them is 2 minutes.
  354. r.discoveryRatio = ratio * ratio
  355. r.newPeers = 0
  356. r.totalPeers = 0
  357. }
  358. // NOTE: As ratio is always >= 1, discovery ratio is >= 1. Therefore we don't need to worry
  359. // about the next request time being less than the minimum time
  360. return baseTime * time.Duration(r.discoveryRatio)
  361. }
  362. func (r *Reactor) markPeerRequest(peer types.NodeID) error {
  363. r.mtx.Lock()
  364. defer r.mtx.Unlock()
  365. if lastRequestTime, ok := r.lastReceivedRequests[peer]; ok {
  366. if time.Now().Before(lastRequestTime.Add(minReceiveRequestInterval)) {
  367. return fmt.Errorf("peer sent a request too close after a prior one. Minimum interval: %v",
  368. minReceiveRequestInterval)
  369. }
  370. }
  371. r.lastReceivedRequests[peer] = time.Now()
  372. return nil
  373. }
  374. func (r *Reactor) markPeerResponse(peer types.NodeID) error {
  375. r.mtx.Lock()
  376. defer r.mtx.Unlock()
  377. // check if a request to this peer was sent
  378. if _, ok := r.requestsSent[peer]; !ok {
  379. return fmt.Errorf("peer sent a PEX response when none was requested (%v)", peer)
  380. }
  381. delete(r.requestsSent, peer)
  382. // attach to the back of the list so that the peer can be used again for
  383. // future requests
  384. r.availablePeers[peer] = struct{}{}
  385. return nil
  386. }