network

package
v0.1.0-rc.4 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 45 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package network owns the go-libp2p host and the G2 network capabilities: TCP/QUIC transports, Circuit Relay v2 client/service, DCUtR, AutoNAT v2, the independent Raminga Kademlia DHT, AutoRelay, an in-memory PeerStore with a bounded SQLite hint cache, and resource limits.

The public library APIs are used directly. There is no UPnP/NAT-PMP, no STUN and no public IPFS bootstrap/DHT configuration path.

Index

Constants

View Source
const DefaultDialTimeout = 15 * time.Second

DefaultDialTimeout bounds one explicit dial.

Variables

This section is empty.

Functions

func PublishableAddrs

func PublishableAddrs(addrs []ma.Multiaddr) []ma.Multiaddr

PublishableAddrs returns the addresses Raminga publishes: public addresses plus circuit addresses (including circuits through private relay IPs). Content's friends.json uses this same predicate.

Types

type AutoNATStatus

type AutoNATStatus struct {
	Enabled      bool
	State        string
	LastChanged  time.Time
	ProbePeers   []string
	HasProbePeer bool
	UPNP         bool
	NATPMP       bool
	STUN         bool
}

AutoNATStatus reports the real libp2p reachability plus Raminga probe-peer availability. State is "unknown" whenever no Raminga probe peer is connected.

type CachedPeer

type CachedPeer struct {
	PeerID    string
	Addrs     []string
	Source    string
	UpdatedAt time.Time
	ExpiresAt time.Time
}

CachedPeer is one restart hint. ExpiresAt zero means no expiry.

type Config

type Config struct {
	PrivateKey      crypto.PrivKey
	ListenAddrs     []string
	AnnounceAddrs   []string
	PreferIPv6      bool
	UserAgent       string
	Logger          *slog.Logger
	EnableRelay     bool
	EnableDCUtR     bool
	DCUtRTimeout    time.Duration
	EnableAutoRelay bool
	EnableAutoNAT   bool
	Relay           RelayConfig
	DHT             DHTConfig
	Limits          ResourceLimits
	PeerCache       PeerCache
	PeerCacheTTL    time.Duration
	PeerCacheMax    int
	// HTTPRateLimitNow overrides the clock used by the per-peer HTTP token
	// buckets. Nil keeps time.Now; tests inject a deterministic clock.
	HTTPRateLimitNow func() time.Time
	// PausedPeers seeds the in-memory pause set from persisted paused_peers.
	PausedPeers []string
	// Paused is the in-memory predicate; New replaces it with its own set.
	Paused func(peer.ID) bool
}

Config constructs a Network.

type ConnInfo

type ConnInfo struct {
	PeerID      string
	RemoteAddr  string
	LocalAddr   string
	Direction   string
	Transport   string
	Route       string
	RelayPeerID string
	Direct      bool
	Limited     bool
	OpenedAt    time.Time
}

ConnInfo is a snapshot of one connection.

type DCUtRPeer

type DCUtRPeer struct {
	PeerID             string
	Status             string
	Attempts           int
	Successes          int
	Failures           int
	CandidateAddresses []string
	DirectAddress      string
	DirectTransport    string
	RelayAddress       string
	Error              string
	UpdatedAt          time.Time
}

DCUtRPeer is per-peer DCUtR state. Attempts are never reported as success.

type DCUtRStatus

type DCUtRStatus struct {
	Enabled   bool
	Attempts  int
	Successes int
	Failures  int
	Peers     []DCUtRPeer
	Events    []HolePunchEvent
}

DCUtRStatus is a snapshot of the public hole-punch tracer.

type DHT

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

DHT wraps go-libp2p-kad-dht with a fixed Raminga prefix and no public bootstrap defaults.

func NewDHT

func NewDHT(h host.Host, cfg DHTConfig, relay func(peer.AddrInfo) bool, logger *slog.Logger) (*DHT, error)

func (*DHT) AddBootstrapPeer

func (d *DHT) AddBootstrapPeer(ctx context.Context, info peer.AddrInfo)

AddBootstrapPeer applies a newly saved role to the live DHT. It adds the address to the PeerStore and makes one real bootstrap dial in the background; callers return after persistence and never treat dial success as save success. Paused peers are not dialed.

func (*DHT) AddPeer

func (d *DHT) AddPeer(_ context.Context, raw string) (DHTPeer, error)

AddPeer performs a manual PeerStore add with a persistent hint.

func (*DHT) AddressesFromDHT

func (d *DHT) AddressesFromDHT(ctx context.Context, pid peer.ID) ([]string, error)

AddressesFromDHT reads and validates one signed address record, filters unusable addresses and caps the result at 16.

func (*DHT) Close

func (d *DHT) Close() error

func (*DHT) FindPeer

func (d *DHT) FindPeer(ctx context.Context, pid peer.ID) DHTPeer

func (*DHT) ProtocolID

func (d *DHT) ProtocolID() string

SetRelayCandidateCount is filled by Network.Status.

func (*DHT) RefreshBootstrap

func (d *DHT) RefreshBootstrap(ctx context.Context)

RefreshBootstrap asks the DHT to refresh from the current live list (used after removing a role). It never dials a removed peer.

func (*DHT) Start

func (d *DHT) Start(ctx context.Context) error

func (*DHT) Status

func (d *DHT) Status() DHTStatus

Status returns DHT diagnostics, including discovery failures.

type DHTConfig

type DHTConfig struct {
	Enabled        bool
	Mode           string
	ProtocolPrefix string
	BootstrapPeers []string
	// BootstrapPeersFunc, when set, is the live operator-managed bootstrap
	// role list. It lets add/remove take effect without rebuilding the DHT.
	// The function returns complete multiaddrs including /p2p/<peer-id>.
	BootstrapPeersFunc func() []string
	RefreshInterval    time.Duration
	QueryTimeout       time.Duration
	MaxRecords         int
	// Paused reports a persistent local pause; paused bootstrap peers are not
	// seeded or dialled by this package.
	Paused func(peer.ID) bool
}

DHTConfig configures the independent Raminga Kademlia DHT.

type DHTPeer

type DHTPeer struct {
	PeerID  string
	Addrs   []string
	Found   bool
	Source  string
	Error   string
	Elapsed time.Duration
}

DHTPeer is one peer address result.

type DHTStatus

type DHTStatus struct {
	Enabled bool
	// Mode is the mode configured in config.toml: client, server or auto.
	Mode string
	// ActiveMode is the mode the host is actually serving now: client, server,
	// unknown, or disabled. It is derived from registered stream handlers, not
	// from the configured value; libp2p's Mode() returns the configured option.
	ActiveMode                string
	Protocol                  string
	BootstrapPeers            []string
	PublicBootstrapConfigured bool
	RoutingTablePeers         []string
	ConnectedPeers            int
	BootstrapConnected        int
	RelayCandidates           int
	LastBootstrapAt           time.Time
	LastRefreshAt             time.Time
	LastError                 string
	LastLookup                DHTPeer
	LastPublishAt             time.Time
	LastPublishError          string
}

DHTStatus is a point-in-time diagnostic view.

type DialAttempt

type DialAttempt struct {
	Multiaddr string
	Source    string
	Family    string
	OK        bool
	Error     string
	Backoff   bool
	Note      string
}

DialAttempt is one candidate address dialed for a peer. It is exposed through the local API so callers can see which family/address worked or failed.

type DialOutcome

type DialOutcome struct {
	ConnInfo
	Reused             bool
	RequestedTransport string
	TransportChanged   bool
	Source             string
	Attempts           []DialAttempt
	Note               string
}

DialOutcome is the result of dialing one peer. Reused is true when an already-open connection was returned without a new dial.

type HolePunchEvent

type HolePunchEvent struct {
	Timestamp   string
	Type        string
	PeerID      string
	Success     *bool
	Error       string
	RemoteAddrs []string
	Attempt     int
	RTTMs       float64
	ElapsedMs   float64
}

HolePunchEvent is a JSON-safe copy of a go-libp2p holepunch.Event.

type HolePunchTracer

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

HolePunchTracer implements holepunch.EventTracer and records only the events exposed by go-libp2p's public tracer API. A watchdog turns an attempt that never receives a terminal event into a bounded failure with a reason, so a relay-only peer cannot linger at attempts=1 successes=0 failures=0.

func NewHolePunchTracer

func NewHolePunchTracer(watchdog time.Duration) *HolePunchTracer

NewHolePunchTracer creates a tracer. watchdog <= 0 defaults to 20 seconds.

func (*HolePunchTracer) Snapshot

func (t *HolePunchTracer) Snapshot() DCUtRStatus

Snapshot returns a copy for status/evidence.

func (*HolePunchTracer) Trace

func (t *HolePunchTracer) Trace(event *holepunch.Event)

type Network

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

Network wraps the go-libp2p host.

func New

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

New creates the host and the static address/relay-candidate state. Start must be called to launch relay reservations, DHT and reachability tracking.

func (*Network) AddPeer

func (n *Network) AddPeer(ctx context.Context, raw, source string) (PeerEntry, error)

AddPeer adds a peer multiaddr to the in-memory PeerStore and SQLite hint cache. source is "manual", "bootstrap" or "known".

func (*Network) AddPeerHints

func (n *Network) AddPeerHints(pid peer.ID, addrs []ma.Multiaddr, ttl time.Duration)

RestorePeer seeds a friend's stored addresses into the in-memory PeerStore. AddPeerHints adds untrusted listed addresses with a temporary TTL. Reading a friend list never dials; an explicit ConnectListedPeer uses these hints.

func (*Network) AdvertisedAddrs

func (n *Network) AdvertisedAddrs() []string

AdvertisedAddrs returns the AddrsFactory output.

func (*Network) ApplyBootstrapPeer

func (n *Network) ApplyBootstrapPeer(ctx context.Context, info peer.AddrInfo)

ApplyBootstrapPeer applies an already validated and saved peer as one runtime update.

func (*Network) AutoNAT

func (n *Network) AutoNAT() AutoNATStatus

AutoNAT returns real reachability gated on Raminga probe peers.

func (*Network) Close

func (n *Network) Close() error

Close closes the DHT, relay manager, host and connections.

func (*Network) ConnInfo

func (n *Network) ConnInfo(c network.Conn) ConnInfo

ConnInfo snapshots an already-open libp2p connection.

func (*Network) Connect

func (n *Network) Connect(ctx context.Context, raw string) (ConnInfo, error)

Connect dials one explicit peer multiaddr, direct or relayed.

func (*Network) ConnectPeer

func (n *Network) ConnectPeer(ctx context.Context, pid peer.ID) (ConnInfo, error)

ConnectPeer dials peerID using the resolved PeerStore/cache/DHT candidates.

func (*Network) ConnectionInfo

func (n *Network) ConnectionInfo(pid peer.ID) (ConnInfo, error)

ConnectionInfo returns a snapshot for one peer.

func (*Network) Connections

func (n *Network) Connections() []ConnInfo

Connections returns one snapshot per current connection.

func (*Network) DCUtR

func (n *Network) DCUtR() DCUtRStatus

DCUtR returns the public tracer snapshot.

func (*Network) DHT

func (n *Network) DHT() *DHT

DHT returns the DHT facade.

func (*Network) DialContactCard

func (n *Network) DialContactCard(ctx context.Context, pid peer.ID, addrs []ma.Multiaddr, temporary bool) (DialOutcome, error)

func (*Network) DialMultiaddr

func (n *Network) DialMultiaddr(ctx context.Context, raw string) (DialOutcome, error)

DialMultiaddr dials one explicit multiaddr. It does not append PeerStore or DHT candidates: an explicit target is expected to fail honestly if that path is blocked.

func (*Network) DialPeerByID

func (n *Network) DialPeerByID(ctx context.Context, pid peer.ID) (DialOutcome, error)

DialPeerByID dials a peer using addresses from the in-memory PeerStore, the SQLite hint cache and the Raminga DHT. The swarm staggers direct and relay dials and returns the first connection that succeeds.

func (*Network) Disconnect

func (n *Network) Disconnect(pid peer.ID) error

Disconnect closes all connections to a peer.

func (*Network) HTTPClient

func (n *Network) HTTPClient() *p2phttp.Client

HTTPClient is the HTTP-over-libp2p client. Its dial helper uses DialPeerByID, so address fallback and the pause gater stay in one path.

func (*Network) HTTPHandler

func (n *Network) HTTPHandler() *http.ServeMux

HTTPHandler is the mux served on /raminga/http/1.0.0. Chat/content routes can be registered here; the base layer only exposes GET /healthz.

func (*Network) HTTPLimiter

func (n *Network) HTTPLimiter(next http.Handler) http.Handler

HTTPLimiter applies the p2phttp per-peer rate limit to one route. The p2phttp server wrapper already applies per-peer/global concurrency limits.

func (*Network) Host

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

Host returns the underlying host for protocol stream registration.

func (*Network) IsPaused

func (n *Network) IsPaused(pid peer.ID) bool

IsPaused reports the in-memory pause state.

func (*Network) KnownPeerAddrs

func (n *Network) KnownPeerAddrs(pid peer.ID) []ma.Multiaddr

KnownPeerAddrs excludes unsigned hints that are still being tried. They become known addresses only if independently learned or authenticated.

func (*Network) ListenAddrs

func (n *Network) ListenAddrs() []string

ListenAddrs returns actual libp2p listen multiaddrs.

func (*Network) LocalPeerID

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

LocalPeerID returns this host's Peer ID.

func (*Network) MaybeAddConnectRelay

func (n *Network) MaybeAddConnectRelay(ctx context.Context, pid peer.ID) bool

MaybeAddConnectRelay adds a peer reached by a user connect as an AutoRelay candidate when it advertises Circuit Relay v2 hop support. Identify can lag a successful dial, so this waits on go-libp2p's public IdentifyWait with a short bound; it never polls or writes config.

func (*Network) NewStream

func (n *Network) NewStream(ctx context.Context, pid peer.ID, pidProto protocol.ID) (network.Stream, error)

NewStream opens a stream to a peer. Chat streams explicitly allow limited relay connections; go-libp2p refuses them by default.

func (*Network) OpenChatStream

func (n *Network) OpenChatStream(ctx context.Context, pid peer.ID, pidProto protocol.ID) (network.Stream, error)

OpenChatStream opens a stream and allows a limited Circuit Relay v2 connection. It is used only for the application protocol, never for control.

func (*Network) PausePeer

func (n *Network) PausePeer(pid peer.ID) error

PausePeer stops local relay/auto-relay work for a peer and closes its connections. The persisted pause is owned by the caller.

func (*Network) PeerCapabilities

func (n *Network) PeerCapabilities(ctx context.Context, pid peer.ID) (relay, dht bool)

PeerCapabilities reports relay-hop and Raminga-DHT protocol support. It waits for identify only when the peerstore does not know the protocols yet.

func (*Network) Peers

func (n *Network) Peers(ctx context.Context) ([]PeerEntry, error)

Peers merges live connections with cached restart hints. Cached entries are never marked online.

func (*Network) RegisterStreamHandler

func (n *Network) RegisterStreamHandler(pid protocol.ID, handler network.StreamHandler)

RegisterStreamHandler registers a libp2p stream handler.

func (*Network) RelayCandidates

func (n *Network) RelayCandidates() int

RelayCandidates returns the bounded AutoRelay candidate count.

func (*Network) RelayProvider

func (n *Network) RelayProvider() RelayProviderStatus

RelayProvider returns the provider quotas/status.

func (*Network) RelayReservations

func (n *Network) RelayReservations() []RelayReservation

RelayReservations returns the real client reservation states.

func (*Network) RemoveBootstrapPeer

func (n *Network) RemoveBootstrapPeer(pid peer.ID)

RemoveBootstrapPeer removes only the live bootstrap role. It does not drop the peer's addresses, connection, contact record or explicit pause; a later DHT refresh uses the updated source.

func (*Network) ResourceStatus

func (n *Network) ResourceStatus(ctx context.Context) ResourceStatus

ResourceStatus returns limits and current usage.

func (*Network) RestorePeer

func (n *Network) RestorePeer(pid peer.ID, addrs []string)

func (*Network) ResumePeer

func (n *Network) ResumePeer(pid peer.ID)

ResumePeer clears the in-memory pause before an explicit dial.

func (*Network) SeedPeer

func (n *Network) SeedPeer(raw, source string) error

SeedPeer adds a configured bootstrap/pinned peer before Start.

func (*Network) Start

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

Start launches relay reservations, the DHT and reachability tracking.

type PeerCache

type PeerCache interface {
	LoadPeerCache(ctx context.Context) ([]CachedPeer, error)
	UpsertPeerCache(ctx context.Context, peerID string, addrs []string, source string, ttl time.Duration, maxEntries int) error
	CountPeerCache(ctx context.Context) (int, error)
}

PeerCache is the small SQLite-backed hint cache owned by storage. The go-libp2p in-memory PeerStore remains the runtime source of truth.

type PeerEntry

type PeerEntry struct {
	PeerID        string
	Addrs         []string
	Sources       []string
	Online        bool
	Connectedness string
	Direction     string
	Route         string
	Transport     string
	Direct        bool
	Limited       bool
	RelayPeerID   string
	Paused        bool
	LastSeen      time.Time
}

PeerEntry merges current connections and restart hints. Online is true only for a currently connected peer; cached addresses never imply online.

type RelayCandidateSource

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

RelayCandidateSource is the bounded AutoRelay peer source. It is seeded from explicit config relays and later from Raminga DHT-discovered relay peers. AutoRelay calls PeerSource when it needs candidates.

func NewRelayCandidateSource

func NewRelayCandidateSource(max int) *RelayCandidateSource

NewRelayCandidateSource creates a bounded candidate set.

func (*RelayCandidateSource) Add

func (s *RelayCandidateSource) Add(info peer.AddrInfo, source string) bool

Add inserts or refreshes one candidate. source is "config", "dht" or "connect" for diagnostics. Existing order is preserved; new candidates append.

func (*RelayCandidateSource) PeerSource

func (s *RelayCandidateSource) PeerSource(ctx context.Context, num int) <-chan peer.AddrInfo

PeerSource implements autorelay.PeerSource.

func (*RelayCandidateSource) Remove

func (s *RelayCandidateSource) Remove(pid peer.ID)

Remove drops a candidate (used when a peer is paused).

func (*RelayCandidateSource) Snapshot

func (s *RelayCandidateSource) Snapshot() []peer.AddrInfo

Snapshot returns candidates in stable order.

func (*RelayCandidateSource) Sources

func (s *RelayCandidateSource) Sources() map[string]string

Sources returns peer ID -> source for diagnostics.

type RelayConfig

type RelayConfig struct {
	Provider                 bool
	KnownRelays              []string
	MaxReservations          int
	ReservationTTL           time.Duration
	MaxReservationsPerIP     int
	MaxReservationsPerPeer   int
	MaxCircuits              int
	ReservationDataLimit     int64
	ReservationDurationLimit time.Duration
	// OnReserve observes accepted reservation requests. It runs asynchronously
	// and must not block or change the allow/deny decision.
	OnReserve func(peer.ID, string)
	// Paused reports a persistent local pause.
	Paused func(peer.ID) bool
}

RelayConfig configures the Circuit Relay v2 client and provider.

type RelayProviderStatus

type RelayProviderStatus struct {
	Enabled                  bool
	MaxReservations          int
	ReservationTTL           time.Duration
	MaxReservationsPerIP     int
	MaxReservationsPerPeer   int
	MaxCircuits              int
	ReservationDataLimit     int64
	ReservationDurationLimit time.Duration
	Error                    string
}

RelayProviderStatus describes the optional relay service and its quotas. The public relay API does not expose per-reservation counters; quotas are enforced by go-libp2p's relay service.

type RelayReservation

type RelayReservation struct {
	RelayPeerID       string
	RelayAddr         string
	Status            string // connecting|reserving|active|failed|lost|stopped
	ReservationStatus string // active|failed|lost|none
	Attempts          int
	Successes         int
	Failures          int
	ExpiresAt         time.Time
	RelayedAddr       string
	AdvertisedAddr    string
	LimitDuration     time.Duration
	LimitData         uint64
	LastError         string
	UpdatedAt         time.Time
}

RelayReservation is the real reservation state observed from the relay client. Attempts/failures are tracked separately from successes.

type ResourceLimits

type ResourceLimits struct {
	MaxConnections int
	MaxStreams     int
	MaxMemoryBytes int64
	MaxFDs         int
}

ResourceLimits are the go-libp2p resource-manager limits exposed to config.

type ResourceStatus

type ResourceStatus struct {
	Limits          ResourceLimits
	OpenConnections int
	OpenStreams     int
	PeerstorePeers  int
	CacheEntries    int
	Goroutines      int
	HeapAllocBytes  int64
}

ResourceStatus is a point-in-time resource view.

Jump to

Keyboard shortcuts

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