0.27.7
Installable via npm install --save libp2p
, it can also be used directly in the browser.
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')
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
Extends EventEmitter
(any)
Stop the libp2p node by closing its listeners and open connections
void
:
Dials to the provided peer and handshakes with the given protocol.
If successful, the PeerInfo
of the peer will be added to the nodes peerStore
,
and the Connection
will be sent in the callback
((PeerInfo | PeerId | Multiaddr | string))
The peer to dial
(object)
Name | Description |
---|---|
options.signal AbortSignal?
|
Promise<(Connection | any)>
:
Iterates over all peer routers in series to find the given peer.
(String)
The id of the peer to find
Promise<PeerInfo>
:
Iterates over all content routers in series to find providers of the given key. Once a content router succeeds, iteration will stop.
(CID)
The CID key of the content to find
AsyncIterable<PeerInfo>
:
Iterates over all content routers in parallel to notify it is a provider of the given key.
(CID)
The CID key of the content to find
Promise<void>
:
Store the given key/value pair in the DHT.
Promise<void>
:
Get the value to the given key. Times out after 1 minute by default.
(Buffer)
Promise<{from: PeerId, val: Buffer}>
:
Get the n
values to the given key without sorting.
Promise<Array<{from: PeerId, val: Buffer}>>
:
Subscribe the given handler to a pubsub topic
void
:
Unsubscribes from a pubsub topic
Publish messages to the given topics.
Promise<void>
:
Get a list of topics the node is subscribed to.
Array<String>
:
topics
Get a list of the peer-ids that are subscribed to one topic.
(string)
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
.
PeerInfo
:
If getPeerInfo
does not return a peer with multiaddrs,
the libp2p
PeerRouter will be used to attempt to find the peer.
Promise<PeerInfo>
:
(Libp2p)
(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.
Stops the Connection Manager
Sets the value of the given peer. Peers with lower values will be disconnected first.
(PeerId)
(number)
A number between 0 and 1
Tracks the incoming connection and check the connection limit
(Connection)
Removes the connection from tracking
(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)
Type: Object
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.
Extends EventEmitter
(Object
= {}
)
Name | Description |
---|---|
$0.latencyCheckIntervalMs any
|
|
$0.dataEmitIntervalMs any
|
|
$0.asyncTestFn any
|
|
$0.latencyRandomPercentage any
|
(Number
= 500
)
How often to add a latency check event (ms)
(Number
= 5000
)
How often to summarize latency check events. null or 0 disables event firing
(function?)
What cb-style async function to use
(Number
= 5
)
What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.
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));
Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue, it will not count for this time period
SummaryObject
:
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
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.
(Boolean | void)
:
whether the page is now visible or not (undefined is unknown)
Creates an instance of Circuit.
Dial a peer over a relay
(multiaddr)
the multiaddr of the peer to dial
(Object)
dial options
Name | Description |
---|---|
options.signal AbortSignal?
|
An optional abort signal |
Connection
:
the connection
Create a listener
(any)
(Function)
listener
:
Filter check for all Multiaddrs that this transport can dial on
(Array<Multiaddr>)
Array<Multiaddr>
:
Type: Circuit
The protocols the IdentifyService supports
(any)
Listener
:
a transport listener
Add swarm handler and listen for incoming connections
(Multiaddr)
void
:
TODO: Remove the peers from our topology
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
Array<Multiaddr>
:
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.
(object)
Name | Description |
---|---|
options.connection Connection
|
Connection to the relay |
options.request any
|
|
options.circuit Circuit
|
Promise<Connection>
:
Write a response
(StreamHandler)
(CircuitRelay.Status)
Validate incomming HOP/STOP message
(any)
A CircuitRelay unencoded protobuf message
(StreamHandler)
Create a stream handler for connection
Read and decode message
void
:
Encode and write array of buffers
(any)
An unencoded CircuitRelay protobuf message
Return the handshake rest stream and invalidate handler
any
:
A duplex iterable
Close the stream
void
:
(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 )
|
(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)
Clears any pending dials
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.
((PeerInfo | Multiaddr))
The peer to dial
(object?
= {}
)
Name | Description |
---|---|
options.signal AbortSignal?
|
An AbortController signal |
Promise<Connection>
:
(any)
(any)
(any)
(DialRequest)
(TimeoutController)
(Promise)
(function (): void)
Converts the given peer
into a PeerInfo
or Multiaddr
.
((PeerInfo | PeerId | Multiaddr | string))
(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.
(object)
Name | Description |
---|---|
options.signal AbortSignal
|
An AbortController signal |
Connection
:
Must be called for stats to saved. Any data pushed for tracking will be ignored.
Stops all averages timers and prevents new data from being tracked.
Once stop
is called, start
must be called to resume stats tracking.
Gets the global Stats
object
Stats
:
Returns a list of PeerId
strings currently being tracked
Array<string>
:
Returns the Stats
object for the given PeerId
whether it
is a live peer, or in the disconnected peer LRU cache.
(PeerId)
Stats
:
Returns a list of all protocol strings currently being tracked.
Array<string>
:
Returns the Stats
object for the given protocol
.
(string)
Stats
:
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.
(PeerId)
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.
(PeerId)
A peerId string
(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
.
string
:
The peerId string or placeholder string
Merges other
into target
. target
will be modified
and returned.
Stats
:
Creates and returns a Least Recently Used Cache
(Number)
LRUCache
:
A queue based manager for stat processing
Extends EventEmitter
Initializes the internal timer if there are items in the queue. This
should only need to be called if Stats.stop
was previously called, as
Stats.push
will also start the processing.
void
:
Stops processing and computing of stats by clearing the internal timer.
void
:
Returns a clone of the internal movingAverages
Array<MovingAverage>
:
Returns a plain JSON object of the stats
any
:
Adds a Transport
to the manager
(String)
(Transport)
(any
= {}
)
Additional options to pass to the transport
void
:
Stops all listeners
Dials the given Multiaddr over it's supported transport
(Multiaddr)
(any)
Promise<Connection>
:
Returns all Multiaddr's the listeners are using
Array<Multiaddr>
:
Returns all the transports instances.
Iterator<Transport>
:
Finds a transport that matches the given Multiaddr
(Multiaddr)
(Transport | null)
:
Starts listeners for each given Multiaddr.
(Array<Multiaddr>)
Removes the given transport from the manager. If a transport has any running listeners, they will be closed.
(string)
Removes all transports from the manager. If any listeners are running, they will be closed.
(Object)
Name | Description |
---|---|
$0.localPeer any
|
|
$0.metrics any
|
|
$0.cryptos any
|
|
$0.muxers any
|
|
$0.onConnectionEnd any
(default ()=>{} )
|
|
$0.onConnection any
(default ()=>{} )
|
(Object)
Name | Description |
---|---|
$0.localPeer any
|
|
$0.metrics any
|
|
$0.cryptos any
|
|
$0.muxers any
|
|
$0.onConnectionEnd any
(default ()=>{} )
|
|
$0.onConnection any
(default ()=>{} )
|
(object)
Responsible for managing known peers, as well as their addresses and metadata
Extends EventEmitter
Map of peers
Stores the peerInfo of a new peer.
If already exist, its info is updated. If silent
is set to
true, no 'peer' event will be emitted. This can be useful if you
are already in the process of dialing the peer. The peer is technically
known, but may not have been added to the PeerStore yet.
(PeerInfo)
PeerInfo
:
Add a new peer to the store.
(PeerInfo)
PeerInfo
:
Updates an already known peer.
(PeerInfo)
PeerInfo
:
Completely replaces the existing peers metadata with the given peerInfo
(PeerInfo)
void
:
Responsible for notifying registered protocols of events in the network.
Map of connections per peer TODO: this should be handled by connectionManager
Map of topologies
Cleans up the registrar
Add a new connected peer to the record TODO: this should live in the ConnectionManager
(PeerInfo)
(Connection)
void
:
Remove a disconnected peer from the record TODO: this should live in the ConnectionManager
void
:
Get a connection with a peer.
(PeerInfo)
Connection
:
Ping a given peer and wait for its response, getting the operation latency.
(Libp2p)
(PeerInfo)
Promise<Number>
:
Subscribe ping protocol handler.
(Libp2p)
Unsubscribe ping protocol handler.
(Libp2p)
Send an Identify Push update to the list of connections
(Array<Connection>)
Promise<void>
:
Calls push
for all peers in the peerStore
that are connected
(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.
(Connection)
Promise<void>
:
A handler to register with Libp2p to process identify messages.
Promise<void>
:
Replaces the multiaddrs on the given peerInfo
,
with the provided multiaddrs
Replaces the protocols on the given peerInfo
,
with the provided protocols
Takes the addr
and converts it to a Multiaddr if possible
(Multiaddr | null)
: