libp2p
Library for Peer-to-Peer
A modular P2P networking library that originated in IPFS. Supports protocol negotiation, peer discovery, and NAT hole punching, and is used in blockchains such as Filecoin and Polkadot.
Library for Peer-to-Peer
A modular P2P networking library that originated in IPFS. Supports protocol negotiation, peer discovery, and NAT hole punching, and is used in blockchains such as Filecoin and Polkadot.
libp2p is a modular P2P networking library that came into being when Protocol Labs developed IPFS (InterPlanetary File System). Unlike the traditional client-server model, libp2p builds a decentralized network in which every node operates as an equal peer. Its core philosophy is 'modularity': the transport layer (TCP, QUIC, WebSocket), security (TLS, Noise), multiplexing (yamux, mplex), and more can be freely combined.
Protocol negotiation is a core feature of libp2p. When two peers connect, they use the multistream-select protocol to negotiate which protocols they both support. Compatibility is ensured by exchanging version-specified protocol IDs, such as "/ipfs/kad/1.0.0" (Kademlia DHT) or "/meshsub/1.1.0" (GossipSub). This allows backward compatibility to be maintained even as the network evolves.
Peer discovery is the mechanism for finding other nodes in a distributed network. libp2p supports various methods, including Kademlia DHT (distributed hash table), mDNS (local network), Bootstrap nodes, and Rendezvous servers. In particular, the DHT is used not only for peer routing but also for content routing, making it possible to find peers that hold specific data in the network.
NAT traversal enables direct connections between peers behind a firewall/NAT. libp2p provides AutoNAT (NAT status detection), Circuit Relay (connection through a relay server), and Hole Punching (direct connection via UDP/QUIC), which are similar to STUN/TURN. In particular, QUIC-based hole punching has a high success rate and is widely used in real-world P2P communication.
In real production environments, libp2p is the networking layer of several major blockchain projects. Filecoin uses libp2p to handle communication between storage miners and retrieval miners, while Polkadot/Substrate uses it for block propagation and transaction gossip. The Ethereum 2.0 Beacon Chain is also based on libp2p, and tens of thousands of nodes propagate blocks using the GossipSub protocol.
import { createLibp2p } from 'libp2p'
import { tcp } from '@libp2p/tcp'
import { webSockets } from '@libp2p/websockets'
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { kadDHT } from '@libp2p/kad-dht'
import { gossipsub } from '@chainsafe/libp2p-gossipsub'
import { bootstrap } from '@libp2p/bootstrap'
// libp2p 노드 생성
const node = await createLibp2p({
// 전송 계층: TCP + WebSocket 지원
transports: [
tcp(),
webSockets()
],
// 보안 계층: Noise 프로토콜 (TLS 대안)
connectionEncryption: [noise()],
// 스트림 멀티플렉싱: 단일 연결에서 여러 스트림
streamMuxers: [yamux()],
// 피어 발견: Bootstrap 노드 + DHT
peerDiscovery: [
bootstrap({
list: [
'/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',
'/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'
]
})
],
// 서비스: DHT + PubSub
services: {
dht: kadDHT({
clientMode: false // 풀 DHT 노드로 참여
}),
pubsub: gossipsub({
emitSelf: false,
gossipIncoming: true,
floodPublish: true
})
}
})
// 노드 시작
await node.start()
console.log('PeerID:', node.peerId.toString())
console.log('Listening on:', node.getMultiaddrs())
// 커스텀 프로토콜 핸들러 등록
await node.handle('/my-app/1.0.0', async ({ stream }) => {
// 스트림에서 데이터 읽기
for await (const chunk of stream.source) {
console.log('Received:', new TextDecoder().decode(chunk.subarray()))
}
})
// PubSub 토픽 구독
node.services.pubsub.subscribe('my-topic')
node.services.pubsub.addEventListener('message', (evt) => {
console.log(`Topic: ${evt.detail.topic}, Data: ${evt.detail.data}`)
})
// 메시지 발행
await node.services.pubsub.publish('my-topic',
new TextEncoder().encode('Hello P2P!')
)
package main
import (
"context"
"fmt"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
dht "github.com/libp2p/go-libp2p-kad-dht"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/p2p/security/noise"
"github.com/libp2p/go-libp2p/p2p/muxer/yamux"
quic "github.com/libp2p/go-libp2p/p2p/transport/quic"
"github.com/libp2p/go-libp2p/p2p/transport/tcp"
)
func main() {
ctx := context.Background()
// libp2p 호스트 생성
host, err := libp2p.New(
// 전송 계층: TCP + QUIC
libp2p.Transport(tcp.NewTCPTransport),
libp2p.Transport(quic.NewTransport),
// 리스닝 주소
libp2p.ListenAddrStrings(
"/ip4/0.0.0.0/tcp/9000",
"/ip4/0.0.0.0/udp/9000/quic-v1",
),
// 보안: Noise 프로토콜
libp2p.Security(noise.ID, noise.New),
// 멀티플렉싱: yamux
libp2p.Muxer("/yamux/1.0.0", yamux.DefaultTransport),
// NAT 홀펀칭 활성화
libp2p.EnableHolePunching(),
libp2p.EnableAutoRelay(),
)
if err != nil {
panic(err)
}
defer host.Close()
fmt.Printf("PeerID: %s\n", host.ID())
fmt.Printf("Addresses: %v\n", host.Addrs())
// Kademlia DHT 초기화
kademliaDHT, err := dht.New(ctx, host,
dht.Mode(dht.ModeServer), // 풀 DHT 노드
dht.BootstrapPeers(dht.GetDefaultBootstrapPeerAddrInfos()...),
)
if err != nil {
panic(err)
}
// DHT 부트스트랩
if err := kademliaDHT.Bootstrap(ctx); err != nil {
panic(err)
}
// GossipSub PubSub 생성
ps, err := pubsub.NewGossipSub(ctx, host,
pubsub.WithPeerExchange(true),
pubsub.WithFloodPublish(true),
)
if err != nil {
panic(err)
}
// 토픽 조인
topic, err := ps.Join("filecoin/blocks")
if err != nil {
panic(err)
}
// 구독
sub, err := topic.Subscribe()
if err != nil {
panic(err)
}
// 메시지 수신 고루틴
go func() {
for {
msg, err := sub.Next(ctx)
if err != nil {
return
}
fmt.Printf("From: %s, Data: %s\n", msg.GetFrom(), msg.Data)
}
}()
// 블록 대기
select {}
}
use libp2p::{
core::upgrade,
gossipsub, identity, kad, noise,
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux, PeerId, Swarm, Transport,
};
use std::time::Duration;
use tokio::select;
// 커스텀 네트워크 동작 정의
#[derive(NetworkBehaviour)]
struct MyBehaviour {
kademlia: kad::Behaviour,
gossipsub: gossipsub::Behaviour,
}
#[tokio::main]
async fn main() -> Result<(), Box> {
// 키페어 생성 (PeerID 결정)
let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
println!("PeerID: {}", local_peer_id);
// 전송 계층 구성: TCP + Noise + Yamux
let transport = tcp::tokio::Transport::default()
.upgrade(upgrade::Version::V1)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::Config::default())
.boxed();
// Kademlia DHT 설정
let store = kad::store::MemoryStore::new(local_peer_id);
let kademlia = kad::Behaviour::new(local_peer_id, store);
// GossipSub 설정
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(1))
.validation_mode(gossipsub::ValidationMode::Strict)
.build()
.expect("Valid config");
let gossipsub = gossipsub::Behaviour::new(
gossipsub::MessageAuthenticity::Signed(local_key.clone()),
gossipsub_config,
)?;
// Swarm 생성
let behaviour = MyBehaviour { kademlia, gossipsub };
let mut swarm = Swarm::new(
transport,
behaviour,
local_peer_id,
libp2p::swarm::Config::with_tokio_executor(),
);
// 리스닝 시작
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
// 토픽 구독
let topic = gossipsub::IdentTopic::new("polkadot/transactions");
swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
// 이벤트 루프
loop {
select! {
event = swarm.select_next_some() => match event {
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on: {}", address);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Gossipsub(
gossipsub::Event::Message { message, .. }
)) => {
println!(
"Received: {} from {:?}",
String::from_utf8_lossy(&message.data),
message.source
);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Kademlia(
kad::Event::RoutingUpdated { peer, .. }
)) => {
println!("DHT: Added peer {}", peer);
}
_ => {}
}
}
}
}
"I think we should build the networking layer on libp2p. It's used by proven projects like Polkadot and Filecoin, and we can discover peers with the DHT and propagate blocks with GossipSub. Using the QUIC transport also gives a high NAT hole punching success rate."
"If peers can't connect, it's likely a NAT issue. The libp2p AutoNAT log shows the NAT type, and with Symmetric NAT a direct connection is difficult, so you have to go through a Circuit Relay. Try setting up a relay node or enabling QUIC hole punching."
"libp2p handles all communication between IPFS nodes. Blocks are exchanged with the Bitswap protocol, and content providers are found with the Kademlia DHT. To create a private network, set up a libp2p PSK (Pre-Shared Key) to block connections from external nodes."
For a new node to join the network, at least one bootstrap node is required. If you start without bootstrapping, you become an isolated node. Configure public bootstrap nodes or operate seed nodes for a private network.
The default GossipSub message size limit is 1MB. If you send large data, messages are dropped. Use Bitswap or chunking for large data, and use GossipSub for metadata or notifications.
If you don't specify a version in the protocol ID ("/my-app" vs "/my-app/1.0.0"), compatibility problems occur. When changing a protocol, add a new version and also keep the old version's handlers to support gradual migration.
Prefer the QUIC transport (NAT-friendly), configure multiple bootstrap nodes (3 or more), specify protocol versions (/protocol/x.y.z), use DHT client mode only on low-spec devices, and persist the PeerStore for fast connections on restart.