Libp2p nodes implement this interface.

interface Libp2p<T> {
    contentRouting: ContentRouting;
    logger: ComponentLogger;
    metrics?: Metrics;
    peerId: PeerId;
    peerRouting: PeerRouting;
    peerStore: PeerStore;
    services: T;
    status: Libp2pStatus;
    addEventListener<K>(type, listener, options?): void;
    afterStart?(): void | Promise<void>;
    afterStop?(): void | Promise<void>;
    beforeStart?(): void | Promise<void>;
    beforeStop?(): void | Promise<void>;
    dial(peer, options?): Promise<Connection>;
    dialProtocol(peer, protocols, options?): Promise<Stream>;
    dispatchEvent(event): boolean;
    dispatchEvent(event): boolean;
    getConnections(peerId?): Connection[];
    getDialQueue(): PendingDial[];
    getMultiaddrs(): Multiaddr[];
    getPeers(): PeerId[];
    getProtocols(): string[];
    getPublicKey(peer, options?): Promise<Uint8Array>;
    handle(protocol, handler, options?): Promise<void>;
    hangUp(peer, options?): Promise<void>;
    isDialable(multiaddr, options?): Promise<boolean>;
    listenerCount(type): number;
    register(protocol, topology): Promise<string>;
    removeEventListener<K>(type, listener?, options?): void;
    removeEventListener(type, listener?, options?): void;
    safeDispatchEvent<Detail>(type, detail): boolean;
    start(): void | Promise<void>;
    stop(): void | Promise<void>;
    unhandle(protocols): Promise<void>;
    unregister(id): void;
}

Type Parameters

Hierarchy (view full)

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.

Example

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.

Example

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.

Example

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.

Example

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

Example

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.

Example

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

  • 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>

    Example

    const conn = await libp2p.dial(remotePeerId)

    // create a new stream within the connection
    const { stream, protocol } = 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>

    Example

    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[]

    Example

    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[]

    Example

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

    Returns string[]

    Example

    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, the first one is discarded.

    Parameters

    Returns Promise<void>

    Example

    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>

    Example

    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>

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

    Parameters

    Returns Promise<string>

    Example

    const id = await libp2p.register('/echo/1.0.0', {
    onConnect: (peer, connection) => {
    // handle connect
    },
    onDisconnect: (peer, connection) => {
    // handle disconnect
    }
    })
  • Removes the handler for each protocol. The protocol will no longer be supported on streams.

    Parameters

    • protocols: string | string[]

    Returns Promise<void>

    Example

    libp2p.unhandle(['/echo/1.0.0'])
    
  • Unregister topology to no longer be informed when peers connect or disconnect.

    Parameters

    • id: string

    Returns void

    Example

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

    libp2p.unregister(id)