dht

package
v0.0.0-...-d087bcd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 15 Imported by: 0

README

DHT Federation Package

Decentralized server discovery using LibP2P Kademlia DHT for the Violence game.

Overview

This package provides peer-to-peer server discovery without requiring a central federation hub. Game servers can announce themselves to a distributed hash table (DHT), and clients can query for available servers by genre, region, or other criteria.

Features

  • Decentralized Discovery: No single point of failure - servers are discovered through a distributed network
  • 8-Hour TTL: Server records automatically expire after 8 hours
  • Minimum 3 Replicas: Each record is replicated across at least 3 DHT nodes
  • Genre Indexing: Efficient server lookups by game genre
  • Bootstrap Support: Connect to known bootstrap peers for network entry
  • Custom Protocol: Uses /violence protocol prefix to avoid IPFS network conflicts

Usage

Creating a DHT Node
import (
    "context"
    "github.com/opd-ai/violence/pkg/federation/dht"
)

// Server mode (participates in DHT routing)
node, err := dht.NewNode(context.Background(), dht.Config{
    ListenAddrs:    []string{"/ip4/0.0.0.0/tcp/4001"},
    BootstrapPeers: []string{
        "/ip4/bootstrap.example.com/tcp/4001/p2p/12D3Koo...",
    },
    Mode: "server",
})
if err != nil {
    log.Fatal(err)
}
defer node.Close()
Announcing a Server
record := dht.ServerRecord{
    Name:       "my-scifi-server",
    Address:    "203.0.113.5:7777",
    Genre:      "scifi",
    MaxPlayers: 32,
    Uptime:     3600, // seconds
}

ctx := context.Background()
if err := node.AnnounceServer(ctx, record); err != nil {
    log.Fatalf("Failed to announce: %v", err)
}

// Update genre index for efficient searches
if err := node.UpdateGenreIndex(ctx, "scifi", "my-scifi-server", true); err != nil {
    log.Fatalf("Failed to update index: %v", err)
}
Looking Up a Server
ctx := context.Background()
server, err := node.LookupServer(ctx, "my-scifi-server")
if err != nil {
    log.Fatalf("Server not found: %v", err)
}

fmt.Printf("Server: %s at %s\n", server.Name, server.Address)
Querying Servers by Genre
ctx := context.Background()
servers, err := node.QueryServers(ctx, "scifi", 10)
if err != nil {
    log.Fatalf("Query failed: %v", err)
}

for _, srv := range servers {
    fmt.Printf("%s: %s (%d/%d players)\n",
        srv.Name, srv.Address, srv.Players, srv.MaxPlayers)
}

Architecture

DHT Structure
  • Keys: /violence/{namespace}/{value} format
    • Server records: /violence/server/{serverName}
    • Genre indexes: /violence/genre/{genreName}
Record Format

Server records are stored as JSON:

{
    "name": "my-server",
    "address": "203.0.113.5:7777",
    "genre": "scifi",
    "maxPlayers": 32,
    "uptime": 3600,
    "timestamp": "2026-03-01T15:00:00Z"
}
Bootstrap Process
  1. Node connects to configured bootstrap peers (timeout: 30s)
  2. Node joins the DHT network
  3. Node begins participating in routing (server mode) or queries (client mode)
Record Expiration
  • Records have an 8-hour TTL
  • Servers should re-announce every 4 hours to stay visible
  • Expired records are rejected on lookup

Configuration

Node Modes
  • server: Participates in DHT routing, stores records
  • client: Queries DHT but doesn't store records
Bootstrap Peers

Bootstrap peers should be stable, publicly-accessible DHT nodes. For production:

  • Use multiple bootstrap peers for redundancy
  • Include geographically distributed peers
  • Update peer list regularly

Example bootstrap configuration:

BootstrapPeers: []string{
    "/dns4/dht1.violence.example.com/tcp/4001/p2p/12D3Koo...",
    "/dns4/dht2.violence.example.com/tcp/4001/p2p/12D3Koo...",
    "/dns4/dht3.violence.example.com/tcp/4001/p2p/12D3Koo...",
}

Testing

Run tests:

# Unit tests only (fast)
go test ./pkg/federation/dht/... -short

# All tests including integration (slower)
go test ./pkg/federation/dht/... -v

# With coverage
go test ./pkg/federation/dht/... -cover

Integration tests verify:

  • 10-node DHT network operation
  • Bootstrap connection within 30 seconds to ≥3 peers
  • Server lookup within 5 seconds
  • Multi-genre server queries

Performance

Expected Latency
  • Bootstrap: <30 seconds to connect to 3+ peers
  • Server Lookup: <5 seconds (validated in tests)
  • Server Announce: <2 seconds to propagate to network
Network Requirements
  • Bandwidth: ~1 Kbps per DHT node for routing overhead
  • Ports: Configurable, default 4001/tcp
  • NAT: Supports NAT traversal via LibP2P AutoNAT

Fallback to HTTP Hub

For maximum availability, combine DHT with HTTP federation hub:

// Try DHT first
servers, err := dhtNode.QueryServers(ctx, genre, 10)
if err != nil || len(servers) == 0 {
    // Fall back to HTTP hub
    servers, err = httpClient.QueryHub(hubURL, genre)
}

License

See LICENSE file in repository root.

Documentation

Overview

Package dht provides decentralized server discovery using LibP2P Kademlia DHT.

Package dht provides decentralized server discovery using LibP2P Kademlia DHT.

Package dht provides decentralized server discovery using LibP2P Kademlia DHT.

Index

Constants

View Source
const (
	// RecordTTL is the time-to-live for DHT records (8 hours)
	RecordTTL = 8 * time.Hour
	// MinReplicas is the minimum number of replicas per DHT record
	MinReplicas = 3
	// BootstrapTimeout is the max time to wait for bootstrap
	BootstrapTimeout = 30 * time.Second
)
View Source
const (
	// ViolenceNamespace is the DHT namespace for Violence server records
	ViolenceNamespace = "violence"
)

Variables

This section is empty.

Functions

func NewValidator

func NewValidator() record.NamespacedValidator

NewValidator creates a namespaced validator for Violence records.

Types

type Bootstrapper

type Bootstrapper interface {
	Bootstrap(ctx context.Context) error
}

Bootstrap connects to the default IPFS bootstrap peers so the node can join the global DHT network. Callers that only need local connectivity should pass an empty bootstrap list in Config instead.

type Config

type Config struct {
	// ListenAddrs are the multiaddrs to listen on (e.g., "/ip4/0.0.0.0/tcp/0")
	ListenAddrs []string
	// BootstrapPeers are known DHT bootstrap nodes
	BootstrapPeers []string
	// Mode is either "server" or "client" (affects DHT mode)
	Mode string
}

Config holds configuration for DHT node creation.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node represents a DHT node for peer-to-peer server discovery.

func NewNode

func NewNode(ctx context.Context, cfg Config) (*Node, error)

NewNode creates a new DHT node with the given configuration.

func (*Node) Addrs

func (n *Node) Addrs() []multiaddr.Multiaddr

Addrs returns the node's listen addresses.

func (*Node) AnnounceServer

func (n *Node) AnnounceServer(ctx context.Context, record ServerRecord) error

AnnounceServer publishes a server record to the DHT. The record will be replicated across at least MinReplicas peers.

func (*Node) Close

func (n *Node) Close() error

Close shuts down the DHT node.

func (*Node) LookupServer

func (n *Node) LookupServer(ctx context.Context, serverName string) (*ServerRecord, error)

LookupServer retrieves a server record from the DHT by name.

func (*Node) PeerCount

func (n *Node) PeerCount() int

PeerCount returns the number of connected peers.

func (*Node) PeerID

func (n *Node) PeerID() peer.ID

PeerID returns the node's peer ID.

func (*Node) QueryServers

func (n *Node) QueryServers(ctx context.Context, genre string, maxResults int) ([]*ServerRecord, error)

QueryServers searches for servers matching the given genre. Returns up to maxResults servers.

func (*Node) Routing

func (n *Node) Routing() routing.Routing

Routing returns the DHT routing interface.

func (*Node) UpdateGenreIndex

func (n *Node) UpdateGenreIndex(ctx context.Context, genre, serverName string, add bool) error

UpdateGenreIndex updates the genre index with a server name. This allows efficient lookups by genre.

type NodeInterface

type NodeInterface interface {
	// Close shuts down the node and releases all resources.
	Close() error
	// PeerID returns the local peer ID.
	PeerID() peer.ID
	// Addrs returns the listen addresses for this node.
	Addrs() []multiaddr.Multiaddr
	// Routing returns the underlying routing.Routing implementation.
	Routing() routing.Routing
	// PeerCount returns the number of currently connected peers.
	PeerCount() int
}

NodeInterface abstracts the DHT node so that callers can be tested without creating a live libp2p host.

type ServerRecord

type ServerRecord struct {
	Name       string    `json:"name"`
	Address    string    `json:"address"`
	Genre      string    `json:"genre"`
	MaxPlayers int       `json:"maxPlayers"`
	Uptime     int64     `json:"uptime"` // seconds
	Timestamp  time.Time `json:"timestamp"`
}

ServerRecord represents a server announcement stored in the DHT.

type ViolenceValidator

type ViolenceValidator struct{}

ViolenceValidator validates Violence DHT records.

func (ViolenceValidator) Select

func (v ViolenceValidator) Select(key string, values [][]byte) (int, error)

Select chooses the best record when multiple values exist. Returns the index of the best record.

func (ViolenceValidator) Validate

func (v ViolenceValidator) Validate(key string, value []byte) error

Validate validates a DHT record value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址