lp2p

package
v0.39.0-beta.4 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: Apache-2.0 Imports: 45 Imported by: 0

Documentation

Overview

Package lp2p implements auxiliary functions for go-libp2p integration in CometBFT. The name is chosen to avoid conflicts with the p2p package.

Index

Constants

View Source
const MaxReconnectBackoff = 5 * time.Minute
View Source
const MaxStreamSize = 4 * (1 << 20)

MaxStreamSize is the global maximum size of a stream. Protocols should configure their own maximum size.

View Source
const ProtocolIDPrefix = "/p2p/cometbft/1.0.0"

ProtocolIDPrefix is the prefix for all protocol IDs.

View Source
const TimeoutStream = 10 * time.Second

TimeoutStream is the timeout for a stream.

View Source
const TransportQUIC = "quic-v1"

TransportQUIC quic transport. @see https://docs.libp2p.io/concepts/transports/quic

Variables

View Source
var (
	ErrPeerExists = errors.New("peer already exists")
	ErrSelfPeer   = errors.New("peer is self")
)
View Source
var ErrUnsupportedPeerFormat = errors.New("unsupported peer format")

Functions

func AddrInfoFromHostAndID

func AddrInfoFromHostAndID(host, id string) (peer.AddrInfo, error)

func AddressToMultiAddr

func AddressToMultiAddr(addr string, transport string) (ma.Multiaddr, error)

AddressToMultiAddr converts a `listenAddress` to a multiaddr for the given transport Currently, only QUIC is supported. Example: "tcp://1.1.1.1:5678" yields to "/ip4/1.1.1.1/udp/5678/quic-v1"

func BootstrapPeersFromConfig

func BootstrapPeersFromConfig(config config.LibP2PConfig) (map[peer.ID]BootstrapPeer, error)

func IDFromPrivateKey

func IDFromPrivateKey(cosmosPK cmcrypto.PrivKey) (peer.ID, error)

func IsDNSAddr

func IsDNSAddr(addr ma.Multiaddr) bool

IsDNSAddr checks if the given multiaddr is a DNS address.

func PrivateKeyFromCosmosKey

func PrivateKeyFromCosmosKey(key cmcrypto.PrivKey) (crypto.PrivKey, error)

PrivateKeyFromCosmosKey converts a Cosmos private key to a libp2p private key.

func ProtocolID

func ProtocolID(channelID byte) protocol.ID

ProtocolID returns the protocol ID for a given channel Byte is used for compatibility with the original CometBFT implementation.

func ResourceManagerFromConfig

func ResourceManagerFromConfig(cfg config.LibP2PConfig) (network.ResourceManager, rcmgr.Limiter, error)

ResourceManagerFromConfig creates a resource manager from the given config.

func StreamRead

func StreamRead(s network.Stream) ([]byte, error)

StreamRead reads payload from a stream. It doesn't control stream's lifecycle, so it's up to the caller to close the stream. Note: this method doesn't enforce any size limits! Use StreamReadSized instead.

func StreamReadClose

func StreamReadClose(s network.Stream) (payload []byte, err error)

StreamReadClose reads payload from a stream and closes it right after. Also, resets the stream on both ends in case of error.

func StreamReadSized

func StreamReadSized(s network.Stream, maxSize uint64) ([]byte, error)

StreamReadSized reads payload from a stream with a maximum size. It doesn't control stream's lifecycle, so it's up to the caller to close the stream.

func StreamReadSizedClose

func StreamReadSizedClose(s network.Stream, maxSize uint64) (payload []byte, err error)

StreamReadSizedClose reads payload from a stream and closes it right after with a maximum size. Also, resets the stream on both ends in case of error.

func StreamWrite

func StreamWrite(s network.Stream, data []byte) (int, error)

StreamWrite sends payload over a stream w/o waiting for a response. Only guarantees that the recipient will receive the bytes (no "message processed" guarantee). It doesn't control stream's lifecycle, so it's up to the caller to close the stream.

func StreamWriteClose

func StreamWriteClose(s network.Stream, data []byte) (err error)

StreamWriteClose sends payload over a stream and closes it right after. The caller doesn't expect a response in this case. Also, resets the stream on both ends in case of error.

Types

type BootstrapPeer

type BootstrapPeer struct {
	AddrInfo      peer.AddrInfo
	Private       bool
	Persistent    bool
	Unconditional bool
}

BootstrapPeer initial peers to connect to

type ConnGater

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

ConnGater limits the number of simultaneously connected peers. It is only enabled when `lp2p.limits.mode = "custom"` and uses `lp2p.limits.max_peers` as the cap.

The host is injected after host creation because libp2p requires the connection gater option during `libp2p.New(...)`, before the host exists.

func ConnectionGaterFromConfig

func ConnectionGaterFromConfig(cfg config.LibP2PConfig, host *Host) (*ConnGater, bool)

ConnectionGaterFromConfig creates a connection gater from the given config or returns false if disabled.

func (*ConnGater) InterceptAccept

func (c *ConnGater) InterceptAccept(network.ConnMultiaddrs) bool

InterceptAccept is called when a peer attempts to connect. It returns false to reject the connection if the peer count has reached max_peers.

func (*ConnGater) InterceptAddrDial

func (c *ConnGater) InterceptAddrDial(pid peer.ID, _ multiaddr.Multiaddr) bool

func (*ConnGater) InterceptPeerDial

func (c *ConnGater) InterceptPeerDial(pid peer.ID) bool

func (*ConnGater) InterceptSecured

func (c *ConnGater) InterceptSecured(network.Direction, peer.ID, network.ConnMultiaddrs) bool

func (*ConnGater) InterceptUpgraded

func (c *ConnGater) InterceptUpgraded(network.Conn) (allow bool, reason control.DisconnectReason)

func (*ConnGater) SetHost

func (c *ConnGater) SetHost(host *Host)

SetHost sets the host for the connection gater. The host is injected after creation because libp2p requires the connection gater option during libp2p.New, before the host exists.

type ErrorTransient

type ErrorTransient struct {
	Err error
}

ErrorTransient is an error that is transient and can be retried.

func TransientErrorFromAny

func TransientErrorFromAny(v any) (*ErrorTransient, bool)

func (*ErrorTransient) Error

func (e *ErrorTransient) Error() string

func (*ErrorTransient) Unwrap

func (e *ErrorTransient) Unwrap() error

type Host

type Host struct {
	host.Host
	// contains filtered or unexported fields
}

Host is a wrapper around the libp2p host. Note that host should NOT be responsible for high-level peer management as it's Switch's responsibility.

func NewHost

func NewHost(config *config.P2PConfig, nodeKey cmcrypto.PrivKey, logger log.Logger) (*Host, error)

NewHost Host constructor.

func (*Host) AddPeerFailureHandler

func (h *Host) AddPeerFailureHandler(handler func(id peer.ID, err error))

func (*Host) AddrInfo

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

func (*Host) BootstrapPeer

func (h *Host) BootstrapPeer(id peer.ID) (BootstrapPeer, bool)

func (*Host) BootstrapPeers

func (h *Host) BootstrapPeers() map[peer.ID]BootstrapPeer

func (*Host) EmitPeerFailure

func (h *Host) EmitPeerFailure(id peer.ID, err error)

EmitPeerFailure emits a peer failure event to all registered handlers. This semantic is over host.eventBus for simplicity.

func (*Host) Logger

func (h *Host) Logger() log.Logger

func (*Host) Ping

func (h *Host) Ping(ctx context.Context, addrInfo peer.AddrInfo) (time.Duration, error)

Ping pings peers and logs RTT latency (blocking) Keep in might that ping service might be disabled on the counterparty's side.

type Peer

type Peer struct {
	service.BaseService
	// contains filtered or unexported fields
}

Peer represents a remote node connected via libp2p. It implements p2p.Peer interface and wraps the libp2p connection with CometBFT-specific peer attributes and messaging capabilities.

func NewPeer

func NewPeer(
	host *Host,
	addrInfo peer.AddrInfo,
	metrics *p2p.Metrics,
	isPrivate, isPersistent, isUnconditional bool,
) (*Peer, error)

func (*Peer) AddrInfo

func (p *Peer) AddrInfo() peer.AddrInfo

AddrInfo returns original addr info. Note it might differ from host's peerstore

func (*Peer) CloseConn

func (p *Peer) CloseConn() error

func (*Peer) FlushStop

func (*Peer) FlushStop()

func (*Peer) Get

func (p *Peer) Get(key string) any

func (*Peer) GetRemovalFailed

func (*Peer) GetRemovalFailed() bool

func (*Peer) ID

func (p *Peer) ID() p2p.ID

func (*Peer) IsOutbound

func (*Peer) IsOutbound() bool

IsOutbound returns true because all lp2p peers are bi-directional.

func (*Peer) IsPersistent

func (p *Peer) IsPersistent() bool

func (*Peer) IsPrivate

func (p *Peer) IsPrivate() bool

func (*Peer) IsUnconditional

func (p *Peer) IsUnconditional() bool

func (*Peer) NodeInfo

func (p *Peer) NodeInfo() p2p.NodeInfo

NodeInfo returns a DefaultNodeInfo populated with the peer's ID and address. Since libp2p does not perform a CometBFT-style handshake, only the fields derivable from the connection are filled in (ID, listen address).

func (*Peer) RemoteAddr

func (p *Peer) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the peer as a net.Addr.

func (*Peer) RemoteIP

func (p *Peer) RemoteIP() net.IP

RemoteIP returns the remote IP address of the peer derived from its address info.

func (*Peer) Send

func (p *Peer) Send(e p2p.Envelope) bool

Send implements p2p.Peer.

func (*Peer) Set

func (p *Peer) Set(key string, value any)

func (*Peer) SetRemovalFailed

func (*Peer) SetRemovalFailed()

func (*Peer) SocketAddr

func (p *Peer) SocketAddr() *p2p.NetAddress

func (*Peer) Status

func (*Peer) Status() conn.ConnectionStatus

Status returns an empty ConnectionStatus. Per-channel send queue statistics are not available with the libp2p transport.

func (*Peer) String

func (p *Peer) String() string

func (*Peer) TrySend

func (p *Peer) TrySend(e p2p.Envelope) bool

type PeerAddOptions

type PeerAddOptions struct {
	Private       bool
	Persistent    bool
	Unconditional bool
	OnBeforeStart func(p *Peer)
	OnAfterStart  func(p *Peer)
	OnStartFailed func(p *Peer, reason any)
}

PeerAddOptions options for adding a peer to the PeerSet. It includes behavioral flags and lifecycle callbacks for peer initialization.

type PeerRemovalOptions

type PeerRemovalOptions struct {
	Reason      any
	OnAfterStop func(p *Peer, reason any)
}

PeerRemovalOptions options for removing a peer from the PeerSet. If OnAfterStop is provided, it will be called after the peer is stopped. Note that Reason is any due to backwards compatibility.

type PeerSet

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

PeerSet represents a single entrypoint for managing Peer's lifecycle. Note that PeerSet DOESN'T manage networking (e.g. opening/closing connections).

func NewPeerSet

func NewPeerSet(host *Host, metrics *p2p.Metrics, logger log.Logger) *PeerSet

NewPeerSet manager peers for a given switch

func (*PeerSet) Add

func (ps *PeerSet) Add(addrInfo peer.AddrInfo, opts PeerAddOptions) (*Peer, error)

Add adds a new peer to the peer set. Fails if: - peer is already present - peer is self - peer has no addresses

func (*PeerSet) Copy deprecated

func (ps *PeerSet) Copy() []p2p.Peer

Copy returns a copy of the peers list.

Deprecated: use only for backwards compatibility.

func (*PeerSet) ForEach

func (ps *PeerSet) ForEach(fn func(p2p.Peer))

func (*PeerSet) Get

func (ps *PeerSet) Get(key p2p.ID) p2p.Peer

func (*PeerSet) Has

func (ps *PeerSet) Has(key p2p.ID) bool

func (*PeerSet) Random deprecated

func (ps *PeerSet) Random() p2p.Peer

Random returns a random peer from the PeerSet (or nil if no peers are present). This method is not expected to be called frequently as it has O(n log n) complexity.

Deprecated: use only for backwards compatibility.

func (*PeerSet) Remove

func (ps *PeerSet) Remove(key p2p.ID, opts PeerRemovalOptions) error

func (*PeerSet) RemoveAll

func (ps *PeerSet) RemoveAll(opts PeerRemovalOptions)

func (*PeerSet) Size

func (ps *PeerSet) Size() int

Size returns the number of peers in the peerSet.

type Switch

type Switch struct {
	service.BaseService
	// contains filtered or unexported fields
}

Switch represents p2p.Switcher alternative implementation based on go-libp2p. todo add comments to exported methods todo group unused methods

func NewSwitch

func NewSwitch(
	nodeInfo p2p.NodeInfo,
	host *Host,
	reactors []SwitchReactor,
	metrics *p2p.Metrics,
	logger log.Logger,
) (*Switch, error)

NewSwitch constructs a new Switch.

func (*Switch) AddPersistentPeers

func (s *Switch) AddPersistentPeers(addrs []string) error

func (*Switch) AddPrivatePeerIDs

func (s *Switch) AddPrivatePeerIDs(ids []string) error

func (*Switch) AddReactor

func (s *Switch) AddReactor(name string, reactor p2p.Reactor) p2p.Reactor

AddReactor adds the given reactor to the switch. NOTE: Not goroutine safe.

func (*Switch) AddUnconditionalPeerIDs

func (s *Switch) AddUnconditionalPeerIDs(ids []string) error

func (*Switch) Broadcast

func (s *Switch) Broadcast(e p2p.Envelope) chan bool

func (*Switch) BroadcastAsync

func (s *Switch) BroadcastAsync(e p2p.Envelope)

func (*Switch) DialPeerWithAddress

func (s *Switch) DialPeerWithAddress(_ *p2p.NetAddress) error

func (*Switch) DialPeersAsync

func (s *Switch) DialPeersAsync(peers []string) error

func (*Switch) IsDialingOrExistingAddress

func (s *Switch) IsDialingOrExistingAddress(addr *p2p.NetAddress) bool

func (*Switch) IsPeerPersistent

func (s *Switch) IsPeerPersistent(netAddr *p2p.NetAddress) bool

func (*Switch) IsPeerUnconditional

func (s *Switch) IsPeerUnconditional(id p2p.ID) bool

func (*Switch) Log

func (s *Switch) Log() log.Logger

func (*Switch) MarkPeerAsGood

func (s *Switch) MarkPeerAsGood(_ p2p.Peer)

func (*Switch) MaxNumOutboundPeers

func (s *Switch) MaxNumOutboundPeers() int

func (*Switch) NodeInfo

func (s *Switch) NodeInfo() p2p.NodeInfo

func (*Switch) NumPeers

func (s *Switch) NumPeers() (outbound, inbound, dialing int)

func (*Switch) OnStart

func (s *Switch) OnStart() error

func (*Switch) OnStop

func (s *Switch) OnStop()

func (*Switch) Peers

func (s *Switch) Peers() p2p.IPeerSet

func (*Switch) Reactor

func (s *Switch) Reactor(name string) (p2p.Reactor, bool)

func (*Switch) RemoveReactor

func (s *Switch) RemoveReactor(_ string, _ p2p.Reactor)

func (*Switch) StopPeerForError

func (s *Switch) StopPeerForError(peer p2p.Peer, reason any)

func (*Switch) StopPeerGracefully

func (s *Switch) StopPeerGracefully(_ p2p.Peer)

func (*Switch) TryBroadcast

func (s *Switch) TryBroadcast(e p2p.Envelope)

type SwitchReactor

type SwitchReactor struct {
	p2p.Reactor
	Name string
}

SwitchReactor is a pair of name and reactor. Preserves order when adding.

Jump to

Keyboard shortcuts

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