| 1 | import { base64 } from 'multiformats/bases/base64' |
| 2 | import { toObject } from './to-object.js' |
| 3 | import type { Peer } from '../rpc/index.js' |
| 4 | import type { Logger, PeerStore } from '@libp2p/interface' |
| 5 | import type { ConnectionManager } from '@libp2p/interface-internal' |
| 6 | |
| 7 | export interface Components { |
| 8 | connectionManager: ConnectionManager |
| 9 | peerStore: PeerStore |
| 10 | } |
| 11 | |
| 12 | export async function getPeers (components: Components, log: Logger): Promise<Peer[]> { |
| 13 | const peers: Peer[] = [] |
| 14 | const connections = components.connectionManager.getConnectionsMap() |
| 15 | const connectedAddresses = [...connections.values()].flatMap(conn => conn).map(conn => conn.remoteAddr.toString()) |
| 16 | |
| 17 | for (const [peerId, conns] of connections.entries()) { |
| 18 | try { |
| 19 | const peer = await components.peerStore.get(peerId) |
| 20 | |
| 21 | peers.push({ |
| 22 | id: peerId, |
| 23 | addresses: peer.addresses.map(({ isCertified, multiaddr }) => { |
| 24 | return { |
| 25 | multiaddr, |
| 26 | isCertified, |
| 27 | isConnected: connectedAddresses.includes(multiaddr.toString()) |
| 28 | } |
| 29 | }), |
| 30 | protocols: [...peer.protocols], |
| 31 | tags: toObject(peer.tags, (t) => t.value), |
| 32 | metadata: toObject(peer.metadata, (buf) => base64.encode(buf)) |
| 33 | }) |
| 34 | } catch (err) { |
| 35 | log.error('could not load peer data from peer store', err) |
| 36 | |
| 37 | peers.push({ |
| 38 | id: peerId, |
| 39 | addresses: conns.map(conn => { |
| 40 | return { |
| 41 | multiaddr: conn.remoteAddr, |
| 42 | isConnected: connectedAddresses.includes(conn.remoteAddr.toString()) |
| 43 | } |
| 44 | }), |
| 45 | protocols: [], |
| 46 | tags: {}, |
| 47 | metadata: {} |
| 48 | }) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return peers |
| 53 | } |