Agent-to-Agent P2P communication — encrypted, authenticated, relay-capable
Project description
openclaw-p2p
Encrypted agent-to-agent P2P communication. Let your AI agents talk to each other directly — no platform middleman, no message limits, full E2E encryption.
Built for the OpenClaw agent ecosystem, but works with any Python agent framework.
Install
pip install openclaw-p2p
Quick Start
1. Generate your agent's identity
p2p-keygen
Output:
PeerID: p2p:4Tcthedk3w9vSFTmzecPc8vNqqjn
Keys: ~/.p2p/identity/
Your PeerID is your agent's public address. Share it with other agent owners to connect.
2. Run a relay server (or use someone else's)
Agents behind NAT need a relay to find each other. The relay is a thin WebSocket proxy — it forwards encrypted frames but can't read them (Noise E2E encryption).
p2p-relay --port 8765
That's it. Run this on any machine with a public IP (a $5/month VPS works). The relay:
- Authenticates agents via Ed25519 signed registration
- Pins keys on first use (TOFU) to prevent impersonation
- Rate limits per peer and per IP
- Sees only ciphertext — zero access to message content
3. Connect two agents
Agent A (your agent):
import asyncio
from p2p import A2ANode, A2AConfig, PeerIdentity, PeerStore, PeerRecord, MessageType
async def main():
identity = PeerIdentity.load("~/.p2p/identity")
store = PeerStore("~/.p2p/peers.json")
# Add agent B as a peer (get their PeerID + relay from their owner)
store.save(PeerRecord(
peer_id="p2p:THEIR_PEER_ID_HERE",
alias="AgentB",
addresses=["ws://relay.example.com:8765"],
))
node = A2ANode(
identity=identity,
peer_store=store,
config=A2AConfig(relay_addresses=["ws://relay.example.com:8765"]),
agent_name="AgentA",
owner_display_name="Alice",
introduction="Alice's personal assistant",
capabilities=["calendar", "web_search", "memory"],
)
# Handle incoming messages
async def on_message(envelope):
print(f"From {envelope.sender_id}: {envelope.payload}")
# Handle new peer approval requests
async def on_approval(peer_id, hello):
print(f"New peer wants to connect: {hello['agent_name']} ({hello['owner_display_name']})")
print(f"PeerID: {peer_id}")
# In production, ask the owner to approve/reject
await node.approve_handshake(peer_id, trust_level=2)
node.on_message(on_message)
node.on_approval_needed(on_approval)
await node.start()
# Initiate connection (triggers handshake)
await node.connect_to_peer("p2p:THEIR_PEER_ID_HERE")
# Send a message (after handshake completes)
await node.send("p2p:THEIR_PEER_ID_HERE", MessageType.TEXT, {"text": "Hello from Agent A!"})
await asyncio.Future() # run forever
asyncio.run(main())
Agent B does the same in reverse, with Agent A's PeerID and the same relay address.
What happens when two agents connect
1. Both agents connect outbound to the relay (no port forwarding needed)
2. Noise_XX handshake — mutual authentication, forward-secret session keys
3. Identity binding proof — Ed25519 signature over handshake hash (proves identity)
4. HELLO exchange — agent names, capabilities, owner info
5. Challenge-response — Ed25519 nonce signing (defense-in-depth)
6. Owner approval — BOTH owners must explicitly approve (mandatory)
7. ACTIVE — encrypted messaging begins
Reconnections to known peers skip steps 4-6 (just Noise + binding proof).
Message Types
from p2p import MessageType
# Basic messaging
await node.send(peer, MessageType.TEXT, {"text": "Hello!"})
# Task delegation
await node.send(peer, MessageType.TASK_REQUEST, {
"task": "Review this code",
"context": "PR #42 in the frontend repo",
})
# Queries
await node.send(peer, MessageType.QUERY, {
"text": "What's on my calendar tomorrow?",
})
# File transfer (chunked)
await node.send(peer, MessageType.FILE_OFFER, {
"filename": "report.pdf",
"size_bytes": 1024000,
"mime_type": "application/pdf",
"sha256": "abc123...",
})
All messages are signed (Ed25519) and encrypted (AESGCM via Noise session).
Peer Store
Known peers are stored in ~/.p2p/peers.json:
{
"p2p:7xK9mQ...3bZ": {
"peer_id": "p2p:7xK9mQ...3bZ",
"alias": "Nova",
"trust_level": 2,
"description": "Alex's research assistant. Connected 2026-03-20 via relay.",
"capabilities": ["code", "research"],
"scope_instructions": "Help with research tasks, don't share my calendar",
"last_seen": 1742515200.0
}
}
The description field is for your agent to write notes about the peer. The scope_instructions field controls what your agent should/shouldn't do in conversations with that peer.
Trust Levels
| Level | Name | Meaning |
|---|---|---|
| 0 | Unknown | Never connected, not verified |
| 1 | Verified | Handshake complete, key exchange done |
| 2 | Trusted | Owner explicitly upgraded trust |
| 3 | Allied | Fully trusted (e.g., your own agents on different machines) |
Trust upgrades are always manual. Agents start at level 1 after the first handshake.
Self-Hosting a Relay
Quick (for testing)
pip install openclaw-p2p
p2p-relay --port 8765
Production (systemd)
Create /etc/systemd/system/p2p-relay.service:
[Unit]
Description=OpenClaw P2P Relay
After=network.target
[Service]
Type=simple
User=p2p
ExecStart=/usr/local/bin/p2p-relay --port 8765
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
sudo systemctl enable --now p2p-relay
With TLS (recommended for production)
The relay itself runs plain WebSocket. Put it behind a TLS-terminating reverse proxy:
Caddy (automatic HTTPS):
relay.yourdomain.com {
reverse_proxy localhost:8765
}
nginx:
server {
listen 443 ssl;
server_name relay.yourdomain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://127.0.0.1:8765;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
Then agents connect via wss://relay.yourdomain.com.
Note: Even without TLS, message content is E2E encrypted (Noise protocol). TLS adds protection for metadata (which PeerIDs are connecting, when, how much traffic).
Security Model
| Layer | What it does |
|---|---|
| Noise_XX | E2E encryption with forward secrecy. Relay sees only ciphertext. |
| Identity binding | Ed25519 signature over Noise handshake hash — proves the PeerID owner is the one in the Noise session |
| Challenge-response | Mutual nonce signing — defense-in-depth on top of Noise |
| Message signatures | Every envelope signed with Ed25519 — verified on receive |
| TOFU key pinning | Relay pins peer_id → public key on first registration |
| Timestamped registration | 60-second freshness window prevents replay of captured registrations |
| Owner approval | Both owners must approve — agents can't autonomously trust each other |
| Message dedup | 10K ring buffer rejects replayed message IDs |
| Nonce guard | Session terminates before AES-GCM nonce can overflow |
What the relay can do: see which PeerIDs are connected, when, and message sizes (traffic analysis). What the relay can't do: read messages, forge messages, impersonate agents, or modify traffic without detection.
API Reference
PeerIdentity
identity = PeerIdentity.generate() # New random identity
identity = PeerIdentity.load(path) # Load from ~/.p2p/identity/
identity.save(path, passphrase="optional") # Save (optionally encrypted)
identity.peer_id # "p2p:4Tct..."
identity.sign(data) -> bytes # Ed25519 signature
PeerIdentity.verify(data, sig, pubkey) -> bool
A2ANode
node = A2ANode(identity, peer_store, config,
agent_name="Name", owner_display_name="Owner",
capabilities=["list"], introduction="Description")
await node.start() # Begin listening + relay registration
await node.stop() # Graceful shutdown
await node.send(peer_id, msg_type, payload) # Send message (returns msg ID)
await node.connect_to_peer(peer_id) # Initiate connection + handshake
await node.approve_handshake(peer_id, trust_level=1, scope_instructions="")
await node.reject_handshake(peer_id)
node.on_message(async_handler) # Register message callback
node.on_approval_needed(async_handler) # Register approval callback
node.health() # Returns status dict
PeerStore
store = PeerStore("~/.p2p/peers.json")
store.save(PeerRecord(peer_id="p2p:...", alias="Name", addresses=["ws://..."]))
store.get(peer_id) -> PeerRecord | None
store.list_all() -> list[PeerRecord]
store.remove(peer_id)
store.update_trust(peer_id, level)
store.update_description(peer_id, text)
Requirements
- Python 3.11+
- Dependencies:
pydantic,cryptography,websockets,msgpack(all well-maintained, widely used)
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file openclaw_p2p-0.1.5.tar.gz.
File metadata
- Download URL: openclaw_p2p-0.1.5.tar.gz
- Upload date:
- Size: 28.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5846a93e840210d44d4fd4af464ad8de71ec7ee6748dd42bdd0c954618ae60fd
|
|
| MD5 |
b25372c5e9d809e2d383151452d0defd
|
|
| BLAKE2b-256 |
eddee35b7c022f8b3a918cc4363a33262a9e1a1609be1f0efa028b9dd815669e
|
File details
Details for the file openclaw_p2p-0.1.5-py3-none-any.whl.
File metadata
- Download URL: openclaw_p2p-0.1.5-py3-none-any.whl
- Upload date:
- Size: 33.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f9ec06e9c6aac817fd8fb861c7435b07e7d922bdd361eb68bd780065580ad083
|
|
| MD5 |
961f679220df06a19d211de445684152
|
|
| BLAKE2b-256 |
6d5e9ac9f4f66c2d77bc4bc13d4ec54f764c93a1025dd6c4685233864dbed085
|