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.

438 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. logger log.Logger,
  96. peerManager *p2p.PeerManager,
  97. pexCh *p2p.Channel,
  98. peerUpdates *p2p.PeerUpdates,
  99. ) *Reactor {
  100. r := &Reactor{
  101. logger: logger,
  102. peerManager: peerManager,
  103. pexCh: pexCh,
  104. peerUpdates: peerUpdates,
  105. availablePeers: make(map[types.NodeID]struct{}),
  106. requestsSent: make(map[types.NodeID]struct{}),
  107. lastReceivedRequests: make(map[types.NodeID]time.Time),
  108. }
  109. r.BaseService = *service.NewBaseService(logger, "PEX", r)
  110. return r
  111. }
  112. // OnStart starts separate go routines for each p2p Channel and listens for
  113. // envelopes on each. In addition, it also listens for peer updates and handles
  114. // messages on that p2p channel accordingly. The caller must be sure to execute
  115. // OnStop to ensure the outbound p2p Channels are closed.
  116. func (r *Reactor) OnStart(ctx context.Context) error {
  117. go r.processPexCh(ctx)
  118. go r.processPeerUpdates(ctx)
  119. return nil
  120. }
  121. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  122. // blocking until they all exit.
  123. func (r *Reactor) OnStop() {}
  124. // processPexCh implements a blocking event loop where we listen for p2p
  125. // Envelope messages from the pexCh.
  126. func (r *Reactor) processPexCh(ctx context.Context) {
  127. timer := time.NewTimer(0)
  128. defer timer.Stop()
  129. var (
  130. duration = r.calculateNextRequestTime()
  131. err error
  132. )
  133. incoming := make(chan *p2p.Envelope)
  134. go func() {
  135. defer close(incoming)
  136. iter := r.pexCh.Receive(ctx)
  137. for iter.Next(ctx) {
  138. select {
  139. case <-ctx.Done():
  140. return
  141. case incoming <- iter.Envelope():
  142. }
  143. }
  144. }()
  145. for {
  146. timer.Reset(duration)
  147. select {
  148. case <-ctx.Done():
  149. r.logger.Debug("stopped listening on PEX channel; closing...")
  150. return
  151. // outbound requests for new peers
  152. case <-timer.C:
  153. duration, err = r.sendRequestForPeers(ctx)
  154. if err != nil {
  155. return
  156. }
  157. // inbound requests for new peers or responses to requests sent by this
  158. // reactor
  159. case envelope := <-incoming:
  160. duration, err = r.handleMessage(ctx, r.pexCh.ID, envelope)
  161. if err != nil {
  162. r.logger.Error("failed to process message", "ch_id", r.pexCh.ID, "envelope", envelope, "err", err)
  163. if serr := r.pexCh.SendError(ctx, p2p.PeerError{
  164. NodeID: envelope.From,
  165. Err: err,
  166. }); serr != nil {
  167. return
  168. }
  169. }
  170. }
  171. }
  172. }
  173. // processPeerUpdates initiates a blocking process where we listen for and handle
  174. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  175. // close the p2p PeerUpdatesCh gracefully.
  176. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  177. for {
  178. select {
  179. case <-ctx.Done():
  180. r.logger.Debug("stopped listening on peer updates channel; closing...")
  181. return
  182. case peerUpdate := <-r.peerUpdates.Updates():
  183. r.processPeerUpdate(peerUpdate)
  184. }
  185. }
  186. }
  187. // handlePexMessage handles envelopes sent from peers on the PexChannel.
  188. func (r *Reactor) handlePexMessage(ctx context.Context, envelope *p2p.Envelope) (time.Duration, error) {
  189. logger := r.logger.With("peer", envelope.From)
  190. switch msg := envelope.Message.(type) {
  191. case *protop2p.PexRequest:
  192. // check if the peer hasn't sent a prior request too close to this one
  193. // in time
  194. if err := r.markPeerRequest(envelope.From); err != nil {
  195. return time.Minute, err
  196. }
  197. // request peers from the peer manager and parse the NodeAddresses into
  198. // URL strings
  199. nodeAddresses := r.peerManager.Advertise(envelope.From, maxAddresses)
  200. pexAddresses := make([]protop2p.PexAddress, len(nodeAddresses))
  201. for idx, addr := range nodeAddresses {
  202. pexAddresses[idx] = protop2p.PexAddress{
  203. URL: addr.String(),
  204. }
  205. }
  206. if err := r.pexCh.Send(ctx, p2p.Envelope{
  207. To: envelope.From,
  208. Message: &protop2p.PexResponse{Addresses: pexAddresses},
  209. }); err != nil {
  210. return 0, err
  211. }
  212. return time.Second, nil
  213. case *protop2p.PexResponse:
  214. // check if the response matches a request that was made to that peer
  215. if err := r.markPeerResponse(envelope.From); err != nil {
  216. return time.Minute, err
  217. }
  218. // check the size of the response
  219. if len(msg.Addresses) > int(maxAddresses) {
  220. return 10 * time.Minute, fmt.Errorf("peer sent too many addresses (max: %d, got: %d)",
  221. maxAddresses,
  222. len(msg.Addresses),
  223. )
  224. }
  225. for _, pexAddress := range msg.Addresses {
  226. peerAddress, err := p2p.ParseNodeAddress(pexAddress.URL)
  227. if err != nil {
  228. continue
  229. }
  230. added, err := r.peerManager.Add(peerAddress)
  231. if err != nil {
  232. logger.Error("failed to add PEX address", "address", peerAddress, "err", err)
  233. }
  234. if added {
  235. r.newPeers++
  236. logger.Debug("added PEX address", "address", peerAddress)
  237. }
  238. r.totalPeers++
  239. }
  240. return 10 * time.Minute, nil
  241. default:
  242. return time.Second, fmt.Errorf("received unknown message: %T", msg)
  243. }
  244. }
  245. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  246. // It will handle errors and any possible panics gracefully. A caller can handle
  247. // any error returned by sending a PeerError on the respective channel.
  248. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (duration time.Duration, err error) {
  249. defer func() {
  250. if e := recover(); e != nil {
  251. err = fmt.Errorf("panic in processing message: %v", e)
  252. r.logger.Error(
  253. "recovering from processing message panic",
  254. "err", err,
  255. "stack", string(debug.Stack()),
  256. )
  257. }
  258. }()
  259. r.logger.Debug("received PEX message", "peer", envelope.From)
  260. switch chID {
  261. case p2p.ChannelID(PexChannel):
  262. duration, err = r.handlePexMessage(ctx, envelope)
  263. default:
  264. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  265. }
  266. return
  267. }
  268. // processPeerUpdate processes a PeerUpdate. For added peers, PeerStatusUp, we
  269. // send a request for addresses.
  270. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  271. r.logger.Debug("received PEX peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  272. r.mtx.Lock()
  273. defer r.mtx.Unlock()
  274. switch peerUpdate.Status {
  275. case p2p.PeerStatusUp:
  276. r.availablePeers[peerUpdate.NodeID] = struct{}{}
  277. case p2p.PeerStatusDown:
  278. delete(r.availablePeers, peerUpdate.NodeID)
  279. delete(r.requestsSent, peerUpdate.NodeID)
  280. delete(r.lastReceivedRequests, peerUpdate.NodeID)
  281. default:
  282. }
  283. }
  284. // sendRequestForPeers pops the first peerID off the list and sends the
  285. // peer a request for more peer addresses. The function then moves the
  286. // peer into the requestsSent bucket and calculates when the next request
  287. // time should be
  288. func (r *Reactor) sendRequestForPeers(ctx context.Context) (time.Duration, error) {
  289. r.mtx.Lock()
  290. defer r.mtx.Unlock()
  291. if len(r.availablePeers) == 0 {
  292. // no peers are available
  293. r.logger.Debug("no available peers to send request to, waiting...")
  294. return noAvailablePeersWaitPeriod, nil
  295. }
  296. var peerID types.NodeID
  297. // use range to get a random peer.
  298. for peerID = range r.availablePeers {
  299. break
  300. }
  301. // send out the pex request
  302. if err := r.pexCh.Send(ctx, p2p.Envelope{
  303. To: peerID,
  304. Message: &protop2p.PexRequest{},
  305. }); err != nil {
  306. return 0, err
  307. }
  308. // remove the peer from the abvailable peers list and mark it in the requestsSent map
  309. delete(r.availablePeers, peerID)
  310. r.requestsSent[peerID] = struct{}{}
  311. dur := r.calculateNextRequestTime()
  312. r.logger.Debug("peer request sent", "next_request_time", dur)
  313. return dur, nil
  314. }
  315. // calculateNextRequestTime implements something of a proportional controller
  316. // to estimate how often the reactor should be requesting new peer addresses.
  317. // The dependent variable in this calculation is the ratio of new peers to
  318. // all peers that the reactor receives. The interval is thus calculated as the
  319. // inverse squared. In the beginning, all peers should be new peers.
  320. // We expect this ratio to be near 1 and thus the interval to be as short
  321. // as possible. As the node becomes more familiar with the network the ratio of
  322. // new nodes will plummet to a very small number, meaning the interval expands
  323. // to its upper bound.
  324. // CONTRACT: Must use a write lock as nextRequestTime is updated
  325. func (r *Reactor) calculateNextRequestTime() time.Duration {
  326. // check if the peer store is full. If so then there is no need
  327. // to send peer requests too often
  328. if ratio := r.peerManager.PeerRatio(); ratio >= 0.95 {
  329. r.logger.Debug("peer manager near full ratio, sleeping...",
  330. "sleep_period", fullCapacityInterval, "ratio", ratio)
  331. return fullCapacityInterval
  332. }
  333. // baseTime represents the shortest interval that we can send peer requests
  334. // in. For example if we have 10 peers and we can't send a message to the
  335. // same peer every 500ms, then we can send a request every 50ms. In practice
  336. // we use a safety margin of 2, ergo 100ms
  337. peers := tmmath.MinInt(len(r.availablePeers), 50)
  338. baseTime := minReceiveRequestInterval
  339. if peers > 0 {
  340. baseTime = minReceiveRequestInterval * 2 / time.Duration(peers)
  341. }
  342. if r.totalPeers > 0 || r.discoveryRatio == 0 {
  343. // find the ratio of new peers. NOTE: We add 1 to both sides to avoid
  344. // divide by zero problems
  345. ratio := float32(r.totalPeers+1) / float32(r.newPeers+1)
  346. // square the ratio in order to get non linear time intervals
  347. // NOTE: The longest possible interval for a network with 100 or more peers
  348. // where a node is connected to 50 of them is 2 minutes.
  349. r.discoveryRatio = ratio * ratio
  350. r.newPeers = 0
  351. r.totalPeers = 0
  352. }
  353. // NOTE: As ratio is always >= 1, discovery ratio is >= 1. Therefore we don't need to worry
  354. // about the next request time being less than the minimum time
  355. return baseTime * time.Duration(r.discoveryRatio)
  356. }
  357. func (r *Reactor) markPeerRequest(peer types.NodeID) error {
  358. r.mtx.Lock()
  359. defer r.mtx.Unlock()
  360. if lastRequestTime, ok := r.lastReceivedRequests[peer]; ok {
  361. if time.Now().Before(lastRequestTime.Add(minReceiveRequestInterval)) {
  362. return fmt.Errorf("peer sent a request too close after a prior one. Minimum interval: %v",
  363. minReceiveRequestInterval)
  364. }
  365. }
  366. r.lastReceivedRequests[peer] = time.Now()
  367. return nil
  368. }
  369. func (r *Reactor) markPeerResponse(peer types.NodeID) error {
  370. r.mtx.Lock()
  371. defer r.mtx.Unlock()
  372. // check if a request to this peer was sent
  373. if _, ok := r.requestsSent[peer]; !ok {
  374. return fmt.Errorf("peer sent a PEX response when none was requested (%v)", peer)
  375. }
  376. delete(r.requestsSent, peer)
  377. // attach to the back of the list so that the peer can be used again for
  378. // future requests
  379. r.availablePeers[peer] = struct{}{}
  380. return nil
  381. }