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: null | EventHandler<Libp2pEvents<T>[K]>,
            options?: boolean | AddEventListenerOptions,
        ): void;
        afterStart(): void | Promise<void>;
        afterStop(): void | Promise<void>;
        beforeStart(): void | Promise<void>;
        beforeStop(): void | Promise<void>;
        dial(
            peer: PeerId | Multiaddr | Multiaddr[],
            options?: DialOptions,
        ): Promise<Connection>;
        dialProtocol(
            peer: PeerId | Multiaddr | Multiaddr[],
            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: PeerId | Multiaddr, options?: AbortOptions): Promise<void>;
        isDialable(
            multiaddr: Multiaddr | Multiaddr[],
            options?: IsDialableOptions,
        ): Promise<boolean>;
        listenerCount(type: string): number;
        register(protocol: string, topology: Topology): Promise<string>;
        removeEventListener<K extends keyof Libp2pEvents<T>>(
            type: K,
            listener?: null | EventHandler<Libp2pEvents<T>[K]>,
            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[]): Promise<void>;
        unregister(id: string): 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

    • Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

      The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

      When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

      When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

      When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

      If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

      The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

      MDN Reference

      Type Parameters

      Parameters

      Returns void

    • If implemented, this method will be invoked after the start method.

      All other components will have had their start method invoked before this method is called.

      Returns void | Promise<void>

    • If implemented, this method will be invoked after the stop method.

      All other components will have had their stop method invoked before this method is called.

      Returns void | Promise<void>

    • If implemented, this method will be invoked before the start method.

      It should not assume any other components have been started.

      Returns void | Promise<void>

    • If implemented, this method will be invoked before the stop method.

      Any other components will still be running when this method is called.

      Returns void | Promise<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)
    • Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

      MDN Reference

      Parameters

      Returns boolean

    • Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

      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
      }
    • Return the list of dials currently in progress or queued to start

      Returns PendingDial[]

      for (const pendingDial of libp2p.getDialQueue()) {
      console.log(pendingDial)
      }
    • 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> ]
    • Return a list of all peers we currently have a connection open to

      Returns PeerId[]

    • 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
      })
    • Attempts to gracefully close an open connection to the given peer. If the connection is not closed in the grace period, it will be forcefully closed.

      An AbortSignal can optionally be passed to control when the connection is forcefully closed.

      Parameters

      Returns Promise<void>

      await libp2p.hangUp(remotePeerId)
      
    • Given the current node configuration, returns a promise of true or false if the node would attempt to dial the passed multiaddr.

      This means a relevant transport is configured, and the connection gater would not block the dial attempt.

      This may involve resolving DNS addresses so you should pass an AbortSignal.

      Parameters

      Returns Promise<boolean>

    • 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
      }
      })
    • Removes the event listener in target's event listener list with the same type, callback, and options.

      MDN Reference

      Type Parameters

      Parameters

      Returns void

    • Removes the event listener in target's event listener list with the same type, callback, and options.

      MDN Reference

      Parameters

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

      Returns void

    • This method will be invoked to start the component.

      It should not assume that any other components have been started.

      Returns void | Promise<void>

    • This method will be invoked to stop the component.

      It should not assume any other components are running when it is called.

      Returns void | Promise<void>

    • Removes the handler for each protocol. The protocol will no longer be supported on streams.

      Parameters

      • protocols: string | string[]

      Returns Promise<void>

      libp2p.unhandle(['/echo/1.0.0'])
      
    • 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)