p2pnet

package
v0.0.0-...-0b9f5a6 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GradeA = "A"
	GradeB = "B"
	GradeC = "C"
	GradeD = "D"
	GradeF = "F"
)

Grade constants ordered from best to worst.

View Source
const DHTProtocolPrefix = "/peerup"

DHTProtocolPrefix is the default protocol prefix for the private peerup Kademlia DHT. This isolates peerup from the public IPFS Amino DHT (/ipfs/kad/1.0.0), giving us our own routing table at /peerup/kad/1.0.0. For namespace-specific prefixes, use DHTProtocolPrefixForNamespace.

Variables

View Source
var (
	// ErrServiceAlreadyRegistered is returned when trying to register a service
	// that already exists in the registry.
	ErrServiceAlreadyRegistered = errors.New("service already registered")

	// ErrServiceNotFound is returned when trying to unregister or access a service
	// that does not exist in the registry.
	ErrServiceNotFound = errors.New("service not found")

	// ErrNameNotFound is returned when a name cannot be resolved to a peer ID
	// and is not a valid peer ID itself.
	ErrNameNotFound = errors.New("name not found")
)
View Source
var DefaultSTUNServers = []string{
	"stun.l.google.com:19302",
	"stun.cloudflare.com:3478",
}

DefaultSTUNServers are well-known public STUN servers.

View Source
var PeerRelayLimit = &relayv2.RelayLimit{
	Duration: 10 * time.Minute,
	Data:     1 << 17,
}

PeerRelayLimit is the per-circuit limit for peer relays.

View Source
var PeerRelayResources = relayv2.Resources{
	Limit: &relayv2.RelayLimit{
		Duration: 10 * time.Minute,
		Data:     1 << 17,
	},
	ReservationTTL:         30 * time.Minute,
	MaxReservations:        4,
	MaxCircuits:            16,
	BufferSize:             4096,
	MaxReservationsPerPeer: 1,
	MaxReservationsPerIP:   2,
	MaxReservationsPerASN:  4,
}

PeerRelayResources defines conservative resource limits for peer relays. These are much tighter than the VPS relay to avoid overloading home connections.

Functions

func AddRelayAddressesForPeerFunc

func AddRelayAddressesForPeerFunc(h host.Host, relayAddrs []string, target peer.ID) error

AddRelayAddressesForPeerFunc adds relay circuit addresses to the peerstore for a target peer. This is the standalone version that works with any host, matching the pattern from Network.AddRelayAddressesForPeer().

func BidirectionalProxy

func BidirectionalProxy(a, b HalfCloseConn, logPrefix string)

BidirectionalProxy copies data between two half-close-capable connections. It uses two goroutines for each direction, propagates half-close (CloseWrite) when one side finishes sending, and waits for both directions to complete. logPrefix identifies the connection in log messages (e.g., "ssh", "proxy").

func BuildSTUNBindingRequest

func BuildSTUNBindingRequest(txID [12]byte) []byte

BuildSTUNBindingRequest creates a STUN Binding Request packet with the given transaction ID. Exported for testing.

func BuildSTUNBindingResponse

func BuildSTUNBindingResponse(txID [12]byte, ip net.IP, port int) []byte

BuildSTUNBindingResponse creates a STUN Binding Response with an XOR-MAPPED-ADDRESS attribute. Exported for testing.

func ComputeFingerprint

func ComputeFingerprint(a, b peer.ID) (emoji string, numeric string)

ComputeFingerprint computes a deterministic SAS fingerprint for a peer pair. Both peers compute the same fingerprint because both know both peer IDs. Returns both emoji and numeric representations.

func DHTProtocolPrefixForNamespace

func DHTProtocolPrefixForNamespace(namespace string) string

DHTProtocolPrefixForNamespace returns the DHT protocol prefix for a given network namespace. An empty namespace returns the default global prefix ("/peerup"). A non-empty namespace produces "/peerup/<namespace>" which results in the full DHT protocol "/peerup/<namespace>/kad/1.0.0", completely isolated from other namespaces at the protocol level.

func DialWithRetry

func DialWithRetry(dialFunc func() (ServiceConn, error), maxRetries int) func() (ServiceConn, error)

DialWithRetry wraps a dial function with exponential backoff retry. maxRetries is the number of retries after the first attempt (0 = no retry). Returns a new dial function that retries on failure.

func FingerprintPrefix

func FingerprintPrefix(a, b peer.ID) string

FingerprintPrefix returns the first 8 hex chars of the SHA-256 fingerprint for storage in the verified attribute.

func InstrumentedBidirectionalProxy

func InstrumentedBidirectionalProxy(a, b HalfCloseConn, service string, metrics *Metrics)

InstrumentedBidirectionalProxy wraps BidirectionalProxy with metrics. When metrics is nil, it delegates directly to BidirectionalProxy.

func LoadOrCreateIdentity

func LoadOrCreateIdentity(path string) (crypto.PrivKey, error)

LoadOrCreateIdentity loads an existing identity from a file or creates a new one.

func ParseRelayAddrs

func ParseRelayAddrs(relayAddrs []string) ([]peer.AddrInfo, error)

ParseRelayAddrs parses relay multiaddrs into peer.AddrInfo slices. It deduplicates by peer ID and merges addresses for the same relay peer.

func PeerIDFromKeyFile

func PeerIDFromKeyFile(path string) (peer.ID, error)

PeerIDFromKeyFile loads (or creates) a key file and returns the derived peer ID.

func PingPeer

func PingPeer(ctx context.Context, h host.Host, peerID peer.ID, protocolID string, count int, interval time.Duration) <-chan PingResult

PingPeer sends count pings to peerID using the given ping-pong protocol. Results are delivered on the returned channel. The channel is closed when all pings are sent or the context is cancelled.

If count is 0, pings continuously until ctx is cancelled. The caller should read from the channel until it is closed.

func ProxyStreamToTCP

func ProxyStreamToTCP(stream network.Stream, tcpAddr string) error

ProxyStreamToTCP creates a bidirectional proxy between a libp2p stream and a local TCP service.

func ValidateServiceName

func ValidateServiceName(name string) error

ValidateServiceName checks that a service name is safe for use in protocol IDs.

Types

type AuditLogger

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

AuditLogger writes structured audit events for security-relevant actions. All methods are nil-safe: calling any method on a nil *AuditLogger is a no-op. This allows callers to skip nil checks at every call site.

func NewAuditLogger

func NewAuditLogger(handler slog.Handler) *AuditLogger

NewAuditLogger creates an AuditLogger that writes to the given handler. All audit events are written under the "audit" group for easy filtering.

func (*AuditLogger) AuthChange

func (a *AuditLogger) AuthChange(action, peerID string)

AuthChange logs a peer authorization change (add or remove).

func (*AuditLogger) AuthDecision

func (a *AuditLogger) AuthDecision(peerID, direction, result string)

AuthDecision logs an authentication allow/deny decision.

func (*AuditLogger) DaemonAPIAccess

func (a *AuditLogger) DaemonAPIAccess(method, path string, status int)

DaemonAPIAccess logs an API request to the daemon.

func (*AuditLogger) ServiceACLDenied

func (a *AuditLogger) ServiceACLDenied(peerID, service string)

ServiceACLDenied logs a per-service access control denial.

type Config

type Config struct {
	KeyFile        string
	AuthorizedKeys string                    // Path to authorized_keys file (auto-creates gater if Gater is nil)
	Gater          *auth.AuthorizedPeerGater // Pre-created gater (for hot-reload support). Takes precedence over AuthorizedKeys.
	Config         *config.Config
	UserAgent      string // libp2p Identify user agent (e.g. "peerup/0.1.0")

	// Relay configuration (optional)
	EnableRelay        bool     // Enable relay support (AutoRelay + hole punching)
	RelayAddrs         []string // Relay server multiaddrs (e.g., "/ip4/1.2.3.4/tcp/7777/p2p/12D3Koo...")
	ForcePrivate       bool     // Force private reachability (required for relay reservations)
	EnableNATPortMap   bool     // Enable NAT port mapping
	EnableHolePunching bool     // Enable hole punching

	// Resource management
	ResourceLimitsEnabled bool // Enable libp2p resource manager (connection/stream/memory limits)

	// Observability
	Metrics *Metrics // Custom peerup metrics (nil = disabled). When non-nil, libp2p metrics are registered on Metrics.Registry.
}

Config for creating a new P2P network

type DialResult

type DialResult struct {
	PathType PathType      `json:"path_type"`
	Duration time.Duration `json:"duration_ms"`
	Address  string        `json:"address"` // winning multiaddr
}

DialResult is the outcome of a successful PathDialer.DialPeer call.

type HalfCloseConn

type HalfCloseConn interface {
	io.ReadWriteCloser
	CloseWrite() error
}

HalfCloseConn is a connection that supports half-close (CloseWrite). Both ServiceConn (libp2p streams) and tcpHalfCloser (TCP connections) implement this.

type InterfaceInfo

type InterfaceInfo struct {
	Name       string   `json:"name"`
	IPv4Addrs  []string `json:"ipv4_addrs,omitempty"`
	IPv6Addrs  []string `json:"ipv6_addrs,omitempty"`
	IsLoopback bool     `json:"is_loopback"`
}

InterfaceInfo describes a single network interface with its global unicast addresses.

type InterfaceSummary

type InterfaceSummary struct {
	Interfaces      []InterfaceInfo `json:"interfaces"`
	HasGlobalIPv6   bool            `json:"has_global_ipv6"`
	HasGlobalIPv4   bool            `json:"has_global_ipv4"`
	GlobalIPv6Addrs []string        `json:"global_ipv6_addrs,omitempty"`
	GlobalIPv4Addrs []string        `json:"global_ipv4_addrs,omitempty"`
}

InterfaceSummary is the result of DiscoverInterfaces. It provides a snapshot of all network interfaces with global unicast addresses and convenience flags for IPv4/IPv6 availability.

func DiscoverInterfaces

func DiscoverInterfaces() (*InterfaceSummary, error)

DiscoverInterfaces enumerates all network interfaces, filters for global unicast addresses, and returns a summary. Link-local, ULA, and private IPv4 addresses are excluded from the global lists but the interface itself is still reported (for debugging).

type Metrics

type Metrics struct {
	Registry *prometheus.Registry

	// Proxy metrics
	ProxyBytesTotal       *prometheus.CounterVec
	ProxyConnectionsTotal *prometheus.CounterVec
	ProxyActiveConns      *prometheus.GaugeVec
	ProxyDurationSeconds  *prometheus.HistogramVec

	// Auth metrics
	AuthDecisionsTotal *prometheus.CounterVec

	// Hole punch metrics (enhanced from existing holePunchTracer)
	HolePunchTotal           *prometheus.CounterVec
	HolePunchDurationSeconds *prometheus.HistogramVec

	// Daemon API metrics
	DaemonRequestsTotal          *prometheus.CounterVec
	DaemonRequestDurationSeconds *prometheus.HistogramVec

	// Path dial metrics
	PathDialTotal           *prometheus.CounterVec
	PathDialDurationSeconds *prometheus.HistogramVec

	// Connected peers (tracked by PathTracker)
	ConnectedPeers *prometheus.GaugeVec

	// Network change events (tracked by NetworkMonitor)
	NetworkChangeTotal *prometheus.CounterVec

	// STUN probe metrics
	STUNProbeTotal *prometheus.CounterVec

	// Interface metrics
	InterfaceCount *prometheus.GaugeVec

	// Build info
	BuildInfo *prometheus.GaugeVec
}

Metrics holds all custom peerup Prometheus metrics. Uses an isolated prometheus.Registry so peerup metrics don't collide with the global default registry. Each test gets its own Metrics instance.

func NewMetrics

func NewMetrics(version, goVersion string) *Metrics

NewMetrics creates a new Metrics instance with all collectors registered on an isolated registry. The version and goVersion are recorded as labels on the peerup_info gauge.

func (*Metrics) Handler

func (m *Metrics) Handler() http.Handler

Handler returns an http.Handler that serves the Prometheus metrics endpoint.

type NATType

type NATType string

NATType describes the type of NAT based on STUN probing results.

const (
	NATNone              NATType = "none"               // No NAT (public IP matches local)
	NATFullCone          NATType = "full-cone"          // Endpoint-independent mapping
	NATAddressRestricted NATType = "address-restricted" // Same mapping for all destinations
	NATPortRestricted    NATType = "port-restricted"    // Port differs per destination
	NATSymmetric         NATType = "symmetric"          // Different mapping per destination
	NATUnknown           NATType = "unknown"            // Could not determine
)

func (NATType) HolePunchable

func (n NATType) HolePunchable() bool

HolePunchable returns true if this NAT type is amenable to hole punching.

type NameResolver

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

NameResolver resolves names to peer IDs

func NewNameResolver

func NewNameResolver() *NameResolver

NewNameResolver creates a new name resolver

func (*NameResolver) List

func (r *NameResolver) List() map[string]peer.ID

List returns all registered name mappings

func (*NameResolver) LoadFromMap

func (r *NameResolver) LoadFromMap(names map[string]string) error

LoadFromMap loads name mappings from a map

func (*NameResolver) Register

func (r *NameResolver) Register(name string, peerID peer.ID) error

Register registers a name → peer ID mapping

func (*NameResolver) Resolve

func (r *NameResolver) Resolve(name string) (peer.ID, error)

Resolve resolves a name to a peer ID If the name is not found, tries to parse it as a direct peer ID

func (*NameResolver) Unregister

func (r *NameResolver) Unregister(name string)

Unregister removes a name mapping

type Network

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

Network represents a P2P network instance

func New

func New(cfg *Config) (*Network, error)

New creates a new P2P network instance

func (*Network) AddRelayAddressesForPeer

func (n *Network) AddRelayAddressesForPeer(relayAddrs []string, targetPeerID peer.ID) error

AddRelayAddressesForPeer adds relay circuit addresses for a target peer to the peerstore. This allows the client to reach the target peer through the configured relay servers.

func (*Network) Close

func (n *Network) Close() error

Close shuts down the network

func (*Network) ConnectToService

func (n *Network) ConnectToService(peerID peer.ID, serviceName string) (ServiceConn, error)

ConnectToService connects to a remote peer's service with a default 30s timeout.

func (*Network) ConnectToServiceContext

func (n *Network) ConnectToServiceContext(ctx context.Context, peerID peer.ID, serviceName string) (ServiceConn, error)

ConnectToServiceContext connects to a remote peer's service using the provided context.

func (*Network) ExposeService

func (n *Network) ExposeService(name, localAddress string, allowedPeers map[peer.ID]struct{}) error

ExposeService exposes a local TCP service through the P2P network. If allowedPeers is nil, all authorized peers can access the service.

func (*Network) Host

func (n *Network) Host() host.Host

Host returns the underlying libp2p host

func (*Network) ListServices

func (n *Network) ListServices() []*Service

ListServices returns all registered services.

func (*Network) LoadNames

func (n *Network) LoadNames(names map[string]string) error

LoadNames loads name-to-peer-ID mappings from a string map (e.g., from YAML config)

func (*Network) PeerID

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

PeerID returns the peer ID of this network node

func (*Network) RegisterName

func (n *Network) RegisterName(name string, peerID peer.ID) error

RegisterName registers a local name mapping

func (*Network) ResolveName

func (n *Network) ResolveName(name string) (peer.ID, error)

ResolveName resolves a name to a peer ID

func (*Network) UnexposeService

func (n *Network) UnexposeService(name string) error

UnexposeService removes a previously exposed service from the P2P network.

type NetworkChange

type NetworkChange struct {
	Added       []string // new global IPs
	Removed     []string // lost global IPs
	IPv6Changed bool
	IPv4Changed bool
}

NetworkChange describes what changed between two interface snapshots.

type NetworkMonitor

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

NetworkMonitor watches for network interface changes and calls onChange when global IP addresses are added or removed. The platform-specific implementation uses event-driven detection (macOS route socket, Linux Netlink) with polling as a fallback on other platforms.

func NewNetworkMonitor

func NewNetworkMonitor(onChange func(*NetworkChange), m *Metrics) *NetworkMonitor

NewNetworkMonitor creates a NetworkMonitor. Metrics is optional (nil-safe).

func (*NetworkMonitor) Run

func (nm *NetworkMonitor) Run(ctx context.Context)

Run blocks until the context is cancelled. It watches for network changes using platform-specific event sources and calls onChange when global IPs change. The initial interface snapshot is taken on start.

type PathDialer

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

PathDialer connects to peers using parallel path racing. It launches DHT discovery and relay circuit attempts concurrently and returns as soon as the first path succeeds, cancelling the other.

func NewPathDialer

func NewPathDialer(h host.Host, kdht *dht.IpfsDHT, relayAddrs []string, m *Metrics) *PathDialer

NewPathDialer creates a PathDialer. The DHT and metrics are optional (nil-safe).

func (*PathDialer) DialPeer

func (pd *PathDialer) DialPeer(ctx context.Context, peerID peer.ID) (*DialResult, error)

DialPeer connects to the target peer using parallel path racing. If already connected, it returns immediately with the current path type. Otherwise it races DHT discovery against relay circuit, returning the first successful connection.

type PathTracker

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

PathTracker monitors peer connections via the libp2p event bus and maintains per-peer path information (type, transport, IP version).

func NewPathTracker

func NewPathTracker(h host.Host, m *Metrics) *PathTracker

NewPathTracker creates a PathTracker. Metrics is optional (nil-safe).

func (*PathTracker) GetPeerPath

func (pt *PathTracker) GetPeerPath(pid peer.ID) (*PeerPathInfo, bool)

GetPeerPath returns path info for a specific peer.

func (*PathTracker) ListPeerPaths

func (pt *PathTracker) ListPeerPaths() []*PeerPathInfo

ListPeerPaths returns path info for all tracked peers.

func (*PathTracker) Start

func (pt *PathTracker) Start(ctx context.Context)

Start subscribes to peer connectedness events and processes them until the context is cancelled. Call this in a goroutine.

func (*PathTracker) UpdateRTT

func (pt *PathTracker) UpdateRTT(pid peer.ID, rttMs float64)

UpdateRTT records the latest round-trip time for a peer.

type PathType

type PathType string

PathType describes how a peer connection was established.

const (
	PathDirect  PathType = "DIRECT"
	PathRelayed PathType = "RELAYED"
)

func ClassifyMultiaddr

func ClassifyMultiaddr(addr string) (pathType PathType, transport string, ipVersion string)

ClassifyMultiaddr determines path type and extracts transport and IP version from a multiaddr string. Used by PathTracker and status display.

type PeerPathInfo

type PeerPathInfo struct {
	PeerID      string   `json:"peer_id"`
	PathType    PathType `json:"path_type"`    // DIRECT or RELAYED
	Address     string   `json:"address"`      // current multiaddr
	ConnectedAt string   `json:"connected_at"` // RFC 3339
	Transport   string   `json:"transport"`    // quic, tcp, websocket
	IPVersion   string   `json:"ip_version"`   // ipv4, ipv6
	LastRTTMs   float64  `json:"last_rtt_ms,omitempty"`
}

PeerPathInfo describes the current path to a connected peer.

type PeerRelay

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

PeerRelay enables a peer with a public IP to act as a circuit relay for other authorized peers. This reduces dependence on the central VPS relay by letting any peer with a routable address serve as an alternative.

Security: The existing ConnectionGater (authorized_keys peer ID allowlist) applies to relay connections. Only peers in the authorized_keys file can make reservations or create circuits through this relay.

func NewPeerRelay

func NewPeerRelay(h host.Host, m *Metrics) *PeerRelay

NewPeerRelay creates a PeerRelay. The relay is not enabled until Enable() is called. Metrics is optional (nil-safe).

func (*PeerRelay) AutoDetect

func (pr *PeerRelay) AutoDetect(summary *InterfaceSummary)

AutoDetect enables the relay if the host has a global (routable) IP address, or disables it if global addresses are lost. This should be called after interface discovery (I-a) and on network change events (I-d).

func (*PeerRelay) Disable

func (pr *PeerRelay) Disable()

Disable stops the circuit relay service.

func (*PeerRelay) Enable

func (pr *PeerRelay) Enable() error

Enable starts the circuit relay v2 service on this host. Returns nil if already enabled.

func (*PeerRelay) Enabled

func (pr *PeerRelay) Enabled() bool

Enabled returns true if the relay is currently active.

type PingResult

type PingResult struct {
	Seq    int     `json:"seq"`
	PeerID string  `json:"peer_id"`
	RttMs  float64 `json:"rtt_ms"`
	Path   string  `json:"path"`  // "DIRECT" or "RELAYED"
	Error  string  `json:"error"` // empty on success
}

PingResult holds the result of a single ping to a peer.

type PingStats

type PingStats struct {
	Sent     int     `json:"sent"`
	Received int     `json:"received"`
	Lost     int     `json:"lost"`
	LossPct  float64 `json:"loss_pct"`
	MinMs    float64 `json:"min_ms"`
	AvgMs    float64 `json:"avg_ms"`
	MaxMs    float64 `json:"max_ms"`
}

PingStats holds aggregate statistics for a ping session.

func ComputePingStats

func ComputePingStats(results []PingResult) PingStats

ComputePingStats computes aggregate statistics from a slice of ping results.

type ProbeResult

type ProbeResult struct {
	ServerAddr   string        `json:"server_addr"`
	ExternalAddr string        `json:"external_addr,omitempty"`
	ExternalIP   string        `json:"external_ip,omitempty"`
	ExternalPort int           `json:"external_port,omitempty"`
	Latency      time.Duration `json:"latency_ms"`
	Error        string        `json:"error,omitempty"`
}

ProbeResult is the outcome of a single STUN server probe.

type ReachabilityGrade

type ReachabilityGrade struct {
	Grade       string `json:"grade"`
	Label       string `json:"label"`
	Description string `json:"description"`
}

ReachabilityGrade summarizes how reachable this node is from the internet.

func ComputeReachabilityGrade

func ComputeReachabilityGrade(ifaces *InterfaceSummary, stun *STUNResult) ReachabilityGrade

ComputeReachabilityGrade determines the reachability grade from interface discovery and STUN probe results. Either parameter may be nil.

Grade scale:

A  Excellent  Public IPv6 detected
B  Good       Public IPv4 or hole-punchable NAT (full-cone / address-restricted)
C  Fair       Port-restricted NAT
D  Poor       Symmetric NAT / CGNAT
F  Offline    No connectivity detected

type STUNProber

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

STUNProber discovers external address mappings via STUN (RFC 5389 Binding Request). It probes multiple servers to determine the external IP:port and NAT type.

func NewSTUNProber

func NewSTUNProber(servers []string, m *Metrics) *STUNProber

NewSTUNProber creates a STUNProber. If servers is empty, defaults are used. Metrics is optional (nil-safe).

func (*STUNProber) Probe

func (sp *STUNProber) Probe(ctx context.Context) (*STUNResult, error)

Probe sends STUN Binding Requests to all configured servers concurrently and determines NAT type from the results.

func (*STUNProber) Result

func (sp *STUNProber) Result() *STUNResult

Result returns the most recent probe result (thread-safe).

type STUNResult

type STUNResult struct {
	Probes        []ProbeResult `json:"probes"`
	NATType       NATType       `json:"nat_type"`
	ExternalAddrs []string      `json:"external_addrs"`
	ProbedAt      time.Time     `json:"probed_at"`
	BehindCGNAT   bool          `json:"behind_cgnat,omitempty"`
	CGNATNote     string        `json:"cgnat_note,omitempty"`
}

STUNResult is the aggregate result of probing multiple STUN servers.

func (*STUNResult) DetectCGNAT

func (r *STUNResult) DetectCGNAT()

DetectCGNAT checks local network interfaces for RFC 6598 CGNAT addresses (100.64.0.0/10) and sets BehindCGNAT accordingly. This is the only reliable client-side signal for carrier-grade NAT. Mobile carriers using RFC 1918 addresses (172.16-31.x.x) cannot be distinguished from regular home networks.

type Service

type Service struct {
	Name         string               // Service name (e.g., "ssh", "http")
	Protocol     string               // libp2p protocol ID (e.g., "/peerup/ssh/1.0.0")
	LocalAddress string               // Local TCP address (e.g., "localhost:22")
	Enabled      bool                 // Whether this service is enabled
	AllowedPeers map[peer.ID]struct{} // Per-service ACL (nil = all authorized peers allowed)
}

Service represents a service that can be exposed over the P2P network

type ServiceConn

type ServiceConn interface {
	io.ReadWriteCloser
	CloseWrite() error
}

ServiceConn represents a connection to a remote service

type ServiceRegistry

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

ServiceRegistry manages service registration and connections

func NewServiceRegistry

func NewServiceRegistry(h host.Host, metrics *Metrics) *ServiceRegistry

NewServiceRegistry creates a new service registry. Pass nil for metrics to disable instrumentation.

func (*ServiceRegistry) DialService

func (r *ServiceRegistry) DialService(ctx context.Context, peerID peer.ID, protocolID string) (ServiceConn, error)

DialService connects to a remote peer's service

func (*ServiceRegistry) GetService

func (r *ServiceRegistry) GetService(name string) (*Service, bool)

GetService retrieves a registered service by name

func (*ServiceRegistry) ListServices

func (r *ServiceRegistry) ListServices() []*Service

ListServices returns all registered services

func (*ServiceRegistry) RegisterService

func (r *ServiceRegistry) RegisterService(svc *Service) error

RegisterService registers a new service and sets up its stream handler

func (*ServiceRegistry) UnregisterService

func (r *ServiceRegistry) UnregisterService(name string) error

UnregisterService removes a service and its stream handler.

type TCPListener

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

TCPListener creates a local TCP listener that forwards connections to a P2P service

func NewTCPListener

func NewTCPListener(localAddr string, dialFunc func() (ServiceConn, error)) (*TCPListener, error)

NewTCPListener creates a new TCP listener for a P2P service

func (*TCPListener) Addr

func (l *TCPListener) Addr() net.Addr

Addr returns the listener's network address

func (*TCPListener) Close

func (l *TCPListener) Close() error

Close closes the TCP listener

func (*TCPListener) Serve

func (l *TCPListener) Serve() error

Serve accepts connections and forwards them to the P2P service

type TraceHop

type TraceHop struct {
	Hop     int     `json:"hop"`
	PeerID  string  `json:"peer_id"`
	Name    string  `json:"name,omitempty"`    // friendly name if known
	Address string  `json:"address,omitempty"` // multiaddr of this hop
	RttMs   float64 `json:"rtt_ms"`
	Error   string  `json:"error,omitempty"`
}

TraceHop represents a single hop in a P2P traceroute.

type TraceResult

type TraceResult struct {
	Target   string     `json:"target"`
	TargetID string     `json:"target_id"`
	Path     string     `json:"path"` // "DIRECT" or "RELAYED"
	Hops     []TraceHop `json:"hops"`
}

TraceResult holds the full traceroute output.

func TracePeer

func TracePeer(ctx context.Context, h host.Host, targetPeerID peer.ID) (*TraceResult, error)

TracePeer traces the network path to a peer.

libp2p doesn't support TTL-based tracing, so this determines the path by inspecting connection metadata: is the connection direct or relayed? If relayed, it measures RTT to the relay and to the target separately to show per-hop latency - the information that actually matters for debugging.

Jump to

Keyboard shortcuts

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