hyperswarm

repository·main·Indexed 21 days ago

https://github.com/holepunchto/hyperswarm

A distributed networking stack for connecting peers using a Distributed Hash Table (DHT). It provides a high-level API for peer discovery and connection management, allowing developers to find and connect to peers interested in specific 32-byte topics using Noise-encrypted streams. The library supports both client and server modes for joining topics, direct peer connections via public keys, and comprehensive swarm lifecycle management including suspend, resume, and flush operations.

Tokens
2.5K
Snippets
2
Records
22
Agent score
80%

What's inside hyperswarm

  1. How client and server modes work in Hyperswarm

    main

    Hyperswarm uses two modes for joining topics:

    • Server mode: The swarm announces your keypair to the DHT so others can discover you. It accepts incoming connections from clients. When a server connection is emitted, it is not associated with a specific topic; the server only knows it received an incoming connection.
    • Client mode: The swarm queries the DHT to discover available servers and eagerly connects to them. When a client connection is emitted, it is associated with the topic (the peerInfo.topics array will be populated).

    To join as a server, set { server: true }. To join as a client, set { client: true }.

  2. Quickstart: Join a swarm and handle connections

    main

    To use hyperswarm, create a new Hyperswarm instance and use join() with a 32-byte Buffer topic. You can listen for the connection event to receive end-to-end (Noise) encrypted Duplex streams.

    Note: In the example below, swarm2 is used to join the topic. In a real application, you would use the same instance to both join and listen for connections.

    const Hyperswarm = require('hyperswarm')
    
    const swarm = new Hyperswarm()
    
    swarm.on('connection', (conn) => {
      // conn is an end-to-end (Noise) encrypted Duplex stream
      conn.write('this is a server connection')
      conn.end()
    })
    
    const discoveryKey = Buffer.alloc(32).fill('hello world') // must be 32 bytes
    
    // join the swarm, others will find you
    swarm.join(discoveryKey, { server: true, client: true })
  3. Manage direct peer connections

    main

    You can establish or stop connections to specific known peers using their 32-byte Noise public key.

    • swarm.joinPeer(noisePublicKey): Establish a direct connection. Re-establishes automatically on failure.
    • swarm.leavePeer(noisePublicKey): Stop attempting direct connections. Does not close existing connections.
  4. Manage swarm lifecycle (suspend, resume, flush)

    main

    Use these methods to manage the overall state of the swarm:

    • await swarm.flush(): A heavyweight operation that waits for all pending DHT announces and all pending peer connections to complete. Once finished, the swarm has connected to every discoverable peer in its current topics.
    • await swarm.suspend({ log }): Disconnects all peers, stops server listening, and stops discovery. Useful when the runtime suspends.
    • await swarm.resume({ log }): Resumes discovery and re-announces to the DHT.

    Both suspend and resume accept an optional log function.

  5. Inspect peer information with PeerInfo API

    main

    When the connection event is emitted, it provides a PeerInfo object containing metadata about the connected peer.

    Properties:

    • peerInfo.publicKey: The peer's Noise public key.
    • peerInfo.topics: An Array of topics associated with this peer (only populated in client mode).
    • peerInfo.prioritized: Boolean indicating if the swarm is rapidly attempting to reconnect to this peer.

    Methods:

    • peerInfo.ban(banStatus = false): Ban (true) or unban (false) the peer. Banning prevents future reconnection attempts but does not close existing connections.
  6. Control discovery with PeerDiscovery API

    main

    The PeerDiscovery object returned by swarm.join() allows fine-grained control over a specific topic's lifecycle.

    • await discovery.flushed(): (Server mode only) Waits until the topic is fully announced to the DHT and the server is available to the network.
    • await discovery.refresh({ client, server }): Updates configuration and triggers an immediate re-announce (in server mode).
    • await discovery.destroy(): Stops discovering peers for this topic (similar to swarm.leave(topic)).
  7. Construct a new Hyperswarm instance

    main

    Use new Hyperswarm(opts) to create a swarm instance.

    Options (opts):

    • keyPair: A Noise keypair used for DHT listening/connecting. Defaults to a new key pair.
    • seed: A unique, 32-byte, random seed to deterministically generate the key pair.
    • maxPeers: Maximum number of peer connections allowed.
    • firewall: A sync function remotePublicKey => (true|false). If true, the connection is rejected. Defaults to allowing all.
    • dht: A hyperdht instance. Defaults to a new instance.
  8. Join a topic and discover peers

    main

    Use swarm.join(topic, opts) to start discovering and connecting to peers sharing a 32-byte Buffer topic.

    Options (opts):

    • server: Accept server connections for this topic by announcing to the DHT. Defaults to true.
    • client: Actively search for and connect to discovered servers. Defaults to true.
    • limit: Max number of peers to connect to for this topic. Defaults to Infinity.

    Returns a PeerDiscovery object.

  9. Destroy the swarm

    main

    Use destroy({ force }) to completely shut down the swarm, including the DHT and all connections.

    Parameters:

    • force: (Optional) If true, the swarm will destroy the DHT immediately without waiting for discovery sessions to clear.

    Returns: A Promise that resolves when the swarm is fully destroyed.