Convert Figma logo to code with AI

libp2p logojs-libp2p

The JavaScript Implementation of libp2p networking stack.

2,304
442
2,304
88

Top Related Projects

7,436

IPFS implementation in JavaScript

Matrix Client-Server SDK for JavaScript

⚡️ Streaming torrent client for the web

Quick Overview

js-libp2p is a modular peer-to-peer networking stack written in JavaScript. It provides a flexible framework for building distributed applications and services, offering features like peer discovery, connection establishment, and protocol multiplexing. js-libp2p is designed to be used in both Node.js and browser environments.

Pros

  • Highly modular and extensible architecture
  • Cross-platform compatibility (Node.js and browser)
  • Rich ecosystem of plugins and protocols
  • Active development and community support

Cons

  • Learning curve for newcomers due to its modular nature
  • Documentation can be overwhelming for beginners
  • Performance may not match native implementations in some scenarios
  • Rapid development can lead to breaking changes between versions

Code Examples

  1. Creating a basic libp2p node:
import { createLibp2p } from 'libp2p'
import { TCP } from '@libp2p/tcp'
import { Noise } from '@chainsafe/libp2p-noise'
import { Mplex } from '@libp2p/mplex'

const node = await createLibp2p({
  addresses: {
    listen: ['/ip4/0.0.0.0/tcp/0']
  },
  transports: [new TCP()],
  connectionEncryption: [new Noise()],
  streamMuxers: [new Mplex()]
})

await node.start()
console.log('libp2p node started')
  1. Discovering and connecting to peers:
import { createLibp2p } from 'libp2p'
import { MulticastDNS } from '@libp2p/mdns'

const node = await createLibp2p({
  // ... other options
  peerDiscovery: [new MulticastDNS()]
})

node.addEventListener('peer:discovery', (evt) => {
  console.log('Discovered:', evt.detail.id.toString())
  node.dial(evt.detail.id).catch(console.error)
})

await node.start()
  1. Implementing a simple protocol:
import { createLibp2p } from 'libp2p'
import { pipe } from 'it-pipe'

const node = await createLibp2p({
  // ... other options
})

await node.handle('/echo/1.0.0', ({ stream }) => {
  pipe(
    stream,
    async function* (source) {
      for await (const msg of source) {
        yield msg
      }
    },
    stream
  )
})

await node.start()

Getting Started

To get started with js-libp2p:

  1. Install the package:

    npm install libp2p
    
  2. Create a basic node (see the first code example above).

  3. Add desired modules (e.g., transports, peer discovery mechanisms).

  4. Implement your application logic using libp2p's APIs.

  5. Start the node and handle events as needed.

Refer to the official documentation for more detailed instructions and advanced usage.

Competitor Comparisons

7,436

IPFS implementation in JavaScript

Pros of js-ipfs

  • Provides a complete IPFS implementation, including content addressing and distributed file system functionality
  • Offers a higher-level abstraction for decentralized applications
  • Includes built-in support for file storage, retrieval, and sharing

Cons of js-ipfs

  • Larger codebase and potentially higher resource usage due to full IPFS implementation
  • May include unnecessary features for projects that only require networking capabilities
  • Steeper learning curve for developers who only need basic peer-to-peer functionality

Code Comparison

js-ipfs:

import { create } from 'ipfs-core'

const ipfs = await create()
const cid = await ipfs.add('Hello, IPFS!')
console.log('Added file:', cid.toString())

js-libp2p:

import { createLibp2p } from 'libp2p'
import { TCP } from '@libp2p/tcp'

const node = await createLibp2p({
  transports: [new TCP()]
})
await node.start()

js-libp2p focuses on providing a modular networking stack, while js-ipfs builds upon libp2p to offer a complete IPFS implementation. js-libp2p is more suitable for projects requiring custom peer-to-peer networking, whereas js-ipfs is ideal for applications needing full IPFS functionality.

Matrix Client-Server SDK for JavaScript

Pros of matrix-js-sdk

  • Focused on real-time communication and messaging
  • Extensive documentation and API reference
  • Strong community support and active development

Cons of matrix-js-sdk

  • Limited to Matrix protocol, less flexible for other use cases
  • Heavier dependency footprint
  • Steeper learning curve for developers new to Matrix

Code Comparison

matrix-js-sdk:

const client = sdk.createClient({
  baseUrl: "https://matrix.org",
  accessToken: "YOUR_ACCESS_TOKEN",
  userId: "@alice:matrix.org"
});
client.sendMessage("!roomId:matrix.org", {
  msgtype: "m.text",
  body: "Hello, World!"
});

js-libp2p:

const node = await Libp2p.create({
  addresses: { listen: ['/ip4/0.0.0.0/tcp/0'] },
  modules: { transport: [TCP], connEncryption: [NOISE], streamMuxer: [MPLEX] }
});
await node.start();
node.on('peer:discovery', (peerId) => {
  console.log('Discovered:', peerId.toB58String())
});

The matrix-js-sdk code focuses on sending messages within the Matrix ecosystem, while js-libp2p demonstrates peer discovery and network configuration for a more general-purpose, decentralized networking approach.

⚡️ Streaming torrent client for the web

Pros of WebTorrent

  • Specialized for browser-based torrent streaming and file sharing
  • Simpler API for quick implementation of torrent functionality
  • Built-in support for WebRTC, enabling peer-to-peer connections in browsers

Cons of WebTorrent

  • Limited to WebRTC and WebSockets, reducing flexibility in network protocols
  • Focused primarily on torrents, less versatile for other P2P applications
  • Smaller community and ecosystem compared to js-libp2p

Code Comparison

WebTorrent:

const WebTorrent = require('webtorrent')
const client = new WebTorrent()
client.add(torrentId, (torrent) => {
  torrent.files.forEach(file => file.appendTo('body'))
})

js-libp2p:

const Libp2p = require('libp2p')
const node = await Libp2p.create({
  addresses: { listen: ['/ip4/0.0.0.0/tcp/0'] },
  modules: { transport: [TCP], connEncryption: [NOISE], streamMuxer: [MPLEX] }
})
await node.start()

While WebTorrent provides a straightforward API for torrent-specific operations, js-libp2p offers a more flexible and modular approach for building various P2P applications. js-libp2p supports a wider range of protocols and transport layers, making it more suitable for complex P2P systems beyond file sharing.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

libp2p hex logo

The JavaScript implementation of the libp2p Networking Stack.



js-libp2p-monorepo

libp2p.io Discuss codecov CI

JavaScript implementation of libp2p, a modular peer to peer network stack

Project status

This project has been used in production for years in Ethereum, IPFS, and more. It is actively maintained by multiple organizations and continues to be improved! The API might change, but we strictly follow semver.

The documentation in the main branch may contain changes from a pre-release.

If you are looking for the documentation of the latest release, you can view the latest release on npm, or select the tag in github that matches the version you are looking for.

Want to get started? Check our GETTING_STARTED.md guide and examples.

Want to update libp2p in your project? Check our migrations folder.

Table of contents

Background

libp2p is the product of a long and arduous quest to understand the evolution of the Internet networking stack. In order to build P2P applications, devs have long had to make custom ad-hoc solutions to fit their needs, sometimes making some hard assumptions about their runtimes and the state of the network at the time of their development. Today, looking back more than 20 years, we see a clear pattern in the types of mechanisms built around the Internet Protocol, IP, which can be found throughout many layers of the OSI layer system, libp2p distils these mechanisms into flat categories and defines clear interfaces that once exposed, enable other protocols and applications to use and swap them, enabling upgradability and adaptability for the runtime, without breaking the API.

We are in the process of writing better documentation, blog posts, tutorials and a formal specification. Today you can find:

To sum up, libp2p is a "network stack" -- a protocol suite -- that cleanly separates concerns, and enables sophisticated applications to only use the protocols they absolutely need, without giving up interoperability and upgradeability. libp2p grew out of IPFS, but it is built so that lots of people can use it, for lots of different projects.

Roadmap

The js-libp2p roadmap can be found here: https://github.com/libp2p/js-libp2p/blob/main/ROADMAP.md

It represents current projects the js-libp2p maintainers are focused on and provides an estimation of completion targets.

It is complementary to the overarching libp2p project roadmap: https://github.com/libp2p/specs/blob/master/ROADMAP.md

Install

npm install libp2p

Usage

Configuration

For all the information on how you can configure libp2p see CONFIGURATION.md.

Limits

For help configuring your node to resist malicious network peers, see LIMITS.md

Getting started

If you are starting your journey with js-libp2p, read the GETTING_STARTED.md guide.

Tutorials and Examples

You can find multiple examples on the examples repo that will guide you through using libp2p for several scenarios.

Structure

Development

Clone and install dependencies:

> git clone https://github.com/libp2p/js-libp2p.git
> cd js-libp2p
> npm install
> npm run build

Tests

Run unit tests

# run all the unit tsts
> npm test

# run just Node.js tests
> npm run test:node

# run just Browser tests (Chrome)
> npm run test:chrome

Packages

List of packages currently in existence for libp2p

This table is generated using the module package-table with package-table --data=package-list.json.

PackageVersionDepsCICoverage
libp2p
libp2pnpmDepsGitHub CIcodecov
@libp2p/interfacenpmDepsGitHub CIcodecov
transports
@libp2p/tcpnpmDepsGitHub CIcodecov
@libp2p/webrtcnpmDepsGitHub CIcodecov
@libp2p/websocketsnpmDepsGitHub CIcodecov
@libp2p/webtransportnpmDepsGitHub CIcodecov
secure channels
@chainsafe/libp2p-noisenpmDepsGitHub CIcodecov
@libp2p/plaintextnpmDepsGitHub CIcodecov
stream multiplexers
@libp2p/mplexnpmDepsGitHub CIcodecov
@chainsafe/libp2p-yamuxnpmDepsGitHub CIcodecov
peer discovery
@libp2p/bootstrapnpmDepsGitHub CIcodecov
@libp2p/kad-dhtnpmDepsGitHub CIcodecov
@libp2p/mdnsnpmDepsGitHub CIcodecov
@chainsafe/discv5npmDepsGitHub CIcodecov
content routing
@libp2p/http-v1-content-routingnpmDepsGitHub CIcodecov
@libp2p/delegated-content-routingnpmDepsGitHub CIcodecov
@libp2p/kad-dhtnpmDepsGitHub CIcodecov
peer routing
@libp2p/delegated-peer-routingnpmDepsGitHub CIcodecov
@libp2p/kad-dhtnpmDepsGitHub CIcodecov
utilities
@libp2p/cryptonpmDepsGitHub CIcodecov
data types
@libp2p/peer-idnpmDepsGitHub CIcodecov
@libp2p/peer-recordnpmDepsGitHub CIcodecov
pubsub
@ChainSafe/libp2p-gossipsubnpmDepsGitHub CIcodecov
@libp2p/floodsubnpmDepsGitHub CIcodecov

Used by

HOPR Logo Helia (IPFS in JavaScript) logo Peerbit logo Topology logo

And many others...

Contribute

See CONTRIBUTING.md.

API Docs

License

Licensed under either of

NPM DownloadsLast 30 Days