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
- func PublishableAddrs(addrs []ma.Multiaddr) []ma.Multiaddr
- type AutoNATStatus
- type CachedPeer
- type Config
- type ConnInfo
- type DCUtRPeer
- type DCUtRStatus
- type DHT
- func (d *DHT) AddPeer(_ context.Context, raw string) (DHTPeer, error)
- func (d *DHT) AddressesFromDHT(ctx context.Context, pid peer.ID) ([]string, error)
- func (d *DHT) Close() error
- func (d *DHT) FindPeer(ctx context.Context, pid peer.ID) DHTPeer
- func (d *DHT) ProtocolID() string
- func (d *DHT) Start(ctx context.Context) error
- func (d *DHT) Status() DHTStatus
- type DHTConfig
- type DHTPeer
- type DHTStatus
- type DialAttempt
- type DialOutcome
- type HolePunchEvent
- type HolePunchTracer
- type Network
- func (n *Network) AddPeer(ctx context.Context, raw, source string) (PeerEntry, error)
- func (n *Network) AddPeerHints(pid peer.ID, addrs []ma.Multiaddr, ttl time.Duration)
- func (n *Network) AdvertisedAddrs() []string
- func (n *Network) AutoNAT() AutoNATStatus
- func (n *Network) Close() error
- func (n *Network) ConnInfo(c network.Conn) ConnInfo
- func (n *Network) Connect(ctx context.Context, raw string) (ConnInfo, error)
- func (n *Network) ConnectPeer(ctx context.Context, pid peer.ID) (ConnInfo, error)
- func (n *Network) ConnectionInfo(pid peer.ID) (ConnInfo, error)
- func (n *Network) Connections() []ConnInfo
- func (n *Network) DCUtR() DCUtRStatus
- func (n *Network) DHT() *DHT
- func (n *Network) DialMultiaddr(ctx context.Context, raw string) (DialOutcome, error)
- func (n *Network) DialPeerByID(ctx context.Context, pid peer.ID) (DialOutcome, error)
- func (n *Network) Disconnect(pid peer.ID) error
- func (n *Network) HTTPClient() *p2phttp.Client
- func (n *Network) HTTPHandler() *http.ServeMux
- func (n *Network) HTTPLimiter(next http.Handler) http.Handler
- func (n *Network) Host() host.Host
- func (n *Network) IsPaused(pid peer.ID) bool
- func (n *Network) ListenAddrs() []string
- func (n *Network) LocalPeerID() peer.ID
- func (n *Network) MaybeAddConnectRelay(ctx context.Context, pid peer.ID) bool
- func (n *Network) NewStream(ctx context.Context, pid peer.ID, pidProto protocol.ID) (network.Stream, error)
- func (n *Network) OpenChatStream(ctx context.Context, pid peer.ID, pidProto protocol.ID) (network.Stream, error)
- func (n *Network) PausePeer(pid peer.ID) error
- func (n *Network) PeerCapabilities(ctx context.Context, pid peer.ID) (relay, dht bool)
- func (n *Network) Peers(ctx context.Context) ([]PeerEntry, error)
- func (n *Network) RegisterStreamHandler(pid protocol.ID, handler network.StreamHandler)
- func (n *Network) RelayCandidates() int
- func (n *Network) RelayProvider() RelayProviderStatus
- func (n *Network) RelayReservations() []RelayReservation
- func (n *Network) ResourceStatus(ctx context.Context) ResourceStatus
- func (n *Network) RestorePeer(pid peer.ID, addrs []string)
- func (n *Network) ResumePeer(pid peer.ID)
- func (n *Network) SeedPeer(raw, source string) error
- func (n *Network) Start(ctx context.Context) error
- type PeerCache
- type PeerEntry
- type RelayCandidateSource
- func (s *RelayCandidateSource) Add(info peer.AddrInfo, source string) bool
- func (s *RelayCandidateSource) PeerSource(ctx context.Context, num int) <-chan peer.AddrInfo
- func (s *RelayCandidateSource) Remove(pid peer.ID)
- func (s *RelayCandidateSource) Snapshot() []peer.AddrInfo
- func (s *RelayCandidateSource) Sources() map[string]string
- type RelayConfig
- type RelayProviderStatus
- type RelayReservation
- type ResourceLimits
- type ResourceStatus
Constants ¶
const DefaultDialTimeout = 15 * time.Second
DefaultDialTimeout bounds one explicit dial.
Variables ¶
This section is empty.
Functions ¶
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
// 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 (*DHT) AddressesFromDHT ¶
AddressesFromDHT reads and validates one signed address record, filters unusable addresses and caps the result at 16.
func (*DHT) ProtocolID ¶
SetRelayCandidateCount is filled by Network.Status.
type DHTConfig ¶
type DHTConfig struct {
Enabled bool
Mode string
ProtocolPrefix string
BootstrapPeers []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 ¶
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 ¶
AddPeer adds a peer multiaddr to the in-memory PeerStore and SQLite hint cache. source is "manual", "bootstrap" or "known".
func (*Network) AddPeerHints ¶
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 ¶
AdvertisedAddrs returns the AddrsFactory output.
func (*Network) AutoNAT ¶
func (n *Network) AutoNAT() AutoNATStatus
AutoNAT returns real reachability gated on Raminga probe peers.
func (*Network) ConnectPeer ¶
ConnectPeer dials peerID using the resolved PeerStore/cache/DHT candidates.
func (*Network) ConnectionInfo ¶
ConnectionInfo returns a snapshot for one peer.
func (*Network) Connections ¶
Connections returns one snapshot per current connection.
func (*Network) DCUtR ¶
func (n *Network) DCUtR() DCUtRStatus
DCUtR returns the public tracer snapshot.
func (*Network) DialMultiaddr ¶
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 ¶
DialPeerByID dials a peer using addresses from the in-memory PeerStore, the SQLite hint cache and, when no address is known, the Raminga DHT. Candidates are ordered IPv6-first and each one is dialed separately so failures are reported with the address family that failed.
func (*Network) Disconnect ¶
Disconnect closes all connections to a peer.
func (*Network) HTTPClient ¶
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 ¶
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 ¶
HTTPLimiter applies the p2phttp per-peer rate limit to one route. The p2phttp server wrapper already applies per-peer/global concurrency limits.
func (*Network) ListenAddrs ¶
ListenAddrs returns actual libp2p listen multiaddrs.
func (*Network) LocalPeerID ¶
LocalPeerID returns this host's Peer ID.
func (*Network) MaybeAddConnectRelay ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) ResourceStatus ¶
func (n *Network) ResourceStatus(ctx context.Context) ResourceStatus
ResourceStatus returns limits and current usage.
func (*Network) ResumePeer ¶
ResumePeer clears the in-memory pause before an explicit dial.
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 ¶
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 ¶
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.