Documentation
¶
Overview ¶
Package p2p provides a peer-to-peer messaging client built on libp2p. It supports topic-based publish/subscribe messaging with automatic peer discovery, NAT traversal, and relay functionality.
Index ¶
- Variables
- func DefaultPeerScoreParams() *pubsub.PeerScoreParams
- func DefaultPeerScoreThresholds() *pubsub.PeerScoreThresholds
- func GeneratePrivateKey() (crypto.PrivKey, error)
- func PrivateKeyFromHex(keyHex string) (crypto.PrivKey, error)
- func PrivateKeyToHex(priv crypto.PrivKey) (string, error)
- type Client
- type Config
- type DefaultLogger
- type Message
- type P2PClient
- type PeerInfo
- type ResourceLimits
- type SubnetConnLimit
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNameRequired is returned when Config.Name is not provided. ErrNameRequired = errors.New("config.Name is required") // ErrPrivateKeyRequired is returned when Config.PrivateKey is not provided. ErrPrivateKeyRequired = errors.New("config.PrivateKey is required") )
var ErrIncompletePeerScoreConfig = errors.New("PeerScoreParams and PeerScoreThresholds must both be set")
ErrIncompletePeerScoreConfig is returned when only one of PeerScoreParams / PeerScoreThresholds is provided. GossipSub requires both together.
var ErrInvalidAllowedPublisherID = errors.New("invalid AllowedPublisherIDs entry")
ErrInvalidAllowedPublisherID is returned by NewClient when Config.AllowedPublisherIDs contains an entry that is not a valid libp2p peer ID.
Functions ¶
func DefaultPeerScoreParams ¶
func DefaultPeerScoreParams() *pubsub.PeerScoreParams
DefaultPeerScoreParams returns penalty-only GossipSub peer score parameters that provide baseline Sybil resistance without requiring per-topic knowledge:
- IPColocationFactor penalizes many peers sharing the same IP address, so an attacker cannot cheaply run a swarm of Sybils from a handful of hosts.
- BehaviourPenalty punishes GRAFT/PRUNE flooding and broken IWANT promises, re-enabling gossipsub's own flood defenses (which are no-ops when scoring is off).
The scheme is penalty-only: a well-behaved peer sits at score 0 and only misbehavior or colocation drives its score negative. There are no positive terms (no per-topic TopicScoreParams, AppSpecificScore returns 0), so no peer scores above 0 by default. Callers who want a positive buffer for honest/trusted peers should set per-topic TimeInMeshWeight/FirstMessageDeliveriesWeight and/or Config.AppSpecificScore.
A returned pointer is fresh on every call, so callers may mutate it safely.
func DefaultPeerScoreThresholds ¶
func DefaultPeerScoreThresholds() *pubsub.PeerScoreThresholds
DefaultPeerScoreThresholds returns GossipSub score thresholds matched to the penalty-only DefaultPeerScoreParams. AcceptPXThreshold is 0 (not a positive value): because the defaults award no positive score, a positive threshold would be unreachable and reject all peer exchange. At 0, peer records offered via PRUNE are accepted from any non-negatively-scored peer and rejected from peers that scoring has driven negative (Sybil colocation or misbehavior) - which is the vector the mesh needs closed. The negative thresholds leave generous headroom so honest peers behind a shared IP or with a transient behaviour blip are not graylisted.
func GeneratePrivateKey ¶
GeneratePrivateKey generates a new Ed25519 private key. Use this function to create a new key for Config.PrivateKey when setting up a new peer.
func PrivateKeyFromHex ¶
PrivateKeyFromHex loads a private key from a hex string.
Types ¶
type Client ¶
type Client interface {
// Subscribe subscribes to a topic and returns a channel that will receive messages.
// The returned channel is closed when the client is closed; a Subscribe issued
// after Close returns an already-closed channel.
Subscribe(topic string) <-chan Message
// Publish publishes a message to the specified topic.
Publish(ctx context.Context, topic string, data []byte) error
// GetPeers returns information about all known peers on subscribed topics.
GetPeers() []PeerInfo
// GetID returns this peer's ID as a string.
GetID() string
// Connect connects to a peer using a multiaddr string (e.g. "/dns/localhost/tcp/9905/p2p/12D3KooW...").
// This is useful for connecting to static peers that are known ahead of time.
Connect(ctx context.Context, peerMultiaddr string) error
// Close shuts down the client and releases all resources.
Close() error
}
Client defines the interface for a P2P messaging client.
type Config ¶
type Config struct {
// Name is a required identifier for this peer. It will be included in messages
// so other peers can identify the sender.
Name string
// Logger is an optional logger to use for logging. If not provided, the client will use
// DefaultLogger. Set to a custom implementation to integrate with your logging framework.
Logger logger
// PrivateKey is a required private key for the peer.
// This ensures the peer ID remains consistent across restarts.
// Use GeneratePrivateKeyHex() to create a new key for first-time setup.
PrivateKey crypto.PrivKey
// This is used to namespace all topics that we publish to and subscribe to.
ProtocolVersion string
// PeerCacheFile is an optional path to a file for persisting peer information.
// If provided, the client will save connected peers to this file and reload them
// on restart for faster reconnection. If not provided, peer caching is disabled.
PeerCacheFile string
// AnnounceAddrs is an optional list of multiaddr strings that this peer should
// advertise to other peers. This is useful in Kubernetes or other environments
// where the local address differs from the externally reachable address.
// Example: []string{"/ip4/203.0.113.1/tcp/4001"}
// If not provided, libp2p will automatically detect and announce local addresses.
AnnounceAddrs []string
// Port is the network port to listen on for incoming connections. If zero, a random port will be chosen.
Port int
// PeerCacheTTL is the duration after which unseen peers are removed from the cache.
// Peers not seen for longer than this duration will be evicted on next cache load.
// If not provided or zero, defaults to 24 hours (same as go-ethereum).
// Set to a negative value to disable TTL-based eviction.
PeerCacheTTL time.Duration
// BootstrapPeers is an optional list of multiaddr strings for bootstrap servers.
// If provided, these peers will be used for DHT bootstrapping and relay/circuit functionality.
// If not provided, default IPFS bootstrap peers will be used for bootstrapping and relay,
// unless DisableDefaultBootstrapPeers is set.
//
// IMPORTANT: When DHTMode is "off", include ALL known bootstrap servers here for best results.
// Topic peer exchange can only establish direct connections to peers whose addresses are
// in the peerstore, which comes from bootstrap peers and identify protocol exchanges.
//
// Example: []string{
// "/dns4/server1.example.com/tcp/9905/p2p/12D3KooW...",
// "/dns4/server2.example.com/tcp/9905/p2p/12D3KooW...",
// }
BootstrapPeers []string
// DisableDefaultBootstrapPeers stops an empty BootstrapPeers list from falling
// back to the public IPFS bootstrap peers. Set it for private or local networks
// (e.g. regtest) that must not dial, relay through or join the DHT of the public
// IPFS network. Has no effect when BootstrapPeers is non-empty. Default: false.
DisableDefaultBootstrapPeers bool
// StaticPeers is an optional list of multiaddr strings for peers the client
// should always be connected to. Unlike BootstrapPeers, static peers are not
// used for DHT bootstrapping and not used as relay peers; they are simply
// dialed at startup and re-dialed by a maintenance loop if the connection
// drops. Use this for known trusted peers in private/closed networks where
// you want guaranteed direct connectivity regardless of DHT state.
//
// Static peers are dialed in addition to BootstrapPeers, and the same address
// may appear in both lists. The two are not interchangeable, though: when
// AllowedPublisherIDs is in use, listing an address here also grants the peer
// ID it names trust as a publisher, while listing it under BootstrapPeers does
// not. Put a peer here only if you are willing to act on the messages it
// publishes.
//
// Example: []string{
// "/dns4/peer1.internal/tcp/9905/p2p/12D3KooW...",
// "/ip4/192.168.1.10/tcp/9905/p2p/12D3KooW...",
// }
StaticPeers []string
// AllowedPublisherIDs optionally restricts which peers this node accepts
// pubsub messages from, on every topic. It gates message authorship only -
// not connections, not streams, not the peer-address exchange. When empty
// (the default) messages from any peer are accepted, matching previous
// behaviour.
//
// Each entry is a peer ID string (e.g. "12D3KooW..."). An unparseable entry
// is a configuration error and NewClient fails.
//
// Matching is on the authenticated libp2p peer ID of the message author,
// never on the self-reported Name carried in the message envelope, which any
// peer can forge. GossipSub's default StrictSign policy means the author ID
// cannot be spoofed without the corresponding private key.
//
// Messages from peers outside the set are neither delivered to subscribers
// nor forwarded to the mesh, and the sender's peer score is not penalized.
// Connections to those peers are unaffected: they are still dialed, still
// kept connected, and still served the peer-address exchange protocol.
//
// The filter is on authorship, not on freshness or liveness. A message an
// allowlisted publisher authored once can be replayed by any peer and will be
// delivered as new, as soon as libp2p's seen-cache window for it has passed.
// Reject stale or duplicate work at the application layer if that matters.
//
// On a network where peers run GossipSub scoring, persistently failing to
// forward non-allowlisted peers' messages degrades this node's own mesh
// delivery score with its peers, which can get it pruned or graylisted from
// the mesh - in turn degrading delivery of the allowlisted peers' messages
// too. This is a real cost of a narrow allowlist on a scored network, not
// just a cost to the excluded peers.
//
// Because non-allowlisted peers never reach receiveMessages, they are never
// recorded as topic peers: while filtered they do not appear in GetPeers()
// output at all, even though they remain connected, and no peer-address
// discovery is attempted for them either. PeerCacheFile does not follow
// GetPeers() here: it is written from the GossipSub topic peer lists, so a
// filtered peer is still cached and still re-dialed at the next startup.
// The allowlist gates messages, not connections.
//
// When non-empty, the set is augmented with this node's own peer ID (this is
// required: locally published messages pass through the same validators) and
// with the peer IDs that StaticPeers entries name directly through a /p2p/
// component. For a relayed address the ID taken is the target's, never the
// relay's.
//
// Publisher IDs are only ever read from configuration text - these entries
// and the /p2p/ components of StaticPeers. DNS never contributes one. A bare
// /dnsaddr/<host> entry carries no suffix for the resolver to filter its TXT
// records against, so trusting what it resolves to would let whoever answers
// that lookup choose which publishers this node acts on. Such an entry
// therefore contributes no publisher ID at all, is warned about at startup,
// and the set is not rebuilt later: use the /dnsaddr/<host>/p2p/<id> form
// when this allowlist is in use.
//
// BootstrapPeers are NOT implicitly allowed; list them here explicitly if
// they publish.
//
// Example: []string{"12D3KooWA...", "12D3KooWB..."}
AllowedPublisherIDs []string
// DHTMode specifies how this node participates in the DHT.
// Valid values: "server", "client", "off"
//
// - "server": Full DHT participation (advertises, stores provider records, routes queries).
// Connects to the broader IPFS/libp2p DHT network.
// High overhead but collects peer addresses from across the network.
// Use this for: bootstrap/relay servers, public well-connected nodes.
//
// - "client": Queries DHT but doesn't advertise or store records.
// Still crawls DHT network for routing (connects to 100+ peers).
// Reduced overhead but NOT lightweight - still participates in DHT routing.
// Generally not recommended - use "server" or "off" instead.
//
// - "off": Completely disables DHT. Topic-only network mode.
// Only connects to BootstrapPeers and discovers topic peers via GossipSub mesh.
// Most lightweight - no DHT crawling, no random peer connections.
// Uses custom peer address exchange protocol to request direct addresses
// from connected peers (typically bootstrap servers running in "server" mode).
// DHT-based hole punching is not available in this mode. Peers without
// public addresses will communicate via relay circuits through bootstrap servers.
// Ideal for: lightweight clients, isolated topic networks, avoiding DHT overhead.
// RECOMMENDED for abuse-sensitive cloud hosting (Hetzner, OVH, etc.) to avoid
// network scanning alerts from DHT peer discovery connecting to 100+ IPs.
//
// ARCHITECTURE: Run bootstrap servers in "server" mode (collects addresses via DHT),
// and clients in "off" mode (requests addresses from bootstrap servers).
// This creates a hybrid model: servers are well-connected, clients are lightweight.
//
// If not provided or empty, defaults to "server" mode.
DHTMode string
// DHTCleanupInterval is the interval at which the DHT's ProviderManager performs
// garbage collection of expired provider records. The cleanup involves querying all
// provider records and removing expired entries.
// Only applies when DHTMode is "server".
// If not provided or zero, uses the DHT default (1 hour).
// Recommended: 6-24 hours for production to reduce CPU overhead.
// The cleanup frequency trades off between memory usage (stale records) and CPU usage.
DHTCleanupInterval time.Duration
// EnableNAT enables UPnP/NAT-PMP automatic port mapping features.
// When true, the node will scan the local gateway (e.g., 10.0.0.1) to configure port forwarding.
// IMPORTANT: This triggers network scanning alerts on shared hosting (Hetzner, AWS, etc.).
// Only enable for local development behind a home router/NAT.
// Default: false (NAT features disabled for production safety)
EnableNAT bool
// EnableMDNS enables multicast DNS peer discovery on the local network.
// When true, the node broadcasts mDNS queries to discover peers on the same LAN.
// IMPORTANT: Only enable on isolated local networks with proper VLANs. On shared hosting
// (e.g., Hetzner, AWS) without VLANs, mDNS broadcasts appear as network scanning and may
// result in abuse reports.
// Default: false (mDNS disabled for production safety)
// Set to true only for local development networks with proper isolation
EnableMDNS bool
// AllowPrivateIPs allows connections to private/local IP addresses during peer discovery.
// When true, the node will attempt to connect to RFC1918 private networks (10.0.0.0/8,
// 172.16.0.0/12, 192.168.0.0/16), link-local addresses (169.254.0.0/16), and localhost.
// IMPORTANT: Only enable on private networks. On shared hosting, this may trigger network
// scanning alerts.
// Default: false (private IPs filtered for production safety)
// Set to true only for local development or private network deployments
AllowPrivateIPs bool
// MaxConnections is the high water mark for total peer connections.
// When this limit is reached, the connection manager will prune low-value connections
// (DHT routing peers) while protecting high-value peers (topic mesh peers).
// If not provided or zero, defaults to 35.
// Recommended: 25-50 depending on available bandwidth and number of topics.
MaxConnections int
// MinConnections is the low water mark for total peer connections.
// The connection manager will not prune connections below this threshold.
// If not provided or zero, defaults to 25.
// Recommended: Set to MaxConnections - 10 for a reasonable buffer.
MinConnections int
// ConnectionGracePeriod is the duration new connections are protected from pruning.
// This prevents rapid connect/disconnect cycles.
// If not provided or zero, defaults to 20 seconds.
ConnectionGracePeriod time.Duration
// ResourceLimits optionally overrides the libp2p resource manager's limits:
// system-wide connection, stream and file-descriptor caps, per-peer caps,
// and per-subnet connection caps. Unset fields keep go-libp2p's defaults,
// which are auto-scaled to the host's memory and file-descriptor limits and
// can be low on small hosts. Nodes that take heavy inbound churn, such as
// bootstrap or DHT server nodes, should set ConnsInbound explicitly.
// The effective system limits are logged at startup. See ResourceLimits.
ResourceLimits ResourceLimits
// EnablePeerScoring turns on GossipSub peer scoring using the library's built-in
// defaults (DefaultPeerScoreParams / DefaultPeerScoreThresholds). Peer scoring is
// what protects the mesh from Sybil peers: it applies an IP-colocation penalty and
// a behaviour penalty for GRAFT/PRUNE flooding and broken IWANT promises, and it
// gates peer exchange so peer records offered via PRUNE are rejected from any peer
// that has earned a negative score (a Sybil swarm behind few IPs, or a misbehaving
// peer). StaticPeers and BootstrapPeers are registered as GossipSub direct peers so
// scoring can never prune or graylist trusted links.
//
// The gossipsub v1.1 spec requires scoring whenever peer exchange is on; leaving
// this false while peer exchange stays enabled (the default) lets Sybil peers
// capture the topic mesh at no cost. Prefer enabling this, or set
// DisablePeerExchange, in any deployment exposed to untrusted peers.
//
// The defaults are penalty-only: a well-behaved peer sits at score 0, and only
// misbehavior or IP colocation drives a score negative. To award positive score
// to specific peers, or to add per-topic scoring, set PeerScoreParams /
// AppSpecificScore. Default: false (no scoring, for backwards compatibility).
EnablePeerScoring bool
// PeerScoreParams optionally overrides the GossipSub peer score parameters. When
// set, both this and PeerScoreThresholds must be provided. Setting this enables
// peer scoring even if EnablePeerScoring is false. Use DefaultPeerScoreParams() as
// a starting point and add per-topic TopicScoreParams (e.g. positive
// TimeInMeshWeight / FirstMessageDeliveriesWeight, or a negative
// InvalidMessageDeliveriesWeight) for your topics.
PeerScoreParams *pubsub.PeerScoreParams
// PeerScoreThresholds optionally overrides the GossipSub peer score thresholds.
// When set, both this and PeerScoreParams must be provided.
PeerScoreThresholds *pubsub.PeerScoreThresholds
// AppSpecificScore optionally provides an application-specific score for a peer,
// added to its GossipSub score (weighted by PeerScoreParams.AppSpecificWeight = 1
// in the defaults). Use it to award positive score to trusted peers so transient
// penalties cannot push them below the mesh-eligibility threshold. It is only used
// when scoring is enabled; if set it overrides the params' AppSpecificScore.
AppSpecificScore func(peer.ID) float64
// PeerScoreInspect, if set, is called periodically with a snapshot of every peer's
// score, for observability (e.g. exporting metrics or logging graylisted peers).
// Only used when scoring is enabled. The period defaults to 10s.
PeerScoreInspect func(map[peer.ID]*pubsub.PeerScoreSnapshot)
// PeerScoreInspectPeriod is how often PeerScoreInspect is called. Defaults to 10s.
PeerScoreInspectPeriod time.Duration
// DisablePeerExchange turns off GossipSub peer exchange (PX). PX is enabled by
// default. Without peer scoring, PX is strictly worse than no PX because a
// zero AcceptPXThreshold makes the node dial every peer record an attacker hands
// it in a PRUNE. Set this to true as an interim mitigation when peer scoring is not
// enabled. Default: false (peer exchange enabled).
DisablePeerExchange bool
// contains filtered or unexported fields
}
Config contains the configuration options for creating a P2P client.
type DefaultLogger ¶
type DefaultLogger struct{}
DefaultLogger is a simple logger implementation using the standard log package.
func (*DefaultLogger) Debugf ¶
func (d *DefaultLogger) Debugf(format string, v ...any)
Debugf logs a debug message with formatting.
func (*DefaultLogger) Errorf ¶
func (d *DefaultLogger) Errorf(format string, v ...any)
Errorf logs an error message with formatting.
func (*DefaultLogger) Infof ¶
func (d *DefaultLogger) Infof(format string, v ...any)
Infof logs an info message with formatting.
func (*DefaultLogger) Warnf ¶
func (d *DefaultLogger) Warnf(format string, v ...any)
Warnf logs a warning message with formatting.
type Message ¶
type Message struct {
Topic string // The topic this message was received on
From string // The sender's name, as sanitized by the receiver (printable, at most 64 bytes)
FromID string // The sender's peer ID
Data []byte // The message payload
Timestamp time.Time // When the message was received
}
Message represents a received message from a peer.
type P2PClient ¶
type P2PClient = Client
P2PClient is a type alias for Client, maintained for backward compatibility.
type PeerInfo ¶
type PeerInfo struct {
ID string // Peer ID
Name string // Peer name (if known), as sanitized by the receiver (printable, at most 64 bytes)
Addrs []string // Peer addresses
}
PeerInfo contains information about a connected peer.
type ResourceLimits ¶
type ResourceLimits struct {
// Conns is the system-wide limit on open connections, inbound and outbound
// combined. It must not be lower than MaxConnections (the connection
// manager's high water mark), or the connection manager could never reach it.
Conns int
// ConnsInbound is the system-wide limit on inbound connections. Raise it on
// nodes that accept heavy inbound churn, such as bootstrap or DHT server
// nodes. Must not exceed Conns (set or auto-scaled). FD caps inbound
// connections too (each TCP connection holds a file descriptor), so raise
// FD together with ConnsInbound.
ConnsInbound int
// ConnsOutbound is the system-wide limit on outbound connections. Must not
// exceed Conns (set or auto-scaled).
ConnsOutbound int
// Streams is the system-wide limit on open streams, inbound and outbound
// combined.
Streams int
// StreamsInbound is the system-wide limit on inbound streams. Must not
// exceed Streams (set or auto-scaled).
StreamsInbound int
// StreamsOutbound is the system-wide limit on outbound streams. Must not
// exceed Streams (set or auto-scaled).
StreamsOutbound int
// FD is the system-wide limit on file descriptors used for connections.
FD int
// PeerConns is the limit on connections to or from any single peer.
PeerConns int
// PeerConnsInbound is the limit on inbound connections from any single
// peer. Must not exceed PeerConns (set or auto-scaled).
PeerConnsInbound int
// PeerStreamsInbound is the limit on inbound streams from any single peer.
PeerStreamsInbound int
// IPv4SubnetLimits caps connections per IPv4 subnet, matched by source
// address. When non-empty it replaces the go-libp2p default (8 connections per
// /32, i.e. per IP address) as a whole, so include every prefix you want
// limited. Loopback stays unlimited.
IPv4SubnetLimits []SubnetConnLimit
// IPv6SubnetLimits caps connections per IPv6 subnet. When non-empty it replaces
// the go-libp2p defaults (8 per /56 and 64 per /48) as a whole.
IPv6SubnetLimits []SubnetConnLimit
}
ResourceLimits overrides limits of the libp2p resource manager.
Every field is optional. A zero value (or empty slice) keeps the go-libp2p default for that limit, which is auto-scaled to the host's memory and file-descriptor limits. A zero ResourceLimits leaves the resource manager entirely to go-libp2p, exactly as before this option existed. Negative values are rejected.
Overrides are applied on top of the auto-scaled defaults, so setting one field never changes the others. An inbound or outbound limit that is set must not exceed its total, whether that total is set here or left at its auto-scaled default: raising ConnsInbound above the auto-scaled Conns needs Conns set too, or NewClient fails. Lowering only a total is fine; the directional limits are then capped at it. The resource manager's Prometheus metrics (libp2p_rcmgr_*) report the effective limits either way.
type SubnetConnLimit ¶
type SubnetConnLimit struct {
// PrefixLength is the subnet size in bits: 0-32 for IPv4, 0-128 for IPv6.
// 32 (IPv4) or 128 (IPv6) limits each address on its own.
PrefixLength int
// Conns is the maximum number of connections per subnet. Must be positive.
Conns int
}
SubnetConnLimit caps the number of connections from all addresses sharing the same PrefixLength-bit network prefix.


