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.

1408 lines
43 KiB

  1. package p2p
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "math/rand"
  8. "sort"
  9. "sync"
  10. "time"
  11. "github.com/gogo/protobuf/proto"
  12. "github.com/google/orderedcode"
  13. dbm "github.com/tendermint/tm-db"
  14. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  15. p2pproto "github.com/tendermint/tendermint/proto/tendermint/p2p"
  16. "github.com/tendermint/tendermint/types"
  17. )
  18. const (
  19. // retryNever is returned by retryDelay() when retries are disabled.
  20. retryNever time.Duration = math.MaxInt64
  21. )
  22. // PeerStatus is a peer status.
  23. //
  24. // The peer manager has many more internal states for a peer (e.g. dialing,
  25. // connected, evicting, and so on), which are tracked separately. PeerStatus is
  26. // for external use outside of the peer manager.
  27. type PeerStatus string
  28. const (
  29. PeerStatusUp PeerStatus = "up" // connected and ready
  30. PeerStatusDown PeerStatus = "down" // disconnected
  31. PeerStatusGood PeerStatus = "good" // peer observed as good
  32. PeerStatusBad PeerStatus = "bad" // peer observed as bad
  33. )
  34. // PeerScore is a numeric score assigned to a peer (higher is better).
  35. type PeerScore uint8
  36. const (
  37. PeerScorePersistent PeerScore = math.MaxUint8 // persistent peers
  38. )
  39. // PeerUpdate is a peer update event sent via PeerUpdates.
  40. type PeerUpdate struct {
  41. NodeID types.NodeID
  42. Status PeerStatus
  43. }
  44. // PeerUpdates is a peer update subscription with notifications about peer
  45. // events (currently just status changes).
  46. type PeerUpdates struct {
  47. routerUpdatesCh chan PeerUpdate
  48. reactorUpdatesCh chan PeerUpdate
  49. closeCh chan struct{}
  50. closeOnce sync.Once
  51. }
  52. // NewPeerUpdates creates a new PeerUpdates subscription. It is primarily for
  53. // internal use, callers should typically use PeerManager.Subscribe(). The
  54. // subscriber must call Close() when done.
  55. func NewPeerUpdates(updatesCh chan PeerUpdate, buf int) *PeerUpdates {
  56. return &PeerUpdates{
  57. reactorUpdatesCh: updatesCh,
  58. routerUpdatesCh: make(chan PeerUpdate, buf),
  59. closeCh: make(chan struct{}),
  60. }
  61. }
  62. // Updates returns a channel for consuming peer updates.
  63. func (pu *PeerUpdates) Updates() <-chan PeerUpdate {
  64. return pu.reactorUpdatesCh
  65. }
  66. // SendUpdate pushes information about a peer into the routing layer,
  67. // presumably from a peer.
  68. func (pu *PeerUpdates) SendUpdate(update PeerUpdate) {
  69. select {
  70. case <-pu.closeCh:
  71. case pu.routerUpdatesCh <- update:
  72. }
  73. }
  74. // Close closes the peer updates subscription.
  75. func (pu *PeerUpdates) Close() {
  76. pu.closeOnce.Do(func() {
  77. // NOTE: We don't close updatesCh since multiple goroutines may be
  78. // sending on it. The PeerManager senders will select on closeCh as well
  79. // to avoid blocking on a closed subscription.
  80. close(pu.closeCh)
  81. })
  82. }
  83. // Done returns a channel that is closed when the subscription is closed.
  84. func (pu *PeerUpdates) Done() <-chan struct{} {
  85. return pu.closeCh
  86. }
  87. // PeerManagerOptions specifies options for a PeerManager.
  88. type PeerManagerOptions struct {
  89. // PersistentPeers are peers that we want to maintain persistent connections
  90. // to. These will be scored higher than other peers, and if
  91. // MaxConnectedUpgrade is non-zero any lower-scored peers will be evicted if
  92. // necessary to make room for these.
  93. PersistentPeers []types.NodeID
  94. // MaxPeers is the maximum number of peers to track information about, i.e.
  95. // store in the peer store. When exceeded, the lowest-scored unconnected peers
  96. // will be deleted. 0 means no limit.
  97. MaxPeers uint16
  98. // MaxConnected is the maximum number of connected peers (inbound and
  99. // outbound). 0 means no limit.
  100. MaxConnected uint16
  101. // MaxConnectedUpgrade is the maximum number of additional connections to
  102. // use for probing any better-scored peers to upgrade to when all connection
  103. // slots are full. 0 disables peer upgrading.
  104. //
  105. // For example, if we are already connected to MaxConnected peers, but we
  106. // know or learn about better-scored peers (e.g. configured persistent
  107. // peers) that we are not connected too, then we can probe these peers by
  108. // using up to MaxConnectedUpgrade connections, and once connected evict the
  109. // lowest-scored connected peers. This also works for inbound connections,
  110. // i.e. if a higher-scored peer attempts to connect to us, we can accept
  111. // the connection and evict a lower-scored peer.
  112. MaxConnectedUpgrade uint16
  113. // MinRetryTime is the minimum time to wait between retries. Retry times
  114. // double for each retry, up to MaxRetryTime. 0 disables retries.
  115. MinRetryTime time.Duration
  116. // MaxRetryTime is the maximum time to wait between retries. 0 means
  117. // no maximum, in which case the retry time will keep doubling.
  118. MaxRetryTime time.Duration
  119. // MaxRetryTimePersistent is the maximum time to wait between retries for
  120. // peers listed in PersistentPeers. 0 uses MaxRetryTime instead.
  121. MaxRetryTimePersistent time.Duration
  122. // RetryTimeJitter is the upper bound of a random interval added to
  123. // retry times, to avoid thundering herds. 0 disables jitter.
  124. RetryTimeJitter time.Duration
  125. // PeerScores sets fixed scores for specific peers. It is mainly used
  126. // for testing. A score of 0 is ignored.
  127. PeerScores map[types.NodeID]PeerScore
  128. // PrivatePeerIDs defines a set of NodeID objects which the PEX reactor will
  129. // consider private and never gossip.
  130. PrivatePeers map[types.NodeID]struct{}
  131. // persistentPeers provides fast PersistentPeers lookups. It is built
  132. // by optimize().
  133. persistentPeers map[types.NodeID]bool
  134. }
  135. // Validate validates the options.
  136. func (o *PeerManagerOptions) Validate() error {
  137. for _, id := range o.PersistentPeers {
  138. if err := id.Validate(); err != nil {
  139. return fmt.Errorf("invalid PersistentPeer ID %q: %w", id, err)
  140. }
  141. }
  142. for id := range o.PrivatePeers {
  143. if err := id.Validate(); err != nil {
  144. return fmt.Errorf("invalid private peer ID %q: %w", id, err)
  145. }
  146. }
  147. if o.MaxConnected > 0 && len(o.PersistentPeers) > int(o.MaxConnected) {
  148. return fmt.Errorf("number of persistent peers %v can't exceed MaxConnected %v",
  149. len(o.PersistentPeers), o.MaxConnected)
  150. }
  151. if o.MaxPeers > 0 {
  152. if o.MaxConnected == 0 || o.MaxConnected+o.MaxConnectedUpgrade > o.MaxPeers {
  153. return fmt.Errorf("MaxConnected %v and MaxConnectedUpgrade %v can't exceed MaxPeers %v",
  154. o.MaxConnected, o.MaxConnectedUpgrade, o.MaxPeers)
  155. }
  156. }
  157. if o.MaxRetryTime > 0 {
  158. if o.MinRetryTime == 0 {
  159. return errors.New("can't set MaxRetryTime without MinRetryTime")
  160. }
  161. if o.MinRetryTime > o.MaxRetryTime {
  162. return fmt.Errorf("MinRetryTime %v is greater than MaxRetryTime %v",
  163. o.MinRetryTime, o.MaxRetryTime)
  164. }
  165. }
  166. if o.MaxRetryTimePersistent > 0 {
  167. if o.MinRetryTime == 0 {
  168. return errors.New("can't set MaxRetryTimePersistent without MinRetryTime")
  169. }
  170. if o.MinRetryTime > o.MaxRetryTimePersistent {
  171. return fmt.Errorf("MinRetryTime %v is greater than MaxRetryTimePersistent %v",
  172. o.MinRetryTime, o.MaxRetryTimePersistent)
  173. }
  174. }
  175. return nil
  176. }
  177. // isPersistentPeer checks if a peer is in PersistentPeers. It will panic
  178. // if called before optimize().
  179. func (o *PeerManagerOptions) isPersistent(id types.NodeID) bool {
  180. if o.persistentPeers == nil {
  181. panic("isPersistentPeer() called before optimize()")
  182. }
  183. return o.persistentPeers[id]
  184. }
  185. // optimize optimizes operations by pregenerating lookup structures. It's a
  186. // separate method instead of memoizing during calls to avoid dealing with
  187. // concurrency and mutex overhead.
  188. func (o *PeerManagerOptions) optimize() {
  189. o.persistentPeers = make(map[types.NodeID]bool, len(o.PersistentPeers))
  190. for _, p := range o.PersistentPeers {
  191. o.persistentPeers[p] = true
  192. }
  193. }
  194. // PeerManager manages peer lifecycle information, using a peerStore for
  195. // underlying storage. Its primary purpose is to determine which peer to connect
  196. // to next (including retry timers), make sure a peer only has a single active
  197. // connection (either inbound or outbound), and evict peers to make room for
  198. // higher-scored peers. It does not manage actual connections (this is handled
  199. // by the Router), only the peer lifecycle state.
  200. //
  201. // For an outbound connection, the flow is as follows:
  202. // - DialNext: return a peer address to dial, mark peer as dialing.
  203. // - DialFailed: report a dial failure, unmark as dialing.
  204. // - Dialed: report a dial success, unmark as dialing and mark as connected
  205. // (errors if already connected, e.g. by Accepted).
  206. // - Ready: report routing is ready, mark as ready and broadcast PeerStatusUp.
  207. // - Disconnected: report peer disconnect, unmark as connected and broadcasts
  208. // PeerStatusDown.
  209. //
  210. // For an inbound connection, the flow is as follows:
  211. // - Accepted: report inbound connection success, mark as connected (errors if
  212. // already connected, e.g. by Dialed).
  213. // - Ready: report routing is ready, mark as ready and broadcast PeerStatusUp.
  214. // - Disconnected: report peer disconnect, unmark as connected and broadcasts
  215. // PeerStatusDown.
  216. //
  217. // When evicting peers, either because peers are explicitly scheduled for
  218. // eviction or we are connected to too many peers, the flow is as follows:
  219. // - EvictNext: if marked evict and connected, unmark evict and mark evicting.
  220. // If beyond MaxConnected, pick lowest-scored peer and mark evicting.
  221. // - Disconnected: unmark connected, evicting, evict, and broadcast a
  222. // PeerStatusDown peer update.
  223. //
  224. // If all connection slots are full (at MaxConnections), we can use up to
  225. // MaxConnectionsUpgrade additional connections to probe any higher-scored
  226. // unconnected peers, and if we reach them (or they reach us) we allow the
  227. // connection and evict a lower-scored peer. We mark the lower-scored peer as
  228. // upgrading[from]=to to make sure no other higher-scored peers can claim the
  229. // same one for an upgrade. The flow is as follows:
  230. // - Accepted: if upgrade is possible, mark connected and add lower-scored to evict.
  231. // - DialNext: if upgrade is possible, mark upgrading[from]=to and dialing.
  232. // - DialFailed: unmark upgrading[from]=to and dialing.
  233. // - Dialed: unmark upgrading[from]=to and dialing, mark as connected, add
  234. // lower-scored to evict.
  235. // - EvictNext: pick peer from evict, mark as evicting.
  236. // - Disconnected: unmark connected, upgrading[from]=to, evict, evicting.
  237. type PeerManager struct {
  238. selfID types.NodeID
  239. options PeerManagerOptions
  240. rand *rand.Rand
  241. dialWaker *tmsync.Waker // wakes up DialNext() on relevant peer changes
  242. evictWaker *tmsync.Waker // wakes up EvictNext() on relevant peer changes
  243. closeCh chan struct{} // signal channel for Close()
  244. closeOnce sync.Once
  245. mtx sync.Mutex
  246. store *peerStore
  247. subscriptions map[*PeerUpdates]*PeerUpdates // keyed by struct identity (address)
  248. dialing map[types.NodeID]bool // peers being dialed (DialNext → Dialed/DialFail)
  249. upgrading map[types.NodeID]types.NodeID // peers claimed for upgrade (DialNext → Dialed/DialFail)
  250. connected map[types.NodeID]bool // connected peers (Dialed/Accepted → Disconnected)
  251. ready map[types.NodeID]bool // ready peers (Ready → Disconnected)
  252. evict map[types.NodeID]bool // peers scheduled for eviction (Connected → EvictNext)
  253. evicting map[types.NodeID]bool // peers being evicted (EvictNext → Disconnected)
  254. }
  255. // NewPeerManager creates a new peer manager.
  256. func NewPeerManager(selfID types.NodeID, peerDB dbm.DB, options PeerManagerOptions) (*PeerManager, error) {
  257. if selfID == "" {
  258. return nil, errors.New("self ID not given")
  259. }
  260. if err := options.Validate(); err != nil {
  261. return nil, err
  262. }
  263. options.optimize()
  264. store, err := newPeerStore(peerDB)
  265. if err != nil {
  266. return nil, err
  267. }
  268. peerManager := &PeerManager{
  269. selfID: selfID,
  270. options: options,
  271. rand: rand.New(rand.NewSource(time.Now().UnixNano())), // nolint:gosec
  272. dialWaker: tmsync.NewWaker(),
  273. evictWaker: tmsync.NewWaker(),
  274. closeCh: make(chan struct{}),
  275. store: store,
  276. dialing: map[types.NodeID]bool{},
  277. upgrading: map[types.NodeID]types.NodeID{},
  278. connected: map[types.NodeID]bool{},
  279. ready: map[types.NodeID]bool{},
  280. evict: map[types.NodeID]bool{},
  281. evicting: map[types.NodeID]bool{},
  282. subscriptions: map[*PeerUpdates]*PeerUpdates{},
  283. }
  284. if err = peerManager.configurePeers(); err != nil {
  285. return nil, err
  286. }
  287. if err = peerManager.prunePeers(); err != nil {
  288. return nil, err
  289. }
  290. return peerManager, nil
  291. }
  292. // configurePeers configures peers in the peer store with ephemeral runtime
  293. // configuration, e.g. PersistentPeers. It also removes ourself, if we're in the
  294. // peer store. The caller must hold the mutex lock.
  295. func (m *PeerManager) configurePeers() error {
  296. if err := m.store.Delete(m.selfID); err != nil {
  297. return err
  298. }
  299. configure := map[types.NodeID]bool{}
  300. for _, id := range m.options.PersistentPeers {
  301. configure[id] = true
  302. }
  303. for id := range m.options.PeerScores {
  304. configure[id] = true
  305. }
  306. for id := range configure {
  307. if peer, ok := m.store.Get(id); ok {
  308. if err := m.store.Set(m.configurePeer(peer)); err != nil {
  309. return err
  310. }
  311. }
  312. }
  313. return nil
  314. }
  315. // configurePeer configures a peer with ephemeral runtime configuration.
  316. func (m *PeerManager) configurePeer(peer peerInfo) peerInfo {
  317. peer.Persistent = m.options.isPersistent(peer.ID)
  318. peer.FixedScore = m.options.PeerScores[peer.ID]
  319. return peer
  320. }
  321. // newPeerInfo creates a peerInfo for a new peer.
  322. func (m *PeerManager) newPeerInfo(id types.NodeID) peerInfo {
  323. peerInfo := peerInfo{
  324. ID: id,
  325. AddressInfo: map[NodeAddress]*peerAddressInfo{},
  326. }
  327. return m.configurePeer(peerInfo)
  328. }
  329. // prunePeers removes low-scored peers from the peer store if it contains more
  330. // than MaxPeers peers. The caller must hold the mutex lock.
  331. func (m *PeerManager) prunePeers() error {
  332. if m.options.MaxPeers == 0 || m.store.Size() <= int(m.options.MaxPeers) {
  333. return nil
  334. }
  335. ranked := m.store.Ranked()
  336. for i := len(ranked) - 1; i >= 0; i-- {
  337. peerID := ranked[i].ID
  338. switch {
  339. case m.store.Size() <= int(m.options.MaxPeers):
  340. return nil
  341. case m.dialing[peerID]:
  342. case m.connected[peerID]:
  343. default:
  344. if err := m.store.Delete(peerID); err != nil {
  345. return err
  346. }
  347. }
  348. }
  349. return nil
  350. }
  351. // Add adds a peer to the manager, given as an address. If the peer already
  352. // exists, the address is added to it if it isn't already present. This will push
  353. // low scoring peers out of the address book if it exceeds the maximum size.
  354. func (m *PeerManager) Add(address NodeAddress) (bool, error) {
  355. if err := address.Validate(); err != nil {
  356. return false, err
  357. }
  358. if address.NodeID == m.selfID {
  359. return false, fmt.Errorf("can't add self (%v) to peer store", m.selfID)
  360. }
  361. m.mtx.Lock()
  362. defer m.mtx.Unlock()
  363. peer, ok := m.store.Get(address.NodeID)
  364. if !ok {
  365. peer = m.newPeerInfo(address.NodeID)
  366. }
  367. _, ok = peer.AddressInfo[address]
  368. // if we already have the peer address, there's no need to continue
  369. if ok {
  370. return false, nil
  371. }
  372. // else add the new address
  373. peer.AddressInfo[address] = &peerAddressInfo{Address: address}
  374. if err := m.store.Set(peer); err != nil {
  375. return false, err
  376. }
  377. if err := m.prunePeers(); err != nil {
  378. return true, err
  379. }
  380. m.dialWaker.Wake()
  381. return true, nil
  382. }
  383. // PeerRatio returns the ratio of peer addresses stored to the maximum size.
  384. func (m *PeerManager) PeerRatio() float64 {
  385. m.mtx.Lock()
  386. defer m.mtx.Unlock()
  387. if m.options.MaxPeers == 0 {
  388. return 0
  389. }
  390. return float64(m.store.Size()) / float64(m.options.MaxPeers)
  391. }
  392. // DialNext finds an appropriate peer address to dial, and marks it as dialing.
  393. // If no peer is found, or all connection slots are full, it blocks until one
  394. // becomes available. The caller must call Dialed() or DialFailed() for the
  395. // returned peer.
  396. func (m *PeerManager) DialNext(ctx context.Context) (NodeAddress, error) {
  397. for {
  398. address, err := m.TryDialNext()
  399. if err != nil || (address != NodeAddress{}) {
  400. return address, err
  401. }
  402. select {
  403. case <-m.dialWaker.Sleep():
  404. case <-ctx.Done():
  405. return NodeAddress{}, ctx.Err()
  406. }
  407. }
  408. }
  409. // TryDialNext is equivalent to DialNext(), but immediately returns an empty
  410. // address if no peers or connection slots are available.
  411. func (m *PeerManager) TryDialNext() (NodeAddress, error) {
  412. m.mtx.Lock()
  413. defer m.mtx.Unlock()
  414. // We allow dialing MaxConnected+MaxConnectedUpgrade peers. Including
  415. // MaxConnectedUpgrade allows us to probe additional peers that have a
  416. // higher score than any other peers, and if successful evict it.
  417. if m.options.MaxConnected > 0 && len(m.connected)+len(m.dialing) >=
  418. int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
  419. return NodeAddress{}, nil
  420. }
  421. for _, peer := range m.store.Ranked() {
  422. if m.dialing[peer.ID] || m.connected[peer.ID] {
  423. continue
  424. }
  425. for _, addressInfo := range peer.AddressInfo {
  426. if time.Since(addressInfo.LastDialFailure) < m.retryDelay(addressInfo.DialFailures, peer.Persistent) {
  427. continue
  428. }
  429. // We now have an eligible address to dial. If we're full but have
  430. // upgrade capacity (as checked above), we find a lower-scored peer
  431. // we can replace and mark it as upgrading so noone else claims it.
  432. //
  433. // If we don't find one, there is no point in trying additional
  434. // peers, since they will all have the same or lower score than this
  435. // peer (since they're ordered by score via peerStore.Ranked).
  436. if m.options.MaxConnected > 0 && len(m.connected) >= int(m.options.MaxConnected) {
  437. upgradeFromPeer := m.findUpgradeCandidate(peer.ID, peer.Score())
  438. if upgradeFromPeer == "" {
  439. return NodeAddress{}, nil
  440. }
  441. m.upgrading[upgradeFromPeer] = peer.ID
  442. }
  443. m.dialing[peer.ID] = true
  444. return addressInfo.Address, nil
  445. }
  446. }
  447. return NodeAddress{}, nil
  448. }
  449. // DialFailed reports a failed dial attempt. This will make the peer available
  450. // for dialing again when appropriate (possibly after a retry timeout).
  451. //
  452. // FIXME: This should probably delete or mark bad addresses/peers after some time.
  453. func (m *PeerManager) DialFailed(ctx context.Context, address NodeAddress) error {
  454. m.mtx.Lock()
  455. defer m.mtx.Unlock()
  456. delete(m.dialing, address.NodeID)
  457. for from, to := range m.upgrading {
  458. if to == address.NodeID {
  459. delete(m.upgrading, from) // Unmark failed upgrade attempt.
  460. }
  461. }
  462. peer, ok := m.store.Get(address.NodeID)
  463. if !ok { // Peer may have been removed while dialing, ignore.
  464. return nil
  465. }
  466. addressInfo, ok := peer.AddressInfo[address]
  467. if !ok {
  468. return nil // Assume the address has been removed, ignore.
  469. }
  470. addressInfo.LastDialFailure = time.Now().UTC()
  471. addressInfo.DialFailures++
  472. if err := m.store.Set(peer); err != nil {
  473. return err
  474. }
  475. // We spawn a goroutine that notifies DialNext() again when the retry
  476. // timeout has elapsed, so that we can consider dialing it again. We
  477. // calculate the retry delay outside the goroutine, since it must hold
  478. // the mutex lock.
  479. if d := m.retryDelay(addressInfo.DialFailures, peer.Persistent); d != 0 && d != retryNever {
  480. go func() {
  481. // Use an explicit timer with deferred cleanup instead of
  482. // time.After(), to avoid leaking goroutines on PeerManager.Close().
  483. timer := time.NewTimer(d)
  484. defer timer.Stop()
  485. select {
  486. case <-timer.C:
  487. m.dialWaker.Wake()
  488. case <-m.closeCh:
  489. case <-ctx.Done():
  490. }
  491. }()
  492. } else {
  493. m.dialWaker.Wake()
  494. }
  495. return nil
  496. }
  497. // Dialed marks a peer as successfully dialed. Any further connections will be
  498. // rejected, and once disconnected the peer may be dialed again.
  499. func (m *PeerManager) Dialed(address NodeAddress) error {
  500. m.mtx.Lock()
  501. defer m.mtx.Unlock()
  502. delete(m.dialing, address.NodeID)
  503. var upgradeFromPeer types.NodeID
  504. for from, to := range m.upgrading {
  505. if to == address.NodeID {
  506. delete(m.upgrading, from)
  507. upgradeFromPeer = from
  508. // Don't break, just in case this peer was marked as upgrading for
  509. // multiple lower-scored peers (shouldn't really happen).
  510. }
  511. }
  512. if address.NodeID == m.selfID {
  513. return fmt.Errorf("rejecting connection to self (%v)", address.NodeID)
  514. }
  515. if m.connected[address.NodeID] {
  516. return fmt.Errorf("peer %v is already connected", address.NodeID)
  517. }
  518. if m.options.MaxConnected > 0 && len(m.connected) >= int(m.options.MaxConnected) {
  519. if upgradeFromPeer == "" || len(m.connected) >=
  520. int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
  521. return fmt.Errorf("already connected to maximum number of peers")
  522. }
  523. }
  524. peer, ok := m.store.Get(address.NodeID)
  525. if !ok {
  526. return fmt.Errorf("peer %q was removed while dialing", address.NodeID)
  527. }
  528. now := time.Now().UTC()
  529. peer.LastConnected = now
  530. if addressInfo, ok := peer.AddressInfo[address]; ok {
  531. addressInfo.DialFailures = 0
  532. addressInfo.LastDialSuccess = now
  533. // If not found, assume address has been removed.
  534. }
  535. if err := m.store.Set(peer); err != nil {
  536. return err
  537. }
  538. if upgradeFromPeer != "" && m.options.MaxConnected > 0 &&
  539. len(m.connected) >= int(m.options.MaxConnected) {
  540. // Look for an even lower-scored peer that may have appeared since we
  541. // started the upgrade.
  542. if p, ok := m.store.Get(upgradeFromPeer); ok {
  543. if u := m.findUpgradeCandidate(p.ID, p.Score()); u != "" {
  544. upgradeFromPeer = u
  545. }
  546. }
  547. m.evict[upgradeFromPeer] = true
  548. }
  549. m.connected[peer.ID] = true
  550. m.evictWaker.Wake()
  551. return nil
  552. }
  553. // Accepted marks an incoming peer connection successfully accepted. If the peer
  554. // is already connected or we don't allow additional connections then this will
  555. // return an error.
  556. //
  557. // If full but MaxConnectedUpgrade is non-zero and the incoming peer is
  558. // better-scored than any existing peers, then we accept it and evict a
  559. // lower-scored peer.
  560. //
  561. // NOTE: We can't take an address here, since e.g. TCP uses a different port
  562. // number for outbound traffic than inbound traffic, so the peer's endpoint
  563. // wouldn't necessarily be an appropriate address to dial.
  564. //
  565. // FIXME: When we accept a connection from a peer, we should register that
  566. // peer's address in the peer store so that we can dial it later. In order to do
  567. // that, we'll need to get the remote address after all, but as noted above that
  568. // can't be the remote endpoint since that will usually have the wrong port
  569. // number.
  570. func (m *PeerManager) Accepted(peerID types.NodeID) error {
  571. m.mtx.Lock()
  572. defer m.mtx.Unlock()
  573. if peerID == m.selfID {
  574. return fmt.Errorf("rejecting connection from self (%v)", peerID)
  575. }
  576. if m.connected[peerID] {
  577. return fmt.Errorf("peer %q is already connected", peerID)
  578. }
  579. if m.options.MaxConnected > 0 &&
  580. len(m.connected) >= int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
  581. return fmt.Errorf("already connected to maximum number of peers")
  582. }
  583. peer, ok := m.store.Get(peerID)
  584. if !ok {
  585. peer = m.newPeerInfo(peerID)
  586. }
  587. // reset this to avoid penalizing peers for their past transgressions
  588. for _, addr := range peer.AddressInfo {
  589. addr.DialFailures = 0
  590. }
  591. // If all connections slots are full, but we allow upgrades (and we checked
  592. // above that we have upgrade capacity), then we can look for a lower-scored
  593. // peer to replace and if found accept the connection anyway and evict it.
  594. var upgradeFromPeer types.NodeID
  595. if m.options.MaxConnected > 0 && len(m.connected) >= int(m.options.MaxConnected) {
  596. upgradeFromPeer = m.findUpgradeCandidate(peer.ID, peer.Score())
  597. if upgradeFromPeer == "" {
  598. return fmt.Errorf("already connected to maximum number of peers")
  599. }
  600. }
  601. peer.LastConnected = time.Now().UTC()
  602. if err := m.store.Set(peer); err != nil {
  603. return err
  604. }
  605. m.connected[peerID] = true
  606. if upgradeFromPeer != "" {
  607. m.evict[upgradeFromPeer] = true
  608. }
  609. m.evictWaker.Wake()
  610. return nil
  611. }
  612. // Ready marks a peer as ready, broadcasting status updates to subscribers. The
  613. // peer must already be marked as connected. This is separate from Dialed() and
  614. // Accepted() to allow the router to set up its internal queues before reactors
  615. // start sending messages.
  616. func (m *PeerManager) Ready(peerID types.NodeID) {
  617. m.mtx.Lock()
  618. defer m.mtx.Unlock()
  619. if m.connected[peerID] {
  620. m.ready[peerID] = true
  621. m.broadcast(PeerUpdate{
  622. NodeID: peerID,
  623. Status: PeerStatusUp,
  624. })
  625. }
  626. }
  627. // EvictNext returns the next peer to evict (i.e. disconnect). If no evictable
  628. // peers are found, the call will block until one becomes available.
  629. func (m *PeerManager) EvictNext(ctx context.Context) (types.NodeID, error) {
  630. for {
  631. id, err := m.TryEvictNext()
  632. if err != nil || id != "" {
  633. return id, err
  634. }
  635. select {
  636. case <-m.evictWaker.Sleep():
  637. case <-ctx.Done():
  638. return "", ctx.Err()
  639. }
  640. }
  641. }
  642. // TryEvictNext is equivalent to EvictNext, but immediately returns an empty
  643. // node ID if no evictable peers are found.
  644. func (m *PeerManager) TryEvictNext() (types.NodeID, error) {
  645. m.mtx.Lock()
  646. defer m.mtx.Unlock()
  647. // If any connected peers are explicitly scheduled for eviction, we return a
  648. // random one.
  649. for peerID := range m.evict {
  650. delete(m.evict, peerID)
  651. if m.connected[peerID] && !m.evicting[peerID] {
  652. m.evicting[peerID] = true
  653. return peerID, nil
  654. }
  655. }
  656. // If we're below capacity, we don't need to evict anything.
  657. if m.options.MaxConnected == 0 ||
  658. len(m.connected)-len(m.evicting) <= int(m.options.MaxConnected) {
  659. return "", nil
  660. }
  661. // If we're above capacity (shouldn't really happen), just pick the
  662. // lowest-ranked peer to evict.
  663. ranked := m.store.Ranked()
  664. for i := len(ranked) - 1; i >= 0; i-- {
  665. peer := ranked[i]
  666. if m.connected[peer.ID] && !m.evicting[peer.ID] {
  667. m.evicting[peer.ID] = true
  668. return peer.ID, nil
  669. }
  670. }
  671. return "", nil
  672. }
  673. // Disconnected unmarks a peer as connected, allowing it to be dialed or
  674. // accepted again as appropriate.
  675. func (m *PeerManager) Disconnected(peerID types.NodeID) {
  676. m.mtx.Lock()
  677. defer m.mtx.Unlock()
  678. ready := m.ready[peerID]
  679. delete(m.connected, peerID)
  680. delete(m.upgrading, peerID)
  681. delete(m.evict, peerID)
  682. delete(m.evicting, peerID)
  683. delete(m.ready, peerID)
  684. if ready {
  685. m.broadcast(PeerUpdate{
  686. NodeID: peerID,
  687. Status: PeerStatusDown,
  688. })
  689. }
  690. m.dialWaker.Wake()
  691. }
  692. // Errored reports a peer error, causing the peer to be evicted if it's
  693. // currently connected.
  694. //
  695. // FIXME: This should probably be replaced with a peer behavior API, see
  696. // PeerError comments for more details.
  697. //
  698. // FIXME: This will cause the peer manager to immediately try to reconnect to
  699. // the peer, which is probably not always what we want.
  700. func (m *PeerManager) Errored(peerID types.NodeID, err error) {
  701. m.mtx.Lock()
  702. defer m.mtx.Unlock()
  703. if m.connected[peerID] {
  704. m.evict[peerID] = true
  705. }
  706. m.evictWaker.Wake()
  707. }
  708. // Advertise returns a list of peer addresses to advertise to a peer.
  709. //
  710. // FIXME: This is fairly naïve and only returns the addresses of the
  711. // highest-ranked peers.
  712. func (m *PeerManager) Advertise(peerID types.NodeID, limit uint16) []NodeAddress {
  713. m.mtx.Lock()
  714. defer m.mtx.Unlock()
  715. addresses := make([]NodeAddress, 0, limit)
  716. for _, peer := range m.store.Ranked() {
  717. if peer.ID == peerID {
  718. continue
  719. }
  720. for nodeAddr, addressInfo := range peer.AddressInfo {
  721. if len(addresses) >= int(limit) {
  722. return addresses
  723. }
  724. // only add non-private NodeIDs
  725. if _, ok := m.options.PrivatePeers[nodeAddr.NodeID]; !ok {
  726. addresses = append(addresses, addressInfo.Address)
  727. }
  728. }
  729. }
  730. return addresses
  731. }
  732. // Subscribe subscribes to peer updates. The caller must consume the peer
  733. // updates in a timely fashion and close the subscription when done, otherwise
  734. // the PeerManager will halt.
  735. func (m *PeerManager) Subscribe(ctx context.Context) *PeerUpdates {
  736. // FIXME: We use a size 1 buffer here. When we broadcast a peer update
  737. // we have to loop over all of the subscriptions, and we want to avoid
  738. // having to block and wait for a context switch before continuing on
  739. // to the next subscriptions. This also prevents tail latencies from
  740. // compounding. Limiting it to 1 means that the subscribers are still
  741. // reasonably in sync. However, this should probably be benchmarked.
  742. peerUpdates := NewPeerUpdates(make(chan PeerUpdate, 1), 1)
  743. m.Register(ctx, peerUpdates)
  744. return peerUpdates
  745. }
  746. // Register allows you to inject a custom PeerUpdate instance into the
  747. // PeerManager, rather than relying on the instance constructed by the
  748. // Subscribe method, which wraps the functionality of the Register
  749. // method.
  750. //
  751. // The caller must consume the peer updates from this PeerUpdates
  752. // instance in a timely fashion and close the subscription when done,
  753. // otherwise the PeerManager will halt.
  754. func (m *PeerManager) Register(ctx context.Context, peerUpdates *PeerUpdates) {
  755. m.mtx.Lock()
  756. m.subscriptions[peerUpdates] = peerUpdates
  757. m.mtx.Unlock()
  758. go func() {
  759. for {
  760. select {
  761. case <-peerUpdates.closeCh:
  762. return
  763. case <-m.closeCh:
  764. return
  765. case <-ctx.Done():
  766. return
  767. case pu := <-peerUpdates.routerUpdatesCh:
  768. m.processPeerEvent(pu)
  769. }
  770. }
  771. }()
  772. go func() {
  773. select {
  774. case <-peerUpdates.Done():
  775. m.mtx.Lock()
  776. delete(m.subscriptions, peerUpdates)
  777. m.mtx.Unlock()
  778. case <-m.closeCh:
  779. case <-ctx.Done():
  780. }
  781. }()
  782. }
  783. func (m *PeerManager) processPeerEvent(pu PeerUpdate) {
  784. m.mtx.Lock()
  785. defer m.mtx.Unlock()
  786. if _, ok := m.store.peers[pu.NodeID]; !ok {
  787. m.store.peers[pu.NodeID] = &peerInfo{}
  788. }
  789. switch pu.Status {
  790. case PeerStatusBad:
  791. m.store.peers[pu.NodeID].MutableScore--
  792. case PeerStatusGood:
  793. m.store.peers[pu.NodeID].MutableScore++
  794. }
  795. }
  796. // broadcast broadcasts a peer update to all subscriptions. The caller must
  797. // already hold the mutex lock, to make sure updates are sent in the same order
  798. // as the PeerManager processes them, but this means subscribers must be
  799. // responsive at all times or the entire PeerManager will halt.
  800. //
  801. // FIXME: Consider using an internal channel to buffer updates while also
  802. // maintaining order if this is a problem.
  803. func (m *PeerManager) broadcast(peerUpdate PeerUpdate) {
  804. for _, sub := range m.subscriptions {
  805. // We have to check closeCh separately first, otherwise there's a 50%
  806. // chance the second select will send on a closed subscription.
  807. select {
  808. case <-sub.closeCh:
  809. continue
  810. default:
  811. }
  812. select {
  813. case sub.reactorUpdatesCh <- peerUpdate:
  814. case <-sub.closeCh:
  815. }
  816. }
  817. }
  818. // Close closes the peer manager, releasing resources (i.e. goroutines).
  819. func (m *PeerManager) Close() {
  820. m.closeOnce.Do(func() {
  821. close(m.closeCh)
  822. })
  823. }
  824. // Addresses returns all known addresses for a peer, primarily for testing.
  825. // The order is arbitrary.
  826. func (m *PeerManager) Addresses(peerID types.NodeID) []NodeAddress {
  827. m.mtx.Lock()
  828. defer m.mtx.Unlock()
  829. addresses := []NodeAddress{}
  830. if peer, ok := m.store.Get(peerID); ok {
  831. for _, addressInfo := range peer.AddressInfo {
  832. addresses = append(addresses, addressInfo.Address)
  833. }
  834. }
  835. return addresses
  836. }
  837. // Peers returns all known peers, primarily for testing. The order is arbitrary.
  838. func (m *PeerManager) Peers() []types.NodeID {
  839. m.mtx.Lock()
  840. defer m.mtx.Unlock()
  841. peers := []types.NodeID{}
  842. for _, peer := range m.store.Ranked() {
  843. peers = append(peers, peer.ID)
  844. }
  845. return peers
  846. }
  847. // Scores returns the peer scores for all known peers, primarily for testing.
  848. func (m *PeerManager) Scores() map[types.NodeID]PeerScore {
  849. m.mtx.Lock()
  850. defer m.mtx.Unlock()
  851. scores := map[types.NodeID]PeerScore{}
  852. for _, peer := range m.store.Ranked() {
  853. scores[peer.ID] = peer.Score()
  854. }
  855. return scores
  856. }
  857. // Status returns the status for a peer, primarily for testing.
  858. func (m *PeerManager) Status(id types.NodeID) PeerStatus {
  859. m.mtx.Lock()
  860. defer m.mtx.Unlock()
  861. switch {
  862. case m.ready[id]:
  863. return PeerStatusUp
  864. default:
  865. return PeerStatusDown
  866. }
  867. }
  868. // findUpgradeCandidate looks for a lower-scored peer that we could evict
  869. // to make room for the given peer. Returns an empty ID if none is found.
  870. // If the peer is already being upgraded to, we return that same upgrade.
  871. // The caller must hold the mutex lock.
  872. func (m *PeerManager) findUpgradeCandidate(id types.NodeID, score PeerScore) types.NodeID {
  873. for from, to := range m.upgrading {
  874. if to == id {
  875. return from
  876. }
  877. }
  878. ranked := m.store.Ranked()
  879. for i := len(ranked) - 1; i >= 0; i-- {
  880. candidate := ranked[i]
  881. switch {
  882. case candidate.Score() >= score:
  883. return "" // no further peers can be scored lower, due to sorting
  884. case !m.connected[candidate.ID]:
  885. case m.evict[candidate.ID]:
  886. case m.evicting[candidate.ID]:
  887. case m.upgrading[candidate.ID] != "":
  888. default:
  889. return candidate.ID
  890. }
  891. }
  892. return ""
  893. }
  894. // retryDelay calculates a dial retry delay using exponential backoff, based on
  895. // retry settings in PeerManagerOptions. If retries are disabled (i.e.
  896. // MinRetryTime is 0), this returns retryNever (i.e. an infinite retry delay).
  897. // The caller must hold the mutex lock (for m.rand which is not thread-safe).
  898. func (m *PeerManager) retryDelay(failures uint32, persistent bool) time.Duration {
  899. if failures == 0 {
  900. return 0
  901. }
  902. if m.options.MinRetryTime == 0 {
  903. return retryNever
  904. }
  905. maxDelay := m.options.MaxRetryTime
  906. if persistent && m.options.MaxRetryTimePersistent > 0 {
  907. maxDelay = m.options.MaxRetryTimePersistent
  908. }
  909. delay := m.options.MinRetryTime * time.Duration(math.Pow(2, float64(failures-1)))
  910. if maxDelay > 0 && delay > maxDelay {
  911. delay = maxDelay
  912. }
  913. if m.options.RetryTimeJitter > 0 {
  914. delay += time.Duration(m.rand.Int63n(int64(m.options.RetryTimeJitter)))
  915. }
  916. return delay
  917. }
  918. // GetHeight returns a peer's height, as reported via SetHeight, or 0 if the
  919. // peer or height is unknown.
  920. //
  921. // FIXME: This is a temporary workaround to share state between the consensus
  922. // and mempool reactors, carried over from the legacy P2P stack. Reactors should
  923. // not have dependencies on each other, instead tracking this themselves.
  924. func (m *PeerManager) GetHeight(peerID types.NodeID) int64 {
  925. m.mtx.Lock()
  926. defer m.mtx.Unlock()
  927. peer, _ := m.store.Get(peerID)
  928. return peer.Height
  929. }
  930. // SetHeight stores a peer's height, making it available via GetHeight.
  931. //
  932. // FIXME: This is a temporary workaround to share state between the consensus
  933. // and mempool reactors, carried over from the legacy P2P stack. Reactors should
  934. // not have dependencies on each other, instead tracking this themselves.
  935. func (m *PeerManager) SetHeight(peerID types.NodeID, height int64) error {
  936. m.mtx.Lock()
  937. defer m.mtx.Unlock()
  938. peer, ok := m.store.Get(peerID)
  939. if !ok {
  940. peer = m.newPeerInfo(peerID)
  941. }
  942. peer.Height = height
  943. return m.store.Set(peer)
  944. }
  945. // peerStore stores information about peers. It is not thread-safe, assuming it
  946. // is only used by PeerManager which handles concurrency control. This allows
  947. // the manager to execute multiple operations atomically via its own mutex.
  948. //
  949. // The entire set of peers is kept in memory, for performance. It is loaded
  950. // from disk on initialization, and any changes are written back to disk
  951. // (without fsync, since we can afford to lose recent writes).
  952. type peerStore struct {
  953. db dbm.DB
  954. peers map[types.NodeID]*peerInfo
  955. ranked []*peerInfo // cache for Ranked(), nil invalidates cache
  956. }
  957. // newPeerStore creates a new peer store, loading all persisted peers from the
  958. // database into memory.
  959. func newPeerStore(db dbm.DB) (*peerStore, error) {
  960. if db == nil {
  961. return nil, errors.New("no database provided")
  962. }
  963. store := &peerStore{db: db}
  964. if err := store.loadPeers(); err != nil {
  965. return nil, err
  966. }
  967. return store, nil
  968. }
  969. // loadPeers loads all peers from the database into memory.
  970. func (s *peerStore) loadPeers() error {
  971. peers := map[types.NodeID]*peerInfo{}
  972. start, end := keyPeerInfoRange()
  973. iter, err := s.db.Iterator(start, end)
  974. if err != nil {
  975. return err
  976. }
  977. defer iter.Close()
  978. for ; iter.Valid(); iter.Next() {
  979. // FIXME: We may want to tolerate failures here, by simply logging
  980. // the errors and ignoring the faulty peer entries.
  981. msg := new(p2pproto.PeerInfo)
  982. if err := proto.Unmarshal(iter.Value(), msg); err != nil {
  983. return fmt.Errorf("invalid peer Protobuf data: %w", err)
  984. }
  985. peer, err := peerInfoFromProto(msg)
  986. if err != nil {
  987. return fmt.Errorf("invalid peer data: %w", err)
  988. }
  989. peers[peer.ID] = peer
  990. }
  991. if iter.Error() != nil {
  992. return iter.Error()
  993. }
  994. s.peers = peers
  995. s.ranked = nil // invalidate cache if populated
  996. return nil
  997. }
  998. // Get fetches a peer. The boolean indicates whether the peer existed or not.
  999. // The returned peer info is a copy, and can be mutated at will.
  1000. func (s *peerStore) Get(id types.NodeID) (peerInfo, bool) {
  1001. peer, ok := s.peers[id]
  1002. return peer.Copy(), ok
  1003. }
  1004. // Set stores peer data. The input data will be copied, and can safely be reused
  1005. // by the caller.
  1006. func (s *peerStore) Set(peer peerInfo) error {
  1007. if err := peer.Validate(); err != nil {
  1008. return err
  1009. }
  1010. peer = peer.Copy()
  1011. // FIXME: We may want to optimize this by avoiding saving to the database
  1012. // if there haven't been any changes to persisted fields.
  1013. bz, err := peer.ToProto().Marshal()
  1014. if err != nil {
  1015. return err
  1016. }
  1017. if err = s.db.Set(keyPeerInfo(peer.ID), bz); err != nil {
  1018. return err
  1019. }
  1020. if current, ok := s.peers[peer.ID]; !ok || current.Score() != peer.Score() {
  1021. // If the peer is new, or its score changes, we invalidate the Ranked() cache.
  1022. s.peers[peer.ID] = &peer
  1023. s.ranked = nil
  1024. } else {
  1025. // Otherwise, since s.ranked contains pointers to the old data and we
  1026. // want those pointers to remain valid with the new data, we have to
  1027. // update the existing pointer address.
  1028. *current = peer
  1029. }
  1030. return nil
  1031. }
  1032. // Delete deletes a peer, or does nothing if it does not exist.
  1033. func (s *peerStore) Delete(id types.NodeID) error {
  1034. if _, ok := s.peers[id]; !ok {
  1035. return nil
  1036. }
  1037. if err := s.db.Delete(keyPeerInfo(id)); err != nil {
  1038. return err
  1039. }
  1040. delete(s.peers, id)
  1041. s.ranked = nil
  1042. return nil
  1043. }
  1044. // List retrieves all peers in an arbitrary order. The returned data is a copy,
  1045. // and can be mutated at will.
  1046. func (s *peerStore) List() []peerInfo {
  1047. peers := make([]peerInfo, 0, len(s.peers))
  1048. for _, peer := range s.peers {
  1049. peers = append(peers, peer.Copy())
  1050. }
  1051. return peers
  1052. }
  1053. // Ranked returns a list of peers ordered by score (better peers first). Peers
  1054. // with equal scores are returned in an arbitrary order. The returned list must
  1055. // not be mutated or accessed concurrently by the caller, since it returns
  1056. // pointers to internal peerStore data for performance.
  1057. //
  1058. // Ranked is used to determine both which peers to dial, which ones to evict,
  1059. // and which ones to delete completely.
  1060. //
  1061. // FIXME: For now, we simply maintain a cache in s.ranked which is invalidated
  1062. // by setting it to nil, but if necessary we should use a better data structure
  1063. // for this (e.g. a heap or ordered map).
  1064. //
  1065. // FIXME: The scoring logic is currently very naïve, see peerInfo.Score().
  1066. func (s *peerStore) Ranked() []*peerInfo {
  1067. if s.ranked != nil {
  1068. return s.ranked
  1069. }
  1070. s.ranked = make([]*peerInfo, 0, len(s.peers))
  1071. for _, peer := range s.peers {
  1072. s.ranked = append(s.ranked, peer)
  1073. }
  1074. sort.Slice(s.ranked, func(i, j int) bool {
  1075. // FIXME: If necessary, consider precomputing scores before sorting,
  1076. // to reduce the number of Score() calls.
  1077. return s.ranked[i].Score() > s.ranked[j].Score()
  1078. })
  1079. return s.ranked
  1080. }
  1081. // Size returns the number of peers in the peer store.
  1082. func (s *peerStore) Size() int {
  1083. return len(s.peers)
  1084. }
  1085. // peerInfo contains peer information stored in a peerStore.
  1086. type peerInfo struct {
  1087. ID types.NodeID
  1088. AddressInfo map[NodeAddress]*peerAddressInfo
  1089. LastConnected time.Time
  1090. // These fields are ephemeral, i.e. not persisted to the database.
  1091. Persistent bool
  1092. Height int64
  1093. FixedScore PeerScore // mainly for tests
  1094. MutableScore int64 // updated by router
  1095. }
  1096. // peerInfoFromProto converts a Protobuf PeerInfo message to a peerInfo,
  1097. // erroring if the data is invalid.
  1098. func peerInfoFromProto(msg *p2pproto.PeerInfo) (*peerInfo, error) {
  1099. p := &peerInfo{
  1100. ID: types.NodeID(msg.ID),
  1101. AddressInfo: map[NodeAddress]*peerAddressInfo{},
  1102. }
  1103. if msg.LastConnected != nil {
  1104. p.LastConnected = *msg.LastConnected
  1105. }
  1106. for _, a := range msg.AddressInfo {
  1107. addressInfo, err := peerAddressInfoFromProto(a)
  1108. if err != nil {
  1109. return nil, err
  1110. }
  1111. p.AddressInfo[addressInfo.Address] = addressInfo
  1112. }
  1113. return p, p.Validate()
  1114. }
  1115. // ToProto converts the peerInfo to p2pproto.PeerInfo for database storage. The
  1116. // Protobuf type only contains persisted fields, while ephemeral fields are
  1117. // discarded. The returned message may contain pointers to original data, since
  1118. // it is expected to be serialized immediately.
  1119. func (p *peerInfo) ToProto() *p2pproto.PeerInfo {
  1120. msg := &p2pproto.PeerInfo{
  1121. ID: string(p.ID),
  1122. LastConnected: &p.LastConnected,
  1123. }
  1124. for _, addressInfo := range p.AddressInfo {
  1125. msg.AddressInfo = append(msg.AddressInfo, addressInfo.ToProto())
  1126. }
  1127. if msg.LastConnected.IsZero() {
  1128. msg.LastConnected = nil
  1129. }
  1130. return msg
  1131. }
  1132. // Copy returns a deep copy of the peer info.
  1133. func (p *peerInfo) Copy() peerInfo {
  1134. if p == nil {
  1135. return peerInfo{}
  1136. }
  1137. c := *p
  1138. for i, addressInfo := range c.AddressInfo {
  1139. addressInfoCopy := addressInfo.Copy()
  1140. c.AddressInfo[i] = &addressInfoCopy
  1141. }
  1142. return c
  1143. }
  1144. // Score calculates a score for the peer. Higher-scored peers will be
  1145. // preferred over lower scores.
  1146. func (p *peerInfo) Score() PeerScore {
  1147. if p.FixedScore > 0 {
  1148. return p.FixedScore
  1149. }
  1150. if p.Persistent {
  1151. return PeerScorePersistent
  1152. }
  1153. score := p.MutableScore
  1154. for _, addr := range p.AddressInfo {
  1155. // DialFailures is reset when dials succeed, so this
  1156. // is either the number of dial failures or 0.
  1157. score -= int64(addr.DialFailures)
  1158. }
  1159. if score <= 0 {
  1160. return 0
  1161. }
  1162. if score >= math.MaxUint8 {
  1163. return PeerScore(math.MaxUint8)
  1164. }
  1165. return PeerScore(score)
  1166. }
  1167. // Validate validates the peer info.
  1168. func (p *peerInfo) Validate() error {
  1169. if p.ID == "" {
  1170. return errors.New("no peer ID")
  1171. }
  1172. return nil
  1173. }
  1174. // peerAddressInfo contains information and statistics about a peer address.
  1175. type peerAddressInfo struct {
  1176. Address NodeAddress
  1177. LastDialSuccess time.Time
  1178. LastDialFailure time.Time
  1179. DialFailures uint32 // since last successful dial
  1180. }
  1181. // peerAddressInfoFromProto converts a Protobuf PeerAddressInfo message
  1182. // to a peerAddressInfo.
  1183. func peerAddressInfoFromProto(msg *p2pproto.PeerAddressInfo) (*peerAddressInfo, error) {
  1184. address, err := ParseNodeAddress(msg.Address)
  1185. if err != nil {
  1186. return nil, fmt.Errorf("invalid address %q: %w", address, err)
  1187. }
  1188. addressInfo := &peerAddressInfo{
  1189. Address: address,
  1190. DialFailures: msg.DialFailures,
  1191. }
  1192. if msg.LastDialSuccess != nil {
  1193. addressInfo.LastDialSuccess = *msg.LastDialSuccess
  1194. }
  1195. if msg.LastDialFailure != nil {
  1196. addressInfo.LastDialFailure = *msg.LastDialFailure
  1197. }
  1198. return addressInfo, addressInfo.Validate()
  1199. }
  1200. // ToProto converts the address into to a Protobuf message for serialization.
  1201. func (a *peerAddressInfo) ToProto() *p2pproto.PeerAddressInfo {
  1202. msg := &p2pproto.PeerAddressInfo{
  1203. Address: a.Address.String(),
  1204. LastDialSuccess: &a.LastDialSuccess,
  1205. LastDialFailure: &a.LastDialFailure,
  1206. DialFailures: a.DialFailures,
  1207. }
  1208. if msg.LastDialSuccess.IsZero() {
  1209. msg.LastDialSuccess = nil
  1210. }
  1211. if msg.LastDialFailure.IsZero() {
  1212. msg.LastDialFailure = nil
  1213. }
  1214. return msg
  1215. }
  1216. // Copy returns a copy of the address info.
  1217. func (a *peerAddressInfo) Copy() peerAddressInfo {
  1218. return *a
  1219. }
  1220. // Validate validates the address info.
  1221. func (a *peerAddressInfo) Validate() error {
  1222. return a.Address.Validate()
  1223. }
  1224. // Database key prefixes.
  1225. const (
  1226. prefixPeerInfo int64 = 1
  1227. )
  1228. // keyPeerInfo generates a peerInfo database key.
  1229. func keyPeerInfo(id types.NodeID) []byte {
  1230. key, err := orderedcode.Append(nil, prefixPeerInfo, string(id))
  1231. if err != nil {
  1232. panic(err)
  1233. }
  1234. return key
  1235. }
  1236. // keyPeerInfoRange generates start/end keys for the entire peerInfo key range.
  1237. func keyPeerInfoRange() ([]byte, []byte) {
  1238. start, err := orderedcode.Append(nil, prefixPeerInfo, "")
  1239. if err != nil {
  1240. panic(err)
  1241. }
  1242. end, err := orderedcode.Append(nil, prefixPeerInfo, orderedcode.Infinity)
  1243. if err != nil {
  1244. panic(err)
  1245. }
  1246. return start, end
  1247. }