libp2p

0.27.7

Intro

Installable via npm install --save libp2p, it can also be used directly in the browser.

Download

The source is available for download from GitHub. Alternatively, you can install using npm:

$ npm install --save libp2p

You can then require() libp2p as normal:

const libp2P = require('libp2p')

In the Browser

libp2p should work in any ECMAScript 2018 environment out of the box.

Usage:

<script type="text/javascript" src="index.js"></script>

The portable versions of libp2p, including index.js and index.min.js, are included in the /dist folder. libp2p can also be found on unpkg.com under

new Libp2p(_options: any)

Extends EventEmitter

Parameters
_options (any)
Static Members
create(options)
Instance Members
emit(eventName, args)
start()
stop()
connections
dial(peer, options)
dialProtocol(peer, protocols, options)
hangUp(peer)
ping(peer)
handle(protocols, handler)
unhandle(protocols)

Iterates over all peer routers in series to find the given peer.

findPeer(id: String, options: object?): Promise<PeerInfo>
Parameters
id (String) The id of the peer to find
options (object?)
Name Description
options.timeout number? How long the query should run
Returns
Promise<PeerInfo>:

Iterates over all content routers in series to find providers of the given key. Once a content router succeeds, iteration will stop.

findProviders(key: CID, options: object?): AsyncIterable<PeerInfo>
Parameters
key (CID) The CID key of the content to find
options (object?)
Name Description
options.timeout number? How long the query should run
options.maxNumProviders number? maximum number of providers to find
Returns
AsyncIterable<PeerInfo>:

Iterates over all content routers in parallel to notify it is a provider of the given key.

provide(key: CID): Promise<void>
Parameters
key (CID) The CID key of the content to find
Returns
Promise<void>:

Store the given key/value pair in the DHT.

put(key: Buffer, value: Buffer, options: Object?): Promise<void>
Parameters
key (Buffer)
value (Buffer)
options (Object?) put options
Name Description
options.minPeers number? minimum number of peers required to successfully put
Returns
Promise<void>:

Get the value to the given key. Times out after 1 minute by default.

get(key: Buffer, options: Object?): Promise<{from: PeerId, val: Buffer}>
Parameters
key (Buffer)
options (Object?) get options
Name Description
options.timeout number? optional timeout (default: 60000)
Returns
Promise<{from: PeerId, val: Buffer}>:

Get the n values to the given key without sorting.

getMany(key: Buffer, nVals: number, options: Object?): Promise<Array<{from: PeerId, val: Buffer}>>
Parameters
key (Buffer)
nVals (number)
options (Object?) get options
Name Description
options.timeout number? optional timeout (default: 60000)
Returns
Promise<Array<{from: PeerId, val: Buffer}>>:

subscribe

src/pubsub.js

Subscribe the given handler to a pubsub topic

subscribe(topic: string, handler: function): void
Parameters
topic (string)
handler (function) The handler to subscribe
Returns
void:

unsubscribe

src/pubsub.js

Unsubscribes from a pubsub topic

unsubscribe(topic: string, handler: function?)
Parameters
topic (string)
handler (function?) The handler to unsubscribe from

Publish messages to the given topics.

publish(topic: (Array<string> | string), data: Buffer): Promise<void>
Parameters
topic ((Array<string> | string))
data (Buffer)
Returns
Promise<void>:

getTopics

src/pubsub.js

Get a list of topics the node is subscribed to.

getTopics(): Array<String>
Returns
Array<String>: topics

getSubscribers

src/pubsub.js

Get a list of the peer-ids that are subscribed to one topic.

getSubscribers(topic: string): Array<string>
Parameters
topic (string)
Returns
Array<string>:

Converts the given peer to a PeerInfo instance. The PeerStore will be checked for the resulting peer, and the peer will be updated in the PeerStore.

getPeerInfo(peer: (PeerInfo | PeerId | Multiaddr | string), peerStore: PeerStore): PeerInfo
Parameters
peer ((PeerInfo | PeerId | Multiaddr | string))
peerStore (PeerStore)
Returns
PeerInfo:

getPeerInfoRemote

src/get-peer-info.js

If getPeerInfo does not return a peer with multiaddrs, the libp2p PeerRouter will be used to attempt to find the peer.

getPeerInfoRemote(peer: (PeerInfo | PeerId | Multiaddr | string), libp2p: Libp2p): Promise<PeerInfo>
Parameters
peer ((PeerInfo | PeerId | Multiaddr | string))
libp2p (Libp2p)
Returns
Promise<PeerInfo>:
new constructor(libp2p: Libp2p, options: object)
Parameters
libp2p (Libp2p)
options (object)
Name Description
options.maxConnections Number The maximum number of connections allowed. Default=Infinity
options.minConnections Number The minimum number of connections to avoid pruning. Default=0
options.maxData Number The max data (in and out), per average interval to allow. Default=Infinity
options.maxSentData Number The max outgoing data, per average interval to allow. Default=Infinity
options.maxReceivedData Number The max incoming data, per average interval to allow.. Default=Infinity
options.maxEventLoopDelay Number The upper limit the event loop can take to run. Default=Infinity
options.pollInterval Number How often, in milliseconds, metrics and latency should be checked. Default=2000
options.movingAverageInterval Number How often, in milliseconds, to compute averages. Default=60000
options.defaultPeerValue Number The value of the peer. Default=1

Starts the Connection Manager. If Metrics are not enabled on libp2p only event loop and connection limits will be monitored.

start()

Stops the Connection Manager

stop()

Sets the value of the given peer. Peers with lower values will be disconnected first.

setPeerValue(peerId: PeerId, value: number)
Parameters
peerId (PeerId)
value (number) A number between 0 and 1

Tracks the incoming connection and check the connection limit

onConnect(connection: Connection)
Parameters
connection (Connection)

Removes the connection from tracking

onDisconnect(connection: Connection)
Parameters
connection (Connection)

This code is based on latency-monitor (https://github.com/mlucool/latency-monitor) by mlucool (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)

globalThis
SummaryObject

Type: Object

Properties
events (Number) : How many events were called
minMS (Number) : What was the min time for a cb to be called
maxMS (Number) : What was the max time for a cb to be called
avgMs (Number) : What was the average time for a cb to be called
lengthMs (Number) : How long this interval was in ms

A class to monitor latency of any async function which works in a browser or node. This works by periodically calling the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this. This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.

The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop and timing how long it takes to get back.

new LatencyMonitor($0: Object, latencyCheckIntervalMs: Number, dataEmitIntervalMs: Number, asyncTestFn: function?, latencyRandomPercentage: Number)

Extends EventEmitter

Parameters
$0 (Object = {})
Name Description
$0.latencyCheckIntervalMs any
$0.dataEmitIntervalMs any
$0.asyncTestFn any
$0.latencyRandomPercentage any
latencyCheckIntervalMs (Number = 500) How often to add a latency check event (ms)
dataEmitIntervalMs (Number = 5000) How often to summarize latency check events. null or 0 disables event firing
asyncTestFn (function?) What cb-style async function to use
latencyRandomPercentage (Number = 5) What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.
Example
const monitor = new LatencyMonitor();
monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary));
const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping});
monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary));
Instance Members
getSummary()

This code is based on latency-monitor (https://github.com/mlucool/latency-monitor) by mlucool (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)

Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.

Warning: This does not work on all browsers, but should work on all modern browsers

new VisibilityChangeEmitter()
Example
const myVisibilityEmitter = new VisibilityChangeEmitter();

    myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {
       if ( pageInFocus ){
           // Page is in focus
           console.log('In focus');
       }
       else {
           // Page is blurred
           console.log('Out of focus');
       }
    });
    // To access the visibility state directly, call:
    console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());

The function returns true if the page is visible or false if the page is not visible and undefined if the page visibility API is not supported by the browser.

isVisible(): (Boolean | void)
Returns
(Boolean | void): whether the page is now visible or not (undefined is unknown)

Creates an instance of Circuit.

new constructor(options: object)
Parameters
options (object)
Name Description
options.libp2p Libp2p
options.upgrader Upgrader

Dial a peer over a relay

dial(ma: multiaddr, options: Object): Connection
Parameters
ma (multiaddr) the multiaddr of the peer to dial
options (Object) dial options
Name Description
options.signal AbortSignal? An optional abort signal
Returns
Connection: the connection

createListener

src/circuit/index.js

Create a listener

createListener(options: any, handler: Function): listener
Parameters
options (any)
handler (Function)
Returns
listener:

Filter check for all Multiaddrs that this transport can dial on

filter(multiaddrs: Array<Multiaddr>): Array<Multiaddr>
Parameters
multiaddrs (Array<Multiaddr>)
Returns
Array<Multiaddr>:
index

Type: Circuit

Static Members
multicodecs
listener(circuit: any): Listener
Parameters
circuit (any)
Returns
Listener: a transport listener
Static Members
listen(addr)
close()
getAddrs()

Performs a HOP request to a relay peer, to request a connection to another peer. A new, virtual, connection will be created between the two via the relay.

hop(options: object): Promise<Connection>
Parameters
options (object)
Name Description
options.connection Connection Connection to the relay
options.request any
options.circuit Circuit
Returns
Promise<Connection>:

Write a response

writeResponse(streamHandler: StreamHandler, status: CircuitRelay.Status)
Parameters
streamHandler (StreamHandler)
status (CircuitRelay.Status)

Validate incomming HOP/STOP message

validateAddrs(msg: any, streamHandler: StreamHandler)
Parameters
msg (any) A CircuitRelay unencoded protobuf message
streamHandler (StreamHandler)

Create a stream handler for connection

constructor(options: object)
Parameters
options (object)
Name Description
options.stream any A duplex iterable
options.maxLength Number (default 4096) max bytes length of message

Read and decode message

read(): void
Returns
void:

Encode and write array of buffers

write(msg: any)
Parameters
msg (any) An unencoded CircuitRelay protobuf message

Return the handshake rest stream and invalidate handler

rest(): any
Returns
any: A duplex iterable

Close the stream

close(): void
Returns
void:
new constructor($0: Object, options: object, peerStore: Peerstore)
Parameters
$0 (Object)
Name Description
$0.transportManager any
$0.peerStore any
$0.concurrency any (default MAX_PARALLEL_DIALS)
$0.timeout any (default DIAL_TIMEOUT)
$0.perPeerLimit any (default MAX_PER_PEER_DIALS)
options (object)
Name Description
options.transportManager TransportManager
options.concurrency number Number of max concurrent dials. Defaults to MAX_PARALLEL_DIALS
options.timeout number How long a dial attempt is allowed to take. Defaults to DIAL_TIMEOUT
peerStore (Peerstore)

Clears any pending dials

destroy()

connectToPeer

src/dialer/index.js

Connects to a given PeerId or Multiaddr by dialing all of its known addresses. The dial to the first address that is successfully able to upgrade a connection will be used.

connectToPeer(peer: (PeerInfo | Multiaddr), options: object?): Promise<Connection>
Parameters
peer ((PeerInfo | Multiaddr)) The peer to dial
options (object? = {})
Name Description
options.signal AbortSignal? An AbortController signal
Returns
Promise<Connection>:

_createDialTarget

src/dialer/index.js
_createDialTarget(peer: any)
Parameters
peer (any)
Properties
id (string)
addrs (Array<Multiaddr>)

_createPendingDial

src/dialer/index.js
_createPendingDial(dialTarget: any, options: any)
Parameters
dialTarget (any)
options (any)
Properties
dialRequest (DialRequest)
controller (TimeoutController)
promise (Promise)
destroy (function (): void)

Converts the given peer into a PeerInfo or Multiaddr.

getDialable(peer: (PeerInfo | PeerId | Multiaddr | string)): (PeerInfo | Multiaddr)
Parameters
peer ((PeerInfo | PeerId | Multiaddr | string))
Returns
(PeerInfo | Multiaddr):

Manages running the dialAction on multiple provided addrs in parallel up to a maximum determined by the number of tokens returned from dialer.getTokens. Once a DialRequest is created, it can be started using DialRequest.run(options). Once a single dial has succeeded, all other dials in the request will be cancelled.

constructor(options: object)
Parameters
options (object)
Name Description
options.addrs Array<Multiaddr>
options.dialAction function (Multiaddr): Promise<Connection>
options.dialer Dialer
run(options: object): Connection
Parameters
options (object)
Name Description
options.signal AbortSignal An AbortController signal
Returns
Connection:
constructor(options: object)
Parameters
options (object)
Name Description
options.computeThrottleMaxQueueSize number
options.computeThrottleTimeout number
options.movingAverageIntervals Array<number>
options.maxOldPeersRetention number

Must be called for stats to saved. Any data pushed for tracking will be ignored.

start()

Stops all averages timers and prevents new data from being tracked. Once stop is called, start must be called to resume stats tracking.

stop()

Gets the global Stats object

global
Returns
Stats:

Returns a list of PeerId strings currently being tracked

peers
Returns
Array<string>:

Returns the Stats object for the given PeerId whether it is a live peer, or in the disconnected peer LRU cache.

forPeer(peerId: PeerId): Stats
Parameters
peerId (PeerId)
Returns
Stats:

Returns a list of all protocol strings currently being tracked.

protocols
Returns
Array<string>:

Returns the Stats object for the given protocol.

forProtocol(protocol: string): Stats
Parameters
protocol (string)
Returns
Stats:

onPeerDisconnected

src/metrics/index.js

Should be called when all connections to a given peer have closed. The Stats collection for the peer will be stopped and moved to an LRU for temporary retention.

onPeerDisconnected(peerId: PeerId)
Parameters
peerId (PeerId)

updatePlaceholder

src/metrics/index.js

Replaces the PeerId string with the given peerId. If stats are already being tracked for the given peerId, the placeholder stats will be merged with the existing stats.

updatePlaceholder(placeholder: PeerId, peerId: PeerId)
Parameters
placeholder (PeerId) A peerId string
peerId (PeerId)

Tracks data running through a given Duplex Iterable stream. If the peerId is not provided, a placeholder string will be created and returned. This allows lazy tracking of a peer when the peer is not yet known. When the PeerId is known, Metrics.updatePlaceholder should be called with the placeholder string returned from here, and the known PeerId.

trackStream(options: Object): string
Parameters
options (Object)
Name Description
options.stream {sink: function (any), source: function ()} A duplex iterable stream
options.protocol string? The protocol the stream is running
options.peerId PeerId? The id of the remote peer that's connected
options.remotePeer any
Returns
string: The peerId string or placeholder string

Merges other into target. target will be modified and returned.

mergeStats(target: Stats, other: Stats): Stats
Parameters
target (Stats)
other (Stats)
Returns
Stats:

Creates and returns a Least Recently Used Cache

old-peers(maxSize: Number): LRUCache
Parameters
maxSize (Number)
Returns
LRUCache:

A queue based manager for stat processing

new Stats(initialCounters: Array<string>, options: any)

Extends EventEmitter

Parameters
initialCounters (Array<string>)
options (any)
Instance Members
start()
stop()
snapshot
movingAverages
toJSON()
push(counter, inc)
new constructor(options: object)
Parameters
options (object)
Name Description
options.libp2p Libp2p The Libp2p instance. It will be passed to the transports.
options.upgrader Upgrader The upgrader to provide to the transports

Adds a Transport to the manager

add(key: String, Transport: Transport, transportOptions: any): void
Parameters
key (String)
Transport (Transport)
transportOptions (any = {}) Additional options to pass to the transport
Returns
void:

Stops all listeners

close()

Dials the given Multiaddr over it's supported transport

dial(ma: Multiaddr, options: any): Promise<Connection>
Parameters
ma (Multiaddr)
options (any)
Returns
Promise<Connection>:

Returns all Multiaddr's the listeners are using

getAddrs(): Array<Multiaddr>
Returns
Array<Multiaddr>:

Returns all the transports instances.

getTransports(): Iterator<Transport>
Returns
Iterator<Transport>:

transportForMultiaddr

src/transport-manager.js

Finds a transport that matches the given Multiaddr

transportForMultiaddr(ma: Multiaddr): (Transport | null)
Parameters
ma (Multiaddr)
Returns
(Transport | null):

Starts listeners for each given Multiaddr.

listen(addrs: Array<Multiaddr>)
Parameters
addrs (Array<Multiaddr>)

Removes the given transport from the manager. If a transport has any running listeners, they will be closed.

remove(key: string)
Parameters
key (string)

Removes all transports from the manager. If any listeners are running, they will be closed.

removeAll()
new Upgrader($0: Object)
Parameters
$0 (Object)
Name Description
$0.localPeer any
$0.metrics any
$0.cryptos any
$0.muxers any
$0.onConnectionEnd any (default ()=>{})
$0.onConnection any (default ()=>{})
Properties
sink (function)
source (AsyncIterator)
conn (any)
remoteAddr (Multiaddr)
Instance Members
upgradeInbound(maConn)
upgradeOutbound(maConn)
new Upgrader($0: Object, options: object)
Parameters
$0 (Object)
Name Description
$0.localPeer any
$0.metrics any
$0.cryptos any
$0.muxers any
$0.onConnectionEnd any (default ()=>{})
$0.onConnection any (default ()=>{})
options (object)
Properties
conn (any) : A duplex iterable
remotePeer (PeerId)
protocol (string)
Instance Members
upgradeInbound(maConn)
upgradeOutbound(maConn)

Responsible for managing known peers, as well as their addresses and metadata

new PeerStore()

Extends EventEmitter

Instance Members
peers
put(peerInfo, options = {silent:false})
add(peerInfo)
update(peerInfo)
get(peerId)
has(peerId)
remove(peerId)
replace(peerInfo)
multiaddrsForPeer(peer)

Responsible for notifying registered protocols of events in the network.

new Registrar($0: Object, props: Object)
Parameters
$0 (Object)
Name Description
$0.peerStore any
props (Object)
Instance Members
connections
topologies
close()
onConnect(peerInfo, conn)
onDisconnect(peerInfo, connection, error?)
getConnection(peerInfo)
register(topology)
unregister(id)

Ping a given peer and wait for its response, getting the operation latency.

ping(node: Libp2p, peer: PeerInfo): Promise<Number>
Parameters
node (Libp2p)
peer (PeerInfo)
Returns
Promise<Number>:

Subscribe ping protocol handler.

mount(node: Libp2p)
Parameters
node (Libp2p)

Unsubscribe ping protocol handler.

unmount(node: Libp2p)
Parameters
node (Libp2p)
new constructor(options: object)
Parameters
options (object)
Name Description
options.registrar Registrar
options.protocols Map<string, handler> A reference to the protocols we support
options.peerInfo PeerInfo The peer running the identify service
registrar
peerInfo

Send an Identify Push update to the list of connections

push(connections: Array<Connection>): Promise<void>
Parameters
connections (Array<Connection>)
Returns
Promise<void>:

pushToPeerStore

src/identify/index.js

Calls push for all peers in the peerStore that are connected

pushToPeerStore(peerStore: PeerStore)
Parameters
peerStore (PeerStore)

Requests the Identify message from peer associated with the given connection. If the identified peer does not match the PeerId associated with the connection, an error will be thrown.

identify(connection: Connection): Promise<void>
Parameters
connection (Connection)
Returns
Promise<void>:

A handler to register with Libp2p to process identify messages.

handleMessage(options: object): Promise<void>
Parameters
options (object)
Name Description
options.connection Connection
options.stream any
options.protocol String
Returns
Promise<void>:

updatePeerAddresses

src/identify/index.js

Replaces the multiaddrs on the given peerInfo, with the provided multiaddrs

updatePeerAddresses(peerInfo: PeerInfo, multiaddrs: (Array<Multiaddr> | Array<Buffer>))
Parameters
peerInfo (PeerInfo)
multiaddrs ((Array<Multiaddr> | Array<Buffer>))

updatePeerProtocols

src/identify/index.js

Replaces the protocols on the given peerInfo, with the provided protocols

updatePeerProtocols(peerInfo: PeerInfo, protocols: Array<string>)
Parameters
peerInfo (PeerInfo)
protocols (Array<string>)

getCleanMultiaddr

src/identify/index.js

Takes the addr and converts it to a Multiaddr if possible

getCleanMultiaddr(addr: (Buffer | String)): (Multiaddr | null)
Parameters
addr ((Buffer | String))
Returns
(Multiaddr | null):