networking

package
v0.0.0-...-da72ffe Latest Latest
Warning

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

Go to latest
Published: May 16, 2025 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultRetryConfig = RetryConfig{
	MaxRetries:      5,
	InitialInterval: 500 * time.Millisecond,
	MaxInterval:     10 * time.Second,
	Multiplier:      2,
}

DefaultRetryConfig provides a default configuration for retries.

View Source
var (
	NetworkStateType state.StateType = "networking"
)

Functions

func CreateNode

func CreateNode(cfg config.Networking, logger logger.Logger, account *accounts.Account) (host.Host, error)

CreateNode initializes a libp2p host and node based on the provided configuration.

func IsConnectionRefused

func IsConnectionRefused(err error) bool

IsConnectionRefused - Helper function to check for connection refused errors

func VerifySignature

func VerifySignature(rawPubKey []byte, data []byte, signature []byte) error

VerifySignature verifies that the provided signature is valid for the given data and public key.

Parameters: - rawPubKey: The raw bytes of the public key. - data: The original data that was signed. - signature: The signature to verify.

Returns: - error: An error if the verification process fails, nil if successful.

Types

type DiscoveryMetrics

type DiscoveryMetrics struct {
	PeersAdvertisedTotal       metric.Int64Counter
	PeersAdvertisementFailures metric.Int64Counter
	PeersDiscoveredTotal       metric.Int64Counter
	PeersDiscoveryFailures     metric.Int64Counter
	DiscoveryLatencySeconds    metric.Float64Histogram
	BootstrapPeersConnected    metric.Int64Counter
	BootstrapPeersFailed       metric.Int64Counter
	ActivePeers                metric.Int64UpDownCounter
	PeersRemovedTotal          metric.Int64Counter

	// MDNS-specific metrics
	MdnsPeersDiscoveredTotal   metric.Int64Counter
	MdnsPeersLostTotal         metric.Int64Counter
	MdnsConnectionSuccessTotal metric.Int64Counter
	MdnsConnectionFailedTotal  metric.Int64Counter
}

DiscoveryMetrics holds all the metrics instruments for the DiscoveryService.

func InitializeDiscoveryMetrics

func InitializeDiscoveryMetrics(ctx context.Context, meter metric.Meter) (*DiscoveryMetrics, error)

InitializeDiscoveryMetrics initializes the metrics instruments.

func (*DiscoveryMetrics) RecordActivePeers

func (m *DiscoveryMetrics) RecordActivePeers(ctx context.Context, delta int64)

RecordActivePeers updates the current number of active peers. The delta can be positive (peer added) or negative (peer removed).

func (*DiscoveryMetrics) RecordBootstrapPeersConnected

func (m *DiscoveryMetrics) RecordBootstrapPeersConnected(ctx context.Context, count int64)

RecordBootstrapPeersConnected increments the BootstrapPeersConnected counter.

func (*DiscoveryMetrics) RecordBootstrapPeersFailed

func (m *DiscoveryMetrics) RecordBootstrapPeersFailed(ctx context.Context, count int64)

RecordBootstrapPeersFailed increments the BootstrapPeersFailed counter.

func (*DiscoveryMetrics) RecordDiscoveryLatency

func (m *DiscoveryMetrics) RecordDiscoveryLatency(ctx context.Context, latency time.Duration)

RecordDiscoveryLatency records the latency of a discovery operation.

func (*DiscoveryMetrics) RecordMdnsConnectionFailed

func (m *DiscoveryMetrics) RecordMdnsConnectionFailed(ctx context.Context, count int64)

RecordMdnsConnectionFailed increments the MdnsConnectionFailedTotal counter.

func (*DiscoveryMetrics) RecordMdnsConnectionSuccess

func (m *DiscoveryMetrics) RecordMdnsConnectionSuccess(ctx context.Context, count int64)

RecordMdnsConnectionSuccess increments the MdnsConnectionSuccessTotal counter.

func (*DiscoveryMetrics) RecordMdnsPeerDiscovered

func (m *DiscoveryMetrics) RecordMdnsPeerDiscovered(ctx context.Context, count int64)

RecordMdnsPeerDiscovered increments the MdnsPeersDiscoveredTotal counter.

func (*DiscoveryMetrics) RecordMdnsPeerLost

func (m *DiscoveryMetrics) RecordMdnsPeerLost(ctx context.Context, count int64)

RecordMdnsPeerLost increments the MdnsPeersLostTotal counter.

func (*DiscoveryMetrics) RecordPeersAdvertised

func (m *DiscoveryMetrics) RecordPeersAdvertised(ctx context.Context, count int64)

RecordPeersAdvertised increments the PeersAdvertisedTotal counter.

func (*DiscoveryMetrics) RecordPeersAdvertisementFailure

func (m *DiscoveryMetrics) RecordPeersAdvertisementFailure(ctx context.Context, count int64)

RecordPeersAdvertisementFailure increments the PeersAdvertisementFailures counter.

func (*DiscoveryMetrics) RecordPeersDiscovered

func (m *DiscoveryMetrics) RecordPeersDiscovered(ctx context.Context, count int64)

RecordPeersDiscovered increments the PeersDiscoveredTotal counter.

func (*DiscoveryMetrics) RecordPeersDiscoveryFailure

func (m *DiscoveryMetrics) RecordPeersDiscoveryFailure(ctx context.Context, count int64)

RecordPeersDiscoveryFailure increments the PeersDiscoveryFailures counter.

func (*DiscoveryMetrics) RecordPeersRemoved

func (m *DiscoveryMetrics) RecordPeersRemoved(ctx context.Context, count int64)

RecordPeersRemoved increments the PeersRemovedTotal counter.

type DiscoveryService

type DiscoveryService struct {
	DHT            *dht.IpfsDHT
	Discovery      *routing.RoutingDiscovery
	Logger         logger.Logger
	BootstrapPeers []peer.AddrInfo
	Metrics        *DiscoveryMetrics
	Observability  *observability.Observability
	// contains filtered or unexported fields
}

DiscoveryService encapsulates peer discovery mechanisms.

func NewDiscoveryService

func NewDiscoveryService(
	ctx context.Context,
	h host.Host,
	logger logger.Logger,
	bootstrapNode bool,
	bootstrapPeers []peer.AddrInfo,
	obs *observability.Observability,
) (*DiscoveryService, error)

NewDiscoveryService creates a new peer discovery service with a DHT and routing discovery mechanism. Parameters: - ctx: The context for managing cancellation and deadlines. - h: The libp2p host. - logger: The logger instance for logging events. - bootstrapNode: Indicates if this node is a bootstrap node. - bootstrapPeers: A list of bootstrap peers to connect to initially. - obs: The observability instance for metrics and tracing.

func (*DiscoveryService) AddBootstrapPeer

func (ds *DiscoveryService) AddBootstrapPeer(peerInfo peer.AddrInfo) error

AddBootstrapPeer allows adding new bootstrap peers to the DHT dynamically. It connects to the new bootstrap peer and records relevant metrics.

func (*DiscoveryService) Advertise

func (ds *DiscoveryService) Advertise(serviceTag DiscoveryServiceTag, isBootstrap bool) error

Advertise advertises the service with the given service tag. It allows bootstrap nodes to advertise without existing peers.

func (*DiscoveryService) FindPeers

func (ds *DiscoveryService) FindPeers(serviceTag DiscoveryServiceTag) (<-chan peer.AddrInfo, error)

FindPeers discovers peers providing the given service. It returns a channel through which discovered peers are sent.

func (*DiscoveryService) RemovePeer

func (ds *DiscoveryService) RemovePeer(peerID peer.ID)

RemovePeer removes a peer from the DHT routing table. It updates the relevant metrics to reflect the removal.

func (*DiscoveryService) Shutdown

func (ds *DiscoveryService) Shutdown() error

Shutdown gracefully shuts down the discovery service and cleans up resources. It ensures that the DHT is closed and any remaining peers are accounted for in metrics.

func (*DiscoveryService) Start

func (ds *DiscoveryService) Start() error

Start initializes the bootstrap process and connects to bootstrap peers.

type DiscoveryServiceTag

type DiscoveryServiceTag string

func (DiscoveryServiceTag) String

func (dst DiscoveryServiceTag) String() string

type MdnsNotifier

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

MdnsNotifier implements the mdns.Notifee interface to handle peer discovery via mDNS. It supports multiple callbacks for each event type.

func NewMdnsNotifier

func NewMdnsNotifier(network *Network) *MdnsNotifier

NewMdnsNotifier creates a new MdnsNotifier instance with default retry configuration.

func (*MdnsNotifier) HandlePeerFound

func (mdns *MdnsNotifier) HandlePeerFound(pi peer.AddrInfo)

HandlePeerFound is called when a new peer is discovered via mDNS. It attempts to connect to the discovered peer and invokes the appropriate callbacks.

func (*MdnsNotifier) HandlePeerLost

func (mdns *MdnsNotifier) HandlePeerLost(pi peer.AddrInfo)

HandlePeerLost is called when a previously discovered peer is no longer reachable via mDNS. It invokes all registered disconnection callbacks.

func (*MdnsNotifier) SetPeerConnectedCallback

func (mdns *MdnsNotifier) SetPeerConnectedCallback(callback PeerConnectedCallback)

SetPeerConnectedCallback registers a new callback to be invoked upon successful peer connection.

func (*MdnsNotifier) SetPeerConnectionFailedCallback

func (mdns *MdnsNotifier) SetPeerConnectionFailedCallback(callback PeerConnectionFailedCallback)

SetPeerConnectionFailedCallback registers a new callback to be invoked upon failed peer connection.

func (*MdnsNotifier) SetPeerDisconnectedCallback

func (mdns *MdnsNotifier) SetPeerDisconnectedCallback(callback PeerDisconnectedCallback)

SetPeerDisconnectedCallback registers a new callback to be invoked upon peer disconnection.

func (*MdnsNotifier) SetRetryConfig

func (mdns *MdnsNotifier) SetRetryConfig(config RetryConfig)

SetRetryConfig allows setting a custom retry configuration.

type Message

type Message struct {
	Data []byte
}

Message represents a message received from the network.

type MockP2PNetwork

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

MockP2PNetwork is a mock implementation of the P2PNetworkInterface.

func NewMockP2PNetwork

func NewMockP2PNetwork(hostID peer.ID, logger logger.Logger) *MockP2PNetwork

NewMockP2PNetwork initializes a new MockP2PNetwork.

func (*MockP2PNetwork) BroadcastCh

func (m *MockP2PNetwork) BroadcastCh() <-chan struct{}

BroadcastCh returns the broadcast channel.

func (*MockP2PNetwork) BroadcastMessage

func (m *MockP2PNetwork) BroadcastMessage(message []byte) error

BroadcastMessage records the broadcasted message and enqueues it to all subscriptions.

func (*MockP2PNetwork) GetBroadcastedCount

func (m *MockP2PNetwork) GetBroadcastedCount() int

GetBroadcastedCount returns the number of broadcasted messages.

func (*MockP2PNetwork) GetBroadcastedMessages

func (m *MockP2PNetwork) GetBroadcastedMessages() []*Message

GetBroadcastedMessages returns all messages that have been broadcasted.

func (*MockP2PNetwork) HostID

func (m *MockP2PNetwork) HostID() peer.ID

HostID returns the mock host's peer ID.

func (*MockP2PNetwork) PubSubSubscribe

func (m *MockP2PNetwork) PubSubSubscribe(topic string) (Subscription, error)

PubSubSubscribe returns a mock subscription for the given topic.

type MockSubscription

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

MockSubscription is a mock implementation of the Subscription interface.

func NewMockSubscription

func NewMockSubscription() *MockSubscription

NewMockSubscription initializes and returns a new MockSubscription.

func (*MockSubscription) Cancel

func (ms *MockSubscription) Cancel()

Cancel marks the subscription as closed.

func (*MockSubscription) EnqueueMessage

func (ms *MockSubscription) EnqueueMessage(message *Message)

EnqueueMessage allows tests to enqueue messages that will be returned by Next().

func (*MockSubscription) Next

func (ms *MockSubscription) Next(ctx context.Context) (*Message, error)

Next returns the next message in the subscription. If no messages are available, it returns nil without blocking.

type Network

type Network struct {
	Topic      *pubsub.Topic
	ProtocolID protocol.ID

	Logger logger.Logger

	Metrics       *P2PMetrics
	Observability *observability.Observability
	// contains filtered or unexported fields
}

Network defines the core structure of the P2P network.

func NewNetwork

func NewNetwork(ctx context.Context, cfg config.Networking, account *accounts.Account, bootstrapAddrs []peer.AddrInfo, logger logger.Logger, obs *observability.Observability, stateMgr *state.StateManager) (*Network, error)

NewNetwork initializes and returns a new P2P network without starting it.

func (*Network) BroadcastMessage

func (n *Network) BroadcastMessage(message []byte) error

BroadcastMessage sends a message to all peers subscribed to the PubSub topic.

func (*Network) BroadcastPacketOverTopic

func (n *Network) BroadcastPacketOverTopic(ctx context.Context, topic *pubsub.Topic, message []byte) error

BroadcastPacketOverTopic sends a message to all peers subscribed to a specific PubSub topic.

func (*Network) ConnectPeer

func (n *Network) ConnectPeer(peerAddr string) error

ConnectPeer connects to a given peer using its multiaddress.

func (*Network) ConnectPeerInfo

func (n *Network) ConnectPeerInfo(pi peer.AddrInfo) error

ConnectPeerInfo connects to a peer using the provided peer.AddrInfo.

func (*Network) Discovery

func (n *Network) Discovery() *DiscoveryService

func (*Network) HandlerRegistry

func (n *Network) HandlerRegistry() *PacketHandlerRegistry

func (*Network) Host

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

func (*Network) MdnsNotifier

func (n *Network) MdnsNotifier() *MdnsNotifier

func (*Network) PubSubService

func (n *Network) PubSubService() *PubSubService

func (*Network) RegisterPeerConnectedHandler

func (n *Network) RegisterPeerConnectedHandler(handler PeerConnectedHandler) func()

RegisterPeerConnectedHandler allows external packages to register a handler for peer connections. It returns a registration function.

func (*Network) RegisterPeerDisconnectedHandler

func (n *Network) RegisterPeerDisconnectedHandler(handler PeerDisconnectedHandler) func()

RegisterPeerDisconnectedHandler allows external packages to register a handler for peer disconnections. It returns a deregistration function.

func (*Network) SendMessage

func (n *Network) SendMessage(ctx context.Context, protocolId protocol.ID, target peer.ID, message []byte) error

SendMessage sends a direct message to a specific peer using the custom protocol. It prepends the message with its length as a uint32 in little-endian format.

func (*Network) SendToPeer

func (n *Network) SendToPeer(ctx context.Context, peerID peer.ID, protocolID protocol.ID, data []byte) error

SendToPeer sends data securely to a specific peer using a LibP2P stream.

func (*Network) Shutdown

func (n *Network) Shutdown() error

Shutdown gracefully shuts down the P2P network.

func (*Network) Start

func (n *Network) Start() error

Start begins the P2P network's operations.

func (*Network) StartMDNS

func (n *Network) StartMDNS() error

type Notifier

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

Notifier manages the registration and invocation of peer event handlers.

func NewNotifier

func NewNotifier(logger logger.Logger) *Notifier

NewNotifier initializes and returns a new Notifier instance. It accepts a logger to log any internal errors or panics.

func (*Notifier) NotifyPeerConnected

func (n *Notifier) NotifyPeerConnected(ctx context.Context, peerInfo peer.AddrInfo)

NotifyPeerConnected invokes all registered peer connected handlers with the given peer information.

func (*Notifier) NotifyPeerDisconnected

func (n *Notifier) NotifyPeerDisconnected(ctx context.Context, peerID peer.ID)

NotifyPeerDisconnected invokes all registered peer disconnected handlers with the given peer ID.

func (*Notifier) RegisterPeerConnectedHandler

func (n *Notifier) RegisterPeerConnectedHandler(handler PeerConnectedHandler) func()

RegisterPeerConnectedHandler registers a new handler for peer connection events. It returns a deregistration function to remove the handler when it's no longer needed.

func (*Notifier) RegisterPeerDisconnectedHandler

func (n *Notifier) RegisterPeerDisconnectedHandler(handler PeerDisconnectedHandler) func()

RegisterPeerDisconnectedHandler registers a new handler for peer disconnection events. It returns a deregistration function to remove the handler when it's no longer needed.

type P2PMetrics

type P2PMetrics struct {
	PeersConnectedTotal   metric.Int64Counter
	PeersConnectionFailed metric.Int64Counter
	MessagesSentTotal     metric.Int64Counter
	MessagesReceivedTotal metric.Int64Counter
	MessageLatencySeconds metric.Float64Histogram
	ActivePeers           metric.Int64UpDownCounter
	PeersRemovedTotal     metric.Int64Counter
	// Network throughput metrics
	BytesSentTotal     metric.Int64Counter
	BytesReceivedTotal metric.Int64Counter
	// Connection performance metrics
	ConnectionEstablishTimeSeconds metric.Float64Histogram
	ConnectionRetryTotal           metric.Int64Counter
}

P2PMetrics holds all the metrics instruments for the P2PNetwork.

func InitializeP2PMetrics

func InitializeP2PMetrics(ctx context.Context, meter metric.Meter) (*P2PMetrics, error)

InitializeP2PMetrics initializes the metrics instruments for P2PNetwork.

func (*P2PMetrics) RecordActivePeers

func (m *P2PMetrics) RecordActivePeers(ctx context.Context, delta int64)

RecordActivePeers updates the current number of active peers. The delta can be positive (peer added) or negative (peer removed).

func (*P2PMetrics) RecordBytesReceived

func (m *P2PMetrics) RecordBytesReceived(ctx context.Context, byteCount int64)

RecordBytesReceived increments the BytesReceivedTotal counter.

func (*P2PMetrics) RecordBytesSent

func (m *P2PMetrics) RecordBytesSent(ctx context.Context, byteCount int64)

RecordBytesSent increments the BytesSentTotal counter.

func (*P2PMetrics) RecordConnectionEstablishTime

func (m *P2PMetrics) RecordConnectionEstablishTime(ctx context.Context, duration time.Duration)

RecordConnectionEstablishTime records the time taken to establish a P2P connection.

func (*P2PMetrics) RecordConnectionRetry

func (m *P2PMetrics) RecordConnectionRetry(ctx context.Context, count int64)

RecordConnectionRetry increments the ConnectionRetryTotal counter.

func (*P2PMetrics) RecordMessageLatency

func (m *P2PMetrics) RecordMessageLatency(ctx context.Context, latency time.Duration)

RecordMessageLatency records the latency of a message processing.

func (*P2PMetrics) RecordMessagesReceived

func (m *P2PMetrics) RecordMessagesReceived(ctx context.Context, count int64)

RecordMessagesReceived increments the MessagesReceivedTotal counter.

func (*P2PMetrics) RecordMessagesSent

func (m *P2PMetrics) RecordMessagesSent(ctx context.Context, count int64)

RecordMessagesSent increments the MessagesSentTotal counter.

func (*P2PMetrics) RecordPeersConnected

func (m *P2PMetrics) RecordPeersConnected(ctx context.Context, count int64)

RecordPeersConnected increments the PeersConnectedTotal counter.

func (*P2PMetrics) RecordPeersConnectionFailed

func (m *P2PMetrics) RecordPeersConnectionFailed(ctx context.Context, count int64)

RecordPeersConnectionFailed increments the PeersConnectionFailed counter.

func (*P2PMetrics) RecordPeersRemoved

func (m *P2PMetrics) RecordPeersRemoved(ctx context.Context, count int64)

RecordPeersRemoved increments the PeersRemovedTotal counter.

type P2PNetworkInterface

type P2PNetworkInterface interface {
	BroadcastMessage(message []byte) error
	PubSubSubscribe(topic string) (Subscription, error)
	HostID() peer.ID
}

P2PNetworkInterface defines the methods required by the ConsensusProtocol.

type PacketHandlerFunc

type PacketHandlerFunc func(ctx context.Context, msg *packets.NetworkPacket, sender peer.ID) error

PacketHandlerFunc defines the signature for packet handler functions.

type PacketHandlerRegistry

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

PacketHandlerRegistry manages registration and invocation of packet handlers based on packet types.

func NewMessageHandlerRegistry

func NewMessageHandlerRegistry(logger logger.Logger) *PacketHandlerRegistry

NewMessageHandlerRegistry initializes a new MessageHandlerRegistry.

func (*PacketHandlerRegistry) HandlePacket

func (mhr *PacketHandlerRegistry) HandlePacket(ctx context.Context, msg *packets.NetworkPacket, sender peer.ID) error

HandlePacket invokes the appropriate handler based on the message type.

func (*PacketHandlerRegistry) RegisterHandler

func (mhr *PacketHandlerRegistry) RegisterHandler(packetType packets.PacketType, handler PacketHandlerFunc)

RegisterHandler registers a handler for a specific message type.

type PeerConnectedCallback

type PeerConnectedCallback func(context.Context, peer.AddrInfo)

PeerConnectedCallback type for successful peer connections.

type PeerConnectedHandler

type PeerConnectedHandler func(ctx context.Context, peerInfo peer.AddrInfo) error

PeerConnectedHandler defines the callback signature for peer connection events.

type PeerConnectionFailedCallback

type PeerConnectionFailedCallback func(context.Context, peer.AddrInfo, error)

PeerConnectionFailedCallback type for failed peer connections.

type PeerDisconnectedCallback

type PeerDisconnectedCallback func(context.Context, peer.ID)

PeerDisconnectedCallback type for peer disconnections.

type PeerDisconnectedHandler

type PeerDisconnectedHandler func(ctx context.Context, peerID peer.ID) error

PeerDisconnectedHandler defines the callback signature for peer disconnection events.

type PubSubService

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

PubSubService manages PubSub operations for the network.

func NewPubSubService

func NewPubSubService(ctx context.Context, ps *pubsub.PubSub) *PubSubService

NewPubSubService creates a new PubSubService.

func (*PubSubService) JoinTopic

func (ps *PubSubService) JoinTopic(topicName protocol.ID, opts ...pubsub.TopicOpt) (*pubsub.Topic, error)

JoinTopic joins a PubSub topic and stores it.

func (*PubSubService) PubSub

func (ps *PubSubService) PubSub() *pubsub.PubSub

func (*PubSubService) PublishMessage

func (ps *PubSubService) PublishMessage(topicName protocol.ID, message []byte) error

PublishMessage publishes a message to a topic.

func (*PubSubService) Subscribe

func (ps *PubSubService) Subscribe(topicName protocol.ID) (*pubsub.Subscription, error)

Subscribe creates a subscription to a topic.

type RetryConfig

type RetryConfig struct {
	MaxRetries      int
	InitialInterval time.Duration
	MaxInterval     time.Duration
	Multiplier      float64
}

RetryConfig holds the configuration for retry attempts.

type Subscription

type Subscription interface {
	Next(ctx context.Context) (*Message, error)
	Cancel()
}

Subscription defines the methods for receiving messages from a subscription.

type TopicType

type TopicType string

func (TopicType) AsProtocolID

func (t TopicType) AsProtocolID() protocol.ID

func (TopicType) String

func (t TopicType) String() string

Jump to

Keyboard shortcuts

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