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.

1383 lines
42 KiB

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