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.

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