import type Multiaddr from "multiaddr" ; import type PeerId from "peer-id" ; import type { Connection } from "libp2p" ; import type { Peer } from "../core" ; export interface SwarmPeer { addr : Multiaddr ; peer : PeerId | string ; latency ? : string ; muxer ? : string ; streams ? : string [ ] ; error ? : Error ; direction ? : "inbound" | "outbound" ; } export class Swarm { constructor ( private parent ) { } async peers ( options = { } ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } const { verbose } = options ; const peers = [ ] ; for ( const [ peerId , connections ] of this . parent . host . connections ) { for ( const connection of connections ) { const tupple = { addr : connection . remoteAddr , peer : peerId , } ; if ( verbose || options . direction ) { tupple . direction = connection . stat . direction ; } if ( verbose ) { tupple . muxer = connection . stat . multiplexer ; tupple . latency = "n/a" ; } peers . push ( tupple ) ; } } return peers ; } async connect ( addr ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } return this . parent . host . dial ( addr ) ; } async disconnect ( addr ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } return this . parent . host . hangUp ( addr ) ; } async localAddrs ( ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } return this . parent . host . multiaddrs ; } async addrs ( ) { if ( ! this . parent . isOnline ( ) ) { throw new Error ( "peer is not online" ) ; } const peers = [ ] ; for ( const [ peerId , peer ] of this . parent . host . peerStore . peers . entries ( ) ) { peers . push ( { id : peerId , addrs : peer . addresses . map ( ( mi ) => mi . multiaddr ) , } ) ; } return peers ; } }