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.

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