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.

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