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.

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