import type { Metadata } from 'next'; import CodeBlock from '@/components/ui/CodeBlock'; import P2NSFlowDiagram from '@/components/diagrams/P2NSFlowDiagram'; export const metadata: Metadata = { title: 'How It Works - P2NS Documentation', description: 'Complete explanation of how P2NS works from domain registration to accessing services. Understand the P2NS workflow and processes.', keywords: ['P2NS how it works', 'workflow', 'process', 'domain registration', 'P2NS explanation'], authors: [{ name: 'Raven Scott' }], openGraph: { title: 'How It Works - P2NS Documentation', description: 'Complete explanation of how P2NS works from domain registration to accessing services', url: 'https://p2ns.space/docs/how-it-works', siteName: 'P2NS', type: 'website', }, twitter: { card: 'summary_large_image', title: 'How It Works - P2NS Documentation', description: 'Complete explanation of how P2NS works from domain registration to accessing services', }, alternates: { canonical: 'https://p2ns.space/docs/how-it-works', }, }; export default function HowItWorksPage() { return (

How It Works

Understanding the complete P2NS workflow from start to finish

Introduction

P2NS (Peer-to-Peer Name System) is a decentralized DNS system that allows you to access services and websites without relying on traditional DNS servers or centralized infrastructure. Instead, it uses a peer-to-peer network where nodes work together to resolve domain names and establish direct connections.

Unlike traditional DNS where a central authority controls domain names, P2NS uses a distributed ledger where anyone can claim a domain and peers vote to reach consensus on which service should be associated with each domain. This makes it resistant to censorship and single points of failure.

The system uses UDP hole-punching (via HyperDHT) to connect through firewalls and NAT, making it possible to reach services behind restrictive networks. Two P2P layers work together: Hyperswarm on the P2NS topic syncs DNS claims and votes; Holesail uses separate hashes on the DHT for each published service tunnel. Let's walk through exactly how this works, step by step.

The Big Picture

Here's a high-level view of what happens when you access a P2NS domain:

The key components are: peers (Hyperswarm + Corestore/Autopass for DNS state), protomux-rpc (core invites and plugin traffic), Holesail (per-service tunnels), virtual interfaces (local IPs per domain), and HTTPS/HTTP proxies (TLS and routing). Built-in sites such as{' '} p2ns.admin and plugin domains under{' '} plugin-sites/ are resolved without a P2P claim.

Step-by-Step Process

Part 1: Setting Up a Domain (Service Provider Side)

Before anyone can access a service through P2NS, the service provider needs to register their domain. Here's how it works:

1. Generate a Holesail Hash

The service provider first needs to create a Holesail connection hash. They run:

Use --public so the service is announced on HyperDHT for remote peers. This generates a hash like hs://s00084bf87dfa89a3048fb081c0e6207eb5a. That hash is independent of the P2NS swarm topic—peers use it only when connecting to your service tunnel.

2. Create a Domain Claim

Next, they register their domain (e.g., example.tld) by creating a claim in the P2P network. This claim says "I own example.tld and it should point to this Holesail hash." Claims live in the shared Autopass store (dnsPass) on top of Corestore—an append-only, signed log replicated across writers.

You can add domains via the admin UI (https://p2ns.admin),{' '} cache/domains.json (genesis master by default), or the API. On a new network, exactly one node runs as{' '} genesis master (--master --genesis) to create the shared Autopass ledger and{' '} cache/network.json. Everyone else joins with node p2ns.js (joiner) or an optional secondary master (--master without --genesis) after receiving an invite.

The claim is stored with a key like claim:example.tld:claimant-id where claimant-id is a unique identifier for the person making the claim.

3. Peer Discovery and Sync

Once the claim is created, it's automatically synchronized to all connected peers in the network. Each peer maintains a copy of the distributed ledger, so the claim propagates throughout the network. This happens in real-time as peers connect and exchange data.

If multiple people claim the same domain, the network uses a voting and consensus mechanism to decide which claim is legitimate (we'll cover this in detail later).

Part 2: Peer Discovery and Network Formation

For P2NS to work, nodes need to find and connect to each other. This happens automatically using a technology called Hyperswarm.

1. Topic-Based Discovery

All P2NS nodes use the same "topic" to find each other. Think of it like a meeting room number - everyone who wants to participate in P2NS goes to the same room. The topic is a 32-byte buffer from sha256(TOPIC_SEED) (default p2ns-dns), which ensures all P2NS nodes discover each other regardless of where they are in the world.

2. Connection Establishment

When a node starts up, it joins Hyperswarm on this topic. Under the hood, HyperDHT announces and looks up peers, coordinates UDP hole punching, and falls back to encrypted relays when needed. Each connection completes a Noise XX handshake before any application data flows.

The connection process involves:

  • Noise XX handshake proves each peer holds the advertised key
  • Protomux multiplexes core RPC and plugin protocols on the same connection
  • Autopass replicates dnsPass to authorized writers (separate from the P2NS topic used only for discovery)

3. Joining as a Writer (Genesis, Masters, Joiners)

Only peers with Autopass writer access can append claims and votes. All nodes on a network share one Autopass ledger identified by networkId in cache/network.json:

  • Genesis master--master --genesis creates the ledger (once per network)
  • Secondary masters--master on empty storage waits for an invite (no implicit second ledger)
  • Joinersnode p2ns.js; no master flag required for everyday use

Admission uses protomux-rpc on the P2NS swarm connection:

  • invite.request — peer asks a master or writer for an invite
  • invite.deliver / invite.ack — invite wire is delivered and acknowledged
  • core.status — exposes networkId, invite capability, and split-network warnings

Masters may proactively send invites when new peers connect (MASTER_PROACTIVE_INVITE_DELAY). Quorum counts writers with initialized dnsPass, not raw swarm connections. See Architecture and Configuration.

4. Data Synchronization

Once a peer is a writer, new claims and votes append to dnsPass and replicate to other writers through Autopass. Corestore manages the underlying Hypercore logs. When a new claim or vote is added, authorized peers receive it automatically.

This means:

  • Every node has a complete copy of all domain claims and votes
  • New information propagates through the network automatically
  • The network is resilient - if some nodes go offline, others still have the data
  • No central server is needed - the network is truly decentralized

Part 3: DNS Resolution (When Someone Wants to Access)

Now let's see what happens when someone wants to access a P2NS domain. This is where the magic happens!

1. The DNS Query

When you type a domain like https://example.tld in your browser, or when an application makes a DNS query, it goes to the P2NS DNS server (port 53 by default, configurable). This server is configured as your system's DNS resolver, so queries flow through P2NS first.

2. Internal and Local Records

Before P2P lookup, the resolver checks:

  • Internal domains: p2ns.admin and any domain with a plugin under plugin-sites/{domain}/config.json (e.g. peer.directory, peer.paste)
  • Local DNS: entries in cache/local_dns.json override both P2P and public DNS

3. Checking the Cache

First, P2NS checks its local cache to see if it recently resolved this domain. If the cache entry is still valid (typically cached for 30 seconds), it returns the cached result immediately. This makes repeated queries very fast.

4. Querying the P2P Network

If not in cache, P2NS looks up the domain in the distributed ledger. It searches through all the claims stored locally (remember, each node has a complete copy) to find any claims for the requested domain.

The system looks for entries with keys like claim:example.tld:* to find all people who have claimed this domain.

5. Consensus Mechanism

If multiple people have claimed the same domain, P2NS uses a consensus algorithm to determine which one is correct:

  • Count votes: Each claim can have votes from other peers. The system counts how many votes each claimant has received.
  • Check quorum: Configurable via CONSENSUS_QUORUM_THRESHOLD (default 50% of active peers) and CONSENSUS_MIN_VOTES (default 2).
  • Resolve ties: If two claimants have the same number of votes, the system uses a tie-breaker (like preferring the oldest claim).
  • Return the hash: Once consensus is reached, the system returns the Holesail hash associated with the winning claim.

This ensures that everyone in the network agrees on which service should be associated with each domain name.

6. Fallback to Public DNS

If the domain is not internal, not in local DNS, and not resolved via P2P consensus, P2NS forwards to PUBLIC_DNS_SERVER (comma-separated list supported for failover). You can use P2P domains and the public internet through one resolver.

Part 4: Virtual Interface Setup

Once P2NS has the Holesail hash for a domain, it needs to set up local networking to route traffic to that domain. This is where virtual network interfaces come in.

1. Assigning a Local IP Address

P2NS assigns each domain a unique local IP address from a configured subnet (default: 192.168.3.x). For example, the first domain might get 192.168.3.2, the second gets 192.168.3.3, and so on.

You can configure multiple subnets with different IP ranges, and P2NS will automatically allocate IPs from available subnets. This gives you flexibility to organize domains across different network ranges.

2. Creating the Virtual Interface

P2NS creates a virtual network interface (like lo0 on macOS or lo on Linux) and adds the IP address as an alias. This makes the IP address available on your local machine, even though it's not connected to a physical network.

The virtual interface acts like a local network adapter, allowing your system to route traffic to that IP address. When your browser or application connects to the domain, it resolves to this local IP, and the traffic gets intercepted by P2NS for processing.

3. Why Virtual Interfaces?

Virtual interfaces are necessary because:

  • They allow P2NS to intercept traffic destined for P2P domains
  • They provide a consistent local endpoint for routing
  • They enable the HTTPS proxy to handle TLS connections properly
  • They allow multiple domains to coexist on the same machine without conflicts

Part 5: Holesail Connection Establishment

Now that we have a local IP address, P2NS needs to establish a connection to the actual service. This is where Holesail comes in - it's the technology that punches through firewalls and NAT to create direct connections.

1. What Holesail Does

Holesail uses UDP hole-punching to establish connections through firewalls and NAT (Network Address Translation). Traditional networking often fails when both the client and server are behind firewalls, but Holesail solves this by:

  • Using HyperDHT (the distributed hash table) to exchange endpoints and coordinate simultaneous UDP probes
  • Sending UDP packets from both sides simultaneously to "punch holes" in the firewall
  • Establishing a direct peer-to-peer connection once the hole is punched, with encrypted relay fallback when needed
  • Maintaining tunnels; optional FULL_PERSISTENCE keeps clients/servers alive across restarts (see Configuration)

Holesail server and client configs persist under cache/holesail_servers.json and{' '} cache/holesail_clients.json.

2. Using the Hash to Connect

The Holesail hash we got from the domain claim is a random cryptographic string that acts as a key to look up the service on the DHT. When P2NS needs to connect, it:

  • Uses the hash to query the DHT for the service information
  • Retrieves the metadata stored on the DHT (host, port, protocol configuration)
  • Uses this information along with the hash to establish the connection

P2NS creates a Holesail client that uses this hash to look up and connect to the service provider's Holesail server. The connection process happens automatically in the background.

3. Connection Persistence

Once established, the Holesail connection can be kept alive persistently. This means:

  • Subsequent requests to the same domain reuse the existing connection (faster)
  • The connection automatically reconnects if it drops
  • You can configure timeout behavior for non-persistent connections
  • Multiple domains can share connections when appropriate

Part 6: HTTPS Proxy and Routing

Now we have a Holesail tunnel established, but we still need to handle HTTPS properly and route requests correctly. This is where the proxy servers come in.

1. TLS Certificate Generation

P2NS automatically generates TLS certificates for each domain using its own Certificate Authority (CA). When you first access a P2NS domain, the system:

  • Generates a certificate for the domain if it doesn't exist
  • Signs it with the P2NS root CA
  • Includes the domain name and local IP in the certificate (Subject Alternative Names)
  • Stores the certificate for reuse

You need to trust the P2NS root CA in your browser/system to avoid security warnings. P2NS auto-installs on macOS and Windows; on Linux, Chrome requires both the system CA bundle and the NSS trust database (certutil / ~/.pki/nssdb) — see{' '} Troubleshooting.

2. HTTPS Proxy Server

P2NS runs an HTTPS proxy server on port 443. When your browser makes an HTTPS request to a P2NS domain:

  • The request goes to the P2NS HTTPS proxy
  • The proxy uses the domain's TLS certificate to establish a secure connection with your browser
  • The proxy then forwards the request through the Holesail tunnel to the actual service
  • Responses flow back through the tunnel and proxy to your browser

3. HTTP to HTTPS Redirect

P2NS also runs an HTTP server on port 80 that automatically redirects all HTTP requests to HTTPS. This ensures all connections are encrypted and secure.

4. WebSocket Support

The proxy also supports WebSocket connections, allowing real-time applications to work through P2NS. WebSocket upgrades are handled transparently, maintaining the connection through the Holesail tunnel.

Part 7: Complete Request Flow

Let's put it all together! Here's exactly what happens when you access a P2NS domain:

  1. You type https://example.tld in your browser
  2. DNS query: Your system queries the P2NS DNS server (port 53) for example.tld
  3. Cache check: P2NS checks its cache - if found and valid, returns cached result
  4. P2P lookup: If not cached, P2NS searches the distributed ledger for claims matching example.tld
  5. Consensus: If multiple claims exist, P2NS runs consensus algorithm to determine the correct hash
  6. Hash retrieved: P2NS gets the Holesail hash (e.g., hs://s00084bf87dfa89a...)
  7. Virtual interface: P2NS assigns/uses a local IP (e.g., 192.168.3.2) for this domain
  8. Holesail client: P2NS creates or reuses a Holesail client connection using the hash
  9. Tunnel established: The Holesail connection punches through firewalls and establishes a tunnel
  10. TLS proxy: P2NS sets up an HTTPS proxy using the domain's TLS certificate
  11. Browser connects: Your browser connects to the P2NS HTTPS proxy (port 443)
  12. Request forwarded: The proxy forwards your request through the Holesail tunnel to the actual service
  13. Response received: The service responds, and the response flows back through the tunnel
  14. You see the website: The response reaches your browser, and you see the content!

All of this happens automatically in milliseconds! The first request might take a bit longer as connections are established, but subsequent requests are much faster as connections are reused.

Consensus and Voting

One of the most important aspects of P2NS is how it handles conflicts when multiple people claim the same domain. The consensus mechanism ensures the network agrees on which service should be associated with each domain.

How Voting Works

When a peer sees a domain claim, they can vote for it by creating a vote entry in the ledger. The vote key looks like: vote:example.tld:claimant-id:voter-id

Peers typically vote for the claim they believe is legitimate. This could be based on:

  • Who they know and trust
  • Which claim was made first (timestamp)
  • Which service they want to use
  • Automatic voting based on local claims

Quorum Requirements

For a domain to be considered "resolved" (consensus reached), it must meet quorum requirements:

  • Percentage threshold: CONSENSUS_QUORUM_THRESHOLD (default 0.5 = 50% of active peers)
  • Minimum votes: CONSENSUS_MIN_VOTES (default 2), regardless of peer count
  • Vote validation: Votes must reference existing claims (invalid votes are ignored)

This ensures that consensus isn't reached by just one or two nodes, but represents actual network agreement.

Tie-Breaking Strategies

When multiple claimants have the same number of votes, P2NS uses tie-breaking strategies:

  • Timestamp: Prefer the oldest claim (CONSENSUS_TIE_BREAKER=timestamp, default)
  • Claimant age: Prefer the claimant with the longest history in the network
  • Lexicographic: Alphabetical ordering of claimant IDs

This deterministic approach ensures all nodes reach the same conclusion when resolving ties, maintaining network consistency.

Key Technologies Explained Simply

P2NS uses several advanced technologies. Here's what each one does in simple terms:

Hyperswarm & HyperDHT

What it does: Discovers other P2NS nodes on topic sha256(TOPIC_SEED), coordinates hole punching, and opens encrypted swarm connections.

Simple analogy: A distributed meeting room—everyone who joins the same topic can find each other without a central directory server.

Protomux / protomux-rpc

What it does: Multiplexes JSON-RPC methods on each peer connection—core invites, consensus helpers, and per-plugin protocols.

Simple analogy: Several phone lines over one secure call—core control traffic and plugin apps share the same tunnel without mixing messages.

Corestore & Autopass

What it does: Corestore holds Hypercore append-only logs; Autopass (dnsPass) stores claims and votes with invite-gated writers.

Simple analogy: A signed ledger everyone authorized can append to—entries are immutable and verifiable by Merkle proofs, not by trusting who sent them.

Holesail

What it does: Publishes and connects to service tunnels by hash on HyperDHT—separate from the P2NS DNS swarm topic.

Simple analogy: A dedicated address for your web server or game port; DNS consensus points a domain name at that address.

Real-World Example

Let's walk through a concrete example to see how everything fits together:

Scenario: Alice hosts a blog, Bob wants to read it

Step 1: Alice Sets Up Her Blog (Service Provider)

  • Alice runs a blog server on her home computer (port 80)
  • She generates a Holesail hash: hs://s00084bf87dfa89a3048fb081c0e6207eb5a
  • She claims the domain alice.blog with this hash
  • The claim is stored in the P2P network and synced to all peers

Step 2: Bob's Node Joins the Network

  • Bob starts his P2NS node
  • His node connects to Hyperswarm and discovers other peers
  • The distributed ledger syncs, and Bob's node now knows about alice.blog

Step 3: Bob Accesses the Blog

  • Bob types https://alice.blog in his browser
  • DNS query goes to P2NS DNS server
  • P2NS looks up alice.blog in the ledger
  • Finds Alice's claim and gets the Holesail hash
  • Assigns local IP 192.168.3.2 to alice.blog
  • Creates Holesail client connection using the hash
  • Holesail punches through firewalls and connects to Alice's server
  • HTTPS proxy routes the request through the tunnel
  • Alice's blog server responds with the blog content
  • Response flows back through the tunnel to Bob's browser
  • Bob sees Alice's blog!

Timeline: All of this happens in under a second for the first request. Subsequent requests are even faster because the Holesail connection is reused.

The magic: Even though Alice and Bob are both behind firewalls and NAT, they can communicate directly thanks to Holesail's UDP hole-punching. No central server needed, no port forwarding required!

Scenario: Service Subscriptions - Multiple Services, Automatic Management

Service subscriptions allow peers to automatically connect to services hosted by domain owners. This is especially useful when a domain owner hosts multiple services (like a web server, API, and game server) and wants others to easily access them.

Step 1: Alice Hosts Multiple Services

  • Alice owns the domain alice.services
  • She hosts three services:
    • Web Server: Port 80, TCP protocol, service name "web"
    • API Server: Port 8080, TCP protocol, service name "api"
    • Game Server: Port 25565, UDP protocol, service name "game"
  • Alice opens the P2NS admin panel and navigates to the "Host" tab
  • For each service, she creates a Holesail hash and uses the "Create Client" button to add it to her domain
  • When creating each client, she specifies the service name and protocol (TCP or UDP)
  • The system automatically updates the domain's claim record with a clients array containing all three services
  • This claim record is automatically synced to all peers in the network

Example claim record structure:

Step 2: Bob Discovers and Subscribes to Services

  • Bob opens the P2NS admin panel and navigates to the "Service Subscription" modal
  • He searches for alice.services and sees all three available services
  • Bob has two options:
    • Subscribe to individual services: He selects just the "web" and "api" services
    • Subscribe to all: He enables "Subscribe All" for alice.services
  • Bob chooses "Subscribe All" - this means he'll automatically get all current and future services from Alice
  • P2NS automatically creates Holesail clients for all three services:
    • alice.services_web (TCP client)
    • alice.services_api (TCP client)
    • alice.services_game (UDP client)
  • Each client establishes a Holesail connection to the corresponding service
  • Bob's subscription preferences are saved locally in cache/subscriptions.json

Step 3: Dynamic Synchronization - Alice Adds a New Service

  • Later, Alice adds a fourth service: "chat" server on port 9000 (TCP)
  • She uses the admin panel's "Create Client" button to add the new service to her domain
  • The system automatically updates her domain's claim record to include the new service
  • The updated claim record is automatically synced to all peers
  • Bob's P2NS node detects the change in the claim record (via AutoPass update events)
  • Since Bob has "Subscribe All" enabled for alice.services, P2NS automatically:
    • Creates a new Holesail client: alice.services_chat
    • Establishes the connection
    • Updates Bob's subscription list
  • Bob can now access the chat service without any manual configuration!

Step 4: Dynamic Synchronization - Alice Removes a Service

  • Alice decides to shut down her "game" server
  • She uses the admin panel to delete the Holesail client for the "game" service
  • The system automatically removes it from her domain's claim record
  • The updated claim record syncs to all peers
  • Bob's P2NS node detects the service was removed
  • P2NS automatically:
    • Stops and deletes the alice.services_game Holesail client
    • Frees up the UDP port that was being used
    • Removes the service from Bob's subscription list
  • Bob's system is automatically cleaned up - no manual intervention needed!

Step 5: Auto-Subscription on Bootup

  • When Bob restarts his P2NS node, the system loads his saved subscriptions from cache/subscriptions.json
  • For each subscribed service, P2NS automatically:
    • Creates the Holesail client
    • Establishes the connection
    • Makes the service available immediately
  • If "Subscribe All" is enabled for a domain, P2NS also checks the current claim record and subscribes to any new services that were added while Bob's node was offline
  • Bob doesn't need to manually reconfigure anything - everything just works!

Key Benefits:

  • Automatic Management: Services are automatically added/removed as domain owners update their offerings
  • Persistent Subscriptions: Subscriptions survive reboots and are automatically restored
  • Protocol Support: Works with both TCP and UDP services
  • Subscribe All: Option to automatically get all services from a domain, including future ones
  • No Manual Configuration: Once subscribed, everything is managed automatically

The Power: Service subscriptions make it easy for peers to discover and connect to services across the network. Domain owners can offer multiple services, and subscribers can automatically access them all with minimal configuration. The system handles all the complexity of connection management, protocol differences, and dynamic updates.

Related Documentation

); }