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.

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