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.

1404 lines
42 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(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. }
  490. }()
  491. } else {
  492. m.dialWaker.Wake()
  493. }
  494. return nil
  495. }
  496. // Dialed marks a peer as successfully dialed. Any further connections will be
  497. // rejected, and once disconnected the peer may be dialed again.
  498. func (m *PeerManager) Dialed(address NodeAddress) error {
  499. m.mtx.Lock()
  500. defer m.mtx.Unlock()
  501. delete(m.dialing, address.NodeID)
  502. var upgradeFromPeer types.NodeID
  503. for from, to := range m.upgrading {
  504. if to == address.NodeID {
  505. delete(m.upgrading, from)
  506. upgradeFromPeer = from
  507. // Don't break, just in case this peer was marked as upgrading for
  508. // multiple lower-scored peers (shouldn't really happen).
  509. }
  510. }
  511. if address.NodeID == m.selfID {
  512. return fmt.Errorf("rejecting connection to self (%v)", address.NodeID)
  513. }
  514. if m.connected[address.NodeID] {
  515. return fmt.Errorf("peer %v is already connected", address.NodeID)
  516. }
  517. if m.options.MaxConnected > 0 && len(m.connected) >= int(m.options.MaxConnected) {
  518. if upgradeFromPeer == "" || len(m.connected) >=
  519. int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
  520. return fmt.Errorf("already connected to maximum number of peers")
  521. }
  522. }
  523. peer, ok := m.store.Get(address.NodeID)
  524. if !ok {
  525. return fmt.Errorf("peer %q was removed while dialing", address.NodeID)
  526. }
  527. now := time.Now().UTC()
  528. peer.LastConnected = now
  529. if addressInfo, ok := peer.AddressInfo[address]; ok {
  530. addressInfo.DialFailures = 0
  531. addressInfo.LastDialSuccess = now
  532. // If not found, assume address has been removed.
  533. }
  534. if err := m.store.Set(peer); err != nil {
  535. return err
  536. }
  537. if upgradeFromPeer != "" && m.options.MaxConnected > 0 &&
  538. len(m.connected) >= int(m.options.MaxConnected) {
  539. // Look for an even lower-scored peer that may have appeared since we
  540. // started the upgrade.
  541. if p, ok := m.store.Get(upgradeFromPeer); ok {
  542. if u := m.findUpgradeCandidate(p.ID, p.Score()); u != "" {
  543. upgradeFromPeer = u
  544. }
  545. }
  546. m.evict[upgradeFromPeer] = true
  547. }
  548. m.connected[peer.ID] = true
  549. m.evictWaker.Wake()
  550. return nil
  551. }
  552. // Accepted marks an incoming peer connection successfully accepted. If the peer
  553. // is already connected or we don't allow additional connections then this will
  554. // return an error.
  555. //
  556. // If full but MaxConnectedUpgrade is non-zero and the incoming peer is
  557. // better-scored than any existing peers, then we accept it and evict a
  558. // lower-scored peer.
  559. //
  560. // NOTE: We can't take an address here, since e.g. TCP uses a different port
  561. // number for outbound traffic than inbound traffic, so the peer's endpoint
  562. // wouldn't necessarily be an appropriate address to dial.
  563. //
  564. // FIXME: When we accept a connection from a peer, we should register that
  565. // peer's address in the peer store so that we can dial it later. In order to do
  566. // that, we'll need to get the remote address after all, but as noted above that
  567. // can't be the remote endpoint since that will usually have the wrong port
  568. // number.
  569. func (m *PeerManager) Accepted(peerID types.NodeID) error {
  570. m.mtx.Lock()
  571. defer m.mtx.Unlock()
  572. if peerID == m.selfID {
  573. return fmt.Errorf("rejecting connection from self (%v)", peerID)
  574. }
  575. if m.connected[peerID] {
  576. return fmt.Errorf("peer %q is already connected", peerID)
  577. }
  578. if m.options.MaxConnected > 0 &&
  579. len(m.connected) >= int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
  580. return fmt.Errorf("already connected to maximum number of peers")
  581. }
  582. peer, ok := m.store.Get(peerID)
  583. if !ok {
  584. peer = m.newPeerInfo(peerID)
  585. }
  586. // reset this to avoid penalizing peers for their past transgressions
  587. for _, addr := range peer.AddressInfo {
  588. addr.DialFailures = 0
  589. }
  590. // If all connections slots are full, but we allow upgrades (and we checked
  591. // above that we have upgrade capacity), then we can look for a lower-scored
  592. // peer to replace and if found accept the connection anyway and evict it.
  593. var upgradeFromPeer types.NodeID
  594. if m.options.MaxConnected > 0 && len(m.connected) >= int(m.options.MaxConnected) {
  595. upgradeFromPeer = m.findUpgradeCandidate(peer.ID, peer.Score())
  596. if upgradeFromPeer == "" {
  597. return fmt.Errorf("already connected to maximum number of peers")
  598. }
  599. }
  600. peer.LastConnected = time.Now().UTC()
  601. if err := m.store.Set(peer); err != nil {
  602. return err
  603. }
  604. m.connected[peerID] = true
  605. if upgradeFromPeer != "" {
  606. m.evict[upgradeFromPeer] = true
  607. }
  608. m.evictWaker.Wake()
  609. return nil
  610. }
  611. // Ready marks a peer as ready, broadcasting status updates to subscribers. The
  612. // peer must already be marked as connected. This is separate from Dialed() and
  613. // Accepted() to allow the router to set up its internal queues before reactors
  614. // start sending messages.
  615. func (m *PeerManager) Ready(peerID types.NodeID) {
  616. m.mtx.Lock()
  617. defer m.mtx.Unlock()
  618. if m.connected[peerID] {
  619. m.ready[peerID] = true
  620. m.broadcast(PeerUpdate{
  621. NodeID: peerID,
  622. Status: PeerStatusUp,
  623. })
  624. }
  625. }
  626. // EvictNext returns the next peer to evict (i.e. disconnect). If no evictable
  627. // peers are found, the call will block until one becomes available.
  628. func (m *PeerManager) EvictNext(ctx context.Context) (types.NodeID, error) {
  629. for {
  630. id, err := m.TryEvictNext()
  631. if err != nil || id != "" {
  632. return id, err
  633. }
  634. select {
  635. case <-m.evictWaker.Sleep():
  636. case <-ctx.Done():
  637. return "", ctx.Err()
  638. }
  639. }
  640. }
  641. // TryEvictNext is equivalent to EvictNext, but immediately returns an empty
  642. // node ID if no evictable peers are found.
  643. func (m *PeerManager) TryEvictNext() (types.NodeID, error) {
  644. m.mtx.Lock()
  645. defer m.mtx.Unlock()
  646. // If any connected peers are explicitly scheduled for eviction, we return a
  647. // random one.
  648. for peerID := range m.evict {
  649. delete(m.evict, peerID)
  650. if m.connected[peerID] && !m.evicting[peerID] {
  651. m.evicting[peerID] = true
  652. return peerID, nil
  653. }
  654. }
  655. // If we're below capacity, we don't need to evict anything.
  656. if m.options.MaxConnected == 0 ||
  657. len(m.connected)-len(m.evicting) <= int(m.options.MaxConnected) {
  658. return "", nil
  659. }
  660. // If we're above capacity (shouldn't really happen), just pick the
  661. // lowest-ranked peer to evict.
  662. ranked := m.store.Ranked()
  663. for i := len(ranked) - 1; i >= 0; i-- {
  664. peer := ranked[i]
  665. if m.connected[peer.ID] && !m.evicting[peer.ID] {
  666. m.evicting[peer.ID] = true
  667. return peer.ID, nil
  668. }
  669. }
  670. return "", nil
  671. }
  672. // Disconnected unmarks a peer as connected, allowing it to be dialed or
  673. // accepted again as appropriate.
  674. func (m *PeerManager) Disconnected(peerID types.NodeID) {
  675. m.mtx.Lock()
  676. defer m.mtx.Unlock()
  677. ready := m.ready[peerID]
  678. delete(m.connected, peerID)
  679. delete(m.upgrading, peerID)
  680. delete(m.evict, peerID)
  681. delete(m.evicting, peerID)
  682. delete(m.ready, peerID)
  683. if ready {
  684. m.broadcast(PeerUpdate{
  685. NodeID: peerID,
  686. Status: PeerStatusDown,
  687. })
  688. }
  689. m.dialWaker.Wake()
  690. }
  691. // Errored reports a peer error, causing the peer to be evicted if it's
  692. // currently connected.
  693. //
  694. // FIXME: This should probably be replaced with a peer behavior API, see
  695. // PeerError comments for more details.
  696. //
  697. // FIXME: This will cause the peer manager to immediately try to reconnect to
  698. // the peer, which is probably not always what we want.
  699. func (m *PeerManager) Errored(peerID types.NodeID, err error) {
  700. m.mtx.Lock()
  701. defer m.mtx.Unlock()
  702. if m.connected[peerID] {
  703. m.evict[peerID] = true
  704. }
  705. m.evictWaker.Wake()
  706. }
  707. // Advertise returns a list of peer addresses to advertise to a peer.
  708. //
  709. // FIXME: This is fairly naïve and only returns the addresses of the
  710. // highest-ranked peers.
  711. func (m *PeerManager) Advertise(peerID types.NodeID, limit uint16) []NodeAddress {
  712. m.mtx.Lock()
  713. defer m.mtx.Unlock()
  714. addresses := make([]NodeAddress, 0, limit)
  715. for _, peer := range m.store.Ranked() {
  716. if peer.ID == peerID {
  717. continue
  718. }
  719. for nodeAddr, addressInfo := range peer.AddressInfo {
  720. if len(addresses) >= int(limit) {
  721. return addresses
  722. }
  723. // only add non-private NodeIDs
  724. if _, ok := m.options.PrivatePeers[nodeAddr.NodeID]; !ok {
  725. addresses = append(addresses, addressInfo.Address)
  726. }
  727. }
  728. }
  729. return addresses
  730. }
  731. // Subscribe subscribes to peer updates. The caller must consume the peer
  732. // updates in a timely fashion and close the subscription when done, otherwise
  733. // the PeerManager will halt.
  734. func (m *PeerManager) Subscribe() *PeerUpdates {
  735. // FIXME: We use a size 1 buffer here. When we broadcast a peer update
  736. // we have to loop over all of the subscriptions, and we want to avoid
  737. // having to block and wait for a context switch before continuing on
  738. // to the next subscriptions. This also prevents tail latencies from
  739. // compounding. Limiting it to 1 means that the subscribers are still
  740. // reasonably in sync. However, this should probably be benchmarked.
  741. peerUpdates := NewPeerUpdates(make(chan PeerUpdate, 1), 1)
  742. m.Register(peerUpdates)
  743. return peerUpdates
  744. }
  745. // Register allows you to inject a custom PeerUpdate instance into the
  746. // PeerManager, rather than relying on the instance constructed by the
  747. // Subscribe method, which wraps the functionality of the Register
  748. // method.
  749. //
  750. // The caller must consume the peer updates from this PeerUpdates
  751. // instance in a timely fashion and close the subscription when done,
  752. // otherwise the PeerManager will halt.
  753. func (m *PeerManager) Register(peerUpdates *PeerUpdates) {
  754. m.mtx.Lock()
  755. m.subscriptions[peerUpdates] = peerUpdates
  756. m.mtx.Unlock()
  757. go func() {
  758. for {
  759. select {
  760. case <-peerUpdates.closeCh:
  761. return
  762. case <-m.closeCh:
  763. return
  764. case pu := <-peerUpdates.routerUpdatesCh:
  765. m.processPeerEvent(pu)
  766. }
  767. }
  768. }()
  769. go func() {
  770. select {
  771. case <-peerUpdates.Done():
  772. m.mtx.Lock()
  773. delete(m.subscriptions, peerUpdates)
  774. m.mtx.Unlock()
  775. case <-m.closeCh:
  776. }
  777. }()
  778. }
  779. func (m *PeerManager) processPeerEvent(pu PeerUpdate) {
  780. m.mtx.Lock()
  781. defer m.mtx.Unlock()
  782. if _, ok := m.store.peers[pu.NodeID]; !ok {
  783. m.store.peers[pu.NodeID] = &peerInfo{}
  784. }
  785. switch pu.Status {
  786. case PeerStatusBad:
  787. m.store.peers[pu.NodeID].MutableScore--
  788. case PeerStatusGood:
  789. m.store.peers[pu.NodeID].MutableScore++
  790. }
  791. }
  792. // broadcast broadcasts a peer update to all subscriptions. The caller must
  793. // already hold the mutex lock, to make sure updates are sent in the same order
  794. // as the PeerManager processes them, but this means subscribers must be
  795. // responsive at all times or the entire PeerManager will halt.
  796. //
  797. // FIXME: Consider using an internal channel to buffer updates while also
  798. // maintaining order if this is a problem.
  799. func (m *PeerManager) broadcast(peerUpdate PeerUpdate) {
  800. for _, sub := range m.subscriptions {
  801. // We have to check closeCh separately first, otherwise there's a 50%
  802. // chance the second select will send on a closed subscription.
  803. select {
  804. case <-sub.closeCh:
  805. continue
  806. default:
  807. }
  808. select {
  809. case sub.reactorUpdatesCh <- peerUpdate:
  810. case <-sub.closeCh:
  811. }
  812. }
  813. }
  814. // Close closes the peer manager, releasing resources (i.e. goroutines).
  815. func (m *PeerManager) Close() {
  816. m.closeOnce.Do(func() {
  817. close(m.closeCh)
  818. })
  819. }
  820. // Addresses returns all known addresses for a peer, primarily for testing.
  821. // The order is arbitrary.
  822. func (m *PeerManager) Addresses(peerID types.NodeID) []NodeAddress {
  823. m.mtx.Lock()
  824. defer m.mtx.Unlock()
  825. addresses := []NodeAddress{}
  826. if peer, ok := m.store.Get(peerID); ok {
  827. for _, addressInfo := range peer.AddressInfo {
  828. addresses = append(addresses, addressInfo.Address)
  829. }
  830. }
  831. return addresses
  832. }
  833. // Peers returns all known peers, primarily for testing. The order is arbitrary.
  834. func (m *PeerManager) Peers() []types.NodeID {
  835. m.mtx.Lock()
  836. defer m.mtx.Unlock()
  837. peers := []types.NodeID{}
  838. for _, peer := range m.store.Ranked() {
  839. peers = append(peers, peer.ID)
  840. }
  841. return peers
  842. }
  843. // Scores returns the peer scores for all known peers, primarily for testing.
  844. func (m *PeerManager) Scores() map[types.NodeID]PeerScore {
  845. m.mtx.Lock()
  846. defer m.mtx.Unlock()
  847. scores := map[types.NodeID]PeerScore{}
  848. for _, peer := range m.store.Ranked() {
  849. scores[peer.ID] = peer.Score()
  850. }
  851. return scores
  852. }
  853. // Status returns the status for a peer, primarily for testing.
  854. func (m *PeerManager) Status(id types.NodeID) PeerStatus {
  855. m.mtx.Lock()
  856. defer m.mtx.Unlock()
  857. switch {
  858. case m.ready[id]:
  859. return PeerStatusUp
  860. default:
  861. return PeerStatusDown
  862. }
  863. }
  864. // findUpgradeCandidate looks for a lower-scored peer that we could evict
  865. // to make room for the given peer. Returns an empty ID if none is found.
  866. // If the peer is already being upgraded to, we return that same upgrade.
  867. // The caller must hold the mutex lock.
  868. func (m *PeerManager) findUpgradeCandidate(id types.NodeID, score PeerScore) types.NodeID {
  869. for from, to := range m.upgrading {
  870. if to == id {
  871. return from
  872. }
  873. }
  874. ranked := m.store.Ranked()
  875. for i := len(ranked) - 1; i >= 0; i-- {
  876. candidate := ranked[i]
  877. switch {
  878. case candidate.Score() >= score:
  879. return "" // no further peers can be scored lower, due to sorting
  880. case !m.connected[candidate.ID]:
  881. case m.evict[candidate.ID]:
  882. case m.evicting[candidate.ID]:
  883. case m.upgrading[candidate.ID] != "":
  884. default:
  885. return candidate.ID
  886. }
  887. }
  888. return ""
  889. }
  890. // retryDelay calculates a dial retry delay using exponential backoff, based on
  891. // retry settings in PeerManagerOptions. If retries are disabled (i.e.
  892. // MinRetryTime is 0), this returns retryNever (i.e. an infinite retry delay).
  893. // The caller must hold the mutex lock (for m.rand which is not thread-safe).
  894. func (m *PeerManager) retryDelay(failures uint32, persistent bool) time.Duration {
  895. if failures == 0 {
  896. return 0
  897. }
  898. if m.options.MinRetryTime == 0 {
  899. return retryNever
  900. }
  901. maxDelay := m.options.MaxRetryTime
  902. if persistent && m.options.MaxRetryTimePersistent > 0 {
  903. maxDelay = m.options.MaxRetryTimePersistent
  904. }
  905. delay := m.options.MinRetryTime * time.Duration(math.Pow(2, float64(failures-1)))
  906. if maxDelay > 0 && delay > maxDelay {
  907. delay = maxDelay
  908. }
  909. if m.options.RetryTimeJitter > 0 {
  910. delay += time.Duration(m.rand.Int63n(int64(m.options.RetryTimeJitter)))
  911. }
  912. return delay
  913. }
  914. // GetHeight returns a peer's height, as reported via SetHeight, or 0 if the
  915. // peer or height is unknown.
  916. //
  917. // FIXME: This is a temporary workaround to share state between the consensus
  918. // and mempool reactors, carried over from the legacy P2P stack. Reactors should
  919. // not have dependencies on each other, instead tracking this themselves.
  920. func (m *PeerManager) GetHeight(peerID types.NodeID) int64 {
  921. m.mtx.Lock()
  922. defer m.mtx.Unlock()
  923. peer, _ := m.store.Get(peerID)
  924. return peer.Height
  925. }
  926. // SetHeight stores a peer's height, making it available via GetHeight.
  927. //
  928. // FIXME: This is a temporary workaround to share state between the consensus
  929. // and mempool reactors, carried over from the legacy P2P stack. Reactors should
  930. // not have dependencies on each other, instead tracking this themselves.
  931. func (m *PeerManager) SetHeight(peerID types.NodeID, height int64) error {
  932. m.mtx.Lock()
  933. defer m.mtx.Unlock()
  934. peer, ok := m.store.Get(peerID)
  935. if !ok {
  936. peer = m.newPeerInfo(peerID)
  937. }
  938. peer.Height = height
  939. return m.store.Set(peer)
  940. }
  941. // peerStore stores information about peers. It is not thread-safe, assuming it
  942. // is only used by PeerManager which handles concurrency control. This allows
  943. // the manager to execute multiple operations atomically via its own mutex.
  944. //
  945. // The entire set of peers is kept in memory, for performance. It is loaded
  946. // from disk on initialization, and any changes are written back to disk
  947. // (without fsync, since we can afford to lose recent writes).
  948. type peerStore struct {
  949. db dbm.DB
  950. peers map[types.NodeID]*peerInfo
  951. ranked []*peerInfo // cache for Ranked(), nil invalidates cache
  952. }
  953. // newPeerStore creates a new peer store, loading all persisted peers from the
  954. // database into memory.
  955. func newPeerStore(db dbm.DB) (*peerStore, error) {
  956. if db == nil {
  957. return nil, errors.New("no database provided")
  958. }
  959. store := &peerStore{db: db}
  960. if err := store.loadPeers(); err != nil {
  961. return nil, err
  962. }
  963. return store, nil
  964. }
  965. // loadPeers loads all peers from the database into memory.
  966. func (s *peerStore) loadPeers() error {
  967. peers := map[types.NodeID]*peerInfo{}
  968. start, end := keyPeerInfoRange()
  969. iter, err := s.db.Iterator(start, end)
  970. if err != nil {
  971. return err
  972. }
  973. defer iter.Close()
  974. for ; iter.Valid(); iter.Next() {
  975. // FIXME: We may want to tolerate failures here, by simply logging
  976. // the errors and ignoring the faulty peer entries.
  977. msg := new(p2pproto.PeerInfo)
  978. if err := proto.Unmarshal(iter.Value(), msg); err != nil {
  979. return fmt.Errorf("invalid peer Protobuf data: %w", err)
  980. }
  981. peer, err := peerInfoFromProto(msg)
  982. if err != nil {
  983. return fmt.Errorf("invalid peer data: %w", err)
  984. }
  985. peers[peer.ID] = peer
  986. }
  987. if iter.Error() != nil {
  988. return iter.Error()
  989. }
  990. s.peers = peers
  991. s.ranked = nil // invalidate cache if populated
  992. return nil
  993. }
  994. // Get fetches a peer. The boolean indicates whether the peer existed or not.
  995. // The returned peer info is a copy, and can be mutated at will.
  996. func (s *peerStore) Get(id types.NodeID) (peerInfo, bool) {
  997. peer, ok := s.peers[id]
  998. return peer.Copy(), ok
  999. }
  1000. // Set stores peer data. The input data will be copied, and can safely be reused
  1001. // by the caller.
  1002. func (s *peerStore) Set(peer peerInfo) error {
  1003. if err := peer.Validate(); err != nil {
  1004. return err
  1005. }
  1006. peer = peer.Copy()
  1007. // FIXME: We may want to optimize this by avoiding saving to the database
  1008. // if there haven't been any changes to persisted fields.
  1009. bz, err := peer.ToProto().Marshal()
  1010. if err != nil {
  1011. return err
  1012. }
  1013. if err = s.db.Set(keyPeerInfo(peer.ID), bz); err != nil {
  1014. return err
  1015. }
  1016. if current, ok := s.peers[peer.ID]; !ok || current.Score() != peer.Score() {
  1017. // If the peer is new, or its score changes, we invalidate the Ranked() cache.
  1018. s.peers[peer.ID] = &peer
  1019. s.ranked = nil
  1020. } else {
  1021. // Otherwise, since s.ranked contains pointers to the old data and we
  1022. // want those pointers to remain valid with the new data, we have to
  1023. // update the existing pointer address.
  1024. *current = peer
  1025. }
  1026. return nil
  1027. }
  1028. // Delete deletes a peer, or does nothing if it does not exist.
  1029. func (s *peerStore) Delete(id types.NodeID) error {
  1030. if _, ok := s.peers[id]; !ok {
  1031. return nil
  1032. }
  1033. if err := s.db.Delete(keyPeerInfo(id)); err != nil {
  1034. return err
  1035. }
  1036. delete(s.peers, id)
  1037. s.ranked = nil
  1038. return nil
  1039. }
  1040. // List retrieves all peers in an arbitrary order. The returned data is a copy,
  1041. // and can be mutated at will.
  1042. func (s *peerStore) List() []peerInfo {
  1043. peers := make([]peerInfo, 0, len(s.peers))
  1044. for _, peer := range s.peers {
  1045. peers = append(peers, peer.Copy())
  1046. }
  1047. return peers
  1048. }
  1049. // Ranked returns a list of peers ordered by score (better peers first). Peers
  1050. // with equal scores are returned in an arbitrary order. The returned list must
  1051. // not be mutated or accessed concurrently by the caller, since it returns
  1052. // pointers to internal peerStore data for performance.
  1053. //
  1054. // Ranked is used to determine both which peers to dial, which ones to evict,
  1055. // and which ones to delete completely.
  1056. //
  1057. // FIXME: For now, we simply maintain a cache in s.ranked which is invalidated
  1058. // by setting it to nil, but if necessary we should use a better data structure
  1059. // for this (e.g. a heap or ordered map).
  1060. //
  1061. // FIXME: The scoring logic is currently very naïve, see peerInfo.Score().
  1062. func (s *peerStore) Ranked() []*peerInfo {
  1063. if s.ranked != nil {
  1064. return s.ranked
  1065. }
  1066. s.ranked = make([]*peerInfo, 0, len(s.peers))
  1067. for _, peer := range s.peers {
  1068. s.ranked = append(s.ranked, peer)
  1069. }
  1070. sort.Slice(s.ranked, func(i, j int) bool {
  1071. // FIXME: If necessary, consider precomputing scores before sorting,
  1072. // to reduce the number of Score() calls.
  1073. return s.ranked[i].Score() > s.ranked[j].Score()
  1074. })
  1075. return s.ranked
  1076. }
  1077. // Size returns the number of peers in the peer store.
  1078. func (s *peerStore) Size() int {
  1079. return len(s.peers)
  1080. }
  1081. // peerInfo contains peer information stored in a peerStore.
  1082. type peerInfo struct {
  1083. ID types.NodeID
  1084. AddressInfo map[NodeAddress]*peerAddressInfo
  1085. LastConnected time.Time
  1086. // These fields are ephemeral, i.e. not persisted to the database.
  1087. Persistent bool
  1088. Height int64
  1089. FixedScore PeerScore // mainly for tests
  1090. MutableScore int64 // updated by router
  1091. }
  1092. // peerInfoFromProto converts a Protobuf PeerInfo message to a peerInfo,
  1093. // erroring if the data is invalid.
  1094. func peerInfoFromProto(msg *p2pproto.PeerInfo) (*peerInfo, error) {
  1095. p := &peerInfo{
  1096. ID: types.NodeID(msg.ID),
  1097. AddressInfo: map[NodeAddress]*peerAddressInfo{},
  1098. }
  1099. if msg.LastConnected != nil {
  1100. p.LastConnected = *msg.LastConnected
  1101. }
  1102. for _, a := range msg.AddressInfo {
  1103. addressInfo, err := peerAddressInfoFromProto(a)
  1104. if err != nil {
  1105. return nil, err
  1106. }
  1107. p.AddressInfo[addressInfo.Address] = addressInfo
  1108. }
  1109. return p, p.Validate()
  1110. }
  1111. // ToProto converts the peerInfo to p2pproto.PeerInfo for database storage. The
  1112. // Protobuf type only contains persisted fields, while ephemeral fields are
  1113. // discarded. The returned message may contain pointers to original data, since
  1114. // it is expected to be serialized immediately.
  1115. func (p *peerInfo) ToProto() *p2pproto.PeerInfo {
  1116. msg := &p2pproto.PeerInfo{
  1117. ID: string(p.ID),
  1118. LastConnected: &p.LastConnected,
  1119. }
  1120. for _, addressInfo := range p.AddressInfo {
  1121. msg.AddressInfo = append(msg.AddressInfo, addressInfo.ToProto())
  1122. }
  1123. if msg.LastConnected.IsZero() {
  1124. msg.LastConnected = nil
  1125. }
  1126. return msg
  1127. }
  1128. // Copy returns a deep copy of the peer info.
  1129. func (p *peerInfo) Copy() peerInfo {
  1130. if p == nil {
  1131. return peerInfo{}
  1132. }
  1133. c := *p
  1134. for i, addressInfo := range c.AddressInfo {
  1135. addressInfoCopy := addressInfo.Copy()
  1136. c.AddressInfo[i] = &addressInfoCopy
  1137. }
  1138. return c
  1139. }
  1140. // Score calculates a score for the peer. Higher-scored peers will be
  1141. // preferred over lower scores.
  1142. func (p *peerInfo) Score() PeerScore {
  1143. if p.FixedScore > 0 {
  1144. return p.FixedScore
  1145. }
  1146. if p.Persistent {
  1147. return PeerScorePersistent
  1148. }
  1149. score := p.MutableScore
  1150. for _, addr := range p.AddressInfo {
  1151. // DialFailures is reset when dials succeed, so this
  1152. // is either the number of dial failures or 0.
  1153. score -= int64(addr.DialFailures)
  1154. }
  1155. if score <= 0 {
  1156. return 0
  1157. }
  1158. if score >= math.MaxUint8 {
  1159. return PeerScore(math.MaxUint8)
  1160. }
  1161. return PeerScore(score)
  1162. }
  1163. // Validate validates the peer info.
  1164. func (p *peerInfo) Validate() error {
  1165. if p.ID == "" {
  1166. return errors.New("no peer ID")
  1167. }
  1168. return nil
  1169. }
  1170. // peerAddressInfo contains information and statistics about a peer address.
  1171. type peerAddressInfo struct {
  1172. Address NodeAddress
  1173. LastDialSuccess time.Time
  1174. LastDialFailure time.Time
  1175. DialFailures uint32 // since last successful dial
  1176. }
  1177. // peerAddressInfoFromProto converts a Protobuf PeerAddressInfo message
  1178. // to a peerAddressInfo.
  1179. func peerAddressInfoFromProto(msg *p2pproto.PeerAddressInfo) (*peerAddressInfo, error) {
  1180. address, err := ParseNodeAddress(msg.Address)
  1181. if err != nil {
  1182. return nil, fmt.Errorf("invalid address %q: %w", address, err)
  1183. }
  1184. addressInfo := &peerAddressInfo{
  1185. Address: address,
  1186. DialFailures: msg.DialFailures,
  1187. }
  1188. if msg.LastDialSuccess != nil {
  1189. addressInfo.LastDialSuccess = *msg.LastDialSuccess
  1190. }
  1191. if msg.LastDialFailure != nil {
  1192. addressInfo.LastDialFailure = *msg.LastDialFailure
  1193. }
  1194. return addressInfo, addressInfo.Validate()
  1195. }
  1196. // ToProto converts the address into to a Protobuf message for serialization.
  1197. func (a *peerAddressInfo) ToProto() *p2pproto.PeerAddressInfo {
  1198. msg := &p2pproto.PeerAddressInfo{
  1199. Address: a.Address.String(),
  1200. LastDialSuccess: &a.LastDialSuccess,
  1201. LastDialFailure: &a.LastDialFailure,
  1202. DialFailures: a.DialFailures,
  1203. }
  1204. if msg.LastDialSuccess.IsZero() {
  1205. msg.LastDialSuccess = nil
  1206. }
  1207. if msg.LastDialFailure.IsZero() {
  1208. msg.LastDialFailure = nil
  1209. }
  1210. return msg
  1211. }
  1212. // Copy returns a copy of the address info.
  1213. func (a *peerAddressInfo) Copy() peerAddressInfo {
  1214. return *a
  1215. }
  1216. // Validate validates the address info.
  1217. func (a *peerAddressInfo) Validate() error {
  1218. return a.Address.Validate()
  1219. }
  1220. // Database key prefixes.
  1221. const (
  1222. prefixPeerInfo int64 = 1
  1223. )
  1224. // keyPeerInfo generates a peerInfo database key.
  1225. func keyPeerInfo(id types.NodeID) []byte {
  1226. key, err := orderedcode.Append(nil, prefixPeerInfo, string(id))
  1227. if err != nil {
  1228. panic(err)
  1229. }
  1230. return key
  1231. }
  1232. // keyPeerInfoRange generates start/end keys for the entire peerInfo key range.
  1233. func keyPeerInfoRange() ([]byte, []byte) {
  1234. start, err := orderedcode.Append(nil, prefixPeerInfo, "")
  1235. if err != nil {
  1236. panic(err)
  1237. }
  1238. end, err := orderedcode.Append(nil, prefixPeerInfo, orderedcode.Infinity)
  1239. if err != nil {
  1240. panic(err)
  1241. }
  1242. return start, end
  1243. }