libp2p

0.26.2

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 ES2015 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)
Instance Members
emit(eventName, args)
start(callback)
stop(callback)
dial(peer, callback)
dialProtocol(peer, protocol, callback)
dialFSM(peer, protocol, callback)
hangUp(peer, callback)
ping(peer, callback)

createLibp2p

src/index.js

Like new Libp2p(options) except it will create a PeerInfo instance if one is not provided in options.

createLibp2p
Parameters
options (object) Libp2p configuration options
callback (function (Error, Libp2p))
Returns
void:
new Switch(peerInfo: any, peerBook: any, options: any)

Extends EventEmitter

Parameters
peerInfo (any)
peerBook (any)
options (any)
Instance Members
availableTransports(peerInfo)
handle(protocol, handlerFunc, matchFunc)
unhandle(protocol)
hangUp(peer, callback)
hasTransports()
start(callback)
stop(callback)

Creates an instance of Dialer.

constructor(swarm: Swarm, options: any)
Parameters
swarm (Swarm) the swarm
options (any) config options

_dialSwarmRelays

src/circuit/circuit.js

Dial the relays in the Addresses.Swarm config

_dialSwarmRelays(relays: Array): void
Parameters
relays (Array)
Returns
void:

Dial a peer over a relay

dial(ma: multiaddr, options: Object, cb: Function): Connection
Parameters
ma (multiaddr) the multiaddr of the peer to dial
options (Object) dial options
cb (Function) a callback called once dialed
Returns
Connection: the connection

Create a listener

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

Filter check for all multiaddresses that this transport can dial on

filter(multiaddrs: any): Array<multiaddr>
Parameters
multiaddrs (any)
Returns
Array<multiaddr>:

Creates an instance of Dialer.

constructor(swarm: Swarm, options: any)
Parameters
swarm (Swarm) the swarm
options (any) config options

Helper that returns a relay connection

_dialRelayHelper(relay: any, callback: any): Function
Parameters
relay (any)
callback (any)
Returns
Function: callback

Dial a peer over a relay

dial(ma: multiaddr, cb: Function): Connection
Parameters
ma (multiaddr) the multiaddr of the peer to dial
cb (Function) a callback called once dialed
Returns
Connection: the connection

Does the peer support the HOP protocol

canHop(peer: PeerInfo, callback: Function): void
Parameters
peer (PeerInfo)
callback (Function)
Returns
void:

Create a stream handler for connection

constructor(conn: Connection, cb: (Function | undefined), timeout: Number, maxLength: Number)
Parameters
conn (Connection) connection to read/write
cb ((Function | undefined)) handshake callback called on error
timeout (Number) handshake timeout
maxLength (Number) max bytes length of message

Read and decode message

read(cb: Function): (void | Function)
Parameters
cb (Function)
Returns
(void | Function):

Encode and write array of buffers

write(msg: Array<Buffer>, cb: Function?): Function
Parameters
msg (Array<Buffer>)
cb (Function?)
Returns
Function:

Get the raw Connection

getRawConn(): (null | Connection | any)
Returns
(null | Connection | any):

Return the handshake rest stream and invalidate handler

rest(): (any | {source, sink})
Returns
(any | {source, sink}):

Close the stream

close(): undefined
Returns
undefined:

Get b58 string from multiaddr or peerinfo

getB58String(peer: (Multiaddr | PeerInfo)): any
Parameters
peer ((Multiaddr | PeerInfo))
Returns
any:

Checks if peer has an existing connection

isPeerConnected(peerId: String, swarm: Swarm): Boolean
Parameters
peerId (String)
swarm (Swarm)
Returns
Boolean:

Write a response

writeResponse(streamHandler: StreamHandler, status: CircuitRelay.Status, cb: Function): any
Parameters
streamHandler (StreamHandler)
status (CircuitRelay.Status)
cb (Function)
Returns
any:

Validate incomming HOP/STOP message

validateAddrs(msg: CircuitRelay, streamHandler: StreamHandler, type: CircuitRelay.Type, cb: Function): any
Parameters
msg (CircuitRelay)
streamHandler (StreamHandler)
type (CircuitRelay.Type)
cb (Function)
Returns
any:

Add swarm handler and listen for incoming connections

listen(ma: Multiaddr, callback: Function): void
Parameters
ma (Multiaddr)
callback (Function)
Returns
void:

Remove swarm listener

close(cb: Function): void
Parameters
cb (Function)
Returns
void:

Get fixed up multiaddrs

NOTE: This method will grab the peers multiaddrs and expand them such that:

a) If it's an existing /p2p-circuit address for a specific relay i.e. /ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit this method will expand the address to /ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer where QmPeer is this peers id b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit addr, such when dialing over a relay with this address, it will create the circuit using the encapsulated transport address. This is useful when for example, a peer should only be dialed over TCP rather than any other transport

getAddrs(callback: Function): void
Parameters
callback (Function)
Returns
void:

Handle the incoming STOP message

handle(msg: {}, sh: StreamHandler, callback: Function): undefined
Parameters
msg ({}) the parsed protobuf message
sh (StreamHandler) the stream handler wrapped connection
callback (Function) callback
Returns
undefined:

Construct a Circuit object

This class will handle incoming circuit connections and either start a relay or hand the relayed connection to the swarm

constructor(swarm: Swarm, options: Object)
Parameters
swarm (Swarm)
options (Object)

Handle the relay message

handle(message: CircuitRelay, sh: StreamHandler): any
Parameters
message (CircuitRelay)
sh (StreamHandler)
Returns
any:

Connect to STOP

_connectToStop(peer: PeerInfo, srcSh: StreamHandler, callback: function): void
Parameters
peer (PeerInfo)
srcSh (StreamHandler)
callback (function)
Returns
void:

Negotiate STOP

_negotiateStop(dstSh: StreamHandler, srcSh: StreamHandler, message: CircuitRelay, callback: function): void
Parameters
dstSh (StreamHandler)
srcSh (StreamHandler)
message (CircuitRelay)
callback (function)
Returns
void:

TransportManager

src/switch/transport.js

Manages the transports for the switch. This simplifies dialing and listening across multiple transports.

new TransportManager(_switch: any)
Parameters
_switch (any)
Static Members
dialables(transport, multiaddrs, peerInfo)
Instance Members
add(key, transport)
remove(key, callback)
removeAll(callback)
dial(key, peerInfo, callback)
listen(key, _options, handler, callback)
close(key, callback)

Expand addresses in peer info into array of addresses with and without peer ID suffix.

ourAddresses(peerInfo: PeerInfo): Array<String>
Parameters
peerInfo (PeerInfo) Our peer info object
Returns
Array<String>:

Get the destination address of a (possibly relay) multiaddr as a string

getDestination(addr: Multiaddr): String
Parameters
addr (Multiaddr)
Returns
String:

Track dials per peer and limited them.

new LimitDialer(perPeerLimit: number, dialTimeout: number)
Parameters
perPeerLimit (number)
dialTimeout (number)
Instance Members
dialMany(peer, transport, addrs, callback)
dialSingle(peer, transport, addr, token, callback)

Queue up the amount of dials to a given peer.

new DialQueue(limit: number, dialTimeout: number)
Parameters
limit (number)
dialTimeout (number)
Instance Members
push(transport, addr, token, callback)

For a given multistream, registers to handle the given connection

msHandle(multistream: MultistreamDialer, connection: Connection): Promise
Parameters
multistream (MultistreamDialer)
connection (Connection)
Returns
Promise:

For a given multistream, selects the given protocol

msSelect(multistream: MultistreamDialer, protocol: string): Promise
Parameters
multistream (MultistreamDialer)
protocol (string)
Returns
Promise: Resolves the selected Connection

identifyDialer

src/switch/utils.js

Runs identify for the given connection and verifies it against the PeerInfo provided

identifyDialer(connection: Connection, cryptoPeerInfo: PeerInfo): Promise
Parameters
connection (Connection)
cryptoPeerInfo (PeerInfo) The PeerInfo determined during crypto exchange
Returns
Promise: Resolves {peerInfo, observedAddrs}

Get unique values from arr using getValue to determine what is used for uniqueness

uniqueBy(arr: Array, getValue: function (value)): Array
Parameters
arr (Array) The array to get unique values for
getValue (function (value)) The function to determine what is compared
Returns
Array:

Contains methods for binding handlers to the Switch in order to better manage its connections.

new ConnectionManager(_switch: any)
Parameters
_switch (any)
Instance Members
addStreamMuxer(muxer)
crypto(tag, encrypt)
enableCircuitRelay(config)
reuse()
ConnectionOptions

Type: Object

Properties
_switch (Switch) : Our switch instance
peerInfo (PeerInfo) : The PeerInfo of the peer to dial
muxer (Muxer) : Optional - A muxed connection
conn (Connection) : Optional - The base connection
type (string) : Optional - identify the connection as incoming or outgoing. Defaults to out.

ConnectionFSM handles the complex logic of managing a connection between peers. ConnectionFSM is internally composed of a state machine to help improve the usability and debuggability of connections. The state machine also helps to improve the ability to handle dial backoff, coalescing dials and dial locks.

new ConnectionFSM(connectionOptions: ConnectionOptions)

Extends BaseConnection

Parameters
connectionOptions (ConnectionOptions)
Name Description
connectionOptions._switch any
connectionOptions.peerInfo any
connectionOptions.muxer any
connectionOptions.conn any
connectionOptions.type any (default 'out')
Instance Members
dial()
shake(protocol, callback)
upgrade()
_onDialed()
_onDisconnecting()
_didUpgrade(err)
_onStateError(err)
_dial(dialRequest: DialRequest): void
Parameters
dialRequest (DialRequest)
Name Description
dialRequest.peerInfo any
dialRequest.protocol any
dialRequest.options any
dialRequest.callback any
Returns
void:

Starts the DialQueueManager

start(callback: function)
Parameters
callback (function)

Aborts all dials that are queued. This should only be used when the Switch is being stopped

stop(callback: function)
Parameters
callback (function)

Clears the denylist for a given peer

clearDenylist(peerInfo: PeerInfo)
Parameters
peerInfo (PeerInfo)

Attempts to establish a connection to the given peerInfo at a lower priority than a standard dial.

connect(peerInfo: PeerInfo, options: object, callback: function (Error, Connection))
Parameters
peerInfo (PeerInfo)
options (object)
Name Description
options.useFSM boolean Whether or not to return a ConnectionFSM . Defaults to false.
options.priority number Lowest priority goes first. Defaults to 20.
callback (function (Error, Connection))

Adds the dial request to the queue for the given peerInfo The request will be added with a high priority (10).

dial(peerInfo: PeerInfo, protocol: string, callback: function (Error, Connection))
Parameters
peerInfo (PeerInfo)
protocol (string)
callback (function (Error, Connection))

Behaves like dial, except it calls back with a ConnectionFSM

dialFSM(peerInfo: PeerInfo, protocol: string, callback: function (Error, ConnectionFSM))
Parameters
peerInfo (PeerInfo)
protocol (string)
callback (function (Error, ConnectionFSM))
new constructor(_switch: Switch)
Parameters
_switch (Switch)

Allows the DialQueueManager to execute dials

start()

Iterates over all items in the DialerQueue and executes there callback with an error.

This causes the entire DialerQueue to be drained

stop()

Adds the dialRequest to the queue and ensures queue is running

add(dialRequest: DialRequest): void
Parameters
dialRequest (DialRequest)
Name Description
dialRequest.peerInfo any
dialRequest.protocol any
dialRequest.options any
dialRequest.callback any
Returns
void:

Will execute up to MAX_PARALLEL_DIALS dials

run()

Will remove the peerInfo from the dial denylist

clearDenylist(peerInfo: PeerInfo)
Parameters
peerInfo (PeerInfo)

Returns the Queue for the given peerInfo

getQueue(peerInfo: PeerInfo): Queue
Parameters
peerInfo (PeerInfo)
Returns
Queue:

Components required to execute a dial

DialRequest

Type: Object

Properties
peerInfo (PeerInfo) : The peer to dial to
protocol (string?) : The protocol to create a stream for
options (object)
  • options.useFSM boolean

    If callback should return a ConnectionFSM

  • options.priority number

    The priority of the dial

NewConnection

Type: Object

Properties
connectionFSM (ConnectionFSM)
didCreate (boolean)

createConnectionWithProtocol

src/switch/dialer/queue.js

Attempts to create a new connection or stream (when muxed), via negotiation of the given protocol. If no protocol is provided, no action will be taken and callback will be called immediately with no error or values.

createConnectionWithProtocol(options: object): void
Parameters
options (object)
Name Description
options.protocol string
options.connection ConnectionFSM
options.callback function (Error, Connection)
Returns
void:

A convenience array wrapper for controlling a per peer queue

new Queue(peerId: string, _switch: Switch, onStopped: function (string)): Queue
Parameters
peerId (string)
_switch (Switch)
onStopped (function (string)) Called when the queue stops
Returns
Queue:
Instance Members
add(protocol, useFSM, callback)
isDialAllowed()
start()
stop()
abort()
denylist()

Takes a transport key and returns a connection handler function

transportKey
Parameters
transportKey (string) The key of the transport to handle connections for
handler (function) A custom handler to use
Returns
function (Connection): A connection handler function

Takes a base connection and manages listening behavior

conn
Parameters
conn (Connection) The connection to manage
Returns
void:

Puts the state into its disconnecting flow

close(err: Error): void
Parameters
err (Error) Will be emitted if provided
Returns
void:

Gets the current state of the connection

getState(): string
Returns
string: The current state of the connection

Puts the state into encrypting mode

encrypt(): void
Returns
void:

Puts the state into privatizing mode

protect(): void
Returns
void:

Puts the state into muxing mode

upgrade(): void
Returns
void:

Event handler for disconnected.

_onDisconnected(): void
Returns
void:

Event handler for privatized

_onPrivatized(): void
Returns
void:

Creates a pull stream to run the given Connection stream through the given Observer. This provides a way to more easily monitor connections and their metadata. A new Connection will be returned that contains has the attached Observer.

observe-connection(transport: Transport, protocol: string, connection: Connection, observer: Observer): Connection
Parameters
transport (Transport)
protocol (string)
connection (Connection)
observer (Observer)
Returns
Connection:

An encryption stub in the instance that the default crypto has not been overriden for the Switch

plaintext

Takes a Switch and returns an Observer that can be used in conjunction with observe-connection.js. The returned Observer comes with incoming and outgoing properties that can be used in pull streams to emit all metadata for messages that pass through a Connection.

observer(swtch: Switch): EventEmitter
Parameters
swtch (Switch)
Returns
EventEmitter:

Binds to message events on the given observer to generate stats based on the Peer, Protocol and Transport used for the message. Stat events will be emitted via the update event.

Parameters
observer (Observer)
_options (any)
Returns
Stats:

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
push(counter, inc)

Creates and returns a Least Recently Used Cache

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

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

findPeer
Parameters
id (String) The id of the peer to find
options (object)
Name Description
options.maxTimeout number How long the query should run
callback (function (Error, Result<Array>))
Returns
void:

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

findProviders
Parameters
key (CID) The CID key of the content to find
options (object)
Name Description
options.maxTimeout number How long the query should run
options.maxNumProviders number maximum number of providers to find
callback (function (Error, Result<Array>))
Returns
void:

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

provide
Parameters
key (CID) The CID key of the content to find
callback (function (Error))
Returns
void:

subscribe

src/pubsub.js

Subscribe the given handler to a pubsub topic

subscribe(topic: string, handler: function, options: (object | null)?, callback: function?): (Promise | void)
Parameters
topic (string)
handler (function) The handler to subscribe
options ((object | null)?)
callback (function?) An optional callback
Returns
(Promise | void): A promise is returned if no callback is provided
Example

Subscribe a handler to a topic

// `null` must be passed for options until subscribe is no longer using promisify
const handler = (message) => { }
await libp2p.subscribe(topic, handler, null)

Use a callback instead of the Promise api

// `options` may be passed or omitted when supplying a callback
const handler = (message) => { }
libp2p.subscribe(topic, handler, callback)

unsubscribe

src/pubsub.js

Unsubscribes from a pubsub topic

unsubscribe(topic: string, handler: (function | null), callback: function?): (Promise | void)
Parameters
topic (string)
handler ((function | null)) The handler to unsubscribe from
callback (function?) An optional callback
Returns
(Promise | void): A promise is returned if no callback is provided
Example

Unsubscribe a topic for all handlers

// `null` must be passed until unsubscribe is no longer using promisify
await libp2p.unsubscribe(topic, null)

Unsubscribe a topic for 1 handler

await libp2p.unsubscribe(topic, handler)

Use a callback instead of the Promise api

libp2p.unsubscribe(topic, handler, callback)

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

getPeerInfo(peer: (PeerInfo | PeerId | Multiaddr | string), peerBook: PeerBook): PeerInfo
Parameters
peer ((PeerInfo | PeerId | Multiaddr | string))
peerBook (PeerBook)
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>: