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.

1306 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.Register(peerUpdates)
  708. return peerUpdates
  709. }
  710. // Register allows you to inject a custom PeerUpdate instance into the
  711. // PeerManager, rather than relying on the instance constructed by the
  712. // Subscribe method, which wraps the functionality of the Register
  713. // method.
  714. //
  715. // The caller must consume the peer updates from this PeerUpdates
  716. // instance in a timely fashion and close the subscription when done,
  717. // otherwise the PeerManager will halt.
  718. func (m *PeerManager) Register(peerUpdates *PeerUpdates) {
  719. m.mtx.Lock()
  720. m.subscriptions[peerUpdates] = peerUpdates
  721. m.mtx.Unlock()
  722. go func() {
  723. select {
  724. case <-peerUpdates.Done():
  725. m.mtx.Lock()
  726. delete(m.subscriptions, peerUpdates)
  727. m.mtx.Unlock()
  728. case <-m.closeCh:
  729. }
  730. }()
  731. }
  732. // broadcast broadcasts a peer update to all subscriptions. The caller must
  733. // already hold the mutex lock, to make sure updates are sent in the same order
  734. // as the PeerManager processes them, but this means subscribers must be
  735. // responsive at all times or the entire PeerManager will halt.
  736. //
  737. // FIXME: Consider using an internal channel to buffer updates while also
  738. // maintaining order if this is a problem.
  739. func (m *PeerManager) broadcast(peerUpdate PeerUpdate) {
  740. for _, sub := range m.subscriptions {
  741. // We have to check closeCh separately first, otherwise there's a 50%
  742. // chance the second select will send on a closed subscription.
  743. select {
  744. case <-sub.closeCh:
  745. continue
  746. default:
  747. }
  748. select {
  749. case sub.updatesCh <- peerUpdate:
  750. case <-sub.closeCh:
  751. }
  752. }
  753. }
  754. // Close closes the peer manager, releasing resources (i.e. goroutines).
  755. func (m *PeerManager) Close() {
  756. m.closeOnce.Do(func() {
  757. close(m.closeCh)
  758. })
  759. }
  760. // Addresses returns all known addresses for a peer, primarily for testing.
  761. // The order is arbitrary.
  762. func (m *PeerManager) Addresses(peerID NodeID) []NodeAddress {
  763. m.mtx.Lock()
  764. defer m.mtx.Unlock()
  765. addresses := []NodeAddress{}
  766. if peer, ok := m.store.Get(peerID); ok {
  767. for _, addressInfo := range peer.AddressInfo {
  768. addresses = append(addresses, addressInfo.Address)
  769. }
  770. }
  771. return addresses
  772. }
  773. // Peers returns all known peers, primarily for testing. The order is arbitrary.
  774. func (m *PeerManager) Peers() []NodeID {
  775. m.mtx.Lock()
  776. defer m.mtx.Unlock()
  777. peers := []NodeID{}
  778. for _, peer := range m.store.Ranked() {
  779. peers = append(peers, peer.ID)
  780. }
  781. return peers
  782. }
  783. // Scores returns the peer scores for all known peers, primarily for testing.
  784. func (m *PeerManager) Scores() map[NodeID]PeerScore {
  785. m.mtx.Lock()
  786. defer m.mtx.Unlock()
  787. scores := map[NodeID]PeerScore{}
  788. for _, peer := range m.store.Ranked() {
  789. scores[peer.ID] = peer.Score()
  790. }
  791. return scores
  792. }
  793. // Status returns the status for a peer, primarily for testing.
  794. func (m *PeerManager) Status(id NodeID) PeerStatus {
  795. m.mtx.Lock()
  796. defer m.mtx.Unlock()
  797. switch {
  798. case m.ready[id]:
  799. return PeerStatusUp
  800. default:
  801. return PeerStatusDown
  802. }
  803. }
  804. // findUpgradeCandidate looks for a lower-scored peer that we could evict
  805. // to make room for the given peer. Returns an empty ID if none is found.
  806. // If the peer is already being upgraded to, we return that same upgrade.
  807. // The caller must hold the mutex lock.
  808. func (m *PeerManager) findUpgradeCandidate(id NodeID, score PeerScore) NodeID {
  809. for from, to := range m.upgrading {
  810. if to == id {
  811. return from
  812. }
  813. }
  814. ranked := m.store.Ranked()
  815. for i := len(ranked) - 1; i >= 0; i-- {
  816. candidate := ranked[i]
  817. switch {
  818. case candidate.Score() >= score:
  819. return "" // no further peers can be scored lower, due to sorting
  820. case !m.connected[candidate.ID]:
  821. case m.evict[candidate.ID]:
  822. case m.evicting[candidate.ID]:
  823. case m.upgrading[candidate.ID] != "":
  824. default:
  825. return candidate.ID
  826. }
  827. }
  828. return ""
  829. }
  830. // retryDelay calculates a dial retry delay using exponential backoff, based on
  831. // retry settings in PeerManagerOptions. If retries are disabled (i.e.
  832. // MinRetryTime is 0), this returns retryNever (i.e. an infinite retry delay).
  833. // The caller must hold the mutex lock (for m.rand which is not thread-safe).
  834. func (m *PeerManager) retryDelay(failures uint32, persistent bool) time.Duration {
  835. if failures == 0 {
  836. return 0
  837. }
  838. if m.options.MinRetryTime == 0 {
  839. return retryNever
  840. }
  841. maxDelay := m.options.MaxRetryTime
  842. if persistent && m.options.MaxRetryTimePersistent > 0 {
  843. maxDelay = m.options.MaxRetryTimePersistent
  844. }
  845. delay := m.options.MinRetryTime * time.Duration(math.Pow(2, float64(failures-1)))
  846. if maxDelay > 0 && delay > maxDelay {
  847. delay = maxDelay
  848. }
  849. if m.options.RetryTimeJitter > 0 {
  850. delay += time.Duration(m.rand.Int63n(int64(m.options.RetryTimeJitter)))
  851. }
  852. return delay
  853. }
  854. // GetHeight returns a peer's height, as reported via SetHeight, or 0 if the
  855. // peer or height is unknown.
  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) GetHeight(peerID NodeID) int64 {
  861. m.mtx.Lock()
  862. defer m.mtx.Unlock()
  863. peer, _ := m.store.Get(peerID)
  864. return peer.Height
  865. }
  866. // SetHeight stores a peer's height, making it available via GetHeight.
  867. //
  868. // FIXME: This is a temporary workaround to share state between the consensus
  869. // and mempool reactors, carried over from the legacy P2P stack. Reactors should
  870. // not have dependencies on each other, instead tracking this themselves.
  871. func (m *PeerManager) SetHeight(peerID NodeID, height int64) error {
  872. m.mtx.Lock()
  873. defer m.mtx.Unlock()
  874. peer, ok := m.store.Get(peerID)
  875. if !ok {
  876. peer = m.newPeerInfo(peerID)
  877. }
  878. peer.Height = height
  879. return m.store.Set(peer)
  880. }
  881. // peerStore stores information about peers. It is not thread-safe, assuming it
  882. // is only used by PeerManager which handles concurrency control. This allows
  883. // the manager to execute multiple operations atomically via its own mutex.
  884. //
  885. // The entire set of peers is kept in memory, for performance. It is loaded
  886. // from disk on initialization, and any changes are written back to disk
  887. // (without fsync, since we can afford to lose recent writes).
  888. type peerStore struct {
  889. db dbm.DB
  890. peers map[NodeID]*peerInfo
  891. ranked []*peerInfo // cache for Ranked(), nil invalidates cache
  892. }
  893. // newPeerStore creates a new peer store, loading all persisted peers from the
  894. // database into memory.
  895. func newPeerStore(db dbm.DB) (*peerStore, error) {
  896. if db == nil {
  897. return nil, errors.New("no database provided")
  898. }
  899. store := &peerStore{db: db}
  900. if err := store.loadPeers(); err != nil {
  901. return nil, err
  902. }
  903. return store, nil
  904. }
  905. // loadPeers loads all peers from the database into memory.
  906. func (s *peerStore) loadPeers() error {
  907. peers := map[NodeID]*peerInfo{}
  908. start, end := keyPeerInfoRange()
  909. iter, err := s.db.Iterator(start, end)
  910. if err != nil {
  911. return err
  912. }
  913. defer iter.Close()
  914. for ; iter.Valid(); iter.Next() {
  915. // FIXME: We may want to tolerate failures here, by simply logging
  916. // the errors and ignoring the faulty peer entries.
  917. msg := new(p2pproto.PeerInfo)
  918. if err := proto.Unmarshal(iter.Value(), msg); err != nil {
  919. return fmt.Errorf("invalid peer Protobuf data: %w", err)
  920. }
  921. peer, err := peerInfoFromProto(msg)
  922. if err != nil {
  923. return fmt.Errorf("invalid peer data: %w", err)
  924. }
  925. peers[peer.ID] = peer
  926. }
  927. if iter.Error() != nil {
  928. return iter.Error()
  929. }
  930. s.peers = peers
  931. s.ranked = nil // invalidate cache if populated
  932. return nil
  933. }
  934. // Get fetches a peer. The boolean indicates whether the peer existed or not.
  935. // The returned peer info is a copy, and can be mutated at will.
  936. func (s *peerStore) Get(id NodeID) (peerInfo, bool) {
  937. peer, ok := s.peers[id]
  938. return peer.Copy(), ok
  939. }
  940. // Set stores peer data. The input data will be copied, and can safely be reused
  941. // by the caller.
  942. func (s *peerStore) Set(peer peerInfo) error {
  943. if err := peer.Validate(); err != nil {
  944. return err
  945. }
  946. peer = peer.Copy()
  947. // FIXME: We may want to optimize this by avoiding saving to the database
  948. // if there haven't been any changes to persisted fields.
  949. bz, err := peer.ToProto().Marshal()
  950. if err != nil {
  951. return err
  952. }
  953. if err = s.db.Set(keyPeerInfo(peer.ID), bz); err != nil {
  954. return err
  955. }
  956. if current, ok := s.peers[peer.ID]; !ok || current.Score() != peer.Score() {
  957. // If the peer is new, or its score changes, we invalidate the Ranked() cache.
  958. s.peers[peer.ID] = &peer
  959. s.ranked = nil
  960. } else {
  961. // Otherwise, since s.ranked contains pointers to the old data and we
  962. // want those pointers to remain valid with the new data, we have to
  963. // update the existing pointer address.
  964. *current = peer
  965. }
  966. return nil
  967. }
  968. // Delete deletes a peer, or does nothing if it does not exist.
  969. func (s *peerStore) Delete(id NodeID) error {
  970. if _, ok := s.peers[id]; !ok {
  971. return nil
  972. }
  973. if err := s.db.Delete(keyPeerInfo(id)); err != nil {
  974. return err
  975. }
  976. delete(s.peers, id)
  977. s.ranked = nil
  978. return nil
  979. }
  980. // List retrieves all peers in an arbitrary order. The returned data is a copy,
  981. // and can be mutated at will.
  982. func (s *peerStore) List() []peerInfo {
  983. peers := make([]peerInfo, 0, len(s.peers))
  984. for _, peer := range s.peers {
  985. peers = append(peers, peer.Copy())
  986. }
  987. return peers
  988. }
  989. // Ranked returns a list of peers ordered by score (better peers first). Peers
  990. // with equal scores are returned in an arbitrary order. The returned list must
  991. // not be mutated or accessed concurrently by the caller, since it returns
  992. // pointers to internal peerStore data for performance.
  993. //
  994. // Ranked is used to determine both which peers to dial, which ones to evict,
  995. // and which ones to delete completely.
  996. //
  997. // FIXME: For now, we simply maintain a cache in s.ranked which is invalidated
  998. // by setting it to nil, but if necessary we should use a better data structure
  999. // for this (e.g. a heap or ordered map).
  1000. //
  1001. // FIXME: The scoring logic is currently very naïve, see peerInfo.Score().
  1002. func (s *peerStore) Ranked() []*peerInfo {
  1003. if s.ranked != nil {
  1004. return s.ranked
  1005. }
  1006. s.ranked = make([]*peerInfo, 0, len(s.peers))
  1007. for _, peer := range s.peers {
  1008. s.ranked = append(s.ranked, peer)
  1009. }
  1010. sort.Slice(s.ranked, func(i, j int) bool {
  1011. // FIXME: If necessary, consider precomputing scores before sorting,
  1012. // to reduce the number of Score() calls.
  1013. return s.ranked[i].Score() > s.ranked[j].Score()
  1014. })
  1015. return s.ranked
  1016. }
  1017. // Size returns the number of peers in the peer store.
  1018. func (s *peerStore) Size() int {
  1019. return len(s.peers)
  1020. }
  1021. // peerInfo contains peer information stored in a peerStore.
  1022. type peerInfo struct {
  1023. ID NodeID
  1024. AddressInfo map[NodeAddress]*peerAddressInfo
  1025. LastConnected time.Time
  1026. // These fields are ephemeral, i.e. not persisted to the database.
  1027. Persistent bool
  1028. Height int64
  1029. FixedScore PeerScore // mainly for tests
  1030. }
  1031. // peerInfoFromProto converts a Protobuf PeerInfo message to a peerInfo,
  1032. // erroring if the data is invalid.
  1033. func peerInfoFromProto(msg *p2pproto.PeerInfo) (*peerInfo, error) {
  1034. p := &peerInfo{
  1035. ID: NodeID(msg.ID),
  1036. AddressInfo: map[NodeAddress]*peerAddressInfo{},
  1037. }
  1038. if msg.LastConnected != nil {
  1039. p.LastConnected = *msg.LastConnected
  1040. }
  1041. for _, a := range msg.AddressInfo {
  1042. addressInfo, err := peerAddressInfoFromProto(a)
  1043. if err != nil {
  1044. return nil, err
  1045. }
  1046. p.AddressInfo[addressInfo.Address] = addressInfo
  1047. }
  1048. return p, p.Validate()
  1049. }
  1050. // ToProto converts the peerInfo to p2pproto.PeerInfo for database storage. The
  1051. // Protobuf type only contains persisted fields, while ephemeral fields are
  1052. // discarded. The returned message may contain pointers to original data, since
  1053. // it is expected to be serialized immediately.
  1054. func (p *peerInfo) ToProto() *p2pproto.PeerInfo {
  1055. msg := &p2pproto.PeerInfo{
  1056. ID: string(p.ID),
  1057. LastConnected: &p.LastConnected,
  1058. }
  1059. for _, addressInfo := range p.AddressInfo {
  1060. msg.AddressInfo = append(msg.AddressInfo, addressInfo.ToProto())
  1061. }
  1062. if msg.LastConnected.IsZero() {
  1063. msg.LastConnected = nil
  1064. }
  1065. return msg
  1066. }
  1067. // Copy returns a deep copy of the peer info.
  1068. func (p *peerInfo) Copy() peerInfo {
  1069. if p == nil {
  1070. return peerInfo{}
  1071. }
  1072. c := *p
  1073. for i, addressInfo := range c.AddressInfo {
  1074. addressInfoCopy := addressInfo.Copy()
  1075. c.AddressInfo[i] = &addressInfoCopy
  1076. }
  1077. return c
  1078. }
  1079. // Score calculates a score for the peer. Higher-scored peers will be
  1080. // preferred over lower scores.
  1081. func (p *peerInfo) Score() PeerScore {
  1082. var score PeerScore
  1083. if p.FixedScore > 0 {
  1084. return p.FixedScore
  1085. }
  1086. if p.Persistent {
  1087. score += PeerScorePersistent
  1088. }
  1089. return score
  1090. }
  1091. // Validate validates the peer info.
  1092. func (p *peerInfo) Validate() error {
  1093. if p.ID == "" {
  1094. return errors.New("no peer ID")
  1095. }
  1096. return nil
  1097. }
  1098. // peerAddressInfo contains information and statistics about a peer address.
  1099. type peerAddressInfo struct {
  1100. Address NodeAddress
  1101. LastDialSuccess time.Time
  1102. LastDialFailure time.Time
  1103. DialFailures uint32 // since last successful dial
  1104. }
  1105. // peerAddressInfoFromProto converts a Protobuf PeerAddressInfo message
  1106. // to a peerAddressInfo.
  1107. func peerAddressInfoFromProto(msg *p2pproto.PeerAddressInfo) (*peerAddressInfo, error) {
  1108. address, err := ParseNodeAddress(msg.Address)
  1109. if err != nil {
  1110. return nil, fmt.Errorf("invalid address %q: %w", address, err)
  1111. }
  1112. addressInfo := &peerAddressInfo{
  1113. Address: address,
  1114. DialFailures: msg.DialFailures,
  1115. }
  1116. if msg.LastDialSuccess != nil {
  1117. addressInfo.LastDialSuccess = *msg.LastDialSuccess
  1118. }
  1119. if msg.LastDialFailure != nil {
  1120. addressInfo.LastDialFailure = *msg.LastDialFailure
  1121. }
  1122. return addressInfo, addressInfo.Validate()
  1123. }
  1124. // ToProto converts the address into to a Protobuf message for serialization.
  1125. func (a *peerAddressInfo) ToProto() *p2pproto.PeerAddressInfo {
  1126. msg := &p2pproto.PeerAddressInfo{
  1127. Address: a.Address.String(),
  1128. LastDialSuccess: &a.LastDialSuccess,
  1129. LastDialFailure: &a.LastDialFailure,
  1130. DialFailures: a.DialFailures,
  1131. }
  1132. if msg.LastDialSuccess.IsZero() {
  1133. msg.LastDialSuccess = nil
  1134. }
  1135. if msg.LastDialFailure.IsZero() {
  1136. msg.LastDialFailure = nil
  1137. }
  1138. return msg
  1139. }
  1140. // Copy returns a copy of the address info.
  1141. func (a *peerAddressInfo) Copy() peerAddressInfo {
  1142. return *a
  1143. }
  1144. // Validate validates the address info.
  1145. func (a *peerAddressInfo) Validate() error {
  1146. return a.Address.Validate()
  1147. }
  1148. // Database key prefixes.
  1149. const (
  1150. prefixPeerInfo int64 = 1
  1151. )
  1152. // keyPeerInfo generates a peerInfo database key.
  1153. func keyPeerInfo(id NodeID) []byte {
  1154. key, err := orderedcode.Append(nil, prefixPeerInfo, string(id))
  1155. if err != nil {
  1156. panic(err)
  1157. }
  1158. return key
  1159. }
  1160. // keyPeerInfoRange generates start/end keys for the entire peerInfo key range.
  1161. func keyPeerInfoRange() ([]byte, []byte) {
  1162. start, err := orderedcode.Append(nil, prefixPeerInfo, "")
  1163. if err != nil {
  1164. panic(err)
  1165. }
  1166. end, err := orderedcode.Append(nil, prefixPeerInfo, orderedcode.Infinity)
  1167. if err != nil {
  1168. panic(err)
  1169. }
  1170. return start, end
  1171. }