p2p

package module
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 39 Imported by: 7

README

🛰  go-p2p-message-bus

Idiomatic Go P2P messaging library with auto-discovery, NAT traversal, and channel-based pub/sub.


Release Go Version License


CI / CD    Build Last Commit      Quality    Coverage
Security    Scorecard Security      Community    Contributors Ask DeepWiki


Project Navigation
📦 Installation 🧪 Examples & Tests 📚 Documentation
🤝 Contributing 🛠️ Code Standards ⚡ Benchmarks
🤖 AI Usage 📝 License 👥 Maintainers

🧩 What's Inside?

Features

  • Simple API: Create a client, subscribe to topics, and publish messages with minimal code
  • Channel-based: Receive messages through Go channels for idiomatic concurrent programming
  • Auto-discovery: Automatic peer discovery via DHT, mDNS, and peer caching
  • NAT traversal: Built-in support for hole punching and relay connections
  • Persistent peers: Automatically caches and reconnects to known peers
  • Connection limiting: Smart connection manager prioritizes topic peers over routing peers (default: 25-35 connections)

🚀 Quick Start

Get started in 60 seconds
package main

import (
    "fmt"
    "log"

    "github.com/bsv-blockchain/go-p2p-message-bus"
)

func main() {
    // Generate a private key (do this once and save it)
    keyHex, err := p2p.GeneratePrivateKeyHex()
    if err != nil {
        log.Fatal(err)
    }
    // In production, save keyHex to config file, env var, or database

    // Create a P2P client
    client, err := p2p.NewPeer(p2p.Config{
        Name:          "my-node",
        PrivateKeyHex: keyHex,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Subscribe to a topic
    msgChan := client.Subscribe("my-topic")

    // Receive messages
    go func() {
        for msg := range msgChan {
            fmt.Printf("Received from %s: %s\n", msg.From, string(msg.Data))
        }
    }()

    // Publish a message
    if err := client.Publish("my-topic", []byte("Hello, P2P!")); err != nil {
        log.Printf("Error publishing: %v", err)
    }

    // Get connected peers
    peers := client.GetPeers()
    for _, peer := range peers {
        fmt.Printf("Peer: %s [%s]\n", peer.Name, peer.ID)
    }

    select {} // Wait forever
}

📦 Installation

go-p2p-message-bus requires a supported release of Go.

go get -u github.com/bsv-blockchain/go-p2p-message-bus

📚 Documentation

API Reference
Config
type Config struct {
    Name           string         // Required: identifier for this peer (receivers keep at most 64 printable bytes)
    BootstrapPeers []string       // Optional: initial peers to connect to
    Logger         Logger         // Optional: custom logger (uses DefaultLogger if not provided)
    PrivateKey     crypto.PrivKey // Required: private key for persistent peer ID
    PeerCacheFile  string         // Optional: file path for peer persistence
    AnnounceAddrs  []string       // Optional: addresses to advertise to peers (for K8s)
}

Logger Interface:

The library defines a Logger interface and provides a DefaultLogger implementation:

type Logger interface {
    Debugf(format string, v ...any)
    Infof(format string, v ...any)
    Warnf(format string, v ...any)
    Errorf(format string, v ...any)
}

// DefaultLogger is provided out of the box
logger := &p2p.DefaultLogger{}

// Or use your own custom logger that implements the interface

Persistent Peer Identity:

The PrivateKeyHex field is required to ensure consistent peer IDs across restarts:

// Generate a new key for first-time setup
keyHex, err := p2p.GeneratePrivateKeyHex()
if err != nil {
    log.Fatal(err)
}
// Save keyHex somewhere (env var, config file, database, etc.)

// Create client with the saved key
client, err := p2p.NewPeer(p2p.Config{
    Name:          "node1",
    PrivateKeyHex: keyHex,
})

// You can also retrieve the key from an existing client
retrievedKey, _ := client.GetPrivateKeyHex()

Peer Persistence:

The PeerCacheFile field is optional and enables peer persistence for faster reconnection:

client, err := p2p.NewPeer(p2p.Config{
    Name:          "node1",
    PrivateKey:    privKey,
    PeerCacheFile: "peers.json", // Enable peer caching
})

When enabled:

  • Connected topic peers are saved to the specified file, at most once every 30 seconds
  • Each save merges into the existing file: peers not connected right now are kept until they are older than PeerCacheTTL (default 24h), and the newest 100 peers are kept
  • Only peers that have sent a valid message are cached; announcing a topic subscription is not enough
  • The file is replaced atomically (written to a temporary file in the same directory, then renamed), so its directory must be writable; it is also saved once more on Close
  • On restart, the client will reconnect to previously known peers
  • This significantly speeds up network reconnection
  • If not provided, peer caching is disabled

Resource Manager Limits:

The libp2p resource manager caps connections, streams and file descriptors. By default go-libp2p auto-scales these limits to the host's memory and file-descriptor limits, so the inbound connection limit can land in the low hundreds on a small host. Nodes that take heavy inbound churn, such as bootstrap or DHT server nodes, should set the limits explicitly with ResourceLimits:

client, err := p2p.NewClient(p2p.Config{
    Name:       "bootstrap1",
    PrivateKey: privKey,
    ResourceLimits: p2p.ResourceLimits{
        Conns:        8192, // system-wide, inbound + outbound; must be >= MaxConnections
        ConnsInbound: 4096,
        FD:           8192,
        // Optional per-subnet caps; a non-empty list replaces go-libp2p's default for that family.
        IPv4SubnetLimits: []p2p.SubnetConnLimit{{PrefixLength: 32, Conns: 8}, {PrefixLength: 24, Conns: 32}},
    },
})
Field Scope go-libp2p default when unset
Conns, ConnsInbound, ConnsOutbound system auto-scaled
Streams, StreamsInbound, StreamsOutbound system auto-scaled
FD system auto-scaled
PeerConns, PeerConnsInbound, PeerStreamsInbound each peer auto-scaled
IPv4SubnetLimits each IPv4 subnet 8 connections per address (/32)
IPv6SubnetLimits each IPv6 subnet 8 per /56, 64 per /48
  • Zero (or an empty list) keeps the go-libp2p default for that field; a zero ResourceLimits leaves the resource manager entirely to go-libp2p, as before
  • Overrides apply on top of the auto-scaled defaults, so setting one field never changes another (raising Conns does not raise ConnsOutbound)
  • An inbound or outbound limit you set can't exceed its total, whether the total is set or auto-scaled: raising ConnsInbound above the auto-scaled Conns needs Conns set too, otherwise libp2p would silently cap it. Lowering only a total is fine; libp2p caps the unset directional limits at it
  • FD also caps inbound connections (each TCP connection holds a file descriptor), so raise it together with ConnsInbound
  • NewClient rejects negative values, a set inbound/outbound part larger than its effective total (ConnsInbound > Conns, StreamsInbound > Streams, PeerConnsInbound > PeerConns, ...), Conns below MaxConnections, and subnet entries with an out-of-range prefix or a non-positive count
  • The effective system limits are logged once at startup: Resource manager system limits: conns=... inbound=... outbound=... streams=... fd=... memory=...
  • The libp2p_rcmgr_* Prometheus metrics keep working and report the effective limits

Restricting Which Peers You Accept Messages From:

The AllowedPublisherIDs field restricts inbound pubsub messages to a known set of publishers. It gates message authorship only — not connections, not streams, not the peer-address exchange. It is empty by default, which accepts messages from everyone:

client, err := p2p.NewClient(p2p.Config{
    Name:       "node1",
    PrivateKey: privKey,
    AllowedPublisherIDs: []string{
        "12D3KooWA...",
        "12D3KooWB...",
    },
})

When set:

  • Messages authored by any other peer are neither delivered to subscribers nor forwarded to the mesh
  • The sending peer's GossipSub score is not penalized — a peer you do not listen to has not misbehaved
  • Connections are unaffected: unlisted peers are still dialed, still kept connected, and still served the peer-address exchange protocol
  • On a network where peers run GossipSub scoring, persistently failing to forward non-allowlisted peers' messages can degrade this node's own mesh delivery score and get it pruned or graylisted, in turn degrading delivery for the allowlisted peers too
  • Your own peer ID is added automatically, as are the peer IDs that StaticPeers entries name directly with a /p2p/ component. For a relayed (/p2p-circuit/) address the ID taken is the target's, not the relay's. BootstrapPeers are not added
  • Publisher IDs come only from configuration text — AllowedPublisherIDs and the /p2p/ components of StaticPeers — never from DNS. A bare /dnsaddr/<host> entry has no suffix for the resolver to filter its TXT records against, so trusting what it resolves to would let whoever answers that lookup pick this node's publishers. Such an entry contributes no ID, is warned about at startup, and the set is never rebuilt — use the /dnsaddr/<host>/p2p/<id> form when this allowlist is in use
  • Listing an address under StaticPeers therefore grants it publisher trust; listing the same address under BootstrapPeers does not
  • Filtered peers never reach the message-receive path, so they are never recorded as topic peers: while filtered they do not appear in GetPeers() output at all, even though they stay connected, and no peer-address discovery is attempted for them. 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
  • An entry that is not a valid peer ID makes NewClient fail

Filtering is on the authenticated libp2p peer ID of the message author, so it cannot be bypassed by a peer claiming another peer's Name. Note that this is an identity filter, not a content filter, and it does not protect against a compromised key belonging to a listed peer. It filters 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 once libp2p's seen-cache window for it has passed, so reject stale or duplicate work at the application layer if that matters.

Validating Messages Before They Are Relayed:

GossipSub forwards a message to the mesh before Subscribe hands it to you, so a size check in your subscriber protects only your own node. TopicValidators runs before delivery and before forwarding:

client, err := p2p.NewClient(p2p.Config{
    Name:       "node1",
    PrivateKey: privKey,
    TopicValidators: map[string]p2p.TopicValidator{
        "myapp-block": {
            MaxPayloadSize: 10 * 1024,
            // Optional, runs on the decoded payload; must be cheap and non-blocking.
            Validate: func(ctx context.Context, from peer.ID, data []byte) pubsub.ValidationResult {
                if !json.Valid(data) {
                    return pubsub.ValidationReject
                }
                return pubsub.ValidationAccept
            },
        },
    },
})
  • The key is the topic name exactly as passed to Subscribe and Publish
  • MaxPayloadSize is required. The raw envelope is size-checked before it is decoded, so an oversized message costs no decoding work
  • A failing message is rejected: it is neither delivered nor forwarded. With peer scoring on, pubsub charges the rejection to the peer that forwarded it, on topics whose score params weight invalid deliveries. Validate may return ValidationIgnore instead to drop without penalty
  • Messages the AllowedPublisherIDs filter drops are ignored, never rejected, so the allowlist's no-penalty promise holds
  • Publish sends Name sanitized to 64 printable bytes, the form receivers keep anyway, so a long name cannot push a payload over the limit
  • Validate receives the authenticated author's peer ID, not the peer that forwarded the message
  • Your own publishes pass the same validator; a rejected Publish returns a pubsub.ValidationError
  • Rejections are logged as one aggregate line per topic per interval: Dropped N message(s) on topic <topic> that failed validation since the last report

MaxMessageSize overrides the pubsub wire limit (default 1MiB), but it limits whole RPC frames, not single messages. A peer packs several messages and control traffic into one frame sized by its own limit, and a frame over yours resets that peer's stream. Lower it only when every peer on the network runs the same lower limit; use TopicValidators to bound message sizes.

Kubernetes Support:

The AnnounceAddrs field allows you to specify the external addresses that your peer should advertise. This is essential in Kubernetes where the pod's internal IP differs from the externally accessible address:

// Get external address from environment or K8s service
externalIP := os.Getenv("EXTERNAL_IP")      // e.g., "203.0.113.1"
externalPort := os.Getenv("EXTERNAL_PORT")  // e.g., "30001"

client, err := p2p.NewPeer(p2p.Config{
    Name:       "node1",
    PrivateKey: privKey,
    AnnounceAddrs: []string{
        fmt.Sprintf("/ip4/%s/tcp/%s", externalIP, externalPort),
    },
})

Common Kubernetes scenarios:

  • LoadBalancer Service: Use the external IP of the LoadBalancer
  • NodePort Service: Use the node's external IP and the NodePort
  • Ingress with TCP: Use the ingress external IP and configured port

Without AnnounceAddrs, libp2p will announce the pod's internal IP, which won't be reachable from outside the cluster.

Client Methods

GeneratePrivateKeyHex

func GeneratePrivateKeyHex() (string, error)

Generates a new Ed25519 private key and returns it as a hex string. Use this function to create a new key for Config.PrivateKeyHex when setting up a new peer for the first time.

NewPeer

func NewPeer(config Config) (*Client, error)

Creates and starts a new P2P client. The client automatically:

  • Creates a libp2p host with NAT traversal support
  • Bootstraps to the DHT network
  • Starts peer discovery (DHT + mDNS)
  • Connects to cached peers from previous sessions

Note: Requires Config.PrivateKeyHex to be set. Use GeneratePrivateKeyHex() to create a new key.

Subscribe

func (c *Client) Subscribe(topic string) <-chan Message

Subscribes to a topic and returns a channel that receives messages. The channel is closed when the client is closed (a Subscribe issued after Close returns an already-closed channel).

Publish

func (c *Client) Publish(topic string, data []byte) error

Publishes a message to a topic. The message is broadcast to all peers subscribed to the topic.

GetPeers

func (c *Client) GetPeers() []PeerInfo

Returns the peers that authored a message on a joined topic and are connected now or were heard from within the last hour. At most 10,000 such authors are tracked; connected ones are always kept.

GetID

func (c *Client) GetID() string

Returns this peer's ID as a string.

GetPrivateKeyHex

func (c *Client) GetPrivateKeyHex() (string, error)

Returns the hex-encoded private key for this peer. This can be saved and used in Config.PrivateKey to maintain the same peer ID across restarts.

Close

func (c *Client) Close() error

Shuts down the client and releases all resources.

Data Types

Message

type Message struct {
    Topic     string    // Topic this message was received on
    From      string    // Sender's name, as sanitized by the receiver (printable, at most 64 bytes)
    FromID    string    // Sender's peer ID
    Data      []byte    // Message payload
    Timestamp time.Time // When the message was received
}

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
}

Development Build Commands

Get the MAGE-X build tool for development:

go install github.com/mrz1836/mage-x/cmd/magex@latest

View all build commands

magex help
Repository Features

This repository includes 25+ built-in features covering CI/CD, security, code quality, developer experience, and community tooling.

View the full Repository Features list →

Library Deployment

This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:

brew install goreleaser

The release process is defined in the .goreleaser.yml configuration file.

Then create and push a new Git tag using:

magex version:bump push=true bump=patch branch=main

This process ensures consistent, repeatable releases with properly versioned artifacts and citation metadata.

Pre-commit Hooks

Set up the Go-Pre-commit System to run the same formatting, linting, and tests defined in AGENTS.md before every commit:

go install github.com/mrz1836/go-pre-commit/cmd/go-pre-commit@latest
go-pre-commit install

The system is configured via modular environment files and provides 17x faster execution than traditional Python-based pre-commit hooks. See the complete documentation for details.

GitHub Workflows

All workflows are driven by modular configuration in .github/env/ — no YAML editing required.

View all workflows and the control center →

Updating Dependencies

To update all dependencies (Go modules, linters, and related tools), run:

magex deps:update

This command ensures all dependencies are brought up to date in a single step, including Go modules and any tools managed by MAGE-X. It is the recommended way to keep your development environment and CI in sync with the latest versions.


🔧 How It Works

Peer Discovery, NAT Traversal, and Message Routing

Peer Discovery

The library uses multiple discovery mechanisms:

  • DHT: Connects to IPFS bootstrap peers and advertises topics on the distributed hash table
  • mDNS: Discovers peers on the local network
  • Peer Cache: Persists peer information to disk for faster reconnection across restarts

NAT Traversal

Automatically handles NAT traversal through:

  • Hole Punching: Attempts direct connections between NAT'd peers
  • Relay: Falls back to relay connections when direct connections fail
  • UPnP/NAT-PMP: Automatically configures port forwarding when possible

Message Routing

Uses GossipSub for efficient topic-based message propagation:

  • Messages are distributed using an optimized gossip protocol
  • Reduces bandwidth while maintaining reliability
  • Automatically handles peer mesh management and scoring

🧪 Examples & Tests

All unit tests and examples run via GitHub Actions and use Go version 1.24.x. View the configuration file.

Run all tests (fast):

magex test

Run all tests with race detector (slower):

magex test:race
Running the Example

See cmd/example/main.go for a complete working example.

To run the example:

go run ./cmd/example -name "node1"

In another terminal:

go run ./cmd/example -name "node2"

The two nodes will discover each other and exchange messages.


⚡ Benchmarks

Run the Go benchmarks:

magex bench

🛠️ Code Standards

Read more about this Go project's code standards.


🤖 AI Usage & Assistant Guidelines

Read the AI Usage & Assistant Guidelines for details on how AI is used in this project and how to interact with AI assistants.


👥 Maintainers

Siggi Galt MrZ
Siggi Dylan MrZ

🤝 Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬.

Stars


📝 License

License

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

Constants

This section is empty.

Variables

View Source
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")
)
View Source
var (
	// ErrInvalidTopicValidator is returned when a Config.TopicValidators entry
	// has no positive MaxPayloadSize.
	ErrInvalidTopicValidator = errors.New("topic validator MaxPayloadSize must be positive")
	// ErrInvalidMaxMessageSize is returned when Config.MaxMessageSize is negative.
	ErrInvalidMaxMessageSize = errors.New("MaxMessageSize must not be negative")
)
View Source
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.

View Source
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

func GeneratePrivateKey() (crypto.PrivKey, error)

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

func PrivateKeyFromHex(keyHex string) (crypto.PrivKey, error)

PrivateKeyFromHex loads a private key from a hex string.

func PrivateKeyToHex

func PrivateKeyToHex(priv crypto.PrivKey) (string, error)

PrivateKeyToHex converts a private key to a hex string for storage.

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 the peers that authored a message on a joined topic and
	// are connected now or were heard from within the last hour. At most 10,000
	// such authors are tracked; connected ones are always kept.
	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.

func NewClient

func NewClient(config Config) (Client, error)

NewClient creates and initializes a new P2P client. It automatically starts the client and begins peer discovery.

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 are dropped when the cache is
	// loaded or saved.
	// 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

	// TopicValidators optionally validates messages per topic before GossipSub
	// delivers or forwards them. The key is the topic name exactly as passed to
	// Subscribe and Publish. Without a validator a topic accepts any signed
	// message up to the pubsub wire limit and relays it to its mesh peers before
	// the subscriber ever sees it, so caps applied after Subscribe protect only
	// this node, never the network.
	//
	// Each validator bounds the payload size and may run a further check; see
	// TopicValidator. A failing message is rejected (ValidationReject), so it is
	// neither delivered nor forwarded. With peer scoring on, pubsub charges the
	// rejection to the peer that forwarded the message, and only on topics whose
	// TopicScoreParams weight invalid deliveries. Messages the AllowedPublisherIDs
	// filter drops are ignored, never rejected. Local publishes pass the same
	// validator, and a rejected Publish returns a pubsub.ValidationError.
	// Rejections are logged as one aggregate line per topic per interval.
	TopicValidators map[string]TopicValidator

	// MaxMessageSize optionally overrides the pubsub wire limit (default 1MiB,
	// pubsub.DefaultMaxMessageSize). Zero keeps the default.
	//
	// This limit bounds whole RPC frames, not single messages: a peer packs
	// several messages, IWANT replies and control traffic into one frame, sized
	// by its own limit. A frame over this node's limit resets the stream from
	// that peer, dropping everything in flight on it. Lowering it below what
	// other peers on the network use therefore loses legitimate traffic. Use
	// TopicValidators to bound message sizes; lower this only on a network where
	// every peer runs the same, lower limit.
	MaxMessageSize int
	// 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.

type TopicValidator added in v0.3.2

type TopicValidator struct {
	// MaxPayloadSize is the largest payload, in bytes, accepted on the topic.
	// It must be positive. The envelope is size-checked against it before it
	// is decoded, so an oversized message costs no decoding work.
	MaxPayloadSize int

	// Validate optionally runs a further check on the decoded payload. from is
	// the message's authenticated author, not the peer that forwarded it.
	// Return ValidationReject for an invalid message, ValidationIgnore to drop
	// it without penalty. Messages from authors outside AllowedPublisherIDs are
	// ignored before Validate is called.
	//
	// It runs inline on pubsub's validation workers, for every inbound message
	// on the topic and for this node's own publishes, so it must be cheap and
	// must not block: a slow Validate stalls validation for every topic.
	Validate func(ctx context.Context, from peer.ID, data []byte) pubsub.ValidationResult
}

TopicValidator checks messages on one topic before GossipSub delivers or forwards them. See Config.TopicValidators.

Directories

Path Synopsis
cmd
example command
Package main provides an example P2P messaging application with topic subscription and broadcasting.
Package main provides an example P2P messaging application with topic subscription and broadcasting.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL