libp2p
    Preparing search index...

    Interface Libp2p<T>

    Libp2p nodes implement this interface.

    interface Libp2p<T extends ServiceMap = ServiceMap> {
        contentRouting: ContentRouting;
        logger: ComponentLogger;
        metrics?: Metrics;
        peerId: PeerId;
        peerRouting: PeerRouting;
        peerStore: PeerStore;
        services: T;
        status: Libp2pStatus;
        addEventListener<K extends keyof Libp2pEvents<T>>(
            type: K,
            listener: EventHandler<Libp2pEvents<T>[K]> | null,
            options?: boolean | AddEventListenerOptions,
        ): void;
        afterStart?(): void | Promise<void>;
        afterStop?(): void | Promise<void>;
        beforeStart?(): void | Promise<void>;
        beforeStop?(): void | Promise<void>;
        dial(peer: DialTarget, options?: DialOptions): Promise<Connection>;
        dialProtocol(
            peer: DialTarget,
            protocols: string | string[],
            options?: DialProtocolOptions,
        ): Promise<Stream>;
        dispatchEvent(event: Event): boolean;
        dispatchEvent(event: Event): boolean;
        getConnections(peerId?: PeerId): Connection[];
        getDialQueue(): PendingDial[];
        getMultiaddrs(): Multiaddr[];
        getPeers(): PeerId[];
        getProtocols(): string[];
        getPublicKey(
            peer: Ed25519PeerId,
            options?: AbortOptions,
        ): Promise<Ed25519PublicKey>;
        getPublicKey(
            peer: Secp256k1PeerId,
            options?: AbortOptions,
        ): Promise<Secp256k1PublicKey>;
        getPublicKey(
            peer: RSAPeerId,
            options?: AbortOptions,
        ): Promise<RSAPublicKey>;
        getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>;
        getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>;
        handle(
            protocol: string | string[],
            handler: StreamHandler,
            options?: StreamHandlerOptions,
        ): Promise<void>;
        hangUp(peer: Multiaddr | PeerId, options?: AbortOptions): Promise<void>;
        isDialable(
            multiaddr: Multiaddr | Multiaddr[],
            options?: IsDialableOptions,
        ): Promise<boolean>;
        listenerCount(type: string): number;
        register(
            protocol: string,
            topology: Topology,
            options?: AbortOptions,
        ): Promise<string>;
        removeEventListener<K extends keyof Libp2pEvents<T>>(
            type: K,
            listener?: EventHandler<Libp2pEvents<T>[K]> | null,
            options?: boolean | EventListenerOptions,
        ): void;
        removeEventListener(
            type: string,
            listener?: EventHandler<Event>,
            options?: boolean | EventListenerOptions,
        ): void;
        safeDispatchEvent<Detail>(
            type: keyof Libp2pEvents<T>,
            detail?: CustomEventInit<Detail>,
        ): boolean;
        start(): void | Promise<void>;
        stop(): void | Promise<void>;
        unhandle(
            protocols: string | string[],
            options?: AbortOptions,
        ): Promise<void>;
        unregister(id: string): void;
        unuse(protocol: string): void;
        use(
            protocol: string,
            middleware: StreamMiddleware | StreamMiddleware[],
        ): void;
    }

    Type Parameters

    Hierarchy (View Summary)

    Index

    Properties

    contentRouting: ContentRouting

    The content routing subsystem allows the user to find providers for content, let the network know they are providers for content, and get/put values to the DHT.

    for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {
    console.info(peerInfo)
    // { id: PeerId(12D3Foo...), multiaddrs: [] ... }
    }

    The logger used by this libp2p node

    metrics?: Metrics

    The metrics subsystem allows recording values to assess the health/performance of the running node.

    const metric = libp2p.metrics.registerMetric({
    'my-metric'
    })

    // later
    metric.update(5)
    peerId: PeerId

    The PeerId is a unique identifier for a node on the network.

    It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys, the key itself.

    console.info(libp2p.peerId)
    // PeerId(12D3Foo...)
    peerRouting: PeerRouting

    The peer routing subsystem allows the user to find peers on the network or to find peers close to binary keys.

    const peerInfo = await libp2p.peerRouting.findPeer(peerId)
    console.info(peerInfo)
    // { id: PeerId(12D3Foo...), multiaddrs: [] ... }
    for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {
    console.info(peerInfo)
    // { id: PeerId(12D3Foo...), multiaddrs: [] ... }
    }
    peerStore: PeerStore

    The peer store holds information we know about other peers on the network.

    • multiaddrs, supported protocols, etc.
    const peer = await libp2p.peerStore.get(peerId)
    console.info(peer)
    // { id: PeerId(12D3Foo...), addresses: [] ... }
    services: T

    A set of user defined services

    status: Libp2pStatus

    The current status of the libp2p node

    Methods

    • The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

      MDN Reference

      Type Parameters

      Parameters

      Returns void

    • Dials to the provided peer. If successful, the known metadata of the peer will be added to the nodes peerStore.

      If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.

      Parameters

      Returns Promise<Connection>

      const conn = await libp2p.dial(remotePeerId)

      // create a new stream within the connection
      const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])

      // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version

      // ...
      await conn.close()
    • Dials to the provided peer and tries to handshake with the given protocols in order. If successful, the known metadata of the peer will be added to the nodes peerStore, and the MuxedStream will be returned together with the successful negotiated protocol.

      Parameters

      Returns Promise<Stream>

      import { pipe } from 'it-pipe'

      const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)

      // Use this new stream like any other duplex stream
      pipe([1, 2, 3], stream, consume)
    • The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

      MDN Reference

      Parameters

      Returns boolean

    • The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

      MDN Reference

      Parameters

      Returns boolean

    • Return a list of all connections this node has open, optionally filtering by a PeerId

      Parameters

      Returns Connection[]

      for (const connection of libp2p.getConnections()) {
      console.log(peerId, connection.remoteAddr.toString())
      // Logs the PeerId string and the observed remote multiaddr of each Connection
      }
    • Get a deduplicated list of peer advertising multiaddrs by concatenating the listen addresses used by transports with any configured announce addresses as well as observed addresses reported by peers.

      If Announce addrs are specified, configured listen addresses will be ignored though observed addresses will still be included.

      Returns Multiaddr[]

      const listenMa = libp2p.getMultiaddrs()
      // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]
    • Returns a list of supported protocols

      Returns string[]

      const protocols = libp2p.getProtocols()
      // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]
    • Sets up multistream-select routing of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. handle must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.

      libp2p.handle(protocols, handler, options)

      In the event of a new handler for the same protocol being added and error will be thrown. Pass force: true to override this.

      Parameters

      Returns Promise<void>

      const handler = ({ connection, stream, protocol }) => {
      // use stream or connection according to the needs
      }

      libp2p.handle('/echo/1.0.0', handler, {
      maxInboundStreams: 5,
      maxOutboundStreams: 5
      })
    • Parameters

      • type: string

      Returns number

    • Register a topology to be informed when peers are encountered that support the specified protocol

      Parameters

      Returns Promise<string>

      const id = await libp2p.register('/echo/1.0.0', {
      onConnect: (peer, connection) => {
      // handle connect
      },
      onDisconnect: (peer, connection) => {
      // handle disconnect
      }
      })
    • The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.

      MDN Reference

      Type Parameters

      Parameters

      Returns void

    • The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.

      MDN Reference

      Parameters

      • type: string
      • Optionallistener: EventHandler<Event>
      • Optionaloptions: boolean | EventListenerOptions

      Returns void

    • Unregister topology to no longer be informed when peers connect or disconnect.

      Parameters

      • id: string

      Returns void

      const id = await libp2p.register(...)

      libp2p.unregister(id)
    • Deregisters all middleware for the passed protocol.

      Parameters

      • protocol: string

      Returns void

      libp2p.unuse('/my/protocol/1.0.0')
      // any previously registered middleware will no longer be invoked
    • Registers one or more middleware implementations that will be invoked for incoming and outgoing protocol streams that match the passed protocol.

      Parameters

      Returns void

      libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {
      // do something with stream and/or connection
      next(stream, connection)
      })