libp2p

package
v1.9.2 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: Apache-2.0, MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DHTOptions

type DHTOptions struct {
	// BootstrapPeers seeds the DHT routing table. Reuse the libp2p
	// host's bootstrap list for simplicity.
	BootstrapPeers []string
	// NetworkName is the Filecoin network identifier used to construct
	// the DHT protocol ID. Defaults to build.MainnetNetworkName.
	//
	// Why this matters: Filecoin's DHT protocol is
	// /fil/kad/<network>/kad/1.0.0 (e.g. /fil/kad/testnetnet/kad/1.0.0
	// on mainnet). A bare /fil/kad/1.0.0 client cannot peer with any
	// real Filecoin node — the protocol negotiation fails and the peer
	// gets evicted from the routing table. We pass
	// build.MainnetNetworkName here to match what Lotus and Forest
	// advertise.
	NetworkName string
	// RefreshInterval controls how often the background loop refreshes
	// the DHT routing table + reconnects to bootstrap peers if peer
	// count fell. Default 5 minutes.
	RefreshInterval time.Duration
	// TargetPeers is the floor below which the refresh loop tries
	// harder (re-bootstraps + dials more aggressively). Default 30.
	TargetPeers int

	// ClosestWalkInterval drives the fast loop that runs
	// dht.GetClosestPeers(self) to populate the routing table from
	// across the swarm. Default 5 minutes.
	ClosestWalkInterval time.Duration
	// DialWalkInterval drives the slower loop that walks the DHT
	// routing table and opportunistically dials peers we don't already
	// have a connection to, capped by the host's connmgr high-water.
	// Default 10 minutes.
	DialWalkInterval time.Duration
	// MaxDialsPerCycle caps the number of outbound dials a single
	// dial-walk cycle initiates. Default 25 — enough to grow the peer
	// set without thundering, and well below the connmgr trim trigger.
	MaxDialsPerCycle int
	// PerDialTimeout caps each outbound dial. Default 8 seconds.
	PerDialTimeout time.Duration
}

DHTOptions configures the Kademlia client.

type Host

type Host struct {
	H      host.Host
	PubSub *pubsub.PubSub

	// Phase 10: BandwidthCounter is the libp2p-standard metrics reporter
	// installed via libp2p.BandwidthReporter on construction. RPC's
	// NetBandwidthStats reads from this counter directly. Nil only when
	// HostConfig.DisableBandwidthCounter is set (used by tests).
	BW *metrics.BandwidthCounter
	// contains filtered or unexported fields
}

Host wraps a libp2p Host + GossipSub PubSub instance.

func New

func New(ctx context.Context, cfg HostConfig) (*Host, error)

New constructs and starts a libp2p Host and a GossipSub PubSub on it. The caller is responsible for calling Close().

func (*Host) AddCleanup

func (h *Host) AddCleanup(cb func())

AddCleanup registers a callback to fire on Close.

func (*Host) Close

func (h *Host) Close() error

Close shuts down the host. Subsequent PubSub publishes will fail.

func (*Host) ContentRouter

func (h *Host) ContentRouter() routing.ContentDiscovery

EnableDHT starts a Kademlia DHT in client mode on this host and runs a background refresh loop + V1.2.1 discovery walks. Safe to call once per Host.

The DHT itself is exposed via Host.kdht; most callers don't need it. The peer count is observable via Host.PeerCount(). ContentRouter returns the Kademlia DHT as a routing.ContentDiscovery for Bitswap provider lookups, or nil when no DHT is enabled (Bitswap then broadcasts WANT-HAVE to connected peers only, which is sufficient for the gossip-connected peer set). lantern#50.

func (*Host) EnableDHT

func (h *Host) EnableDHT(ctx context.Context, opts DHTOptions) error

func (*Host) ID

func (h *Host) ID() peer.ID

ID returns the libp2p peer ID of this node.

func (*Host) IsTrustedPeer

func (h *Host) IsTrustedPeer(p peer.ID) bool

IsTrustedPeer reports whether p is part of the protected trusted floor (bootstrap/beacon/direct peers pinned via ProtectPeers, #80). The head corroboration gate uses this as the super-vote: a head forwarded by a trusted floor peer is corroborated regardless of source count.

func (*Host) KeepaliveStats

func (h *Host) KeepaliveStats() KeepaliveStats

KeepaliveStats returns a snapshot of keepalive activity counters.

func (*Host) ListenAddrs

func (h *Host) ListenAddrs() []string

ListenAddrs returns the multiaddrs the host is listening on.

func (*Host) MaxPeers

func (h *Host) MaxPeers() int

MaxPeers returns the configured connection-manager high-water-mark.

func (*Host) MinPeers

func (h *Host) MinPeers() int

MinPeers returns the configured connection-manager low-water-mark.

func (*Host) NetInfo

func (h *Host) NetInfo() handlers.NetInfo

NetInfo returns a handlers.NetInfo wrapper around h. The returned value holds h by reference: it's cheap to construct and safe to share.

func (*Host) PeerCount

func (h *Host) PeerCount() int

PeerCount returns the current number of connected peers.

func (*Host) PeerHighWaterMark

func (h *Host) PeerHighWaterMark() int

PeerHighWaterMark returns the peer count observed at the last refresh tick. Useful for `lantern info`'s observability output.

func (*Host) ProtectPeers

func (h *Host) ProtectPeers(peers []string, tag string) int

ProtectPeers marks the given multiaddr peers as connmgr-protected under tag, making them an un-evictable floor the connection-manager trim path will never drop (#80). Used for the trusted bootstrap/beacon/direct-peer set so a dial flood from an attacker can't fully replace the peer table. Safe to call repeatedly; unparseable/empty entries are skipped. Returns the count of peers actually protected.

func (*Host) PublicAddrs

func (h *Host) PublicAddrs() []string

PublicAddrs returns the host's listen addrs filtered to those libp2p believes are publicly dialable. On a light client behind NAT this list is typically empty; on a public beacon it carries the dial-back addrs.

func (*Host) Reachability

func (h *Host) Reachability() network.Reachability

Reachability returns the latest AutoNAT-discovered reachability. Defaults to ReachabilityUnknown until the AmbientAutoNAT subsystem produces its first measurement (~30s post-bootstrap on a public peer).

func (*Host) RunDHTDiscovery

func (h *Host) RunDHTDiscovery(ctx context.Context, d *dht.IpfsDHT, opts DHTOptions)

RunDHTDiscovery starts the V1.2.1 closest-walk + dial-walk loops on an arbitrary DHT instance and returns immediately. Used by EnableDHT (client-mode DHT) and by cmd/lantern/beacon (server-mode DHT) so both daemon and beacon paths get the same active peer growth.

The loops respect ctx cancellation; pass a context that's cancelled when the host is being torn down. Safe to call multiple times if you really want overlapping walks (don't).

func (*Host) TriggerKeepalive

func (h *Host) TriggerKeepalive(ctx context.Context) (before, after int, err error)

TriggerKeepalive runs a single keepalive cycle synchronously and returns the peer count observed before and after. Issue #14 exposes this so the dashboard 'Find more peers' button can manually fire the loop instead of waiting up to 30s for the periodic tick.

Safe to call from HTTP handlers: bounded by the ctx timeout, no long-running side effects, no goroutine leaks. Returns the same counters runKeepalive bumps so the caller can include them in the response.

type HostConfig

type HostConfig struct {
	// Listen multiaddrs. Default: ["/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/udp/0/quic-v1"].
	ListenAddrs []string
	// BootstrapPeers is the list of multiaddrs to dial on startup.
	BootstrapPeers []string
	// MaxPeers is the connection-manager *high-water-mark*: when peer
	// count exceeds this, connmgr starts trimming the lowest-tagged
	// connections after the grace period. Default 200 (V1.2.1 lift;
	// previously 50 hard cap).
	MaxPeers int
	// MinPeers is the connection-manager *low-water-mark*: connmgr keeps
	// at least this many peers around even under trim pressure, and the
	// DHT discovery loop targets this number when dialing fresh peers.
	// Default 50.
	MinPeers int
	// ConnMgrGrace is how long a new connection is protected from trim.
	// Default 20 seconds.
	ConnMgrGrace time.Duration
	// UserAgent overrides the libp2p User-Agent. Default is derived from
	// internal/buildinfo so the wire identifier tracks the release tag.
	UserAgent string
	// DisableBandwidthCounter skips the metrics.BandwidthCounter wiring.
	// Used by tests that don't want to allocate the counter.
	DisableBandwidthCounter bool
	// GossipSubDirectPeers is a list of libp2p multiaddrs that the
	// gossipsub router should treat as direct mesh neighbours for the
	// block / message topics. We use it to pin big fast Filecoin nodes
	// (ChainSafe, chain.love, filincubator, devtty) into our mesh so
	// new heads propagate at the same speed they do for those nodes.
	// Defaults to BootstrapPeers when empty.
	GossipSubDirectPeers []string
	// PubSubTracer, when set, is registered as gossipsub's RawTracer at
	// construction. Used by the head-corroboration tracker (#80 part 2)
	// so duplicate block deliveries are counted per source peer.
	PubSubTracer pubsub.RawTracer
}

HostConfig configures the Lantern libp2p node.

type KeepaliveStats

type KeepaliveStats struct {
	Cycles        uint64 // total keepalive ticks
	Triggered     uint64 // cycles where we were below MinPeers and acted
	BootstrapDial uint64 // cumulative bootstrap-peer dials
	RoutingDial   uint64 // cumulative routing-table-walk dials
	// Stuck: cumulative count of peers we dialed on the previous tick
	// that were NOT still connected when the next tick fired. High Stuck
	// values relative to RoutingDial indicate peers are accepting the
	// libp2p stream then closing the connection. That's the failure mode
	// the issue #9 follow-up was diagnosed against.
	Stuck uint64
	// ClosestWalks fired by the keepalive (aggressive, only when peer
	// count is below MinPeers/2). Separate from the periodic 5-minute
	// dhtClosestWalkLoop.
	ClosestWalks  uint64
	LastPeerCount int // peer count observed at the last tick
}

KeepaliveStats reports observable activity from the keepalive loop. Exposed so the dashboard / lantern info can show whether the loop is actively topping up peer count.

Jump to

Keyboard shortcuts

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