0.28.2
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
:
Load keychain keys from the datastore. Imports the private key as 'self', if needed.
void
:
Dials to the provided peer and handshakes with the given protocol.
If successful, the known metadata of the peer will be added to the nodes peerStore
,
and the Connection
will be returned
((PeerId | Multiaddr | string))
The peer to dial
(object)
Name | Description |
---|---|
options.signal AbortSignal?
|
Promise<(Connection | any)>
:
Get peer advertising multiaddrs by concating the addresses used by transports to listen with the announce addresses. Duplicated addresses and noAnnounce addresses are filtered out.
Array<Multiaddr>
:
Iterates over all peer routers in series to find the given peer.
(String)
The id of the peer to find
Promise<{id: PeerId, multiaddrs: Array<Multiaddr>}>
:
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<{id: PeerId, multiaddrs: Array<Multiaddr>}>
:
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 Peer
object.
If a multiaddr is received, the addressBook is updated.
{id: PeerId, multiaddrs: Array<Multiaddr>}
:
Responsible for managing this peers addresses. Peers can specify their listen, announce and noAnnounce addresses. The listen addresses will be used by the libp2p transports to listen for new connections, while the announce an noAnnounce addresses will be combined with the listen addresses for address adverstising to other peers in the network.
(Object
= {}
)
Name | Description |
---|---|
$0.listen any
(default [] )
|
|
$0.announce any
(default [] )
|
|
$0.noAnnounce any
(default [] )
|
(object?)
Responsible for managing known connections.
Extends EventEmitter
Map of peer identifiers to their peer value for pruning connections.
Map of connections per peer
Get current number of open connections.
Starts the Connection Manager. If Metrics are not enabled on libp2p only event loop and connection limits will be monitored.
Stops the Connection Manager
Cleans up the connections
Tracks the incoming connection and check the connection limit
(Connection)
Removes the connection from tracking
(Connection)
Get a connection with a peer.
(PeerId)
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 peer
by dialing all of its known addresses.
The dial to the first address that is successfully able to upgrade a connection
will be used.
((PeerId | Multiaddr | string))
The peer to dial
(object?
= {}
)
Name | Description |
---|---|
options.signal AbortSignal?
|
An AbortController signal |
Promise<Connection>
:
(any)
(any)
(any)
(DialRequest)
(TimeoutController)
(Promise)
(function (): void)
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
:
Information about a key.
Type: Object
Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.
A key in the store has two entries
(DS)
where the key are.
(object)
???
Gets an object that can encrypt/decrypt protected data using the Cryptographic Message Syntax (CMS).
CMS describes an encapsulation syntax for data protection. It is used to digitally sign, digest, authenticate, or encrypt arbitrary message content.
CMS
:
Cryptographic Message Syntax (aka PKCS #7)
CMS describes an encapsulation syntax for data protection. It is used to digitally sign, digest, authenticate, or encrypt arbitrary message content.
See RFC 5652 for all the details.
(Keychain)
the available keys
Gets a self-signed X.509 certificate for the key.
The output Buffer contains the PKCS #7 message in DER.
TODO: move to libp2p-crypto package
(KeyInfo)
The id and name of the key
(RsaPrivateKey)
The naked key
undefined
:
Finds the first item in a collection that is matched in the
asyncCompare
function.
asyncCompare
is an async function that must
resolve to either true
or false
.
(Array)
(function (any))
An async function that returns a boolean
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 listen 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.
Enum Transport Manager Fault Tolerance values. FATAL_ALL should be used for failing in any listen circumstance. NO_FATAL should be used for not failing when not listening.
Type: number
(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, protocols and metadata.
Extends EventEmitter
AddressBook containing a map of peerIdStr to Address.
KeyBook containing a map of peerIdStr to their PeerId with public keys.
MetadataBook containing a map of peerIdStr to their metadata Map.
ProtoBook containing a map of peerIdStr to supported protocols.
Start the PeerStore.
Stop the PeerStore.
Get the stored information of a given peer.
(PeerId)
Peer
:
The AddressBook is responsible for keeping the known multiaddrs of a peer.
Extends Book
(PeerStore)
Map known peers to their known Addresses.
Set known multiaddrs of a provided peer.
(PeerId)
(Array<Multiaddr>)
AddressBook
:
Add known addresses of a provided peer. If the peer is not known, it is set with the given addresses.
(PeerId)
(Array<Multiaddr>)
AddressBook
:
PeerStore Event emitter, used by the AddressBook to emit: "peer" - emitted when a peer is discovered by the node. "change:multiaddrs" - emitted when the known multiaddrs of a peer change.
PeerStore Event emitter, used by the ProtoBook to emit: "change:protocols" - emitted when the known protocols of a peer change.
The Book is the skeleton for the PeerStore books.
(Object)
Name | Description |
---|---|
$0.peerStore any
|
|
$0.eventName any
|
|
$0.eventProperty any
|
|
$0.eventTransformer any
(default passthrough )
|
(Object)
Map known peers to their data.
The KeyBook is responsible for keeping the known public keys of a peer.
Extends Book
(PeerStore)
Map known peers to their known Public Key.
Get Public key of the given PeerId, if stored.
(PeerId)
(RsaPublicKey | Ed25519PublicKey | Secp256k1PublicKey)
:
The MetadataBook is responsible for keeping the known supported protocols of a peer.
Extends Book
(PeerStore)
Set data into the datastructure
PeerStore Event emitter, used by the MetadataBook to emit: "change:metadata" - emitted when the known metadata of a peer change.
The ProtoBook is responsible for keeping the known supported protocols of a peer.
Extends Book
(PeerStore)
Responsible for managing the persistence of data in the PeerStore.
Extends PeerStore
Backend datastore used to persist data.
Peers modified after the latest data persisted.
Peers metadata changed mapping peer identifers to metadata changed.
Responsible for notifying registered protocols of events in the network.
Map of topologies
Get a connection with a peer.
(PeerId)
Connection
:
Ping a given peer and wait for its response, getting the operation latency.
(Libp2p)
(PeerId)
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>
:
Takes the addr
and converts it to a Multiaddr if possible
(Multiaddr | null)
: