### Minimal Hyperswarm Setup Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md A basic example demonstrating how to create a Hyperswarm instance, listen for connections, and join a topic. ```javascript const Hyperswarm = require('hyperswarm') // Create a swarm instance const swarm = new Hyperswarm() // Listen for connections swarm.on('connection', (socket) => { console.log('New connection!') socket.pipe(process.stdout) process.stdin.pipe(socket) }) // Join a topic const topic = Buffer.alloc(32).fill('my-chat') swarm.join(topic) // The swarm is now discoverable and will accept connections ``` -------------------------------- ### Minimal Hyperswarm Setup Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md This is the most basic setup for a Hyperswarm instance. It initializes the swarm with default settings. ```javascript const swarm = new Hyperswarm() ``` -------------------------------- ### Install Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/README.md Install the hyperswarm module using npm. ```bash npm install hyperswarm ``` -------------------------------- ### Hyperswarm Initialization with Firewall Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/types.md Example of setting up a Hyperswarm instance with a firewall function to block specific peers by their public key. ```javascript const blocklist = new Set([ 'peer-key-1', 'peer-key-2' ]) const swarm = new Hyperswarm({ firewall: (remotePublicKey) => { const hexKey = remotePublicKey.toString('hex') return blocklist.has(hexKey) } }) ``` -------------------------------- ### Hyperswarm Initialization with Keypair Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/types.md Example of initializing Hyperswarm with a pre-defined Noise Keypair. The public key uniquely identifies the peer on the network. ```javascript const swarm = new Hyperswarm({ keyPair: { publicKey: Buffer.from('...', 'hex'), secretKey: Buffer.from('...', 'hex') } }) console.log(swarm.keyPair.publicKey.toString('hex')) ``` -------------------------------- ### Secure Hyperswarm Setup with Firewall Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Implements a secure Hyperswarm setup using a firewall to restrict connections to an allowlisted set of peers. Peers are identified by their public keys. ```javascript const allowedPeers = new Set(JSON.parse(process.env.ALLOWED_PEERS || '[]')) const swarm = new Hyperswarm({ seed: Buffer.from(process.env.PEER_SEED, 'hex'), firewall: (remotePublicKey) => { const hexKey = remotePublicKey.toString('hex') // Only allow peers in the allowlist if (!allowedPeers.has(hexKey)) { console.log('Rejected unknown peer:', hexKey) return true // reject } return false // accept } }) ``` -------------------------------- ### Production Hyperswarm Setup Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md A comprehensive production setup for Hyperswarm. It includes peer seeding from environment variables, connection limits, firewall rules, bootstrap nodes, and custom relay logic. ```javascript const swarm = new Hyperswarm({ seed: Buffer.from(process.env.PEER_SEED, 'hex'), maxPeers: 256, maxClientConnections: 100, maxServerConnections: 200, maxParallel: 8, firewall: (key) => { // Check blocklist return blocklist.has(key.toString('hex')) }, bootstrap: [ { host: '203.0.0.113.1', port: 49737 }, { host: '203.0.0.113.2', port: 49737 } ], backoffs: [2000, 10000, 30000, 300000], jitter: 1000, relayThrough: (force, swarm) => { if (force || swarm.dht.randomized) { return [relayServer] } return null } }) ``` -------------------------------- ### Start Hyperswarm and Join Topic Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md Initializes a Hyperswarm instance and joins a specific topic, making the service discoverable. Waits for the join to be flushed before proceeding. ```javascript const swarm = new Hyperswarm() // Join topics const topic1 = Buffer.alloc(32).fill('service-1') const discovery1 = swarm.join(topic1, { server: true }) // Wait for initial announcement/discovery await discovery1.flushed() console.log('Service is now discoverable') ``` -------------------------------- ### Hyperswarm Initialization with Relay Function Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/types.md Example of configuring Hyperswarm to use relay servers based on connection requirements and network conditions. ```javascript const swarm = new Hyperswarm({ relayThrough: (force, swarm) => { if (force) { // Must use relay return [relayNode1, relayNode2] } else if (swarm.dht.randomized) { // Use relay if behind randomized NAT return [relayNode1] } return null } }) ``` -------------------------------- ### Initialize Hyperswarm in Node.js Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/README.md Use this snippet to initialize the Hyperswarm client in a Node.js environment. Ensure the 'hyperswarm' package is installed. ```javascript const Hyperswarm = require('hyperswarm') const swarm = new Hyperswarm() ``` -------------------------------- ### Development Hyperswarm Setup with Logging Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Configures Hyperswarm for development with a specific seed, limited peers, and parallel connections. Includes backoff and jitter settings for network stability. ```javascript const swarm = new Hyperswarm({ seed: Buffer.alloc(32).fill('dev'), maxPeers: 10, maxParallel: 2, backoffs: [500, 1000, 5000, 10000], jitter: 100 }) ``` -------------------------------- ### Handling Noise Socket Connections Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/types.md Example of how to handle incoming connections using a NoiseSocket. It demonstrates logging connection details, sending and receiving data, and managing keep-alives and errors. ```javascript swarm.on('connection', (socket, peerInfo) => { console.log('Connected via:', socket.isInitiator ? 'outbound' : 'inbound') console.log('Unique connection ID:', socket.handshakeHash.toString('hex')) // Write data to peer socket.write('Hello') // Receive data socket.on('data', (chunk) => { console.log('Received:', chunk.toString()) }) // Keep connection alive socket.on('timeout', () => { socket.sendKeepAlive() }) socket.on('error', (err) => { console.error('Connection error:', err.message) }) }) ``` -------------------------------- ### swarm.join(topic, opts = {}) Source: https://github.com/holepunchto/hyperswarm/blob/main/README.md Starts discovering and connecting to peers sharing a specific topic. Peers are emitted as 'connection' events. ```APIDOC ## swarm.join(topic, opts = {}) ### Description Start discovering and connecting to peers sharing a common topic. As new peers are connected to, they will be emitted from the swarm as `connection` events. `topic` must be a 32-byte Buffer `opts` can include: - `server`: Accept server connections for this topic by announcing yourself to the DHT. Defaults to `true`. - `client`: Actively search for and connect to discovered servers. Defaults to `true`. - `limit`: Set the max number of peers to connect to when joining the topic. Defaults to `Infinity`. Returns a [`PeerDiscovery`](#peerdiscovery-api) object. ``` -------------------------------- ### Join a Topic Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/README.md Join a specific topic to start discovering and announcing peers. Configure whether to act as a server, client, or both, and set a peer limit for the topic. Await `flushed()` to ensure initial DHT operations are complete. ```javascript const topic = Buffer.alloc(32).fill('my-service') const discovery = swarm.join(topic, { server: true, // Announce availability client: true, // Discover others limit: Infinity // Max peers for this topic }) await discovery.flushed() // Wait for initial DHT operations ``` -------------------------------- ### High-Performance Hyperswarm Setup Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Optimizes Hyperswarm for high performance by increasing peer limits, connection counts, and parallel operations. It also sets a fixed port for network stability. ```javascript const swarm = new Hyperswarm({ maxPeers: 512, maxClientConnections: 300, maxServerConnections: 512, maxParallel: 16, backoffs: [100, 500, 2000, 60000], jitter: 50, port: 49737 // Fixed port for stability }) ``` -------------------------------- ### await swarm.listen() Source: https://github.com/holepunchto/hyperswarm/blob/main/README.md Explicitly starts listening for incoming connections. This is usually called internally after the first 'join' operation. ```APIDOC ## await swarm.listen() ### Description Explicitly start listening for incoming connections. This will be called internally after the first `join`, so it rarely needs to be called manually. ``` -------------------------------- ### Join a Topic with Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Use `swarm.join` to start discovering and connecting to peers for a specific topic. Configure server and client roles, and set a connection limit. `discovery.flushed()` waits for initial DHT operations. ```javascript const topic = Buffer.alloc(32).fill('chat-room-1') const discovery = swarm.join(topic, { server: true, // Accept incoming connections client: true, // Connect to servers limit: 10 // Connect to max 10 peers }) await discovery.flushed() // Wait for initial DHT announce/lookup ``` -------------------------------- ### Joining a Topic Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/README.md Join a specific topic to start discovering and announcing peers interested in the same data. ```APIDOC ## Joining a Topic ### Description Join a specific topic to start discovering and announcing peers interested in the same data. The `join` method returns a `PeerDiscovery` object that can be used to manage the discovery process. ### Method `swarm.join(topic, [options])` ### Parameters #### Path Parameters - **topic** (Buffer) - Required - The topic to join. #### Query Parameters - **server** (boolean) - Optional - Announce availability for this topic. - **client** (boolean) - Optional - Discover other peers for this topic. - **limit** (number) - Optional - Maximum number of peers to connect to for this topic. ### Returns - **PeerDiscovery** - An object representing the discovery process for the topic. ### Request Example ```javascript const topic = Buffer.alloc(32).fill('my-service') const discovery = swarm.join(topic, { server: true, client: true, limit: Infinity }) await discovery.flushed() // Wait for initial DHT operations ``` ``` -------------------------------- ### swarm.join(topic, opts) Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Starts discovering and connecting to peers for a given topic. It returns a PeerDiscovery session object for controlling topic-specific discovery and connections. ```APIDOC ## swarm.join(topic, opts) ### Description Start discovering and connecting to peers sharing a topic. Returns immediately with a PeerDiscovery session object for topic-specific control. ### Method `join` ### Parameters #### Path Parameters - **topic** (Buffer) - Required - 32-byte buffer identifying the topic #### Query Parameters - **opts** (object) - Optional - Join options - **server** (boolean) - Optional - Announce and accept server connections for this topic (default: `true`) - **client** (boolean) - Optional - Query and connect as client to this topic (default: `true`) - **limit** (number) - Optional - Maximum peers to connect to for this topic (default: `Infinity`) ### Returns `PeerDiscovery` instance for topic-specific control ### Throws - Error: Topic is not a 32-byte Buffer, or swarm is destroyed ### Example ```js const topic = Buffer.alloc(32).fill('chat-room-1') const discovery = swarm.join(topic, { server: true, // Accept incoming connections client: true, // Connect to servers limit: 10 // Connect to max 10 peers }) await discovery.flushed() // Wait for initial DHT announce/lookup ``` ``` -------------------------------- ### Configure Custom Backoff Intervals Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Set custom retry intervals for peer connections. This example uses shorter intervals than the default. ```javascript const swarm = new Hyperswarm({ backoffs: [500, 2000, 5000, 300000] // Shorter intervals }) ``` -------------------------------- ### Check Server Mode - PeerDiscovery Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Determine if a PeerDiscovery instance is configured to announce itself as a server. This example explicitly sets server mode to true and client mode to false. ```javascript const discovery = swarm.join(topic, { server: true, client: false }) console.log('Server mode:', discovery.isServer) // true console.log('Client mode:', discovery.isClient) // false ``` -------------------------------- ### Check Client Mode - PeerDiscovery Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Determine if a PeerDiscovery instance is configured to actively look for peers. This example explicitly sets client mode to true and server mode to false. ```javascript const discovery = swarm.join(topic, { server: false, client: true }) console.log('Client mode:', discovery.isClient) // true console.log('Server mode:', discovery.isServer) // false ``` -------------------------------- ### swarm.listen() Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Explicitly starts listening for incoming peer connections. This is typically called automatically after the first `join()` operation, so manual invocation is usually unnecessary. ```APIDOC ## swarm.listen() ### Description Explicitly start listening for incoming peer connections. Called automatically after the first `join()`, so usually does not need to be called manually. ### Method `listen` ### Returns `Promise` ### Throws - Error: Swarm has been destroyed ### Example ```js // Ensure server is listening before any other operations await swarm.listen() console.log('Server listening for connections') ``` ``` -------------------------------- ### Hyperswarm Echo Server Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md An example of an echo server using Hyperswarm that pipes received data back to the sender. ```javascript const Hyperswarm = require('hyperswarm') const swarm = new Hyperswarm() const topic = Buffer.alloc(32).fill('echo') swarm.on('connection', (socket) => { // Echo back everything received socket.pipe(socket) }) swarm.join(topic, { server: true, client: false }) console.log('Echo server running on topic:', topic.toString('hex')) ``` -------------------------------- ### Hyperswarm Echo Client Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md A client example for an echo server using Hyperswarm, piping standard input to the server and server output to standard output. ```javascript const Hyperswarm = require('hyperswarm') const { stdin, stdout } = process const swarm = new Hyperswarm() const topic = Buffer.alloc(32).fill('echo') swarm.on('connection', (socket) => { // Once connected, pipe stdin to server and server output to stdout stdin.pipe(socket) socket.pipe(stdout) }) swarm.join(topic, { server: false, client: true }) console.log('Connecting to echo server...') ``` -------------------------------- ### Handle New Peer Connections Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Listen for the 'connection' event to get notified when a new peer connects. The event provides a duplex stream for communication and peer metadata. ```javascript swarm.on('connection', (socket, peerInfo) => { // socket: Noise-encrypted duplex stream // peerInfo: PeerInfo instance with peer metadata console.log('Connected to:', peerInfo.publicKey.toString('hex')) console.log('Topics:', peerInfo.topics.map(t => t.toString('hex'))) console.log('Server connection:', peerInfo.server) }) ``` -------------------------------- ### Listen for Connections with Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Call `swarm.listen()` to explicitly start listening for incoming peer connections. This is often called automatically after the first `join()`, but can be invoked manually to ensure the server is ready. ```javascript // Ensure server is listening before any other operations await swarm.listen() console.log('Server listening for connections') ``` -------------------------------- ### Basic Hyperswarm Usage Source: https://github.com/holepunchto/hyperswarm/blob/main/README.md Initialize Hyperswarm, handle incoming connections, and join a topic. Ensure the discovery key is a 32-byte Buffer. ```javascript const Hyperswarm = require('hyperswarm') const swarm = new Hyperswarm() swarm1.on('connection', (conn) => { // swarm1 will receive server connections 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 swarm2.join(discoveryKey, { server: true, client: true }) ``` -------------------------------- ### Get Connection Attempt Count Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-info.md Retrieve the number of connection attempts made to this peer. ```javascript console.log(`Connection attempts: ${peerInfo.attempts}`) ``` -------------------------------- ### PeerInfo Properties Source: https://github.com/holepunchto/hyperswarm/blob/main/README.md Access properties of a PeerInfo object to get details about a connected peer. ```APIDOC ## PeerInfo Properties ### Description Access properties of a `PeerInfo` object to retrieve information about a connected peer. ### Properties - **publicKey** (Buffer): The peer's Noise public key. - **topics** (Array): An array of topics the peer is associated with. This is only updated when the peer is in client mode. - **prioritized** (boolean): If true, the swarm will attempt to reconnect to this peer rapidly. ``` -------------------------------- ### Get Parent Swarm - PeerDiscovery Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Retrieve a reference to the parent Hyperswarm instance from a PeerDiscovery object. ```javascript const discovery = swarm.join(topic) const parentSwarm = discovery.swarm ``` -------------------------------- ### Get Discovered Topic - PeerDiscovery Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Access the topic being discovered by the PeerDiscovery instance. This is a 32-byte Buffer. ```javascript const discovery = swarm.join(topic) console.log('Discovering topic:', discovery.topic.toString('hex')) ``` -------------------------------- ### Get Session Topic Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Retrieve the topic Buffer associated with a peer discovery session. Useful for logging or debugging. ```javascript const session = swarm.join(topic) console.log('Session topic:', session.topic.toString('hex')) ``` -------------------------------- ### Create and Configure Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/INDEX.md Initialize a new Hyperswarm instance with custom configuration options like seed, maximum peers, and firewall settings. ```javascript const swarm = new Hyperswarm({ seed: Buffer.alloc(32), maxPeers: 64, firewall: (key) => false }) ``` -------------------------------- ### Get Last Connected Timestamp Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-info.md Access the timestamp of the last successful connection. Returns -1 if never connected. ```javascript if (peerInfo.connectedTime > -1) { const connectedAt = new Date(peerInfo.connectedTime) console.log('Last connected at:', connectedAt.toISOString()) } ``` -------------------------------- ### Create and Configure Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/INDEX.md Initializes a new Hyperswarm instance with optional configuration like seed, maxPeers, and firewall settings. ```APIDOC ## Create and Configure ```js const swarm = new Hyperswarm({ seed: Buffer.alloc(32), maxPeers: 64, firewall: (key) => false }) ``` See: [configuration.md](configuration.md) ``` -------------------------------- ### Initialize Hyperswarm with Custom DHT Instance Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/architecture.md Use a custom DHT instance for Hyperswarm to configure bootstrap nodes, ports, or share a DHT across multiple swarms. ```javascript const dht = new DHT({ /* custom config */ }) const swarm = new Hyperswarm({ dht }) ``` -------------------------------- ### Key Methods Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/README.md Overview of the essential methods available on the Hyperswarm instance for managing network activity. ```APIDOC ## Key Methods ### Description This section details the primary methods available on the Hyperswarm instance for controlling and interacting with the network. | Method | Parameters | Returns | Purpose | |---|---|---|---| | `join()` | topic, opts | PeerDiscovery | Start discovering/announcing topic | | `leave()` | topic | Promise | Stop discovering topic | | `joinPeer()` | publicKey | void | Connect to specific peer | | `leavePeer()` | publicKey | void | Stop connecting to peer | | `flush()` | — | Promise | Wait for pending connections | | `listen()` | — | Promise | Start accepting connections | | `destroy()` | opts | Promise | Clean shutdown | | `suspend()` | opts | Promise | Pause all networking | | `resume()` | opts | Promise | Resume suspended swarm | ``` -------------------------------- ### Configure DHT Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/README.md Set up Distributed Hash Table (DHT) configuration, including a custom DHT instance, bootstrap nodes, UDP port, and relay server settings. ```javascript { dht: DHT, bootstrap: [], port: 0, relayThrough: config } ``` -------------------------------- ### Get Peer Public Key Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-info.md Access the peer's public key as a Buffer. Convert it to hex for display or identification. ```javascript swarm.on('connection', (socket, peerInfo) => { const hexKey = peerInfo.publicKey.toString('hex') console.log('Connected to peer:', hexKey) }) ``` -------------------------------- ### Configure DHT Bootstrap Nodes Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Specify an array of bootstrap nodes for DHT initialization when a custom DHT instance is not provided. ```javascript const swarm = new Hyperswarm({ bootstrap: [ { host: '203.0.113.1', port: 49737 }, { host: '203.0.113.2', port: 49737 } ] }) ``` -------------------------------- ### Join and Discover Topic Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/INDEX.md Join a specific topic for peer discovery, configuring server and client roles, and setting peer limits. Await the flushed state before proceeding. ```javascript const discovery = swarm.join(topic, { server: true, client: true, limit: Infinity }) await discovery.flushed() ``` -------------------------------- ### Configure Jitter for Retries Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Reduce simultaneous retries by adding random jitter to backoff intervals. This example sets a ±200ms randomness. ```javascript const swarm = new Hyperswarm({ jitter: 200 // ±200ms randomness }) ``` -------------------------------- ### Configure Hyperswarm with Environment Variables Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Instantiate a Hyperswarm client, setting options like seed, max peers, port, and bootstrap nodes based on environment variables. If an environment variable is not set, a default value is used. ```javascript const swarm = new Hyperswarm({ seed: Buffer.from(process.env.PEER_SEED || 'default-seed', 'utf8'), maxPeers: parseInt(process.env.MAX_PEERS || '64'), port: parseInt(process.env.DHT_PORT || '0'), // 0 = auto-select bootstrap: JSON.parse(process.env.DHT_BOOTSTRAP || '[]') }) ``` -------------------------------- ### Get Topic Status with Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Use `swarm.status` to retrieve the `PeerDiscovery` session for a given topic. Returns `null` if the topic is not currently joined. ```javascript const topic = Buffer.alloc(32).fill('chat-room') const discovery = swarm.status(topic) if (discovery) { console.log(`Topic is active as ${discovery.isServer ? 'server' : 'client'}`) } ``` -------------------------------- ### Get Parent Swarm Instance Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Access the parent Hyperswarm instance from a PeerDiscoverySession. This can be useful for managing multiple sessions or interacting with the main swarm. ```javascript const session = swarm.join(topic) const parentSwarm = session.swarm ``` -------------------------------- ### new Hyperswarm(opts = {}) Source: https://github.com/holepunchto/hyperswarm/blob/main/README.md Constructs a new Hyperswarm instance. Options can configure key pairs, seeding, maximum peers, firewall rules, and DHT instances. ```APIDOC ## new Hyperswarm(opts = {}) ### Description Construct a new Hyperswarm instance. `opts` can include: - `keyPair`: A Noise keypair that will be used to listen/connect on the DHT. Defaults to a new key pair. - `seed`: A unique, 32-byte, random seed that can be used to deterministically generate the key pair. - `maxPeers`: The maximum number of peer connections to allow. - `firewall`: A sync function of the form `remotePublicKey => (true|false)`. If true, the connection will be rejected. Defaults to allowing all connections. - `dht`: A DHT instance. Defaults to a new instance. ``` -------------------------------- ### Troubleshoot Peer Connection Issues Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md Ensure peers are joined to the same topic and check firewall settings. Monitor connection attempts and use `swarm.flush()` to wait for discovery. ```javascript // Ensure you're joined the same topic const topic = Buffer.alloc(32).fill('my-topic') swarm.join(topic) // Both peers must use same topic // Check firewall isn't blocking swarm.on('ban', (peer, err) => { console.log('Peer rejected:', err.message) }) // Monitor connection attempts swarm.on('update', () => { console.log(`Connecting: ${swarm.connecting}`) console.log(`Connected: ${swarm.connections.size}`) }) // Use flush to wait for discovery await swarm.flush() ``` -------------------------------- ### JoinOptions Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/types.md Options for configuring how a swarm joins a topic. These settings control whether the node acts as a server, a client, or limits the number of peers. ```APIDOC ## Join Options ### Description Options for `swarm.join(topic, opts)`. ### Parameters #### Query Parameters - **server** (boolean) - Optional - Announce and accept connections. Defaults to `true`. - **client** (boolean) - Optional - Query and connect to peers. Defaults to `true`. - **limit** (number) - Optional - Max peers to discover for this topic. Defaults to `Infinity`. ``` -------------------------------- ### Get Connection by Public Key Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/connection-set.md Retrieve the active connection object associated with a given peer public key. Returns undefined if no connection exists for that key. ```javascript const conn = connectionSet.get(peerPublicKey) if (conn) { conn.write('message') } ``` -------------------------------- ### PeerDiscovery Lifecycle Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/architecture.md Illustrates the lifecycle of a PeerDiscovery instance, including initialization, periodic refreshes, and destruction. Refreshes involve DHT announcements or lookups, followed by processing discovered peers and scheduling the next refresh. ```javascript new PeerDiscovery() ↓ _refresh() called ├─ If server: await dht.announce(topic, keyPair) ├─ If client: await dht.lookup(topic) ├─ Process discovered peers: emit to swarm ↓ _refreshLater() schedules next refresh (~10 minutes) ↓ [repeat] ↓ destroy() ├─ If was server: call dht.unannounce() ├─ Cancel pending lookups └─ Stop refresh timer ``` -------------------------------- ### Configure Firewall for Peer Rejection Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/errors.md Sets up a firewall function in the Hyperswarm constructor to block specific peers based on a blocklist. ```javascript const swarm = new Hyperswarm({ firewall: (key) => { const isBlocked = blocklist.has(key.toString('hex')) return isBlocked // true = reject } }) swarm.on('ban', (peerInfo, err) => { if (err.message === 'Peer is firewalled') { console.log('Peer was rejected by firewall') } }) ``` ```javascript swarm.on('ban', (peerInfo, err) => { if (err.message === 'Peer is firewalled') { console.log(`Blocked: ${peerInfo.publicKey.toString('hex')}`) // Could log for audit, update stats, etc. } }) ``` -------------------------------- ### swarm.joinPeer(noisePublicKey) Source: https://github.com/holepunchto/hyperswarm/blob/main/README.md Establishes a direct connection to a known peer identified by their Noise public key. Connections will be reestablished if they fail. ```APIDOC ## swarm.joinPeer(noisePublicKey) ### Description Establish a direct connection to a known peer. `noisePublicKey` must be a 32-byte Buffer As with the standard `join` method, `joinPeer` will ensure that peer connections are reestablished in the event of failures. ``` -------------------------------- ### Swarm Statistics Object Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md An example of the swarm's statistics object, which tracks various operational metrics like connection attempts, opened/closed connections, and banned peers. ```javascript { updates: 0, // Total 'update' events emitted connects: { client: { opened: 0, // Client connections successfully established closed: 0, // Client connections closed attempted: 0 // Client connection attempts }, server: { opened: 0, // Server connections successfully established closed: 0 // Server connections closed } }, bannedPeers: 0 // Total peers that have been banned } ``` -------------------------------- ### Outbound Connection Flow (Client-Initiated) Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/architecture.md Illustrates the sequence of events when a client initiates a connection to a peer in Hyperswarm. This includes discovery, connection attempts, and handling connection events. ```text swarm.join(topic, { client: true }) ↓ PeerDiscovery._refresh() ↓ dht.lookup(topic) ↓ [for each peer discovered] ↓ swarm._handlePeer(peer, topic) ↓ peerInfo._updatePriority() ↓ _enqueue(peerInfo) ↓ _attemptClientConnections() ↓ [while queue has peers && slots available] ↓ _connect(peerInfo) ├─ Check: not banned, not duplicate, passes firewall ├─ dht.connect(remotePublicKey, opts) ├─ Noise handshake ├─ connection.on('open') → emit 'connection' event ├─ connection.on('close') → handle disconnect │ └─ peerInfo.attempts++ │ └─ timer.add(peerInfo) → schedule retry └─ connecting-- ``` -------------------------------- ### Hyperswarm ConnectionSet Usage Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/architecture.md Demonstrates the usage of the ConnectionSet in Hyperswarm for efficient tracking of connections. It shows how to check for existing connections, add new ones, and remove closed connections. ```javascript // Check if already connected const existing = this._allConnections.get(conn.remotePublicKey) // Add new connection this._allConnections.add(conn) // Remove closed connection this._allConnections.delete(conn) ``` -------------------------------- ### Inbound Connection Flow (Server-Accepted) Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/architecture.md Details the process when Hyperswarm accepts an incoming connection initiated by another peer. This covers server setup, connection handling, and event management. ```text swarm.join(topic, { server: true }) ↓ swarm.listen() ↓ dht.createServer() starts listening ↓ [when peer connects] ↓ _handleServerConnection(conn) ├─ Check for duplicates ├─ Check firewall ├─ Create or update PeerInfo ├─ Add to _allConnections ├─ Emit 'connection' event └─ Handle on('close') ├─ Remove from connections ├─ Check if should ban └─ Attempt reconnect if needed ``` -------------------------------- ### Hyperswarm Constructor Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Initializes a new Hyperswarm instance. You can configure various network and connection parameters through the options object. ```APIDOC ## new Hyperswarm(opts = {}) ### Description Creates a new Hyperswarm instance with optional configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (object) - Optional - Configuration options object - **opts.seed** (Buffer) - Optional - 32-byte buffer for deterministic keypair generation - **opts.keyPair** (object) - Optional - Noise keypair `{ publicKey, secretKey }` for peer identity - **opts.maxPeers** (number) - Optional - Maximum number of concurrent peer connections (Default: `64`) - **opts.maxClientConnections** (number) - Optional - Maximum outbound client connections (Default: `Infinity`) - **opts.maxServerConnections** (number) - Optional - Maximum inbound server connections (Default: `Infinity`) - **opts.maxParallel** (number) - Optional - Maximum parallel connection attempts in progress (Default: `3`) - **opts.firewall** (function) - Optional - Sync function `(remotePublicKey) => boolean` to reject connections (Default: none) - **opts.dht** (object) - Optional - Hyperdht instance for lower-level control (Default: new) - **opts.bootstrap** (array) - Optional - Bootstrap nodes for DHT initialization - **opts.nodes** (array) - Optional - DHT nodes configuration - **opts.port** (number) - Optional - UDP port for DHT - **opts.deferRandomPunch** (boolean) - Optional - Defer random holepunch attempts - **opts.randomPunchInterval** (number) - Optional - Interval for random holepunch attempts (ms) - **opts.handshakeClearWait** (number) - Optional - DHT server handshake clear wait time (ms) - **opts.backoffs** (array) - Optional - Retry backoff intervals for failed connections (Default: `[1s, 5s, 15s, 10m]`) - **opts.jitter** (number) - Optional - Jitter added to backoff intervals (ms) (Default: `500`) - **opts.relayThrough** (function|object) - Optional - Configuration for connection relay through DHT relay nodes ### Request Example ```javascript const swarm = new Hyperswarm({ seed: Buffer.alloc(32).fill('my-app'), maxPeers: 100, firewall: (key) => { return bannedPeers.has(key.toString('hex')) } }) ``` ### Response #### Success Response (200) Hyperswarm instance #### Response Example ```javascript // Hyperswarm instance is returned ``` ### Throws - **Error**: If created with an invalid seed or keypair ``` -------------------------------- ### Configure Security Firewall Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/README.md Implement a firewall function to accept or reject peers based on their public key. This function should return a boolean. ```javascript { firewall: (remotePublicKey) => boolean } ``` -------------------------------- ### Configure Additional DHT Nodes Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Provide additional DHT node configuration options, which are passed to the DHT if a custom instance is not supplied. ```javascript const swarm = new Hyperswarm({ nodes: [...] // Array of node configurations }) ``` -------------------------------- ### Provide Custom DHT Instance Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Instantiate and provide a custom hyperdht instance for advanced control over network behavior, including port and bootstrap nodes. ```javascript const DHT = require('hyperdht') const dht = new DHT({ port: 30000, bootstrap: [...] // Array of bootstrap nodes }) const swarm = new Hyperswarm({ dht }) ``` -------------------------------- ### Implement Custom Firewall Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/configuration.md Configure a synchronous firewall function to accept or reject incoming peer connections based on their public key. This is useful for implementing allowlists or blocklists. ```javascript const bannedPeers = new Set([ 'peer1hex', 'peer2hex' ]) const swarm = new Hyperswarm({ firewall: (remotePublicKey) => { const hexKey = remotePublicKey.toString('hex') return bannedPeers.has(hexKey) // true = reject } }) ``` -------------------------------- ### JoinOptions Interface Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/types.md Defines options for joining a topic. Use `server` to announce and accept connections, `client` to query and connect to peers, and `limit` to set the maximum number of peers to discover for a topic. ```typescript interface JoinOptions { server?: boolean client?: boolean limit?: number } ``` -------------------------------- ### Suspend and Resume Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md Demonstrates how to suspend and resume a Hyperswarm instance, useful for handling application pauses or system sleep events. Includes optional logging for suspend/resume operations. ```javascript const swarm = new Hyperswarm() // On app pause/background app.on('pause', async () => { console.log('App pausing, suspending swarm...') await swarm.suspend({ log: (msg) => console.log('[suspend]', msg) }) }) // On app resume/foreground app.on('resume', async () => { console.log('App resuming, resuming swarm...') await swarm.resume({ log: (msg) => console.log('[resume]', msg) }) }) ``` -------------------------------- ### Handle New Connections in Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-info.md Listen for new connections and log peer information. This is the fundamental event for interacting with connected peers. ```javascript const swarm = new Hyperswarm() swarm.on('connection', (socket, peerInfo) => { console.log('Connected to:', peerInfo.publicKey.toString('hex')) console.log('Type:', peerInfo.client ? 'client' : 'server') socket.on('data', (data) => { console.log('Received:', data.toString()) }) socket.on('error', (err) => { console.error('Connection error:', err) }) }) ``` -------------------------------- ### Multiple Sessions on One Topic Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md Demonstrates how to manage multiple independent sessions (server-only, client-only) for the same topic within a single Hyperswarm instance. Connections are multiplexed. ```javascript const topic = Buffer.alloc(32).fill('shared-topic') // First session: server-only const serverSession = swarm.join(topic, { server: true, client: false }) // Second session: client-only const clientSession = swarm.join(topic, { server: false, client: true }) // Both sessions are active on the same swarm // Connections are multiplexed over single peer-to-peer connection ``` -------------------------------- ### Create DHT Server Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Create a low-level DHT server using the swarm's underlying DHT instance. This is for advanced use cases requiring direct DHT access. ```javascript const dhtServer = swarm.dht.createServer((conn) => { // Lower-level DHT connection handling }) ``` -------------------------------- ### Join Topics in Different Hyperswarm Modes Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md When joining a topic, specify server, client, or both modes. Server mode accepts connections, client mode initiates connections, and both modes allow for bidirectional participation. Choose the mode that fits your application's role. ```javascript const topic = Buffer.alloc(32).fill('my-app') // As a service (only accept connections) swarm.join(topic, { server: true, client: false }) // As a client (only connect to services) swarm.join(topic, { server: false, client: true }) // As a peer (both) swarm.join(topic, { server: true, client: true }) ``` -------------------------------- ### Join Topic in Server and Client Mode Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Join a topic with both server and client modes enabled, setting a connection limit. Listens for incoming connections and logs connected peer public keys. ```javascript const swarm = new Hyperswarm() const topic = Buffer.alloc(32).fill('my-topic') const discovery = swarm.join(topic, { server: true, // Accept connections client: true, // Connect to peers limit: 20 // Max 20 connections }) swarm.on('connection', (socket, peerInfo) => { console.log('Connected to:', peerInfo.publicKey.toString('hex')) socket.on('data', (data) => { console.log('Received:', data.toString()) }) }) await discovery.flushed() console.log('Topic is discoverable') ``` -------------------------------- ### Handle Peer Connections Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/INDEX.md Set up an event listener for new connections to the swarm. Inside the handler, you can process incoming data and send data back to the peer. ```javascript swarm.on('connection', (socket, peerInfo) => { socket.on('data', (data) => { ... }) socket.write(data) }) ``` -------------------------------- ### Hyperswarm Connection and State Logging Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/errors.md Set up event listeners to track connection lifecycle, peer bans, swarm state updates, and discovery information. This helps in debugging and understanding network behavior. ```javascript const swarm = new Hyperswarm() // Track connection lifecycle swarm.on('connection', (socket, peerInfo) => { const id = peerInfo.publicKey.toString('hex').slice(0, 8) console.log(`[${id}] Connected (${peerInfo.client ? 'client' : 'server'})`) socket.on('close', () => { console.log(`[${id}] Disconnected`) }) }) // Track peer lifecycle swarm.on('ban', (peerInfo, err) => { const id = peerInfo.publicKey.toString('hex').slice(0, 8) console.log(`[${id}] Banned: ${err.message}`) }) // Track state changes swarm.on('update', () => { console.log(`Swarm state: connecting=${swarm.connecting}, connected=${swarm.connections.size}`) }) // Track discovery for (const discovery of swarm.topics()) { console.log(`Topic: ${discovery.topic.toString('hex').slice(0, 16)}... Server: ${discovery.isServer} Client: ${discovery.isClient}`) } ``` -------------------------------- ### Define and Compare Topics in Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/getting-started.md Topics are 32-byte Buffers used to identify groups of peers. Use Buffer.alloc(32).fill() for simple topics or derive from a stable hash for more complex applications. Ensure topics are consistent for peers to find each other. ```javascript const topic1 = Buffer.alloc(32).fill('my-app') const topic2 = Buffer.alloc(32).fill('my-app') console.log(topic1.equals(topic2)) // true // Different topics: const topic3 = Buffer.alloc(32).fill('another-app') console.log(topic1.equals(topic3)) // false ``` -------------------------------- ### Switch Topic Discovery Modes Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Dynamically switch the discovery mode of an active session from server-only to mixed server and client mode, and then to client-only. ```javascript const discovery = swarm.join(topic, { server: true, client: false }) // Start as server-only, later add client mode await discovery.refresh({ server: true, client: true }) // Then switch to client-only await discovery.refresh({ server: false, client: true }) ``` -------------------------------- ### Basic Peer Discovery Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/index.md Connect to peers interested in a common topic. This snippet demonstrates joining a topic in both server and client modes, handling incoming/outgoing connections, and waiting for discovery to complete. ```javascript const Hyperswarm = require('hyperswarm') const swarm = new Hyperswarm() swarm.on('connection', (socket, peerInfo) => { // Handle incoming or outgoing connections console.log('Connected to peer:', peerInfo.publicKey.toString('hex')) socket.pipe(process.stdout) process.stdin.pipe(socket) }) const topic = Buffer.alloc(32).fill('my-topic-name') swarm.join(topic, { server: true, client: true }) await swarm.flush() // Wait for discovery to complete ``` -------------------------------- ### Creating a Swarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/README.md Instantiate a new Hyperswarm object with optional configuration for seeding, maximum peers, and firewall rules. ```APIDOC ## Creating a Swarm ### Description Instantiate a new Hyperswarm object with optional configuration for seeding, maximum peers, and firewall rules. ### Method `new Hyperswarm(options)` ### Parameters #### Options - **seed** (Buffer) - Optional - A buffer used for seeding the swarm. - **maxPeers** (number) - Optional - The maximum number of peers to connect to. - **firewall** (function) - Optional - A function to determine if a peer should be allowed. ### Request Example ```javascript const Hyperswarm = require('hyperswarm') const swarm = new Hyperswarm({ seed: Buffer.alloc(32).fill('my-app'), maxPeers: 64, firewall: (key) => false }) ``` ``` -------------------------------- ### Connection Filtering with Firewall Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/index.md Implement a custom firewall to accept or reject incoming connections based on peer public keys. This allows for fine-grained control over network access. ```javascript const swarm = new Hyperswarm({ firewall: (remotePublicKey) => { // Return true to reject, false to accept const isBlocked = blockedPeers.has(remotePublicKey.toString('hex')) return isBlocked } }) ``` -------------------------------- ### discovery.isServer Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-discovery.md Boolean indicating whether this discovery is announcing as a server. ```APIDOC ## discovery.isServer ### Description Boolean indicating whether this discovery is announcing as a server. ### Type `boolean` ### Example ```js const discovery = swarm.join(topic, { server: true, client: false }) console.log('Server mode:', discovery.isServer) // true console.log('Client mode:', discovery.isClient) // false ``` ``` -------------------------------- ### Handle New Topic Announcement Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/peer-info.md Listen for new topic announcements from a peer. This event is emitted in client mode discoveries. ```javascript swarm.on('connection', (socket, peerInfo) => { peerInfo.on('topic', (topic) => { console.log('Peer announced new topic:', topic.toString('hex')) }) }) ``` -------------------------------- ### Join a Specific Peer with Hyperswarm Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/api-reference/hyperswarm.md Use `swarm.joinPeer` to establish a direct connection to a peer identified by their public key. The connection is established asynchronously and will emit a 'connection' event. ```javascript const peerKey = Buffer.from('...', 'hex') // 32-byte key swarm.joinPeer(peerKey) swarm.on('connection', (socket, peerInfo) => { if (peerInfo.publicKey.equals(peerKey)) { console.log('Connected to target peer') } }) ``` -------------------------------- ### Trace Hyperswarm Connection Events Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/architecture.md Listen for 'connection', 'update', and 'ban' events to log peer information and swarm state changes. Requires the swarm object to be initialized. ```javascript swarm.on('connection', (socket, peerInfo) => { console.log('Connection:', peerInfo.publicKey.toString('hex').slice(0, 8)) }) swarm.on('update', () => { console.log('State update:', { connecting: swarm.connecting, connected: swarm.connections.size }) }) swarm.on('ban', (peerInfo, err) => { console.log('Ban:', peerInfo.publicKey.toString('hex').slice(0, 8), err.message) }) ``` -------------------------------- ### Duplicate Connection Handling Logic Source: https://github.com/holepunchto/hyperswarm/blob/main/_autodocs/architecture.md Explains how Hyperswarm manages scenarios where both peers attempt to establish a connection simultaneously. It prioritizes which connection to keep based on established criteria. ```text Peer A → Peer B (connection 1) Peer B → Peer A (connection 2) _handleServerConnection(connection 2) ├─ existing = _allConnections.get(remotePublicKey) ├─ If existing is established (rawBytesRead > 0 && rawBytesWritten > 0) │ └─ Keep connection 2 (newer) ├─ Else if both are initiating │ └─ Keep the one that's "supposed to" (based on key comparison) └─ Else └─ Keep connection 1 (existing) ```