- Static Functions
- Instance Methods
loadkeychain
start
stop
dial
dialProtocol
hangUp
handle
unhandle
ping
fetch
fetchService.registerLookupFunction
fetchService.unRegisterLookupFunction
multiaddrs
addressManager.getListenAddrs
addressManager.getAnnounceAddrs
contentRouting.findProviders
contentRouting.provide
contentRouting.put
contentRouting.get
contentRouting.getMany
peerRouting.findPeer
peerRouting.getClosestPeers
peerStore.addressBook.add
peerStore.addressBook.delete
peerStore.addressBook.get
peerStore.addressBook.getMultiaddrsForPeer
peerStore.addressBook.set
peerStore.keyBook.delete
peerStore.keyBook.get
peerStore.keyBook.set
peerStore.metadataBook.delete
peerStore.metadataBook.deleteValue
peerStore.metadataBook.get
peerStore.metadataBook.getValue
peerStore.metadataBook.set
peerStore.protoBook.add
peerStore.protoBook.delete
peerStore.protoBook.get
peerStore.protoBook.remove
peerStore.protoBook.set
peerStore.delete
peerStore.get
peerStore.peers
peerStore.tagPeer
peerStore.unTagPeer
peerStore.getTags
pubsub.getSubscribers
pubsub.getTopics
pubsub.publish
pubsub.subscribe
pubsub.unsubscribe
pubsub.on
pubsub.removeListener
pubsub.topicValidators.set
pubsub.topicValidators.delete
connectionManager.get
connectionManager.size
keychain.createKey
keychain.renameKey
keychain.removeKey
keychain.exportKey
keychain.importKey
keychain.importPeer
keychain.listKeys
keychain.findKeyById
keychain.findKeyByName
keychain.cms.encrypt
keychain.cms.decrypt
metrics.global
metrics.peers
metrics.protocols
metrics.forPeer
metrics.forProtocol
- Events
- Types
Creates an instance of Libp2p.
create(options)
Name | Type | Description |
---|---|---|
options | object |
libp2p options |
options.modules | Array<object> |
libp2p modules to use |
[options.addresses] | { listen: Array<string>, announce: Array<string>, announceFilter: (ma: Array<multiaddr>) => Array<multiaddr> } |
Addresses for transport listening and to advertise to the network |
[options.config] | object |
libp2p modules configuration and core configuration |
[options.identify] | { protocolPrefix: string, host: { agentVersion: string }, timeout: number, maxIdentifyMessageSize: number } |
libp2p identify protocol options |
[options.ping] | { protocolPrefix: string } |
libp2p ping protocol options |
[options.fetch] | { protocolPrefix: string } |
libp2p fetch protocol options |
[options.connectionManager] | object |
libp2p Connection Manager configuration |
[options.transportManager] | object |
libp2p transport manager configuration |
[options.datastore] | object |
must implement ipfs/interface-datastore (in memory datastore will be used if not provided) |
[options.dialer] | object |
libp2p Dialer configuration |
[options.keychain] | object |
keychain configuration |
[options.metrics] | object |
libp2p Metrics configuration |
[options.peerId] | PeerId |
peerId instance (it will be created if not provided) |
[options.peerRouting] | object |
libp2p Peer routing service configuration |
[options.peerStore] | object |
libp2p PeerStore configuration |
For Libp2p configurations and modules details read the Configuration Document.
Type | Description |
---|---|
Promise<Libp2p> |
Promise resolves with the Libp2p instance |
import { createLibp2p } from 'libp2p'
import { TCP } from '@libp2p/tcp'
import { Mplex } from '@libp2p/mplex'
import { Noise } from '@chainsafe/libp2p-noise'
async function main () {
// specify options
const options = {
transports: [new TCP()],
streamMuxers: [new Mplex()],
connectionEncryption: [new Noise()]
}
// create libp2p
const libp2p = await createLibp2p(options)
}
main()
Note: The PeerId
option is not required and will be generated if it is not provided.
Alternative
As an alternative, it is possible to create a Libp2p instance with the constructor:import { createLibp2p } from 'libp2p'
import { TCP } from '@libp2p/tcp'
import { Mplex } from '@libp2p/mplex'
import { Noise } from '@chainsafe/libp2p-noise'
async function main () {
const peerId = await PeerId.create();
// specify options
// peerId is required when Libp2p is instantiated via the constructor
const options = {
peerId,
transports: [new TCP()],
streamMuxers: [new Mplex()],
connectionEncryption: [new Noise()]
}
// create libp2p
const libp2p = new Libp2p(options)
}
main()
Required keys in the options
object:
peerId
: instance ofPeerId
that contains the peer Keys (optional when using.create
).modules.transport
: An array that must include at least 1 compliant transport. See modules that implement the transport interface.
Load keychain keys from the datastore, importing the private key as 'self', if needed.
libp2p.loadKeychain()
Type | Description |
---|---|
Promise |
Promise resolves when the keychain is ready |
import { createLibp2p } from 'libp2p'
// ...
const libp2p = await createLibp2p({
// ...
keychain: {
pass: '0123456789pass1234567890'
}
})
// load keychain
await libp2p.loadKeychain()
Starts the libp2p node.
libp2p.start()
Type | Description |
---|---|
Promise |
Promise resolves when the node is ready |
import { createLibp2p } from 'libp2p'
// ...
const libp2p = await createLibp2p(options)
// start libp2p
await libp2p.start()
Stops the libp2p node.
libp2p.stop()
Type | Description |
---|---|
Promise |
Promise resolves when the node is fully stopped |
import { createLibp2p } from 'libp2p'
// ...
const libp2p = await createLibp2p(options)
// ...
// stop libp2p
await libp2p.stop()
TODO with address-manager
.
A Getter that returns a Map of the current Connections libp2p has to other peers.
libp2p.connections
Type | Description |
---|---|
Map<string, Array<Connection>> |
A map of PeerId strings to Connection Arrays |
for (const [peerId, connections] of libp2p.connections) {
for (const connection of connections) {
console.log(peerId, connection.remoteAddr.toString())
// Logs the PeerId string and the observed remote multiaddr of each Connection
}
}
dial(peer, options)
Name | Type | Description |
---|---|---|
peer | PeerId |Multiaddr |string |
The peer to dial. |
[options] | object |
dial options |
[options.signal] | AbortSignal |
An AbortSignal instance obtained from an AbortController that can be used to abort the connection before it completes |
Note: If a Multiaddr
or its string is provided, it must include the peer id. Moreover, if a PeerId
is given, the peer will need to have known multiaddrs for it in the PeerStore.
Type | Description |
---|---|
Promise<Connection> |
Promise resolves with the Connection instance |
// ...
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 another peer in the network and selects a protocol to communicate with that peer. The stream between both parties is returned, together with the negotiated protocol.
dialProtocol(peer, protocols, options)
Name | Type | Description |
---|---|---|
peer | PeerId |Multiaddr |string |
The peer to dial. |
protocols | `string | Array` |
[options] | object |
dial options |
[options.signal] | AbortSignal |
An AbortSignal instance obtained from an AbortController that can be used to abort the connection before it completes |
Note: If a Multiaddr
or its string is provided, it must include the peer id. Moreover, if a PeerId
is given, the peer will need to have known multiaddrs for it in the PeerStore.
Type | Description |
---|---|
Promise<{ stream:*, protocol:string }> |
Promise resolves with a duplex stream and the protocol used |
// ...
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)
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.
hangUp(peer)
Name | Type | Description |
---|---|---|
peer | PeerId |Multiaddr |string |
peer to hang up |
Type | Description |
---|---|
Promise<void> |
Promise resolves once connection closes |
// ...
await libp2p.hangUp(remotePeerId)
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.
Name | Type | Description |
---|---|---|
protocols | `Array | string` |
handler | function({ connection:*, stream:*, protocol:string }) |
handler to call |
options | StreamHandlerOptions |
Options including protocol stream limits |
// ...
const handler = ({ connection, stream, protocol }) => {
// use stream or connection according to the needs
}
libp2p.handle('/echo/1.0.0', handler, {
maxInboundStreams: 5,
maxOutboundStreams: 5
})
Unregisters all handlers with the given protocols
libp2p.unhandle(protocols)
Name | Type | Description |
---|---|---|
protocols | `Array | string` |
// ...
libp2p.unhandle(['/echo/1.0.0'])
Pings a given peer and get the operation's latency.
libp2p.ping(peer)
Name | Type | Description |
---|---|---|
peer | PeerId |Multiaddr |string |
peer to ping |
Type | Description |
---|---|
Promise<number> |
Latency of the operation in ms |
// ...
const latency = await libp2p.ping(otherPeerId)
Fetch a value from a remote node
libp2p.fetch(peer, key)
Name | Type | Description |
---|---|---|
peer | PeerId |Multiaddr |string |
peer to ping |
key | string |
A key that corresponds to a value on the remote node |
Type | Description |
---|---|
`Promise<Uint8Array | null>` |
// ...
const value = await libp2p.fetch(otherPeerId, '/some/key')
Register a function to look up values requested by remote nodes
libp2p.fetchService.registerLookupFunction(prefix, lookup)
Name | Type | Description |
---|---|---|
prefix | string |
All queries below this prefix will be passed to the lookup function |
lookup | `(key: string) => Promise<Uint8Array | null>` |
// ...
const value = await libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })
Removes the passed lookup function or any function registered for the passed prefix
libp2p.fetchService.unregisterLookupFunction(prefix, lookup)
Name | Type | Description |
---|---|---|
prefix | string |
All queries below this prefix will be passed to the lookup function |
lookup | `(key: string) => Promise<Uint8Array | null>` |
// ...
libp2p.fetchService.unregisterLookupFunction('/prefix')
Gets the multiaddrs the libp2p node announces to the network. This computes the advertising multiaddrs of the peer by joining the multiaddrs that libp2p transports are listening on with the announce multiaddrs provided in the libp2p config. Configured no announce multiaddrs will be filtered out of the advertised addresses.
libp2p.multiaddrs
Type | Description |
---|---|
Array<Multiaddr> |
Advertising multiaddrs |
// ...
const listenMa = libp2p.multiaddrs
// [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]
Get the multiaddrs that were provided for listening on libp2p transports.
libp2p.addressManager.getListenAddrs()
Type | Description |
---|---|
Array<Multiaddr> |
Provided listening multiaddrs |
// ...
const listenMa = libp2p.addressManager.getListenAddrs()
// [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]
Get the multiaddrs that were provided to announce to the network.
libp2p.addressManager.getAnnounceAddrs()
Type | Description |
---|---|
Array<Multiaddr> |
Provided announce multiaddrs |
// ...
const announceMa = libp2p.addressManager.getAnnounceAddrs()
// [ <Multiaddr 047f00000106f9ba - /dns4/peer.io/...> ]
Get the multiaddrs that libp2p transports are using to listen on.
libp2p.transportManager.getAddrs()
Type | Description |
---|---|
Array<Multiaddr> |
listening multiaddrs |
// ...
const listenMa = libp2p.transportManager.getAddrs()
// [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]
Iterates over all content routers in series to find providers of the given key. Once a content router succeeds, the iteration will stop. If the DHT is enabled, it will be queried first.
libp2p.contentRouting.findProviders(cid, options)
Name | Type | Description |
---|---|---|
cid | CID |
cid to find |
options | object |
operation options |
options.timeout | number |
maximum time the query should run |
options.maxNumProviders | number |
maximum number of providers to find |
Type | Description |
---|---|
AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] } |
Async iterator for peer data |
// Iterate over the providers found for the given cid
for await (const provider of libp2p.contentRouting.findProviders(cid)) {
console.log(provider.id, provider.multiaddrs)
}
Iterates over all content routers in parallel, in order to notify it is a provider of the given key.
libp2p.contentRouting.provide(cid)
Name | Type | Description |
---|---|---|
cid | CID |
cid to provide |
Type | Description |
---|---|
Promise<void> |
Promise resolves once notifications are sent |
// ...
await libp2p.contentRouting.provide(cid)
Writes a value to a key in the DHT.
libp2p.contentRouting.put(key, value, options)
Name | Type | Description |
---|---|---|
key | string |
key to add to the dht |
value | Uint8Array |
value to add to the dht |
[options] | object |
put options |
[options.minPeers] | number |
minimum number of peers required to successfully put (default: closestPeers.length) |
Type | Description |
---|---|
Promise<void> |
Promise resolves once value is stored |
// ...
const key = '/key'
const value = uint8ArrayFromString('oh hello there')
await libp2p.contentRouting.put(key, value)
Queries the DHT for a value stored for a given key.
libp2p.contentRouting.get(key, options)
Name | Type | Description |
---|---|---|
key | string |
key to get from the dht |
[options] | object |
get options |
[options.timeout] | number |
maximum time the query should run |
Type | Description |
---|---|
Promise<Uint8Array> |
Value obtained from the DHT |
// ...
const key = '/key'
const value = await libp2p.contentRouting.get(key)
Queries the DHT for the n values stored for the given key (without sorting).
libp2p.contentRouting.getMany(key, nvals, options)
Name | Type | Description |
---|---|---|
key | string |
key to get from the dht |
nvals | number |
number of values aimed |
[options] | object |
get options |
[options.timeout] | number |
maximum time the query should run |
Type | Description |
---|---|
Promise<Array<{from: PeerId, val: Uint8Array}>> |
Array of records obtained from the DHT |
// ...
const key = '/key'
const records = await libp2p.contentRouting.getMany(key, 2)
Iterates over all peer routers in series to find the given peer. If the DHT is enabled, it will be tried first.
libp2p.peerRouting.findPeer(peerId, options)
Name | Type | Description |
---|---|---|
peerId | PeerId |
ID of the peer to find |
options | object |
operation options |
options.timeout | number |
maximum time the query should run |
Type | Description |
---|---|
Promise<{ id: PeerId, multiaddrs: Multiaddr[] }> |
Peer data of a known peer |
// ...
const peer = await libp2p.peerRouting.findPeer(peerId, options)
Iterates over all content routers in series to get the closest peers of the given key. Once a content router succeeds, the iteration will stop. If the DHT is enabled, it will be queried first.
libp2p.peerRouting.getClosestPeers(cid, options)
Name | Type | Description |
---|---|---|
key | Uint8Array |
A CID like key |
options | object |
operation options |
options.timeout | number |
How long the query can take (ms). |
Type | Description |
---|---|
AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] } |
Async iterator for peer data |
// Iterate over the closest peers found for the given key
for await (const peer of libp2p.peerRouting.getClosestPeers(key)) {
console.log(peer.id, peer.multiaddrs)
}
Adds known multiaddrs
of a given peer. If the peer is not known, it will be set with the provided multiaddrs.
peerStore.addressBook.add(peerId, multiaddrs)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to set |
multiaddrs | Array<Multiaddr> |
Type | Description |
---|---|
AddressBook |
Returns the Address Book component |
peerStore.addressBook.add(peerId, multiaddr)
Delete the provided peer from the book.
peerStore.addressBook.delete(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to remove |
Type | Description |
---|---|
boolean |
true if found and removed |
peerStore.addressBook.delete(peerId)
// false
peerStore.addressBook.set(peerId, multiaddr)
peerStore.addressBook.delete(peerId)
// true
Get the known Addresses
of a provided peer.
peerStore.addressBook.get(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to get |
Type | Description |
---|---|
`Array | undefined` |
peerStore.addressBook.get(peerId)
// undefined
peerStore.addressBook.set(peerId, multiaddr)
peerStore.addressBook.get(peerId)
// [
// {
// multiaddr: /ip4/140.10.2.1/tcp/8000,
// ...
// },
// {
// multiaddr: /ip4/140.10.2.1/ws/8001
// ...
// },
// ]
Get the known Multiaddr
of a provided peer. All returned multiaddrs will include the encapsulated PeerId
of the peer.
peerStore.addressBook.getMultiaddrsForPeer(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to get |
Type | Description |
---|---|
`Array | undefined` |
peerStore.addressBook.getMultiaddrsForPeer(peerId)
// undefined
peerStore.addressBook.set(peerId, multiaddr)
peerStore.addressBook.getMultiaddrsForPeer(peerId)
// [
// /ip4/140.10.2.1/tcp/8000/p2p/QmW8rAgaaA6sRydK1k6vonShQME47aDxaFidbtMevWs73t
// /ip4/140.10.2.1/ws/8001/p2p/QmW8rAgaaA6sRydK1k6vonShQME47aDxaFidbtMevWs73t
// ]
Set known multiaddrs
of a given peer. This will replace previously stored multiaddrs, if available.
Replacing stored multiaddrs might result in losing obtained certified addresses, which is not desirable.
Consider using addressBook.add()
if you're not sure this is what you want to do.
peerStore.addressBook.set(peerId, multiaddrs)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to set |
multiaddrs | Array<Multiaddr> |
Type | Description |
---|---|
AddressBook |
Returns the Address Book component |
peerStore.addressBook.add(peerId, multiaddr)
Delete the provided peer from the book.
peerStore.keyBook.delete(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to remove |
Type | Description |
---|---|
boolean |
true if found and removed |
peerStore.keyBook.delete(peerId)
// false
peerStore.keyBook.set(peerId, publicKey)
peerStore.keyBook.delete(peerId)
// true
Get the known PublicKey
of a provided peer.
peerStore.keyBook.get(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to get |
Type | Description |
---|---|
RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey |
Peer PublicKey |
peerStore.keyBook.get(peerId)
// undefined
peerStore.keyBook.set(peerId, publicKey)
peerStore.keyBook.get(peerId)
// PublicKey
Set known peerId
. This can include its Public Key.
peerStore.keyBook.set(peerId, publicKey)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to set |
publicKey | RsaPublicKey|Ed25519PublicKey|Secp256k1PublicKey |
peer's public key |
Type | Description |
---|---|
KeyBook |
Returns the Key Book component |
const publicKey = peerId.pubKey
peerStore.keyBook.set(peerId, publicKey)
Delete the provided peer from the book.
peerStore.metadataBook.delete(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to remove |
Type | Description |
---|---|
boolean |
true if found and removed |
peerStore.metadataBook.delete(peerId)
// false
peerStore.metadataBook.set(peerId, 'nickname', uint8ArrayFromString('homePeer'))
peerStore.metadataBook.delete(peerId)
// true
Deletes the provided peer metadata key-value pair from the book.
peerStore.metadataBook.deleteValue(peerId, key)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to remove |
key | string |
key of the metadata value to remove |
Type | Description |
---|---|
boolean |
true if found and removed |
peerStore.metadataBook.deleteValue(peerId, 'location')
// false
peerStore.metadataBook.set(peerId, 'location', uint8ArrayFromString('Berlin'))
peerStore.metadataBook.deleteValue(peerId, 'location')
// true
Get the known metadata of a provided peer.
peerStore.metadataBook.get(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to get |
Type | Description |
---|---|
Map<string, Uint8Array> |
Peer Metadata |
peerStore.metadataBook.get(peerId)
// undefined
peerStore.metadataBook.set(peerId, 'location', uint8ArrayFromString('Berlin'))
peerStore.metadataBook.get(peerId)
// Metadata Map
Get specific metadata of a provided peer.
peerStore.metadataBook.getValue(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to get |
key | string |
key of the metadata value to get |
Type | Description |
---|---|
Map<string, Uint8Array> |
Peer Metadata |
peerStore.metadataBook.getValue(peerId, 'location')
// undefined
peerStore.metadataBook.set(peerId, 'location', uint8ArrayFromString('Berlin'))
peerStore.metadataBook.getValue(peerId, 'location')
// Metadata Map
Set known metadata of a given peerId
.
peerStore.metadataBook.set(peerId, key, value)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to set |
key | string |
key of the metadata value to store |
value | Uint8Array |
metadata value to store |
Type | Description |
---|---|
MetadataBook |
Returns the Metadata Book component |
peerStore.metadataBook.set(peerId, 'location', uint8ArrayFromString('Berlin'))
Add known protocols
of a given peer.
peerStore.protoBook.add(peerId, protocols)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to set |
protocols | Array<string> |
protocols to add |
Type | Description |
---|---|
ProtoBook |
Returns the Proto Book component |
peerStore.protoBook.add(peerId, protocols)
Delete the provided peer from the book.
peerStore.protoBook.delete(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to remove |
Type | Description |
---|---|
boolean |
true if found and removed |
peerStore.protoBook.delete(peerId)
// false
peerStore.protoBook.set(peerId, protocols)
peerStore.protoBook.delete(peerId)
// true
Get the known protocols
of a provided peer.
peerStore.protoBook.get(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to get |
Type | Description |
---|---|
Array<string> |
Array of peer's supported protocols |
peerStore.protoBook.get(peerId)
// undefined
peerStore.protoBook.set(peerId, [ '/proto/1.0.0', '/proto/1.1.0' ])
peerStore.protoBook.get(peerId)
// [ '/proto/1.0.0', '/proto/1.1.0' ]
Remove given protocols
of a given peer.
peerStore.protoBook.remove(peerId, protocols)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to set |
protocols | Array<string> |
protocols to remove |
Type | Description |
---|---|
ProtoBook |
Returns the Proto Book component |
peerStore.protoBook.remove(peerId, protocols)
Set known protocols
of a given peer.
peerStore.protoBook.set(peerId, protocols)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to set |
protocols | Array<string> |
protocols to store |
Type | Description |
---|---|
ProtoBook |
Returns the Proto Book component |
peerStore.protoBook.set(peerId, protocols)
Delete the provided peer from every book.
peerStore.delete(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to remove |
Type | Description |
---|---|
boolean |
true if found and removed |
peerStore.delete(peerId)
// false
peerStore.addressBook.set(peerId, multiaddrs)
peerStore.protoBook.set(peerId, protocols)
peerStore.delete(peerId)
// true
peerStore.delete(peerId2)
// false
peerStore.addressBook.set(peerId2, multiaddrs)
peerStore.delete(peerId2)
// true
Get the stored information of a given peer, namely its PeerId
, known Addresses
and supported protocols.
peerStore.get(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
peerId to get |
Type | Description |
---|---|
{ id: PeerId, addresses: Array<Address>, metadata: Map<string, Buffer>}, protocols: Array<string> } |
Peer information of the provided peer |
peerStore.get(peerId)
// false
peerStore.addressBook.set(peerId, multiaddrs)
peerStore.protoBook.set(peerId, protocols)
peerStore.get(peerId)
// {
// id: {},
// addresses: [...],
// protocols: [...]
// }
Get all the stored information of every peer.
peerStore.peers
Type | Description |
---|---|
Map<string, { id: PeerId, addresses: Array<Address>, metadata: Map<string, Buffer>}, protocols: Array<string> }> |
Peer data of every peer known |
for (let [peerIdString, peer] of peerStore.peers.entries()) {
// peer { id, addresses, metadata, protocols }
}
Tags a peer with the specified tag and optional value/expiry time
peerStore.tagPeer(peerId, tag, options)
Name | Type | Description |
---|---|---|
peerId | PeerId |
The peer to tag |
tag | string |
The name of the tag to add |
options | { value?: number, ttl?: number } |
An optional value (1-100) and an optional ttl after which the tag will expire (ms) |
Type | Description |
---|---|
Promise<void> |
Promise resolves once the tag is stored |
await peerStore.tagPeer(peerId, 'my-tag', { value: 100, ttl: Date.now() + 60000 })
Remove the tag from the specified peer
peerStore.unTagPeer(peerId, tag)
Name | Type | Description |
---|---|---|
peerId | PeerId |
The peer to untag |
tag | string |
The name of the tag to remove |
Type | Description |
---|---|
Promise<void> |
Promise resolves once the tag has been removed |
await peerStore.unTagPeer(peerId, 'my-tag')
Remove the tag from the specified peer
peerStore.getTags(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
The peer to get the tags for |
Type | Description |
---|---|
Promise<Array<{ name: string, value: number }>> |
The promise resolves to the list of tags for the passed peer |
await peerStore.getTags(peerId)
Gets a list of the peer-ids that are subscribed to one topic.
libp2p.pubsub.getSubscribers(topic)
Name | Type | Description |
---|---|---|
topic | string |
topic to publish |
Type | Description |
---|---|
Array<string> |
peer-id subscribed to the topic |
const peerIds = libp2p.pubsub.getSubscribers(topic)
Gets a list of topics the node is subscribed to.
libp2p.pubsub.getTopics()
Type | Description |
---|---|
Array<string> |
topics the node is subscribed to |
const topics = libp2p.pubsub.getTopics()
Publishes messages to the given topics.
libp2p.pubsub.publish(topic, data)
Name | Type | Description |
---|---|---|
topic | string |
topic to publish |
data | Uint8Array |
data to publish |
Type | Description |
---|---|
Promise |
publish success |
const topic = 'topic'
const data = uint8ArrayFromString('data')
await libp2p.pubsub.publish(topic, data)
Subscribes to a pubsub topic.
libp2p.pubsub.subscribe(topic)
Name | Type | Description |
---|---|---|
topic | string |
topic to subscribe |
Type | Description |
---|---|
void |
const topic = 'topic'
const handler = (msg) => {
// msg.data - pubsub data received
}
libp2p.pubsub.on(topic, handler)
libp2p.pubsub.subscribe(topic)
Unsubscribes from a pubsub topic.
libp2p.pubsub.unsubscribe(topic)
Name | Type | Description |
---|---|---|
topic | string |
topic to unsubscribe |
Type | Description |
---|---|
void |
const topic = 'topic'
const handler = (msg) => {
// msg.data - pubsub data received
}
libp2p.pubsub.removeListener(topic handler)
libp2p.pubsub.unsubscribe(topic)
A Pubsub router is an EventEmitter and uses its events for pubsub message handlers.
libp2p.pubsub.on(topic, handler)
Name | Type | Description |
---|---|---|
topic | string |
topic to listen |
handler | function({ from: string, data: Uint8Array, seqno: Uint8Array, topicIDs: Array<string>, signature: Uint8Array, key: Uint8Array }) |
handler for new data on topic |
Type | Description |
---|---|
void |
const topic = 'topic'
const handler = (msg) => {
// msg.data - pubsub data received
}
libp2p.pubsub.on(topic, handler)
libp2p.pubsub.subscribe(topic)
A Pubsub router is an EventEmitter and uses its events for pubsub message handlers.
libp2p.pubsub.removeListener(topic, handler)
Name | Type | Description |
---|---|---|
topic | string |
topic to remove listener |
handler | function({ from: string, data: Uint8Array, seqno: Uint8Array, topicIDs: Array<string>, signature: Uint8Array, key: Uint8Array }) |
handler for new data on topic |
Type | Description |
---|---|
void |
const topic = 'topic'
const handler = (msg) => {
// msg.data - pubsub data received
}
libp2p.pubsub.removeListener(topic handler)
libp2p.pubsub.unsubscribe(topic)
Pubsub routers support message validators per topic, which will validate the message before its propagations. Set is used to specify a validator for a topic.
libp2p.pubsub.topicValidators.set(topic, validator)
Name | Type | Description |
---|---|---|
topic | string |
topic to bind a validator |
handler | function({ topic: string, msg: RPC }) |
validator for new data on topic |
Type | Description |
---|---|
Map<string, function(string, RPC)> |
The Map object |
const topic = 'topic'
const validateMessage = (msgTopic, msg) => {
const input = uint8ArrayToString(msg.data)
const validInputs = ['a', 'b', 'c']
if (!validInputs.includes(input)) {
throw new Error('no valid input received')
}
}
libp2p.pubsub.topicValidators.set(topic, validateMessage)
Pubsub routers support message validators per topic, which will validate the message before its propagations. Delete is used to remove a validator for a topic.
libp2p.pubsub.topicValidators.delete(topic)
Name | Type | Description |
---|---|---|
topic | string |
topic to remove a validator |
Type | Description |
---|---|
boolean |
true if an element in the Map object existed and has been removed, or false if the element does not exist. |
const topic = 'topic'
libp2p.pubsub.topicValidators.delete(topic)
Get a connection with a given peer, if it exists.
Name | Type | Description |
---|---|---|
peerId | PeerId |
The peer to find |
Type | Description |
---|---|
Connection |
Connection with the given peer |
libp2p.connectionManager.get(peerId)
Getter for obtaining the current number of open connections.
libp2p.connectionManager.size
// 10
Create a key in the keychain.
libp2p.keychain.createKey(name, type, size)
Name | Type | Description |
---|---|---|
name | string |
The local key name. It cannot already exist. |
type | string |
One of the key types; 'rsa' |
[size] | number |
The key size in bits. Must be provided for rsa keys. |
Type | Description |
---|---|
Promise<{ id, name }> |
Key info object |
const keyInfo = await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
Rename a key in the keychain.
libp2p.keychain.renameKey(oldName, newName)
Name | Type | Description |
---|---|---|
name | string |
The old local key name. It must already exist. |
type | string |
The new local key name. It must not already exist. |
Type | Description |
---|---|
Promise<{ id, name }> |
Key info object |
await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const keyInfo = await libp2p.keychain.renameKey('keyTest', 'keyNewNtest')
Removes a key from the keychain.
libp2p.keychain.removeKey(name)
Name | Type | Description |
---|---|---|
name | string |
The local key name. It must already exist. |
Type | Description |
---|---|
Promise<{ id, name }> |
Key info object |
await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const keyInfo = await libp2p.keychain.removeKey('keyTest')
Export an existing key as a PEM encrypted PKCS #8 string.
libp2p.keychain.exportKey(name, password)
Name | Type | Description |
---|---|---|
name | string |
The local key name. It must already exist. |
password | string |
The password to use. |
Type | Description |
---|---|
Promise<string> |
Key as a PEM encrypted PKCS #8 |
await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const pemKey = await libp2p.keychain.exportKey('keyTest', 'password123')
Import a new key from a PEM encoded PKCS #8 string.
libp2p.keychain.importKey(name, pem, password)
Name | Type | Description |
---|---|---|
name | string |
The local key name. It must not exist. |
pem | string |
The PEM encoded PKCS #8 string. |
password | string |
The password to use. |
Type | Description |
---|---|
Promise<{ id, name }> |
Key info object |
await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const pemKey = await libp2p.keychain.exportKey('keyTest', 'password123')
const keyInfo = await libp2p.keychain.importKey('keyTestImport', pemKey, 'password123')
Import a new key from a PeerId.
libp2p.keychain.importPeer(name, peerId)
Name | Type | Description |
---|---|---|
name | string |
The local key name. It must not exist. |
peerId | 'PeerId' | The PEM encoded PKCS #8 string. |
Type | Description |
---|---|
Promise<{ id, name }> |
Key info object |
const keyInfo = await libp2p.keychain.importPeer('keyTestImport', peerId)
List all the keys.
libp2p.keychain.listKeys()
Type | Description |
---|---|
Promise<Array<{ id, name }>> |
Array of Key info |
const keyInfos = await libp2p.keychain.listKeys()
Find a key by it's id.
libp2p.keychain.findKeyById(id)
Name | Type | Description |
---|---|---|
id | string |
The universally unique key identifier. |
Type | Description |
---|---|
Promise<{ id, name }> |
Key info object |
const keyInfo = await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const keyInfo2 = await libp2p.keychain.findKeyById(keyInfo.id)
Find a key by it's name.
libp2p.keychain.findKeyByName(id)
Name | Type | Description |
---|---|---|
id | string |
The local key name. |
Type | Description |
---|---|
Promise<{ id, name }> |
Key info object |
const keyInfo = await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const keyInfo2 = await libp2p.keychain.findKeyByName('keyTest')
Encrypt protected data using the Cryptographic Message Syntax (CMS).
libp2p.keychain.cms.encrypt(name, data)
Name | Type | Description |
---|---|---|
name | string |
The local key name. |
data | Uint8Array |
The data to encrypt. |
Type | Description |
---|---|
Promise<Uint8Array> |
Encrypted data as a PKCS #7 message in DER. |
const keyInfo = await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const enc = await libp2p.keychain.cms.encrypt('keyTest', uint8ArrayFromString('data'))
Decrypt protected data using the Cryptographic Message Syntax (CMS). The keychain must contain one of the keys used to encrypt the data. If none of the keys exists, an Error is returned with the property 'missingKeys'.
libp2p.keychain.cms.decrypt(cmsData)
Name | Type | Description |
---|---|---|
cmsData | string |
The CMS encrypted data to decrypt. |
Type | Description |
---|---|
Promise<Uint8Array> |
Decrypted data. |
const keyInfo = await libp2p.keychain.createKey('keyTest', 'rsa', 4096)
const enc = await libp2p.keychain.cms.encrypt('keyTest', uint8ArrayFromString('data'))
const decData = await libp2p.keychain.cms.decrypt(enc)
A Stats
object of tracking the global bandwidth of the libp2p node.
const peerIdStrings = libp2p.metrics.peers
An array of PeerId
strings of each peer currently being tracked.
const peerIdStrings = libp2p.metrics.peers
An array of protocol strings that are currently being tracked.
const protocols = libp2p.metrics.protocols
Returns the Stats
object for a given PeerId
if it is being tracked.
libp2p.metrics.forPeer(peerId)
Name | Type | Description |
---|---|---|
peerId | PeerId |
The peer to get stats for |
Type | Description |
---|---|
Stats |
The bandwidth stats of the peer |
const peerStats = libp2p.metrics.forPeer(peerId)
console.log(peerStats.toJSON())
Returns the Stats
object for a given protocol if it is being tracked.
libp2p.metrics.forProtocol(protocol)
Name | Type | Description |
---|---|---|
protocol | string |
The protocol to get stats for |
Type | Description |
---|---|
Stats |
The bandwidth stats of the protocol across all peers |
const peerStats = libp2p.metrics.forProtocol('/meshsub/1.0.0')
console.log(peerStats.toJSON())
Once you have a libp2p instance, you can listen to several events it emits, so that you can be notified of relevant network events.
libp2p.on('error', (err) => {})
err
: instance ofError
libp2p.on('peer:discovery', (peer) => {})
If autoDial
option is true
, applications should not attempt to connect to the peer
unless they are performing a specific action. See peer discovery and auto dial for more information.
peer
: instance ofPeerId
This event will be triggered anytime a new Connection is established to another peer.
libp2p.connectionManager.on('peer:connect', (connection) => {})
connection
: instance ofConnection
This event will be triggered anytime we are disconnected from another peer, regardless of the circumstances of that disconnection. If we happen to have multiple connections to a peer, this event will only be triggered when the last connection is closed.
libp2p.connectionManager.on('peer:disconnect', (connection) => {})
connection
: instance ofConnection
libp2p.peerStore.on('peer', (peerId) => {})
peerId
: instance ofPeerId
libp2p.peerStore.on('change:multiaddrs', ({ peerId, multiaddrs}) => {})
libp2p.peerStore.on('change:protocols', ({ peerId, protocols}) => {})
peerId
: instance ofPeerId
protocols
: array of known, supported protocols for the peer (string identifiers)
This could be in response to a peer telling us about addresses they have observed, or the NatManager performing NAT hole punching.
libp2p.addressManager.on('change:addresses', () => {})
Stats
toJSON<function()>
: Returns a JSON snapshot of the stats.dataReceived<string>
: The stringified value of total incoming data for this stat.dataSent<string>
: The stringified value of total outgoing data for this stat.movingAverages<object>
: The properties are dependent on the configuration of the moving averages interval. Defaults are listed here.['60000']<number>
: The calculated moving average at a 1 minute interval.['300000']<number>
: The calculated moving average at a 5 minute interval.['900000']<number>
: The calculated moving average at a 15 minute interval.
snapshot<object>
: A getter that returns a clone of the raw stats.movingAverages<object>
: A getter that returns a clone of the raw moving averages stats. Note: The properties of this are dependent on configuration. The defaults are shown here.['60000']<MovingAverage>
: The MovingAverage at a 1 minute interval.['300000']<MovingAverage>
: The MovingAverage at a 5 minute interval.['900000']<MovingAverage>
: The MovingAverage at a 15 minute interval.