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.

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