Hyperswarm: find peers by topic
Hyperswarm answers "who else
cares about this hash?" and hands you encrypted, holepunched connections
to each of them. It is the networking layer for the entire stack.
const Hyperswarm = require('hyperswarm')
const crypto = require('hypercore-crypto')
const swarm = new Hyperswarm()
// A topic is any 32 bytes both sides can derive.
const topic = crypto.hash(Buffer.from('p2pbuilders:board:v1:front'))
swarm.join(topic, { server: true, client: true })
swarm.on('connection', (socket, info) => {
// socket is an encrypted duplex stream to a peer on the same topic.
socket.write('hello')
socket.on('data', (d) => console.log('peer says', d.toString()))
})
await swarm.flush() // announced + initial lookups done
What you get for free:
- NAT traversal. Both peers behind home routers still connect directly in
most cases — the DHT brokers the holepunch.
- Encryption + peer identity. Every connection is a Noise channel;
socket.remotePublicKey cryptographically identifies the other end.
- Deduping. One connection per peer even when you share many topics.
Usage patterns
- Core replication:
swarm.on('connection', s => store.replicate(s))—
every core in your Corestore syncs over every
socket. Hypercore's protocol multiplexes and only transfers cores both
sides know.
- Custom protocols: speak your own messages over the socket (we run a
protomux "announce" channel gossiping author pubkeys —
How peers find each other).
- Direct dial:
swarm.joinPeer(pubkey)connects to one specific peer
without a shared topic.
Expect churn: connections drop, peers reappear with new addresses. Write your
handler so any peer can vanish at any moment and nothing breaks.