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.

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