mesh

package
v0.0.0-...-1f1918b Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package mesh provides Hamachi-like mesh networking functionality.

Index

Constants

View Source
const (
	// MaxMetadataKeys is the maximum number of metadata keys per peer
	MaxMetadataKeys = 50
	// MaxMetadataKeyLen is the maximum length of a metadata key
	MaxMetadataKeyLen = 64
	// MaxMetadataValueLen is the maximum length of a metadata value
	MaxMetadataValueLen = 256
)

Peer metadata limits

View Source
const (
	// MaxSeenMessages is the maximum number of seen message IDs to track
	MaxSeenMessages = 10000
)

Broadcast limits

Variables

View Source
var (
	ErrDiscoveryNotConnected = errors.New("discovery: not connected to server")
	ErrDiscoveryFailed       = errors.New("discovery: registration failed")
	ErrDiscoveryTimeout      = errors.New("discovery: operation timed out")
)

Common discovery errors.

View Source
var (
	ErrNoAvailableAddress = errors.New("ipam: no available address in pool")
	ErrAddressInUse       = errors.New("ipam: address already in use")
	ErrAddressOutOfRange  = errors.New("ipam: address out of pool range")
	ErrPeerNotFound       = errors.New("ipam: peer not found")
	ErrAddressReserved    = errors.New("ipam: address is reserved")
)

Common IPAM errors.

View Source
var (
	ErrNodeNotStarted      = errors.New("mesh: node not started")
	ErrNodeAlreadyRunning  = errors.New("mesh: node already running")
	ErrNoPeerConnection    = errors.New("mesh: no connection to peer")
	ErrDeviceNotConfigured = errors.New("mesh: device not configured")
)

MeshNode errors.

Functions

func DefaultPathCostFunc

func DefaultPathCostFunc(latency time.Duration, hopCount int) int

DefaultPathCostFunc is the default path cost function.

Types

type BroadcastConfig

type BroadcastConfig struct {
	// SeenMsgsTTL is how long to remember seen messages.
	SeenMsgsTTL time.Duration

	// DefaultTTL is the default TTL for broadcasts.
	DefaultTTL int

	// CleanupInterval is the interval for cleaning up seen messages.
	CleanupInterval time.Duration
}

BroadcastConfig contains broadcast manager configuration.

func DefaultBroadcastConfig

func DefaultBroadcastConfig() BroadcastConfig

DefaultBroadcastConfig returns a default broadcast configuration.

type BroadcastHandler

type BroadcastHandler func(msg *BroadcastMessage)

BroadcastHandler handles received broadcast messages.

type BroadcastManager

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

BroadcastManager manages broadcast and multicast messaging.

func NewBroadcastManager

func NewBroadcastManager(localPeerID string, router *MeshRouter, config BroadcastConfig) *BroadcastManager

NewBroadcastManager creates a new broadcast manager.

func (*BroadcastManager) AddGroupMember

func (bm *BroadcastManager) AddGroupMember(groupID, peerID string)

AddGroupMember adds a member to a group.

func (*BroadcastManager) Anycast

func (bm *BroadcastManager) Anycast(groupID string, payload []byte) error

Anycast sends a message to the closest member of a group.

func (*BroadcastManager) Broadcast

func (bm *BroadcastManager) Broadcast(payload []byte, ttl int) error

Broadcast sends a message to all peers in the mesh.

func (*BroadcastManager) GetGroupMembers

func (bm *BroadcastManager) GetGroupMembers(groupID string) []string

GetGroupMembers returns members of a group.

func (*BroadcastManager) GetGroups

func (bm *BroadcastManager) GetGroups() []*MulticastGroup

GetGroups returns all joined groups.

func (*BroadcastManager) HandleMessage

func (bm *BroadcastManager) HandleMessage(fromPeerID string, data []byte) error

HandleMessage handles an incoming broadcast message.

func (*BroadcastManager) IsGroupMember

func (bm *BroadcastManager) IsGroupMember(groupID, peerID string) bool

IsGroupMember checks if a peer is a member of a group.

func (*BroadcastManager) JoinGroup

func (bm *BroadcastManager) JoinGroup(groupID, groupName string)

JoinGroup joins a multicast group.

func (*BroadcastManager) LeaveGroup

func (bm *BroadcastManager) LeaveGroup(groupID string)

LeaveGroup leaves a multicast group.

func (*BroadcastManager) Multicast

func (bm *BroadcastManager) Multicast(groupID string, payload []byte, ttl int) error

Multicast sends a message to all members of a group.

func (*BroadcastManager) RegisterHandler

func (bm *BroadcastManager) RegisterHandler(broadcastType BroadcastType, handler BroadcastHandler)

RegisterHandler registers a handler for a broadcast type.

func (*BroadcastManager) RemoveGroupMember

func (bm *BroadcastManager) RemoveGroupMember(groupID, peerID string)

RemoveGroupMember removes a member from a group.

func (*BroadcastManager) SetSendFunc

func (bm *BroadcastManager) SetSendFunc(sendFunc func(peerID string, data []byte) error)

SetSendFunc sets the function used to send messages.

func (*BroadcastManager) Start

func (bm *BroadcastManager) Start() error

Start starts the broadcast manager.

func (*BroadcastManager) Stop

func (bm *BroadcastManager) Stop() error

Stop stops the broadcast manager.

type BroadcastMessage

type BroadcastMessage struct {
	// ID is a unique message identifier.
	ID string `json:"id"`

	// Type is the broadcast type.
	Type BroadcastType `json:"type"`

	// SrcPeerID is the source peer ID.
	SrcPeerID string `json:"src_peer_id"`

	// GroupID is the multicast group (for multicast/anycast).
	GroupID string `json:"group_id,omitempty"`

	// TTL is the time-to-live (hop count).
	TTL int `json:"ttl"`

	// Timestamp is when the message was created.
	Timestamp time.Time `json:"timestamp"`

	// Payload is the message data.
	Payload []byte `json:"payload"`
}

BroadcastMessage represents a broadcast message.

type BroadcastType

type BroadcastType int

BroadcastType represents the type of broadcast.

const (
	// BroadcastTypeFlood sends to all peers.
	BroadcastTypeFlood BroadcastType = iota

	// BroadcastTypeMulticast sends to a specific group.
	BroadcastTypeMulticast

	// BroadcastTypeAnycast sends to the closest peer in a group.
	BroadcastTypeAnycast
)

func (BroadcastType) String

func (t BroadcastType) String() string

String returns a human-readable string for the broadcast type.

type Config

type Config struct {
	// Enabled controls whether mesh networking is active (default: false).
	Enabled bool `yaml:"enabled" json:"enabled"`

	// NetworkID is the unique identifier for this mesh network.
	NetworkID string `yaml:"network_id" json:"network_id"`

	// NetworkCIDR is the CIDR block for virtual IP allocation (e.g., "10.100.0.0/16").
	NetworkCIDR string `yaml:"network_cidr" json:"network_cidr"`

	// PeerName is the friendly name for this peer in the network.
	PeerName string `yaml:"peer_name" json:"peer_name"`

	// Device contains network device configuration.
	Device DeviceConfig `yaml:"device" json:"device"`

	// Discovery contains peer discovery settings.
	Discovery DiscoveryConfig `yaml:"discovery" json:"discovery"`

	// STUN contains STUN server configuration for NAT traversal.
	STUN STUNConfig `yaml:"stun" json:"stun"`

	// TURN contains TURN server configuration for relay.
	TURN TURNConfig `yaml:"turn" json:"turn"`

	// Connection contains P2P connection settings.
	Connection ConnectionConfig `yaml:"connection" json:"connection"`

	// Security contains security settings.
	Security SecurityConfig `yaml:"security" json:"security"`
}

Config contains mesh network configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a mesh configuration with sensible defaults.

func (*Config) NetworkPrefix

func (c *Config) NetworkPrefix() (netip.Prefix, error)

NetworkPrefix returns the parsed network prefix.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the mesh configuration.

type ConnectionConfig

type ConnectionConfig struct {
	// DirectConnect controls whether to attempt direct P2P connections (default: true).
	DirectConnect bool `yaml:"direct_connect" json:"direct_connect"`

	// RelayEnabled controls whether to use relay when direct fails (default: true).
	RelayEnabled bool `yaml:"relay_enabled" json:"relay_enabled"`

	// RelayViaPeers controls whether to relay through other peers (default: true).
	RelayViaPeers bool `yaml:"relay_via_peers" json:"relay_via_peers"`

	// ConnectTimeout is the timeout for establishing connections (default: 30s).
	ConnectTimeout time.Duration `yaml:"connect_timeout" json:"connect_timeout"`

	// KeepAliveInterval is the interval for keep-alive packets (default: 25s).
	KeepAliveInterval time.Duration `yaml:"keep_alive_interval" json:"keep_alive_interval"`
}

ConnectionConfig contains P2P connection settings.

type ConnectionType

type ConnectionType string

ConnectionType represents how a peer is connected.

const (
	// ConnectionTypeDirect means direct P2P connection.
	ConnectionTypeDirect ConnectionType = "direct"

	// ConnectionTypeRelayed means connection through a TURN server.
	ConnectionTypeRelayed ConnectionType = "relayed"

	// ConnectionTypeMultiHop means connection through other peers.
	ConnectionTypeMultiHop ConnectionType = "multi_hop"
)

type DeviceConfig

type DeviceConfig struct {
	// Type is the device type: "tun" (Layer 3) or "tap" (Layer 2).
	Type string `yaml:"type" json:"type"`

	// Name is the interface name (e.g., "mesh0").
	Name string `yaml:"name" json:"name"`

	// MTU is the Maximum Transmission Unit (default: 1400).
	MTU int `yaml:"mtu" json:"mtu"`

	// MACAddress is the MAC address for TAP devices (auto-generated if empty).
	MACAddress string `yaml:"mac_address,omitempty" json:"mac_address,omitempty"`
}

DeviceConfig contains network device settings for mesh networking.

func (*DeviceConfig) ToDeviceConfig

func (c *DeviceConfig) ToDeviceConfig(address string) device.Config

ToDeviceConfig converts mesh device config to device.Config.

type DiscoveryClient

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

DiscoveryClient handles peer discovery through the central server.

func NewDiscoveryClient

func NewDiscoveryClient(config DiscoveryConfig, networkID string, localPeer *Peer, registry *PeerRegistry) *DiscoveryClient

NewDiscoveryClient creates a new discovery client.

func (*DiscoveryClient) Events

func (c *DiscoveryClient) Events() <-chan PeerEvent

Events returns the channel for peer events.

func (*DiscoveryClient) IsConnected

func (c *DiscoveryClient) IsConnected() bool

IsConnected returns whether the client is connected to the discovery server.

func (*DiscoveryClient) ListPeers

func (c *DiscoveryClient) ListPeers() ([]PeerInfo, error)

ListPeers retrieves all peers from the discovery server.

func (*DiscoveryClient) Start

func (c *DiscoveryClient) Start(ctx context.Context) error

Start starts the discovery client.

func (*DiscoveryClient) Stop

func (c *DiscoveryClient) Stop() error

Stop stops the discovery client.

func (*DiscoveryClient) UpdateEndpoints

func (c *DiscoveryClient) UpdateEndpoints(endpoints []Endpoint) error

UpdateEndpoints updates this peer's endpoints on the discovery server.

type DiscoveryConfig

type DiscoveryConfig struct {
	// Server is the discovery server address (e.g., "bifrost.example.com:8080").
	Server string `yaml:"server" json:"server"`

	// HeartbeatInterval is how often to send heartbeats (default: 30s).
	HeartbeatInterval time.Duration `yaml:"heartbeat_interval" json:"heartbeat_interval"`

	// PeerTimeout is how long before a peer is considered offline (default: 90s).
	PeerTimeout time.Duration `yaml:"peer_timeout" json:"peer_timeout"`

	// Token is the authentication token for the discovery server.
	Token string `yaml:"token,omitempty" json:"token,omitempty"`
}

DiscoveryConfig contains peer discovery settings.

type Endpoint

type Endpoint struct {
	// Address is the IP address or hostname.
	Address string `json:"address"`

	// Port is the port number.
	Port uint16 `json:"port"`

	// Type is the endpoint type: "local", "reflexive", "relay".
	Type string `json:"type"`

	// Priority is used for endpoint selection.
	Priority int `json:"priority"`
}

Endpoint represents a network endpoint for a peer.

type EthernetBroadcastHandler

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

EthernetBroadcastHandler handles Ethernet broadcast frames for TAP devices.

func NewEthernetBroadcastHandler

func NewEthernetBroadcastHandler(manager *BroadcastManager) *EthernetBroadcastHandler

NewEthernetBroadcastHandler creates a new Ethernet broadcast handler.

func (*EthernetBroadcastHandler) HandleFrame

func (h *EthernetBroadcastHandler) HandleFrame(dstMAC net.HardwareAddr, frame []byte) error

HandleFrame handles an Ethernet broadcast/multicast frame.

type ForwardingEntry

type ForwardingEntry struct {
	DestIP    netip.Prefix
	NextHopIP netip.Addr
	Interface string
	Metric    int
}

ForwardingEntry represents an entry in the forwarding table.

type HelloAckMessage

type HelloAckMessage struct {
	PeerID       string     `json:"peer_id"`
	VirtualIP    netip.Addr `json:"virtual_ip"`
	RequestTime  time.Time  `json:"request_time"`
	ResponseTime time.Time  `json:"response_time"`
}

HelloAckMessage acknowledges a hello.

type HelloMessage

type HelloMessage struct {
	PeerID    string     `json:"peer_id"`
	VirtualIP netip.Addr `json:"virtual_ip"`
	Timestamp time.Time  `json:"timestamp"`
	Neighbors []string   `json:"neighbors,omitempty"`
}

HelloMessage is a periodic keepalive.

type IPAllocator

type IPAllocator interface {
	// Allocate allocates an IP address for a peer.
	Allocate(peerID string) (netip.Addr, error)

	// AllocateSpecific allocates a specific IP address for a peer.
	AllocateSpecific(peerID string, addr netip.Addr) error

	// Release releases an IP address allocation.
	Release(peerID string) error

	// GetIP returns the IP address for a peer.
	GetIP(peerID string) (netip.Addr, bool)

	// GetPeer returns the peer ID for an IP address.
	GetPeer(addr netip.Addr) (string, bool)

	// Available returns the number of available addresses.
	Available() int

	// Used returns the number of used addresses.
	Used() int
}

IPAllocator manages virtual IP address allocation for a mesh network.

type Lease

type Lease struct {
	PeerID    string     `json:"peer_id"`
	Address   netip.Addr `json:"address"`
	Allocated time.Time  `json:"allocated"`
	Expires   time.Time  `json:"expires,omitempty"`
	Static    bool       `json:"static"`
}

Lease represents an IP address lease.

func (*Lease) TTL

func (l *Lease) TTL() time.Duration

TTL returns the remaining time-to-live for the lease.

type LinkInfo

type LinkInfo struct {
	NeighborID string        `json:"neighbor_id"`
	Latency    time.Duration `json:"latency"`
	State      string        `json:"state"` // up, down, degraded
}

LinkInfo describes a link to a neighbor.

type LinkStateUpdate

type LinkStateUpdate struct {
	PeerID    string     `json:"peer_id"`
	SeqNum    uint64     `json:"seq_num"`
	Links     []LinkInfo `json:"links"`
	Timestamp time.Time  `json:"timestamp"`
}

LinkStateUpdate contains link state information.

type MeshNode

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

MeshNode is the central orchestrator that ties all mesh networking components together.

func NewMeshNode

func NewMeshNode(config Config) (*MeshNode, error)

NewMeshNode creates a new mesh node with the given configuration.

func (*MeshNode) GetConnectedPeers

func (n *MeshNode) GetConnectedPeers() []*Peer

GetConnectedPeers returns all connected peers.

func (*MeshNode) GetPeer

func (n *MeshNode) GetPeer(peerID string) (*Peer, bool)

GetPeer returns a peer by ID.

func (*MeshNode) GetPeers

func (n *MeshNode) GetPeers() []*Peer

GetPeers returns all known peers.

func (*MeshNode) GetRoutes

func (n *MeshNode) GetRoutes() []*Route

GetRoutes returns the routing table.

func (*MeshNode) LocalIP

func (n *MeshNode) LocalIP() netip.Addr

LocalIP returns the local virtual IP.

func (*MeshNode) LocalPeerID

func (n *MeshNode) LocalPeerID() string

LocalPeerID returns the local peer ID.

func (*MeshNode) Start

func (n *MeshNode) Start(ctx context.Context) error

Start starts the mesh node and all its components.

func (*MeshNode) Stats

func (n *MeshNode) Stats() NodeStats

Stats returns current node statistics.

func (*MeshNode) Status

func (n *MeshNode) Status() NodeStatus

Status returns the current node status.

func (*MeshNode) Stop

func (n *MeshNode) Stop() error

Stop stops the mesh node and all its components.

type MeshRouter

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

MeshRouter manages the mesh routing table.

func NewMeshRouter

func NewMeshRouter(config RouterConfig) *MeshRouter

NewMeshRouter creates a new mesh router.

func (*MeshRouter) AddDirectRoute

func (r *MeshRouter) AddDirectRoute(peerID string, peerIP netip.Addr, latency time.Duration)

AddDirectRoute adds a direct route to a peer.

func (*MeshRouter) AddRoute

func (r *MeshRouter) AddRoute(route *Route)

AddRoute adds or updates a route.

func (*MeshRouter) ExpireRoutes

func (r *MeshRouter) ExpireRoutes()

ExpireRoutes removes stale routes.

func (*MeshRouter) GetAllRoutes

func (r *MeshRouter) GetAllRoutes() []*Route

GetAllRoutes returns all routes.

func (*MeshRouter) GetBestRoutes

func (r *MeshRouter) GetBestRoutes() []*Route

GetBestRoutes returns the best route to each destination.

func (*MeshRouter) GetDirectPeers

func (r *MeshRouter) GetDirectPeers() []string

GetDirectPeers returns all directly connected peers.

func (*MeshRouter) GetForwardingTable

func (r *MeshRouter) GetForwardingTable() []ForwardingEntry

GetForwardingTable returns the forwarding table.

func (*MeshRouter) GetNextHop

func (r *MeshRouter) GetNextHop(destPeerID string) string

GetNextHop returns the next hop peer ID for a destination.

func (*MeshRouter) GetNextHopByIP

func (r *MeshRouter) GetNextHopByIP(ip netip.Addr) string

GetNextHopByIP returns the next hop peer ID for a virtual IP.

func (*MeshRouter) GetRoute

func (r *MeshRouter) GetRoute(peerID string) *Route

GetRoute returns the best route to a peer.

func (*MeshRouter) GetRouteByIP

func (r *MeshRouter) GetRouteByIP(ip netip.Addr) *Route

GetRouteByIP returns the route for a virtual IP.

func (*MeshRouter) GetStats

func (r *MeshRouter) GetStats() RouteTableStats

GetStats returns routing table statistics.

func (*MeshRouter) IsDirect

func (r *MeshRouter) IsDirect(peerID string) bool

IsDirect returns whether there's a direct route to a peer.

func (*MeshRouter) OnRouteChanged

func (r *MeshRouter) OnRouteChanged(callback func(*Route))

OnRouteChanged sets the route change callback.

func (*MeshRouter) RemoveDirectRoute

func (r *MeshRouter) RemoveDirectRoute(peerID string)

RemoveDirectRoute removes a direct route to a peer.

func (*MeshRouter) UpdateLatency

func (r *MeshRouter) UpdateLatency(peerID string, latency time.Duration)

UpdateLatency updates the latency for a direct route.

type MulticastGroup

type MulticastGroup struct {
	// ID is the group identifier.
	ID string

	// Name is the human-readable group name.
	Name string

	// Members are the peer IDs in the group.
	Members map[string]bool

	// JoinedAt is when this peer joined the group.
	JoinedAt time.Time
}

MulticastGroup represents a multicast group.

type NodeStats

type NodeStats struct {
	Status             NodeStatus    `json:"status"`
	PeerCount          int           `json:"peer_count"`
	ConnectedPeers     int           `json:"connected_peers"`
	DirectConnections  int           `json:"direct_connections"`
	RelayedConnections int           `json:"relayed_connections"`
	BytesSent          int64         `json:"bytes_sent"`
	BytesReceived      int64         `json:"bytes_received"`
	PacketsSent        int64         `json:"packets_sent"`
	PacketsReceived    int64         `json:"packets_received"`
	Uptime             time.Duration `json:"uptime"`
}

NodeStats contains mesh node statistics.

type NodeStatus

type NodeStatus string

NodeStatus represents the current status of the mesh node.

const (
	NodeStatusStopped  NodeStatus = "stopped"
	NodeStatusStarting NodeStatus = "starting"
	NodeStatusRunning  NodeStatus = "running"
	NodeStatusStopping NodeStatus = "stopping"
	NodeStatusError    NodeStatus = "error"
)

type PathCostFunc

type PathCostFunc func(latency time.Duration, hopCount int) int

PathCostFunc calculates the cost of a path.

type Peer

type Peer struct {
	// ID is the unique identifier for this peer.
	ID string `json:"id"`

	// Name is the friendly name for this peer.
	Name string `json:"name"`

	// VirtualIP is the virtual IP address assigned to this peer.
	VirtualIP netip.Addr `json:"virtual_ip"`

	// VirtualMAC is the virtual MAC address for TAP mode.
	VirtualMAC net.HardwareAddr `json:"virtual_mac,omitempty"`

	// PublicKey is the peer's Ed25519 public key (base64 encoded).
	PublicKey string `json:"public_key"`

	// Endpoints is the list of known endpoints for this peer.
	Endpoints []Endpoint `json:"endpoints"`

	// Status is the current connection status.
	Status PeerStatus `json:"status"`

	// ConnectionType is how we're connected to this peer.
	ConnectionType ConnectionType `json:"connection_type,omitempty"`

	// Latency is the measured latency to this peer.
	Latency time.Duration `json:"latency,omitempty"`

	// LastSeen is when we last saw activity from this peer.
	LastSeen time.Time `json:"last_seen"`

	// JoinedAt is when this peer joined the network.
	JoinedAt time.Time `json:"joined_at"`

	// Metadata contains arbitrary peer metadata.
	Metadata map[string]string `json:"metadata,omitempty"`

	// BytesSent is the number of bytes sent to this peer.
	BytesSent int64 `json:"bytes_sent"`

	// BytesReceived is the number of bytes received from this peer.
	BytesReceived int64 `json:"bytes_received"`
	// contains filtered or unexported fields
}

Peer represents a peer in the mesh network.

func NewPeer

func NewPeer(id, name string) *Peer

NewPeer creates a new peer with the given ID.

func (*Peer) AddBytesReceived

func (p *Peer) AddBytesReceived(n int64)

AddBytesReceived adds to the bytes received counter.

func (*Peer) AddBytesSent

func (p *Peer) AddBytesSent(n int64)

AddBytesSent adds to the bytes sent counter.

func (*Peer) AddEndpoint

func (p *Peer) AddEndpoint(endpoint Endpoint)

AddEndpoint adds an endpoint to the peer.

func (*Peer) ClearEndpoints

func (p *Peer) ClearEndpoints()

ClearEndpoints removes all endpoints.

func (*Peer) Clone

func (p *Peer) Clone() *Peer

Clone creates a copy of the peer.

func (*Peer) GetEndpoints

func (p *Peer) GetEndpoints() []Endpoint

GetEndpoints returns a copy of all endpoints.

func (*Peer) GetMetadata

func (p *Peer) GetMetadata(key string) (string, bool)

GetMetadata gets a metadata value.

func (*Peer) IsConnected

func (p *Peer) IsConnected() bool

IsConnected returns true if the peer is connected (directly or via relay).

func (*Peer) IsReachable

func (p *Peer) IsReachable() bool

IsReachable returns true if the peer might be reachable.

func (*Peer) RemoveEndpoint

func (p *Peer) RemoveEndpoint(address string, port uint16)

RemoveEndpoint removes an endpoint from the peer.

func (*Peer) SetConnectionType

func (p *Peer) SetConnectionType(connType ConnectionType)

SetConnectionType sets how we're connected to this peer.

func (*Peer) SetLatency

func (p *Peer) SetLatency(latency time.Duration)

SetLatency sets the measured latency.

func (*Peer) SetMetadata

func (p *Peer) SetMetadata(key, value string) bool

SetMetadata sets a metadata value. Returns false if the key/value exceeds limits or max keys reached.

func (*Peer) SetStatus

func (p *Peer) SetStatus(status PeerStatus)

SetStatus sets the peer's connection status.

func (*Peer) SetVirtualIP

func (p *Peer) SetVirtualIP(ip netip.Addr)

SetVirtualIP sets the peer's virtual IP address.

func (*Peer) SetVirtualMAC

func (p *Peer) SetVirtualMAC(mac net.HardwareAddr)

SetVirtualMAC sets the peer's virtual MAC address.

func (*Peer) UpdateLastSeen

func (p *Peer) UpdateLastSeen()

UpdateLastSeen updates the last seen timestamp.

type PeerEvent

type PeerEvent struct {
	Type      string    `json:"type"` // "join", "leave", "update"
	Peer      PeerInfo  `json:"peer"`
	Timestamp time.Time `json:"timestamp"`
}

PeerEvent represents a peer-related event from the discovery server.

type PeerInfo

type PeerInfo struct {
	ID        string            `json:"id"`
	Name      string            `json:"name"`
	PublicKey string            `json:"public_key"`
	VirtualIP string            `json:"virtual_ip,omitempty"`
	Endpoints []Endpoint        `json:"endpoints,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

PeerInfo is the peer information exchanged with the discovery server.

type PeerRegistry

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

PeerRegistry manages all known peers in a mesh network.

func NewPeerRegistry

func NewPeerRegistry() *PeerRegistry

NewPeerRegistry creates a new peer registry.

func (*PeerRegistry) Add

func (r *PeerRegistry) Add(peer *Peer)

Add adds a peer to the registry.

func (*PeerRegistry) All

func (r *PeerRegistry) All() []*Peer

All returns all peers.

func (*PeerRegistry) Clear

func (r *PeerRegistry) Clear()

Clear removes all peers.

func (*PeerRegistry) Connected

func (r *PeerRegistry) Connected() []*Peer

Connected returns all connected peers.

func (*PeerRegistry) Count

func (r *PeerRegistry) Count() int

Count returns the number of peers.

func (*PeerRegistry) Get

func (r *PeerRegistry) Get(id string) (*Peer, bool)

Get returns a peer by ID.

func (*PeerRegistry) GetByIP

func (r *PeerRegistry) GetByIP(ip netip.Addr) (*Peer, bool)

GetByIP returns a peer by virtual IP.

func (*PeerRegistry) GetByMAC

func (r *PeerRegistry) GetByMAC(mac net.HardwareAddr) (*Peer, bool)

GetByMAC returns a peer by virtual MAC.

func (*PeerRegistry) Remove

func (r *PeerRegistry) Remove(id string)

Remove removes a peer from the registry.

func (*PeerRegistry) UpdatePeerIP

func (r *PeerRegistry) UpdatePeerIP(peer *Peer, newIP netip.Addr)

UpdatePeerIP updates the IP index when a peer's IP changes.

func (*PeerRegistry) UpdatePeerMAC

func (r *PeerRegistry) UpdatePeerMAC(peer *Peer, newMAC net.HardwareAddr)

UpdatePeerMAC updates the MAC index when a peer's MAC changes.

type PeerStatus

type PeerStatus string

PeerStatus represents the connection status of a peer.

const (
	// PeerStatusDiscovered means the peer was found but not yet connected.
	PeerStatusDiscovered PeerStatus = "discovered"

	// PeerStatusConnecting means a connection is being established.
	PeerStatusConnecting PeerStatus = "connecting"

	// PeerStatusConnected means the peer is directly connected.
	PeerStatusConnected PeerStatus = "connected"

	// PeerStatusRelayed means the peer is connected via relay.
	PeerStatusRelayed PeerStatus = "relayed"

	// PeerStatusUnreachable means the peer cannot be reached.
	PeerStatusUnreachable PeerStatus = "unreachable"

	// PeerStatusOffline means the peer is offline.
	PeerStatusOffline PeerStatus = "offline"
)

type PoolAllocator

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

PoolAllocator allocates IP addresses from a pool.

func NewPoolAllocator

func NewPoolAllocator(config PoolConfig) (*PoolAllocator, error)

NewPoolAllocator creates a new IP pool allocator.

func (*PoolAllocator) Allocate

func (a *PoolAllocator) Allocate(peerID string) (netip.Addr, error)

Allocate allocates an IP address for a peer.

func (*PoolAllocator) AllocateSpecific

func (a *PoolAllocator) AllocateSpecific(peerID string, addr netip.Addr) error

AllocateSpecific allocates a specific IP address for a peer.

func (*PoolAllocator) Available

func (a *PoolAllocator) Available() int

Available returns the number of available addresses.

func (*PoolAllocator) Expire

func (a *PoolAllocator) Expire() int

Expire removes expired leases.

func (*PoolAllocator) GetAllLeases

func (a *PoolAllocator) GetAllLeases() []Lease

GetAllLeases returns all current leases.

func (*PoolAllocator) GetIP

func (a *PoolAllocator) GetIP(peerID string) (netip.Addr, bool)

GetIP returns the IP address for a peer.

func (*PoolAllocator) GetPeer

func (a *PoolAllocator) GetPeer(addr netip.Addr) (string, bool)

GetPeer returns the peer ID for an IP address.

func (*PoolAllocator) Prefix

func (a *PoolAllocator) Prefix() netip.Prefix

Prefix returns the network prefix.

func (*PoolAllocator) Release

func (a *PoolAllocator) Release(peerID string) error

Release releases an IP address allocation.

func (*PoolAllocator) Renew

func (a *PoolAllocator) Renew(peerID string) error

Renew renews a lease for a peer.

func (*PoolAllocator) StartExpiryWorker

func (a *PoolAllocator) StartExpiryWorker(interval time.Duration, stopCh <-chan struct{})

StartExpiryWorker starts a background goroutine that periodically expires old leases.

func (*PoolAllocator) Used

func (a *PoolAllocator) Used() int

Used returns the number of used addresses.

type PoolConfig

type PoolConfig struct {
	// NetworkCIDR is the network CIDR (e.g., "10.100.0.0/16").
	NetworkCIDR string

	// GatewayAddress is the gateway IP (usually first usable address).
	// If empty, it won't be reserved.
	GatewayAddress string

	// LeaseTTL is the lease duration (0 = no expiry).
	LeaseTTL time.Duration

	// ReservedAddresses is a list of additional addresses to reserve.
	ReservedAddresses []string
}

PoolConfig contains IP pool configuration.

type ProtocolConfig

type ProtocolConfig struct {
	// HelloInterval is the interval between hello messages.
	HelloInterval time.Duration

	// RouteAnnounceInterval is the interval between route announcements.
	RouteAnnounceInterval time.Duration

	// RouteExpiryInterval is the route expiry check interval.
	RouteExpiryInterval time.Duration

	// DefaultTTL is the default TTL for messages.
	DefaultTTL int

	// MaxRouteAge is the maximum age of a route before expiry.
	MaxRouteAge time.Duration

	// SplitHorizon enables split horizon (don't announce routes back to source).
	SplitHorizon bool

	// PoisonReverse enables poison reverse (announce withdrawn routes with infinite metric).
	PoisonReverse bool
}

ProtocolConfig contains routing protocol configuration.

func DefaultProtocolConfig

func DefaultProtocolConfig() ProtocolConfig

DefaultProtocolConfig returns a default protocol configuration.

type ProtocolMessage

type ProtocolMessage struct {
	Type      ProtocolMessageType `json:"type"`
	SrcPeerID string              `json:"src_peer_id"`
	SeqNum    uint64              `json:"seq_num"`
	TTL       int                 `json:"ttl"`
	Timestamp time.Time           `json:"timestamp"`
	Payload   json.RawMessage     `json:"payload,omitempty"`
}

ProtocolMessage is the base protocol message.

type ProtocolMessageType

type ProtocolMessageType byte

ProtocolMessageType represents the type of protocol message.

const (
	// MsgTypeRouteAnnounce announces routes to neighbors.
	MsgTypeRouteAnnounce ProtocolMessageType = iota + 1

	// MsgTypeRouteRequest requests routes from neighbors.
	MsgTypeRouteRequest

	// MsgTypeRouteWithdraw withdraws a previously announced route.
	MsgTypeRouteWithdraw

	// MsgTypeHello is a periodic hello/keepalive message.
	MsgTypeHello

	// MsgTypeHelloAck acknowledges a hello message.
	MsgTypeHelloAck

	// MsgTypeLinkState announces link state updates.
	MsgTypeLinkState
)

func (ProtocolMessageType) String

func (t ProtocolMessageType) String() string

String returns a human-readable string for the message type.

type RegistrationRequest

type RegistrationRequest struct {
	NetworkID string   `json:"network_id"`
	Peer      PeerInfo `json:"peer"`
}

RegistrationRequest is sent to register with the discovery server.

type RegistrationResponse

type RegistrationResponse struct {
	Success   bool       `json:"success"`
	VirtualIP string     `json:"virtual_ip"`
	Message   string     `json:"message,omitempty"`
	Peers     []PeerInfo `json:"peers,omitempty"`
}

RegistrationResponse is received from the discovery server.

type Route

type Route struct {
	// DestPeerID is the destination peer ID.
	DestPeerID string

	// DestIP is the destination virtual IP.
	DestIP netip.Addr

	// NextHop is the next hop peer ID (empty for direct routes).
	NextHop string

	// Type is the route type.
	Type RouteType

	// Metric is the route cost (lower is better).
	Metric int

	// Latency is the measured latency.
	Latency time.Duration

	// HopCount is the number of hops.
	HopCount int

	// LastUpdated is when the route was last updated.
	LastUpdated time.Time

	// Active indicates if the route is currently active.
	Active bool
}

Route represents a route to a peer.

type RouteAnnouncement

type RouteAnnouncement struct {
	DestPeerID string     `json:"dest_peer_id"`
	DestIP     netip.Addr `json:"dest_ip"`
	Metric     int        `json:"metric"`
	HopCount   int        `json:"hop_count"`
	Path       []string   `json:"path,omitempty"` // For loop prevention
}

RouteAnnouncement contains route information.

type RouteTableStats

type RouteTableStats struct {
	TotalRoutes   int
	DirectRoutes  int
	NextHopRoutes int
	RelayRoutes   int
	Destinations  int
}

RouteTableStats contains routing table statistics.

type RouteType

type RouteType int

RouteType represents the type of route.

const (
	// RouteTypeDirect is a direct route to a peer.
	RouteTypeDirect RouteType = iota

	// RouteTypeNextHop is a route through another peer.
	RouteTypeNextHop

	// RouteTypeRelay is a route through a relay.
	RouteTypeRelay
)

func (RouteType) String

func (t RouteType) String() string

String returns a human-readable string for the route type.

type RouteWithdrawal

type RouteWithdrawal struct {
	DestPeerID string `json:"dest_peer_id"`
}

RouteWithdrawal indicates a route is no longer available.

type RouterConfig

type RouterConfig struct {
	// LocalPeerID is the local peer ID.
	LocalPeerID string

	// LocalIP is the local virtual IP.
	LocalIP netip.Addr

	// MaxHops is the maximum number of hops.
	MaxHops int

	// RouteTimeout is the route expiry timeout.
	RouteTimeout time.Duration

	// PathCostFunc calculates path costs.
	PathCostFunc PathCostFunc
}

RouterConfig contains router configuration.

func DefaultRouterConfig

func DefaultRouterConfig() RouterConfig

DefaultRouterConfig returns a default router configuration.

type RoutingProtocol

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

RoutingProtocol manages the mesh routing protocol.

func NewRoutingProtocol

func NewRoutingProtocol(localPeerID string, localIP netip.Addr, router *MeshRouter, config ProtocolConfig) *RoutingProtocol

NewRoutingProtocol creates a new routing protocol handler.

func (*RoutingProtocol) HandleMessage

func (p *RoutingProtocol) HandleMessage(fromPeerID string, data []byte) error

HandleMessage handles an incoming protocol message.

func (*RoutingProtocol) NotifyPeerConnected

func (p *RoutingProtocol) NotifyPeerConnected(peerID string, peerIP netip.Addr, latency time.Duration)

NotifyPeerConnected notifies the protocol of a new peer connection.

func (*RoutingProtocol) NotifyPeerDisconnected

func (p *RoutingProtocol) NotifyPeerDisconnected(peerID string)

NotifyPeerDisconnected notifies the protocol of a peer disconnection.

func (*RoutingProtocol) SetSendFunc

func (p *RoutingProtocol) SetSendFunc(sendFunc func(peerID string, msg []byte) error)

SetSendFunc sets the function used to send messages to peers.

func (*RoutingProtocol) Start

func (p *RoutingProtocol) Start() error

Start starts the routing protocol.

func (*RoutingProtocol) Stop

func (p *RoutingProtocol) Stop() error

Stop stops the routing protocol.

func (*RoutingProtocol) WithdrawRoute

func (p *RoutingProtocol) WithdrawRoute(destPeerID string)

WithdrawRoute withdraws a route from neighbors.

type STUNConfig

type STUNConfig struct {
	// Servers is a list of STUN server addresses.
	Servers []string `yaml:"servers" json:"servers"`

	// Timeout is the timeout for STUN requests (default: 5s).
	Timeout time.Duration `yaml:"timeout" json:"timeout"`
}

STUNConfig contains STUN server configuration.

type SecurityConfig

type SecurityConfig struct {
	// PrivateKey is the Ed25519 private key for this peer (base64 encoded).
	// If empty, a new key pair will be generated.
	PrivateKey string `yaml:"private_key,omitempty" json:"private_key,omitempty"`

	// AllowedPeers is a list of allowed peer public keys (empty = allow all).
	AllowedPeers []string `yaml:"allowed_peers,omitempty" json:"allowed_peers,omitempty"`

	// RequireEncryption controls whether all connections must be encrypted (default: true).
	RequireEncryption bool `yaml:"require_encryption" json:"require_encryption"`
}

SecurityConfig contains security settings.

type TURNConfig

type TURNConfig struct {
	// Servers is a list of TURN server configurations.
	Servers []TURNServer `yaml:"servers" json:"servers"`

	// Enabled controls whether TURN relay is enabled (default: true).
	Enabled bool `yaml:"enabled" json:"enabled"`
}

TURNConfig contains TURN server configuration.

type TURNServer

type TURNServer struct {
	// URL is the TURN server URL (e.g., "turn:turn.example.com:3478").
	URL string `yaml:"url" json:"url"`

	// Username for TURN authentication.
	Username string `yaml:"username" json:"username"`

	// Password for TURN authentication.
	Password string `yaml:"password" json:"password"`
}

TURNServer contains a single TURN server configuration.

Jump to

Keyboard shortcuts

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