Idiomatic Go P2P messaging library with auto-discovery, NAT traversal, and channel-based pub/sub.
CI / CD Β Β
|
|
Β Β Β Β Quality Β Β
|
|
Security Β Β
|
|
Β Β Β Β Community Β Β
|
|
π¦Β Installation
|
π§ͺΒ ExamplesΒ &Β Tests
|
πΒ Documentation
|
π€Β Contributing
|
π οΈΒ CodeΒ Standards
|
β‘Β Benchmarks
|
π€Β AIΒ Usage
|
πΒ License
|
π₯Β Maintainers
|
- 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)
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
}go-p2p-message-bus requires a supported release of Go.
go get -u github.com/bsv-blockchain/go-p2p-message-bus- API Reference β Dive into the godocs at pkg.go.dev/github.com/bsv-blockchain/go-p2p-message-bus
- Usage Examples β Browse practical patterns either the examples directory or the example tests
- Benchmarks β Check the latest numbers in the benchmark results
- Test Suite β Review both the unit tests and fuzz tests (powered by
testify)
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 interfacePersistent 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
ResourceLimitsleaves 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
Connsdoes not raiseConnsOutbound) - An inbound or outbound limit you set can't exceed its total, whether the total is set or auto-scaled: raising
ConnsInboundabove the auto-scaledConnsneedsConnsset too, otherwise libp2p would silently cap it. Lowering only a total is fine; libp2p caps the unset directional limits at it FDalso caps inbound connections (each TCP connection holds a file descriptor), so raise it together withConnsInboundNewClientrejects negative values, a set inbound/outbound part larger than its effective total (ConnsInbound > Conns,StreamsInbound > Streams,PeerConnsInbound > PeerConns, ...),ConnsbelowMaxConnections, 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
StaticPeersentries name directly with a/p2p/component. For a relayed (/p2p-circuit/) address the ID taken is the target's, not the relay's.BootstrapPeersare not added - Publisher IDs come only from configuration text β
AllowedPublisherIDsand the/p2p/components ofStaticPeersβ 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
StaticPeerstherefore grants it publisher trust; listing the same address underBootstrapPeersdoes 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.PeerCacheFiledoes not followGetPeers()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
NewClientfail
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, non-blocking,
// and must not modify data (subscribers receive the same slice).
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
SubscribeandPublish MaxPayloadSizeis 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.
Validatemay returnValidationIgnoreinstead to drop without penalty - Messages the
AllowedPublisherIDsfilter drops are ignored, never rejected, so the allowlist's no-penalty promise holds PublishsendsNamesanitized to 64 printable bytes, the form receivers keep anyway, so a long name cannot push a payload over the limitValidatereceives the authenticated author's peer ID, not the peer that forwarded the message- Your own publishes pass the same validator; a rejected
Publishreturns apubsub.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 the receiver's limit resets the stream. That cuts both ways: lowered, you reset streams from peers on the default; raised, peers on the default reset the streams you send larger frames on. Change it only when every peer on the network runs the same 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 MessageSubscribes 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) errorPublishes a message to a topic. The message is broadcast to all peers subscribed to the topic.
GetPeers
func (c *Client) GetPeers() []PeerInfoReturns 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.
PeerAddrs
func (c *Client) PeerAddrs(peerID string) []stringReturns the remote multiaddrs of the open connections to one peer, the same strings GetPeers reports as Addrs, or nil if there are none or peerID does not decode. It reads only the connection table, so its cost is proportional to that peer's connections rather than to the tracked authors, and it also covers connected peers that have never authored a message. Use it instead of scanning GetPeers when checking one peer at a time; len(c.PeerAddrs(id)) > 0 tells whether the peer is connected.
BlockAddr / BlockSubnet / BlockPeer
func (c *Client) BlockAddr(ip net.IP) error
func (c *Client) UnblockAddr(ip net.IP) error
func (c *Client) BlockSubnet(ipnet *net.IPNet) error
func (c *Client) UnblockSubnet(ipnet *net.IPNet) error
func (c *Client) BlockPeer(peerID string) error
func (c *Client) UnblockPeer(peerID string) errorEnforce a ban list at connection admission rather than only on the message path. A block refuses new connections in both directions, dialed in or out, and closes the open connections it matches: BlockAddr those whose remote IP is ip (an IPv4 address and its IPv4-mapped IPv6 form are the same), BlockSubnet those whose remote IP is inside ipnet (host bits are ignored), BlockPeer every connection to that peer on any address. A connection whose handshake was already under way when the block was added is closed as soon as it completes.
These rules govern who this node is connected to, not whose messages it sees: GossipSub relays messages, so a blocked peer's messages can still arrive through other neighbours. A relayed connection's remote address is the relay's, so an IP or subnet rule that covers a relay drops every connection through it, and a host that comes in through a relay is refused only by BlockPeer.
Rules live in memory and are lost on Close; a caller that persists its ban list re-applies it after NewClient. UnblockSubnet removes only the exact rule given; it does not split a wider one. While AllowPrivateIPs is false the private, loopback and link-local ranges are built-in rules on the same gater, and no unblock call lifts them. Invalid input returns ErrInvalidIP, ErrInvalidSubnet or an error wrapping ErrInvalidPeerID. All six are safe for concurrent use and after Close.
GetID
func (c *Client) GetID() stringReturns 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() errorShuts 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@latestView all build commands
magex helpRepository Features
This repository includes 25+ built-in features covering CI/CD, security, code quality, developer experience, and community tooling.
Library Deployment
This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:
brew install goreleaserThe 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=mainThis 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 installThe 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.
Updating Dependencies
To update all dependencies (Go modules, linters, and related tools), run:
magex deps:updateThis 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.
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
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 testRun all tests with race detector (slower):
magex test:raceRunning 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.
Run the Go benchmarks:
magex benchRead more about this Go project's code standards.
Read the AI Usage & Assistant Guidelines for details on how AI is used in this project and how to interact with AI assistants.
![]() |
![]() |
![]() |
|---|---|---|
| Siggi | Dylan | MrZ |
View the contributing guidelines and please follow the code of conduct.
All kinds of contributions are welcome π! The most basic way to show your support is to star π the project, or to raise issues π¬.


