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.

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