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.

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