p2p

package
v0.36.4-crescendo-prev... Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2024 License: AGPL-3.0 Imports: 26 Imported by: 10

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidId indicates that the given ID (either `peer.ID` or `flow.Identifier`) has an invalid format.
	ErrInvalidId = errors.New("empty peer ID")

	// ErrUnknownId indicates that the given ID (either `peer.ID` or `flow.Identifier`) is unknown.
	ErrUnknownId = errors.New("unknown ID")
)

Functions

func IsInvalidSubscriptionError added in v0.31.0

func IsInvalidSubscriptionError(this error) bool

func NewInvalidSubscriptionError added in v0.31.0

func NewInvalidSubscriptionError(topic string) error

Types

type BasePubSubAdapterConfig added in v0.29.0

type BasePubSubAdapterConfig struct {
	// MaxMessageSize is the maximum size of a message that can be sent on the pubsub network.
	MaxMessageSize int
}

BasePubSubAdapterConfig is the base configuration for the underlying pubsub implementation. These configurations are common to all pubsub implementations and must be observed by all implementations.

type BasicRateLimiter added in v0.30.0

type BasicRateLimiter interface {
	component.Component
	// Allow returns true if a message with the give size should be allowed to be processed.
	Allow(peerID peer.ID, msgSize int) bool
}

BasicRateLimiter rate limiter interface

type CollectionClusterChangesConsumer added in v0.32.0

type CollectionClusterChangesConsumer interface {
	collection.ClusterEvents
}

CollectionClusterChangesConsumer is the interface for consuming the events of changes in the collection cluster. This is used to notify the node of changes in the collection cluster. LibP2PNode implements this interface and consumes the events to be notified of changes in the clustering channels. The clustering channels are used by the collection nodes of a cluster to communicate with each other. As the cluster (and hence their cluster channels) of collection nodes changes over time (per epoch) the node needs to be notified of these changes.

type ConnectionGater added in v0.29.0

type ConnectionGater interface {
	connmgr.ConnectionGater

	// SetDisallowListOracle sets the disallow list oracle for the connection gater.
	// If one is set, the oracle is consulted upon every incoming or outgoing connection attempt, and
	// the connection is only allowed if the remote peer is not on the disallow list.
	// In Flow blockchain, it is not optional to dismiss the disallow list oracle, and if one is not set
	// the connection gater will panic.
	// Also, it follows a dependency injection pattern and does not allow to set the disallow list oracle more than once,
	// any subsequent calls to this method will result in a panic.
	// Args:
	// 	oracle: the disallow list oracle to set.
	// Returns:
	// 	none
	// Panics:
	// 	if the disallow list oracle is already set.
	SetDisallowListOracle(oracle DisallowListOracle)
}

ConnectionGater the customized interface for the connection gater in the p2p package. It acts as a wrapper around the libp2p connmgr.ConnectionGater interface and adds some custom methods.

type Connector

type Connector interface {
	// Connect connects to the given peer.ID.
	// Note that connection may be established asynchronously. Any error encountered while connecting to the peer.ID
	// is benign and should not be returned. Also, Connect implementation should not cause any blocking or crash.
	// Args:
	// 	ctx: context.Context to be used for the connection
	// 	peerChan: channel to which the peer.AddrInfo of the connected peer.ID is sent.
	// Returns:
	//  none.
	Connect(ctx context.Context, peerChan <-chan peer.AddrInfo)
}

Connector is an interface that allows connecting to a peer.ID.

type ConnectorFactory added in v0.32.0

type ConnectorFactory func(host host.Host) (Connector, error)

ConnectorFactory is a factory function to create a new Connector.

type ConnectorHost added in v0.31.0

type ConnectorHost interface {
	// Connections returns all the connections of the underlying host.
	Connections() []network.Conn

	// IsConnectedTo returns true if the given peer.ID is connected to the underlying host.
	// Args:
	// 	peerID: peer.ID for which the connection status is requested
	// Returns:
	// 	true if the given peer.ID is connected to the underlying host.
	IsConnectedTo(peerId peer.ID) bool

	// PeerInfo returns the peer.AddrInfo for the given peer.ID.
	// Args:
	// 	id: peer.ID for which the peer.AddrInfo is requested
	// Returns:
	// 	peer.AddrInfo for the given peer.ID
	PeerInfo(peerId peer.ID) peer.AddrInfo

	// IsProtected returns true if the given peer.ID is protected from pruning.
	// Args:
	// 	id: peer.ID for which the protection status is requested
	// Returns:
	// 	true if the given peer.ID is protected from pruning
	IsProtected(peerId peer.ID) bool

	// ClosePeer closes the connection to the given peer.ID.
	// Args:
	// 	id: peer.ID for which the connection is to be closed
	// Returns:
	// 	error if there is any error while closing the connection to the given peer.ID. All errors are benign.
	ClosePeer(peerId peer.ID) error

	// ID returns the peer.ID of the underlying host.
	// Returns:
	// 	peer.ID of the underlying host.
	ID() peer.ID
}

ConnectorHost is a wrapper around the libp2p host.Host interface to provide the required functionality for the Connector interface.

type CoreP2P added in v0.32.0

type CoreP2P interface {
	// Start the libp2p node.
	Start(ctx irrecoverable.SignalerContext)
	// Stop terminates the libp2p node.
	Stop() error
	// GetIPPort returns the IP and Port the libp2p node is listening on.
	GetIPPort() (string, string, error)
	// Host returns pointer to host object of node.
	Host() host.Host
	// SetComponentManager sets the component manager for the node.
	// SetComponentManager may be called at most once.
	SetComponentManager(cm *component.ComponentManager)
}

CoreP2P service management capabilities

type CtrlMsgTopicType added in v0.33.1

type CtrlMsgTopicType uint64

CtrlMsgTopicType represents the type of the topic within a control message.

const (
	// CtrlMsgNonClusterTopicType represents a non-cluster-prefixed topic.
	CtrlMsgNonClusterTopicType CtrlMsgTopicType = iota
	// CtrlMsgTopicTypeClusterPrefixed represents a cluster-prefixed topic.
	CtrlMsgTopicTypeClusterPrefixed
)

func (CtrlMsgTopicType) String added in v0.33.1

func (t CtrlMsgTopicType) String() string

type DisallowListCache added in v0.32.0

type DisallowListCache interface {
	// IsDisallowListed determines whether the given peer is disallow-listed for any reason.
	// Args:
	// - peerID: the peer to check.
	// Returns:
	// - []network.DisallowListedCause: the list of causes for which the given peer is disallow-listed. If the peer is not disallow-listed for any reason,
	// a nil slice is returned.
	// - bool: true if the peer is disallow-listed for any reason, false otherwise.
	IsDisallowListed(peerID peer.ID) ([]network.DisallowListedCause, bool)

	// DisallowFor disallow-lists a peer for a cause.
	// Args:
	// - peerID: the peerID of the peer to be disallow-listed.
	// - cause: the cause for disallow-listing the peer.
	// Returns:
	// - the list of causes for which the peer is disallow-listed.
	// - error if the operation fails, error is irrecoverable.
	DisallowFor(peerID peer.ID, cause network.DisallowListedCause) ([]network.DisallowListedCause, error)

	// AllowFor removes a cause from the disallow list cache entity for the peerID.
	// Args:
	// - peerID: the peerID of the peer to be allow-listed.
	// - cause: the cause for allow-listing the peer.
	// Returns:
	// - the list of causes for which the peer is disallow-listed. If the peer is not disallow-listed for any reason,
	// an empty list is returned.
	AllowFor(peerID peer.ID, cause network.DisallowListedCause) []network.DisallowListedCause
}

DisallowListCache is an interface for a cache that keeps the list of disallow-listed peers. It is designed to present a centralized interface for keeping track of disallow-listed peers for different reasons.

type DisallowListCacheConfig added in v0.32.0

type DisallowListCacheConfig struct {
	// MaxSize is the maximum number of peers that can be disallow-listed at any given time.
	// When the cache is full, no further new peers can be disallow-listed.
	// Recommended size is 100 * number of staked nodes.
	MaxSize uint32

	// Metrics is the HeroCache metrics collector to be used for the disallow-list cache.
	Metrics module.HeroCacheMetrics
}

DisallowListCacheConfig is the configuration for the disallow-list cache. The disallow-list cache is used to temporarily disallow-list peers.

type DisallowListNotificationConsumer added in v0.30.0

type DisallowListNotificationConsumer interface {
	// OnDisallowListNotification is called when a new disallow list update notification is distributed.
	// Any error on consuming event must handle internally.
	// The implementation must be concurrency safe.
	// Args:
	// 	id: peer ID of the peer being disallow-listed.
	// 	cause: cause of the peer being disallow-listed (only this cause is added to the peer's disallow-listed causes).
	// Returns:
	// 	none
	OnDisallowListNotification(id peer.ID, cause network.DisallowListedCause)

	// OnAllowListNotification is called when a new allow list update notification is distributed.
	// Any error on consuming event must handle internally.
	// The implementation must be concurrency safe.
	// Args:
	// 	id: peer ID of the peer being allow-listed.
	// 	cause: cause of the peer being allow-listed (only this cause is removed from the peer's disallow-listed causes).
	// Returns:
	// 	none
	OnAllowListNotification(id peer.ID, cause network.DisallowListedCause)
}

DisallowListNotificationConsumer is an interface for consuming disallow/allow list update notifications.

type DisallowListOracle added in v0.32.0

type DisallowListOracle interface {
	// IsDisallowListed determines whether the given peer is disallow-listed for any reason.
	// Args:
	// - peerID: the peer to check.
	// Returns:
	// - []network.DisallowListedCause: the list of causes for which the given peer is disallow-listed. If the peer is not disallow-listed for any reason,
	// a nil slice is returned.
	// - bool: true if the peer is disallow-listed for any reason, false otherwise.
	IsDisallowListed(peerId peer.ID) ([]network.DisallowListedCause, bool)
}

DisallowListOracle is an interface for querying disallow-listed peers.

type GossipSubAdapterConfigFunc added in v0.30.0

type GossipSubAdapterConfigFunc func(*BasePubSubAdapterConfig) PubSubAdapterConfig

type GossipSubApplicationSpecificScoreCache added in v0.33.1

type GossipSubApplicationSpecificScoreCache interface {
	// Get returns the application specific score of a peer from the cache.
	// Args:
	// - peerID: the peer ID of the peer in the GossipSub protocol.
	// Returns:
	// - float64: the application specific score of the peer.
	// - time.Time: the time at which the score was last updated.
	// - bool: true if the score was retrieved successfully, false otherwise.
	Get(peerID peer.ID) (float64, time.Time, bool)

	// AdjustWithInit  adds the application specific score of a peer to the cache.
	// If the peer already has a score in the cache, the score is updated.
	// Args:
	// - peerID: the peer ID of the peer in the GossipSub protocol.
	// - score: the application specific score of the peer.
	// - time: the time at which the score was last updated.
	// Returns:
	// - error on failure to add the score. The returned error is irrecoverable and indicates an exception.
	AdjustWithInit(peerID peer.ID, score float64, time time.Time) error
}

GossipSubApplicationSpecificScoreCache is a cache for storing the application specific score of peers. The application specific score of a peer is used to calculate the GossipSub score of the peer; it contains the spam penalty of the peer, staking score, and subscription penalty. Note that none of the application specific scores, spam penalties, staking scores, and subscription penalties are shared publicly with other peers. Rather they are solely used by the current peer to select the peers to which it will connect on a topic mesh. The cache is expected to have an eject policy to remove the least recently used record when the cache is full. Implementation must be thread-safe, but can be blocking.

type GossipSubBuilder added in v0.30.0

type GossipSubBuilder interface {
	// SetHost sets the host of the builder.
	// If the host has already been set, a fatal error is logged.
	SetHost(host.Host)

	// SetSubscriptionFilter sets the subscription filter of the builder.
	// If the subscription filter has already been set, a fatal error is logged.
	SetSubscriptionFilter(pubsub.SubscriptionFilter)

	// SetGossipSubFactory sets the gossipsub factory of the builder.
	// We expect the node to initialize with a default gossipsub factory. Hence, this function overrides the default config.
	SetGossipSubFactory(GossipSubFactoryFunc)

	// SetGossipSubConfigFunc sets the gossipsub config function of the builder.
	// We expect the node to initialize with a default gossipsub config. Hence, this function overrides the default config.
	SetGossipSubConfigFunc(GossipSubAdapterConfigFunc)

	// EnableGossipSubScoringWithOverride enables peer scoring for the GossipSub pubsub system with the given override.
	// Any existing peer scoring config attribute that is set in the override will override the default peer scoring config.
	// Anything that is left to nil or zero value in the override will be ignored and the default value will be used.
	// Note: it is not recommended to override the default peer scoring config in production unless you know what you are doing.
	// Production Tip: use PeerScoringConfigNoOverride as the argument to this function to enable peer scoring without any override.
	// Args:
	// - PeerScoringConfigOverride: override for the peer scoring config- Recommended to use PeerScoringConfigNoOverride for production.
	// Returns:
	// none
	EnableGossipSubScoringWithOverride(*PeerScoringConfigOverride)

	// SetRoutingSystem sets the routing system of the builder.
	// If the routing system has already been set, a fatal error is logged.
	SetRoutingSystem(routing.Routing)

	// OverrideDefaultRpcInspectorFactory overrides the default RPC inspector suite factory of the builder.
	// A default RPC inspector suite factory is provided by the node. This function overrides the default factory.
	// The purpose of override is to allow the node to provide a custom RPC inspector suite factory for sake of testing
	// or experimentation.
	// It is NOT recommended to override the default RPC inspector suite factory in production unless you know what you are doing.
	OverrideDefaultRpcInspectorFactory(GossipSubRpcInspectorFactoryFunc)

	// Build creates a new GossipSub pubsub system.
	// It returns the newly created GossipSub pubsub system and any errors encountered during its creation.
	//
	// Arguments:
	// - context.Context: the irrecoverable context of the node.
	//
	// Returns:
	// - PubSubAdapter: a GossipSub pubsub system for the libp2p node.
	// - error: if an error occurs during the creation of the GossipSub pubsub system, it is returned. Otherwise, nil is returned.
	// Note that on happy path, the returned error is nil. Any error returned is unexpected and should be handled as irrecoverable.
	Build(irrecoverable.SignalerContext) (PubSubAdapter, error)
}

GossipSubBuilder provides a builder pattern for creating a GossipSub pubsub system.

type GossipSubInvCtrlMsgNotifConsumer added in v0.31.0

type GossipSubInvCtrlMsgNotifConsumer interface {
	// OnInvalidControlMessageNotification is called when a new invalid control message notification is distributed.
	// Any error on consuming event must handle internally.
	// The implementation must be concurrency safe and non-blocking.
	// Note: there is no real-time guarantee on processing the notification.
	OnInvalidControlMessageNotification(*InvCtrlMsgNotif)
}

GossipSubInvCtrlMsgNotifConsumer is the interface for the consumer that consumes gossipsub inspector notifications. It is used to consume notifications in an asynchronous manner. The implementation must be concurrency safe, but can be blocking. This is due to the fact that the consumer is called asynchronously by the distributor.

type GossipSubRPCInspector added in v0.30.0

type GossipSubRPCInspector interface {
	collection.ClusterEvents
	component.Component

	// Name returns the name of the rpc inspector.
	Name() string

	// Inspect inspects an incoming RPC message. This callback func is invoked
	// on ever RPC message received before the message is processed by libp2p.
	// If this func returns any error the RPC message will be dropped.
	Inspect(peer.ID, *pubsub.RPC) error
}

GossipSubRPCInspector abstracts the general behavior of an app specific RPC inspector specifically used to inspect and validate incoming. It is used to implement custom message validation logic. It is injected into the GossipSubRouter and run on every incoming RPC message before the message is processed by libp2p. If the message is invalid the RPC message will be dropped. Implementations must:

  • be concurrency safe
  • be non-blocking

type GossipSubRpcInspectorFactoryFunc added in v0.33.30

GossipSubRpcInspectorFactoryFunc is a function that creates a new RPC inspector. It is used to create an RPC inspector for the gossipsub protocol. The RPC inspectors are used to inspect and validate incoming RPC messages before they are processed by the gossipsub protocol. Args: - logger: logger to use - sporkID: spork ID of the node - cfg: configuration for the RPC inspectors - metrics: metrics to use for the RPC inspectors - heroCacheMetricsFactory: metrics factory for the hero cache - networkingType: networking type of the node, i.e., public or private - identityProvider: identity provider of the node Returns: - GossipSubRPCInspector: new RPC inspector suite - error: error if any, any returned error is irrecoverable.

type GossipSubSpamRecord added in v0.31.0

type GossipSubSpamRecord struct {
	// Decay factor of gossipsub spam penalty.
	// The Penalty is multiplied by the Decay factor every time the Penalty is updated.
	// This is to prevent the Penalty from being stuck at a negative value.
	// Each peer has its own Decay factor based on its behavior.
	// Valid decay value is in the range [0, 1].
	Decay float64
	// Penalty is the application specific Penalty of the peer.
	Penalty float64
	// LastDecayAdjustment records the time of the most recent adjustment in the decay process for a spam record.
	// At each interval, the system evaluates and potentially adjusts the decay rate, which affects how quickly a node's penalty diminishes.
	// The decay process is multiplicative (newPenalty = decayRate * oldPenalty) and operates within a range of 0 to 1. At certain regular intervals, the decay adjustment is evaluated and if the node's penalty falls below the set threshold, the decay rate is modified by the reduction factor, such as 0.01. This modification incrementally increases the decay rate. For example, if the decay rate is `x`, adding the reduction factor results in a decay rate of `x + 0.01`, leading to a slower reduction in penalty. Thus, a higher decay rate actually slows down the recovery process, contrary to accelerating it.
	// The LastDecayAdjustment timestamp is crucial in ensuring balanced and fair penalization, especially important during periods of high message traffic to prevent unintended rapid decay of penalties for malicious nodes.
	LastDecayAdjustment time.Time
}

GossipSubSpamRecord represents spam record of a peer in the GossipSub protocol. It acts as a penalty card for a peer in the GossipSub protocol that keeps the spam penalty of the peer as well as its decay factor. GossipSubSpam record is used to calculate the application specific score of a peer in the GossipSub protocol.

type GossipSubSpamRecordCache added in v0.31.0

type GossipSubSpamRecordCache interface {
	// Get returns the GossipSubSpamRecord of a peer from the cache.
	// Args:
	// - peerID: the peer ID of the peer in the GossipSub protocol.
	// Returns:
	// - *GossipSubSpamRecord: the GossipSubSpamRecord of the peer.
	// - error on failure to retrieve the record. The returned error is irrecoverable and indicates an exception.
	// - bool: true if the record was retrieved successfully, false otherwise.
	Get(peerID peer.ID) (*GossipSubSpamRecord, error, bool)

	// Adjust updates the GossipSub spam penalty of a peer in the cache. If the peer does not have a record in the cache, a new record is created.
	// The order of the pre-processing functions is the same as the order in which they were added to the cache.
	// Args:
	// - peerID: the peer ID of the peer in the GossipSub protocol.
	// - updateFn: the update function to be applied to the record.
	// Returns:
	// - *GossipSubSpamRecord: the updated record.
	// - error on failure to update the record. The returned error is irrecoverable and indicates an exception.
	// Note that if any of the pre-processing functions returns an error, the record is reverted to its original state (prior to applying the update function).
	Adjust(peerID peer.ID, updateFunc UpdateFunction) (*GossipSubSpamRecord, error)

	// Has returns true if the cache contains the GossipSubSpamRecord of the given peer.
	// Args:
	// - peerID: the peer ID of the peer in the GossipSub protocol.
	// Returns:
	// - bool: true if the cache contains the GossipSubSpamRecord of the given peer, false otherwise.
	Has(peerID peer.ID) bool
}

GossipSubSpamRecordCache is a cache for storing the GossipSub spam records of peers. The spam records of peers is used to calculate the application specific score, which is part of the GossipSub score of a peer. Note that none of the spam records, application specific score, and GossipSub score are shared publicly with other peers. Rather they are solely used by the current peer to select the peers to which it will connect on a topic mesh.

Implementation must be thread-safe.

type IDTranslator added in v0.21.1

type IDTranslator interface {
	// GetPeerID returns the peer ID for the given `flow.Identifier`.
	// During normal operations, the following error returns are expected
	//  * ErrUnknownId if the given Identifier is unknown
	//  * ErrInvalidId if the given Identifier has an invalid format.
	//    This error return is only possible, when the Identifier is generated from some
	//    other input (e.g. the node's public key). While the Flow protocol itself makes
	//    no assumptions about the structure of the `Identifier`, protocol extensions
	//    (e.g. for Observers) might impose a strict relationship between both flow
	//    Identifier and peer ID, in which case they can use this error.
	// TODO: implementations do not fully adhere to this convention on error returns
	GetPeerID(flow.Identifier) (peer.ID, error)

	// GetFlowID returns the `flow.Identifier` for the given `peer.ID`.
	// During normal operations, the following error returns are expected
	//  * ErrUnknownId if the given Identifier is unknown
	//  * ErrInvalidId if the given Identifier has an invalid format.
	//    This error return is only possible, when the Identifier is generated from some
	//    other input (e.g. the node's public key). While the Flow protocol itself makes
	//    no assumptions about the structure of the `Identifier`, protocol extensions
	//    (e.g. for Observers) might impose a strict relationship between both flow
	//    Identifier and peer ID, in which case they can use this error.
	// TODO: implementations do not fully adhere to this convention on error returns
	GetFlowID(peer.ID) (flow.Identifier, error)
}

IDTranslator provides an interface for converting from Flow ID's to LibP2P peer ID's and vice versa.

type InvCtrlMsgNotif added in v0.31.0

type InvCtrlMsgNotif struct {
	// PeerID is the ID of the peer that sent the invalid control message.
	PeerID peer.ID
	// Error the error that occurred during validation.
	Error error
	// MsgType the control message type.
	MsgType p2pmsg.ControlMessageType
	// Count the number of errors.
	Count uint64
	// TopicType reports whether the error occurred on a cluster-prefixed topic within the control message.
	// Notifications must be explicitly marked as cluster-prefixed or not because the penalty applied to the GossipSub score
	// for an error on a cluster-prefixed topic is more lenient than the penalty applied to a non-cluster-prefixed topic.
	// This distinction ensures that nodes engaged in cluster-prefixed topic communication are not penalized too harshly,
	// as such communication is vital to the progress of the chain.
	TopicType CtrlMsgTopicType
}

InvCtrlMsgNotif is the notification sent to the consumer when an invalid control message is received. It models the information that is available to the consumer about a misbehaving peer.

func NewInvalidControlMessageNotification added in v0.30.0

func NewInvalidControlMessageNotification(peerID peer.ID, ctlMsgType p2pmsg.ControlMessageType, err error, count uint64, topicType CtrlMsgTopicType) *InvCtrlMsgNotif

NewInvalidControlMessageNotification returns a new *InvCtrlMsgNotif Args:

  • peerID: peer id of the offender.
  • ctlMsgType: the control message type of the rpc message that caused the error.
  • err: the error that occurred.
  • count: the number of occurrences of the error.

Returns:

  • *InvCtlMsgNotif: invalid control message notification.

type InvalidSubscriptionError added in v0.31.0

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

InvalidSubscriptionError indicates that a peer has subscribed to a topic that is not allowed for its role. This error is benign, i.e., it does not indicate an illegal state in the execution of the code. We expect this error when there are malicious peers in the network. But such errors should not lead to a crash of the node.32

func (InvalidSubscriptionError) Error added in v0.31.0

func (e InvalidSubscriptionError) Error() string

type LibP2PNode added in v0.29.0

type LibP2PNode interface {
	module.ReadyDoneAware
	Subscriptions
	// PeerConnections connection status information per peer.
	PeerConnections
	// PeerScore exposes the peer score API.
	PeerScore
	// DisallowListNotificationConsumer exposes the disallow list notification consumer API for the node so that
	// it will be notified when a new disallow list update is distributed.
	DisallowListNotificationConsumer
	// CollectionClusterChangesConsumer  is the interface for consuming the events of changes in the collection cluster.
	// This is used to notify the node of changes in the collection cluster.
	// LibP2PNode implements this interface and consumes the events to be notified of changes in the clustering channels.
	// The clustering channels are used by the collection nodes of a cluster to communicate with each other.
	// As the cluster (and hence their cluster channels) of collection nodes changes over time (per epoch) the node needs to be notified of these changes.
	CollectionClusterChangesConsumer
	// DisallowListOracle exposes the disallow list oracle API for external consumers to query about the disallow list.
	DisallowListOracle

	// CoreP2P service management capabilities
	CoreP2P

	// PeerManagement current peer management functions
	PeerManagement

	// Routable routing related features
	Routable

	// PubSub publish subscribe features for node
	PubSub

	// UnicastManagement node stream management
	UnicastManagement
}

LibP2PNode represents a Flow libp2p node. It provides the network layer with the necessary interface to control the underlying libp2p node. It is essentially the Flow wrapper around the libp2p node, and allows us to define different types of libp2p nodes that can operate in different ways by overriding these methods.

type NodeBuilder added in v0.21.0

type NodeBuilder interface {
	SetBasicResolver(madns.BasicResolver) NodeBuilder
	SetSubscriptionFilter(pubsub.SubscriptionFilter) NodeBuilder
	SetResourceManager(network.ResourceManager) NodeBuilder
	SetConnectionManager(connmgr.ConnManager) NodeBuilder
	SetConnectionGater(ConnectionGater) NodeBuilder
	SetRoutingSystem(func(context.Context, host.Host) (routing.Routing, error)) NodeBuilder

	// OverrideGossipSubScoringConfig overrides the default peer scoring config for the GossipSub protocol.
	// Note that it does not enable peer scoring. The peer scoring is enabled directly by setting the `peer-scoring-enabled` flag to true in `default-config.yaml`, or
	// by setting the `gossipsub-peer-scoring-enabled` runtime flag to true. This function only overrides the default peer scoring config which takes effect
	// only if the peer scoring is enabled (mostly for testing purposes).
	// Any existing peer scoring config attribute that is set in the override will override the default peer scoring config.
	// Anything that is left to nil or zero value in the override will be ignored and the default value will be used.
	// Note: it is not recommended to override the default peer scoring config in production unless you know what you are doing.
	// Args:
	// - PeerScoringConfigOverride: override for the peer scoring config- Recommended to use PeerScoringConfigNoOverride for production.
	// Returns:
	// none
	OverrideGossipSubScoringConfig(*PeerScoringConfigOverride) NodeBuilder

	// OverrideNodeConstructor overrides the default node constructor, i.e., the function that creates a new libp2p node.
	// The purpose of override is to allow the node to provide a custom node constructor for sake of testing or experimentation.
	// It is NOT recommended to override the default node constructor in production unless you know what you are doing.
	// Args:
	// - NodeConstructor: custom node constructor
	// Returns:
	// none
	OverrideNodeConstructor(NodeConstructor) NodeBuilder

	// OverrideGossipSubFactory overrides the default gossipsub factory for the GossipSub protocol.
	// The purpose of override is to allow the node to provide a custom gossipsub factory for sake of testing or experimentation.
	// Note: it is not recommended to override the default gossipsub factory in production unless you know what you are doing.
	// Args:
	// - factory: custom gossipsub factory
	// Returns:
	// - NodeBuilder: the node builder
	OverrideGossipSubFactory(GossipSubFactoryFunc, GossipSubAdapterConfigFunc) NodeBuilder

	// OverrideDefaultRpcInspectorFactory overrides the default rpc inspector factory for the GossipSub protocol.
	// The purpose of override is to allow the node to provide a custom rpc inspector factory for sake of testing or experimentation.
	// Note: it is not recommended to override the default rpc inspector factory in production unless you know what you are doing.
	// Args:
	// - factory: custom rpc inspector factory
	// Returns:
	// - NodeBuilder: the node builder
	OverrideDefaultRpcInspectorFactory(GossipSubRpcInspectorFactoryFunc) NodeBuilder

	// Build creates a new libp2p node. It returns the newly created libp2p node and any errors encountered during its creation.
	// Args:
	// none
	// Returns:
	// - LibP2PNode: a new libp2p node
	// - error: if an error occurs during the creation of the libp2p node, it is returned. Otherwise, nil is returned. Any error returned is unexpected and should be handled as irrecoverable.
	Build() (LibP2PNode, error)
}

NodeBuilder is a builder pattern for creating a libp2p Node instance.

type NodeConfig added in v0.33.1

type NodeConfig struct {
	Parameters *NodeParameters `validate:"required"`
	// logger used to provide logging
	Logger zerolog.Logger `validate:"required"`
	// reference to the libp2p host (https://godoc.org/github.com/libp2p/go-libp2p/core/host)
	Host                 host.Host `validate:"required"`
	PeerManager          PeerManager
	DisallowListCacheCfg *DisallowListCacheConfig `validate:"required"`
}

NodeConfig is the configuration for the libp2p node, it contains the parameters as well as the essential components for setting up the node. It is used to create a new libp2p node.

type NodeConstructor added in v0.33.1

type NodeConstructor func(config *NodeConfig) (LibP2PNode, error)

NodeConstructor is a function that creates a new libp2p node. Args: - config: configuration for the node Returns: - LibP2PNode: new libp2p node - error: error if any, any returned error is irrecoverable.

type NodeParameters added in v0.33.1

type NodeParameters struct {
	EnableProtectedStreams bool `validate:"required"`
}

NodeParameters are the numerical values that are used to configure the libp2p node.

type PeerConnections added in v0.30.0

type PeerConnections interface {
	// IsConnected returns true if address is a direct peer of this node else false.
	// Peers are considered not connected if the underlying libp2p host reports the
	// peers as not connected and there are no connections in the connection list.
	// The following error returns indicate a bug in the code:
	//  * network.ErrIllegalConnectionState if the underlying libp2p host reports connectedness as NotConnected but the connections list
	// 	  to the peer is not empty. This indicates a bug within libp2p.
	IsConnected(peerID peer.ID) (bool, error)
}

PeerConnections subset of funcs related to underlying libp2p host connections.

type PeerFilter added in v0.23.9

type PeerFilter func(peer.ID) error

func AllowAllPeerFilter added in v0.29.0

func AllowAllPeerFilter() PeerFilter

AllowAllPeerFilter returns a peer filter that does not do any filtering.

type PeerManagement added in v0.32.0

type PeerManagement interface {
	// ConnectToPeer connects to the peer with the given peer address information.
	// This method is used to connect to a peer that is not in the peer store.
	ConnectToPeer(ctx context.Context, peerInfo peer.AddrInfo) error
	// RemovePeer closes the connection with the peer.
	RemovePeer(peerID peer.ID) error
	// ListPeers returns list of peer IDs for peers subscribed to the topic.
	ListPeers(topic string) []peer.ID
	// GetPeersForProtocol returns slice peer IDs for the specified protocol ID.
	GetPeersForProtocol(pid protocol.ID) peer.IDSlice
	// GetIPPort returns the IP and Port the libp2p node is listening on.
	GetIPPort() (string, string, error)
	// RoutingTable returns the node routing table
	RoutingTable() *kbucket.RoutingTable
	// Subscribe subscribes the node to the given topic and returns the subscription
	Subscribe(topic channels.Topic, topicValidator TopicValidatorFunc) (Subscription, error)
	// Unsubscribe cancels the subscriber and closes the topic corresponding to the given channel.
	Unsubscribe(topic channels.Topic) error
	// Publish publishes the given payload on the topic.
	Publish(ctx context.Context, messageScope network.OutgoingMessageScope) error
	// Host returns pointer to host object of node.
	Host() host.Host
	// ID returns the peer.ID of the node, which is the unique identifier of the node at the libp2p level.
	// For other libp2p nodes, the current node is identified by this ID.
	ID() peer.ID
	// WithDefaultUnicastProtocol overrides the default handler of the unicast manager and registers all preferred protocols.
	WithDefaultUnicastProtocol(defaultHandler libp2pnet.StreamHandler, preferred []protocols.ProtocolName) error
	// WithPeersProvider sets the PeersProvider for the peer manager.
	// If a peer manager factory is set, this method will set the peer manager's PeersProvider.
	WithPeersProvider(peersProvider PeersProvider)
	// PeerManagerComponent returns the component interface of the peer manager.
	PeerManagerComponent() component.Component
	// RequestPeerUpdate requests an update to the peer connections of this node using the peer manager.
	RequestPeerUpdate()
}

PeerManagement set of node traits related to its lifecycle and metadata retrieval

type PeerManager

type PeerManager interface {
	component.Component
	RateLimiterConsumer

	// RequestPeerUpdate requests an update to the peer connections of this node.
	// If a peer update has already been requested (either as a periodic request or an on-demand
	// request) and is outstanding, then this call is a no-op.
	RequestPeerUpdate()

	// ForceUpdatePeers initiates an update to the peer connections of this node immediately
	ForceUpdatePeers(context.Context)

	// SetPeersProvider sets the peer managers's peers provider and may be called at most once
	SetPeersProvider(PeersProvider)
}

PeerManager adds and removes connections to peers periodically and on request

type PeerManagerFactoryFunc added in v0.21.1

type PeerManagerFactoryFunc func(host host.Host, peersProvider PeersProvider, logger zerolog.Logger) (PeerManager, error)

PeerManagerFactoryFunc is a factory function type for generating a PeerManager instance using the given host, peersProvider and logger

type PeerScore added in v0.30.0

type PeerScore interface {
	// PeerScoreExposer returns the node's peer score exposer implementation.
	// If the node's peer score exposer has not been set, the second return value will be false.
	PeerScoreExposer() PeerScoreExposer
}

PeerScore is the interface for the peer score module. It is used to expose the peer score to other components of the node. It is also used to set the peer score exposer implementation.

type PeerScoreExposer added in v0.30.0

type PeerScoreExposer interface {
	// GetScore returns the overall score for the given peer.
	GetScore(peerID peer.ID) (float64, bool)
	// GetAppScore returns the application score for the given peer.
	GetAppScore(peerID peer.ID) (float64, bool)
	// GetIPColocationFactor returns the IP colocation factor for the given peer.
	GetIPColocationFactor(peerID peer.ID) (float64, bool)
	// GetBehaviourPenalty returns the behaviour penalty for the given peer.
	GetBehaviourPenalty(peerID peer.ID) (float64, bool)
	// GetTopicScores returns the topic scores for the given peer for all topics.
	// The returned map is keyed by topic name.
	GetTopicScores(peerID peer.ID) (map[string]TopicScoreSnapshot, bool)
}

PeerScoreExposer is the interface for the tracer that is used to expose the peers score.

type PeerScoreSnapshot added in v0.30.0

type PeerScoreSnapshot struct {
	// Score the overall score of the peer.
	Score float64
	// Topics map that stores the score of the peer per topic.
	Topics map[string]*TopicScoreSnapshot
	// AppSpecificScore application specific score (set by Flow protocol).
	AppSpecificScore float64

	// A positive value indicates that the peer is colocated with other nodes on the same network id,
	// and can be used to warn of sybil attacks.
	IPColocationFactor float64
	// A positive value indicates that GossipSub has caught the peer misbehaving, and can be used to warn of an attack.
	BehaviourPenalty float64
}

PeerScoreSnapshot is a snapshot of the overall peer score at a given time.

func (PeerScoreSnapshot) IsWarning added in v0.30.0

func (p PeerScoreSnapshot) IsWarning() bool

IsWarning returns true if the peer score is in warning state. When the peer score is in warning state, the peer is considered to be misbehaving.

type PeerScoreTracer added in v0.30.0

type PeerScoreTracer interface {
	component.Component
	PeerScoreExposer
	// UpdatePeerScoreSnapshots updates the peer score snapshot/
	UpdatePeerScoreSnapshots(map[peer.ID]*PeerScoreSnapshot)

	// UpdateInterval returns the update interval for the tracer. The tracer will be receiving updates
	// at this interval.
	UpdateInterval() time.Duration
}

PeerScoreTracer is the interface for the tracer that is used to trace the peer score.

type PeerScoringConfigOverride added in v0.32.0

type PeerScoringConfigOverride struct {
	// TopicScoreParams is a map of topic score parameters for each topic.
	// Override criteria: any topic (i.e., key in the map) will override the default topic score parameters for that topic and
	// the corresponding value in the map will be used instead of the default value.
	// If you don't want to override topic score params for a given topic, simply don't include that topic in the map.
	// If the map is nil, the default topic score parameters are used for all topics.
	TopicScoreParams map[channels.Topic]*pubsub.TopicScoreParams

	// AppSpecificScoreParams is a function that returns the application specific score parameters for a given peer.
	// Override criteria: if the function is not nil, it will override the default application specific score parameters.
	// If the function is nil, the default application specific score parameters are used.
	AppSpecificScoreParams func(peer.ID) float64
}

PeerScoringConfigOverride is a structure that is used to carry over the override values for peer scoring configuration. Any attribute that is set in the override will override the default peer scoring config. Typically, we are not recommending to override the default peer scoring config in production unless you know what you are doing.

type PeerUpdater added in v0.32.0

type PeerUpdater interface {
	// UpdatePeers connects to the given peer.IDs. It also disconnects from any other peers with which it may have
	// previously established connection.
	// UpdatePeers implementation should be idempotent such that multiple calls to connect to the same peer should not
	// create multiple connections
	UpdatePeers(ctx context.Context, peerIDs peer.IDSlice)
}

PeerUpdater connects to the given peer.IDs. It also disconnects from any other peers with which it may have previously established connection.

type PeersProvider added in v0.21.1

type PeersProvider func() peer.IDSlice

type ProtocolPeerCache added in v0.30.0

type ProtocolPeerCache interface {
	// RemovePeer removes the specified peer from the protocol cache.
	RemovePeer(peerID peer.ID)

	// AddProtocols adds the specified protocols for the given peer to the protocol cache.
	AddProtocols(peerID peer.ID, protocols []protocol.ID)

	// RemoveProtocols removes the specified protocols for the given peer from the protocol cache.
	RemoveProtocols(peerID peer.ID, protocols []protocol.ID)

	// GetPeers returns a copy of the set of peers that support the given protocol.
	GetPeers(pid protocol.ID) map[peer.ID]struct{}
}

ProtocolPeerCache is an interface that stores a mapping from protocol ID to peers who support that protocol.

type PubSub added in v0.32.0

type PubSub interface {
	// Subscribe subscribes the node to the given topic and returns the subscription
	Subscribe(topic channels.Topic, topicValidator TopicValidatorFunc) (Subscription, error)
	// Unsubscribe cancels the subscriber and closes the topic.
	Unsubscribe(topic channels.Topic) error
	// Publish publishes the given payload on the topic.
	Publish(ctx context.Context, messageScope flownet.OutgoingMessageScope) error
	// SetPubSub sets the node's pubsub implementation.
	// SetPubSub may be called at most once.
	SetPubSub(ps PubSubAdapter)

	// GetLocalMeshPeers returns the list of peers in the local mesh for the given topic.
	// Args:
	// - topic: the topic.
	// Returns:
	// - []peer.ID: the list of peers in the local mesh for the given topic.
	GetLocalMeshPeers(topic channels.Topic) []peer.ID
}

PubSub publish subscribe features for node

type PubSubAdapter added in v0.29.0

type PubSubAdapter interface {
	component.Component
	// CollectionClusterChangesConsumer  is the interface for consuming the events of changes in the collection cluster.
	// This is used to notify the node of changes in the collection cluster.
	// PubSubAdapter implements this interface and consumes the events to be notified of changes in the clustering channels.
	// The clustering channels are used by the collection nodes of a cluster to communicate with each other.
	// As the cluster (and hence their cluster channels) of collection nodes changes over time (per epoch) the node needs to be notified of these changes.
	CollectionClusterChangesConsumer
	// RegisterTopicValidator registers a validator for topic.
	RegisterTopicValidator(topic string, topicValidator TopicValidatorFunc) error

	// UnregisterTopicValidator removes a validator from a topic.
	// Returns an error if there was no validator registered with the topic.
	UnregisterTopicValidator(topic string) error

	// Join joins the topic and returns a Topic handle.
	// Only one Topic handle should exist per topic, and Join will error if the Topic handle already exists.
	Join(topic string) (Topic, error)

	// GetTopics returns all the topics within the pubsub network that the current peer has subscribed to.
	GetTopics() []string

	// ListPeers returns all the peers subscribed to a topic.
	// Note that the current peer must be subscribed to the topic for it to query for other peers.
	// If the current peer is not subscribed to the topic, an empty list is returned.
	// For example, if current peer has subscribed to topics A and B, then ListPeers only return
	// subscribed peers for topics A and B, and querying for topic C will return an empty list.
	ListPeers(topic string) []peer.ID

	// GetLocalMeshPeers returns the list of peers in the local mesh for the given topic.
	// Args:
	// - topic: the topic.
	// Returns:
	// - []peer.ID: the list of peers in the local mesh for the given topic.
	GetLocalMeshPeers(topic channels.Topic) []peer.ID

	// PeerScoreExposer returns the peer score exposer for the gossipsub adapter. The exposer is a read-only interface
	// for querying peer scores and returns the local scoring table of the underlying gossipsub node.
	// The exposer is only available if the gossipsub adapter was configured with a score tracer.
	// If the gossipsub adapter was not configured with a score tracer, the exposer will be nil.
	// Args:
	//     None.
	// Returns:
	//    The peer score exposer for the gossipsub adapter.
	PeerScoreExposer() PeerScoreExposer
}

PubSubAdapter is the abstraction of the underlying pubsub logic that is used by the Flow network.

type PubSubAdapterConfig added in v0.29.0

type PubSubAdapterConfig interface {
	WithRoutingDiscovery(routing.ContentRouting)
	WithSubscriptionFilter(SubscriptionFilter)
	WithScoreOption(ScoreOptionBuilder)
	WithMessageIdFunction(f func([]byte) string)
	WithTracer(t PubSubTracer)
	// WithScoreTracer sets the tracer for the underlying pubsub score implementation.
	// This is used to expose the local scoring table of the GossipSub node to its higher level components.
	WithScoreTracer(tracer PeerScoreTracer)
	WithRpcInspector(GossipSubRPCInspector)
}

PubSubAdapterConfig abstracts the configuration for the underlying pubsub implementation.

type PubSubTracer added in v0.30.0

type PubSubTracer interface {
	component.Component
	pubsub.RawTracer
	RpcControlTracking
	// DuplicateMessageCount returns the current duplicate message count for the peer.
	// Args:
	// - peer.ID: the peer ID.
	// Returns:
	// - float64: duplicate message count.
	DuplicateMessageCount(peer.ID) float64
	// GetLocalMeshPeers returns the list of peers in the mesh for the given topic.
	// Args:
	// - topic: the topic.
	// Returns:
	// - []peer.ID: the list of peers in the mesh for the given topic.
	GetLocalMeshPeers(topic channels.Topic) []peer.ID
}

PubSubTracer is the abstraction of the underlying pubsub tracer that is used by the Flow network. It wraps the pubsub.RawTracer interface with the component.Component interface so that it can be started and stopped. The RawTracer interface is used to trace the internal events of the pubsub system.

type RateLimiter added in v0.29.0

type RateLimiter interface {
	BasicRateLimiter
	// IsRateLimited returns true if a peer is rate limited.
	IsRateLimited(peerID peer.ID) bool
}

RateLimiter rate limiter with lockout feature that can be used via the IsRateLimited method. This limiter allows users to flag a peer as rate limited for a lockout duration.

type RateLimiterConsumer added in v0.30.0

type RateLimiterConsumer interface {
	OnRateLimitedPeer(pid peer.ID, role, msgType, topic, reason string)
}

RateLimiterConsumer consumes notifications from the ratelimit.RateLimiters whenever a peer is rate limited. Implementations must:

  • be concurrency safe
  • be non-blocking

type RateLimiterOpt added in v0.29.0

type RateLimiterOpt func(limiter RateLimiter)

type Routable added in v0.32.0

type Routable interface {
	// RoutingTable returns the node routing table
	RoutingTable() *kbucket.RoutingTable
	// SetRouting sets the node's routing implementation.
	// SetRouting may be called at most once.
	// Returns:
	// - error: An error, if any occurred during the process; any returned error is irrecoverable.
	SetRouting(r routing.Routing) error
	// Routing returns node routing object.
	Routing() routing.Routing
}

Routable set of node routing capabilities

type RpcControlTracking added in v0.32.0

type RpcControlTracking interface {
	// LastHighestIHaveRPCSize returns the last highest size of iHaves sent in a rpc.
	LastHighestIHaveRPCSize() int64
	// WasIHaveRPCSent checks if an iHave control message with the provided message ID was sent.
	WasIHaveRPCSent(messageID string) bool
}

RpcControlTracking is the abstraction of the underlying libp2p control message tracker used to track message ids advertised by the iHave control messages. This collection of methods can ensure an iWant control message for a message-id corresponds to a broadcast iHave message id. Implementations must be non-blocking and concurrency safe.

type ScoreOptionBuilder added in v0.29.0

type ScoreOptionBuilder interface {
	component.Component
	// BuildFlowPubSubScoreOption builds the pubsub score options as pubsub.Option for the Flow network.
	BuildFlowPubSubScoreOption() (*pubsub.PeerScoreParams, *pubsub.PeerScoreThresholds)
	// TopicScoreParams returns the topic score params for the given topic.
	// If the topic score params for the given topic does not exist, it will return the default topic score params.
	TopicScoreParams(*pubsub.Topic) *pubsub.TopicScoreParams
}

ScoreOptionBuilder abstracts the configuration for the underlying pubsub score implementation.

type StreamFactory added in v0.32.2

type StreamFactory interface {
	SetStreamHandler(protocol.ID, network.StreamHandler)
	// NewStream creates a new stream on the libp2p host.
	// Expected errors during normal operations:
	//   - ErrProtocolNotSupported this indicates remote node is running on a different spork.
	NewStream(context.Context, peer.ID, protocol.ID) (network.Stream, error)
}

StreamFactory is a wrapper around libp2p host.Host to provide abstraction and encapsulation for unicast stream manager so that it can create libp2p streams with finer granularity.

type Subscription added in v0.29.0

type Subscription interface {
	// Cancel cancels the subscription so that the caller will no longer receive messages from the topic.
	Cancel()

	// Topic returns the topic that the subscription is subscribed to.
	Topic() string

	// Next returns the next message from the subscription.
	Next(context.Context) (*pubsub.Message, error)
}

Subscription is the abstraction of the underlying pubsub subscription that is used by the Flow network.

type SubscriptionFilter added in v0.29.0

type SubscriptionFilter interface {
	// CanSubscribe returns true if the current peer can subscribe to the topic.
	CanSubscribe(string) bool

	// FilterIncomingSubscriptions is invoked for all RPCs containing subscription notifications.
	// It filters and returns the subscriptions of interest to the current node.
	FilterIncomingSubscriptions(peer.ID, []*pb.RPC_SubOpts) ([]*pb.RPC_SubOpts, error)
}

SubscriptionFilter is the abstraction of the underlying pubsub subscription filter that is used by the Flow network.

type SubscriptionProvider added in v0.28.0

type SubscriptionProvider interface {
	component.Component
	// GetSubscribedTopics returns all the subscriptions of a peer within the pubsub network.
	// Note that the current peer must be subscribed to the topic for it to the same topics in order
	// to query for other peers, e.g., if current peer has subscribed to topics A and B, and peer1
	// has subscribed to topics A, B, and C, then GetSubscribedTopics(peer1) will return A and B. Since this peer
	// has not subscribed to topic C, it will not be able to query for other peers subscribed to topic C.
	GetSubscribedTopics(pid peer.ID) []string
}

SubscriptionProvider provides a list of topics a peer is subscribed to.

type SubscriptionValidator added in v0.31.0

type SubscriptionValidator interface {
	component.Component
	// CheckSubscribedToAllowedTopics checks if a peer is subscribed to topics that it is allowed to subscribe to.
	// Args:
	// 	pid: the peer ID of the peer to check
	//  role: the role of the peer to check
	// Returns:
	// error: if the peer is subscribed to topics that it is not allowed to subscribe to, an InvalidSubscriptionError is returned.
	// The error is benign, i.e., it does not indicate an illegal state in the execution of the code. We expect this error
	// when there are malicious peers in the network. But such errors should not lead to a crash of the node.
	CheckSubscribedToAllowedTopics(pid peer.ID, role flow.Role) error
}

SubscriptionValidator validates the subscription of a peer to a topic. It is used to ensure that a peer is only subscribed to topics that it is allowed to subscribe to.

type Subscriptions added in v0.30.0

type Subscriptions interface {
	// HasSubscription returns true if the node currently has an active subscription to the topic.
	HasSubscription(topic channels.Topic) bool
	// SetUnicastManager sets the unicast manager for the node.
	SetUnicastManager(uniMgr UnicastManager)
}

Subscriptions set of funcs related to current subscription info of a node.

type Topic added in v0.29.0

type Topic interface {
	// String returns the topic name as a string.
	String() string

	// Close closes the topic.
	Close() error

	// Publish publishes a message to the topic.
	Publish(context.Context, []byte) error

	// Subscribe returns a subscription to the topic so that the caller can receive messages from the topic.
	Subscribe() (Subscription, error)
}

Topic is the abstraction of the underlying pubsub topic that is used by the Flow network.

type TopicProvider added in v0.28.0

type TopicProvider interface {
	// GetTopics returns all the topics within the pubsub network that the current peer has subscribed to.
	GetTopics() []string

	// ListPeers returns all the peers subscribed to a topic.
	// Note that the current peer must be subscribed to the topic for it to query for other peers.
	// If the current peer is not subscribed to the topic, an empty list is returned.
	// For example, if current peer has subscribed to topics A and B, then ListPeers only return
	// subscribed peers for topics A and B, and querying for topic C will return an empty list.
	ListPeers(topic string) []peer.ID
}

TopicProvider provides a low-level abstraction for pubsub to perform topic-related queries. This abstraction is provided to encapsulate the pubsub implementation details from the rest of the codebase.

type TopicScoreSnapshot added in v0.30.0

type TopicScoreSnapshot struct {
	// TimeInMesh total time in mesh.
	TimeInMesh time.Duration
	// FirstMessageDeliveries counter of first message deliveries.
	FirstMessageDeliveries float64
	// MeshMessageDeliveries total mesh message deliveries (in the mesh).
	MeshMessageDeliveries float64
	// InvalidMessageDeliveries counter of invalid message deliveries.
	InvalidMessageDeliveries float64
}

TopicScoreSnapshot is a snapshot of the peer score within a topic at a given time. Note that float64 is used for the counters as they are decayed over the time.

func (TopicScoreSnapshot) IsWarning added in v0.30.0

func (s TopicScoreSnapshot) IsWarning() bool

IsWarning returns true if the topic score is in warning state.

func (TopicScoreSnapshot) String added in v0.30.0

func (s TopicScoreSnapshot) String() string

String returns the string representation of the peer score snapshot.

type TopicValidatorFunc added in v0.29.0

type TopicValidatorFunc func(context.Context, peer.ID, *pubsub.Message) ValidationResult

type UnicastManagement added in v0.32.0

type UnicastManagement interface {
	// OpenAndWriteOnStream opens a new stream to a peer with a protection tag. The protection tag can be used to ensure
	// that the connection to the peer is maintained for a particular purpose. The stream is opened to the given peerID
	// and writingLogic is executed on the stream. The created stream does not need to be reused and can be inexpensively
	// created for each send. Moreover, the stream creation does not incur a round-trip time as the stream negotiation happens
	// on an existing connection.
	//
	// Args:
	// - ctx: The context used to control the stream's lifecycle.
	// - peerID: The ID of the peer to open the stream to.
	// - protectionTag: A tag that protects the connection and ensures that the connection manager keeps it alive, and
	//   won't prune the connection while the tag is active.
	// - writingLogic: A callback function that contains the logic for writing to the stream. It allows an external caller to
	//   write to the stream without having to worry about the stream creation and management.
	//
	// Returns:
	// error: An error, if any occurred during the process. This includes failure in creating the stream, setting the write
	// deadline, executing the writing logic, resetting the stream if the writing logic fails, or closing the stream.
	// All returned errors during this process can be considered benign.
	OpenAndWriteOnStream(ctx context.Context, peerID peer.ID, protectionTag string, writingLogic func(stream libp2pnet.Stream) error) error
	// WithDefaultUnicastProtocol overrides the default handler of the unicast manager and registers all preferred protocols.
	WithDefaultUnicastProtocol(defaultHandler libp2pnet.StreamHandler, preferred []protocols.ProtocolName) error
}

UnicastManagement abstracts the unicast management capabilities of the node.

type UnicastManager added in v0.30.0

type UnicastManager interface {
	// WithDefaultHandler sets the default stream handler for this unicast manager. The default handler is utilized
	// as the core handler for other unicast protocols, e.g., compressions.
	SetDefaultHandler(defaultHandler libp2pnet.StreamHandler)
	// Register registers given protocol name as preferred unicast. Each invocation of register prioritizes the current protocol
	// over previously registered ones.
	// All errors returned from this function can be considered benign.
	Register(unicast protocols.ProtocolName) error
	// CreateStream tries establishing a libp2p stream to the remote peer id. It tries creating streams in the descending order of preference until
	// it either creates a successful stream or runs out of options. Creating stream on each protocol is tried at most `maxAttempts`, and then falls
	// back to the less preferred one.
	// All errors returned from this function can be considered benign.
	CreateStream(ctx context.Context, peerID peer.ID) (libp2pnet.Stream, error)
}

UnicastManager manages libp2p stream negotiation and creation, which is utilized for unicast dispatches.

type UnicastRateLimiterDistributor added in v0.30.0

type UnicastRateLimiterDistributor interface {
	RateLimiterConsumer
	AddConsumer(consumer RateLimiterConsumer)
}

UnicastRateLimiterDistributor consumes then distributes notifications from the ratelimit.RateLimiters whenever a peer is rate limited.

type UpdateFunction added in v0.31.0

type UpdateFunction func(record GossipSubSpamRecord) GossipSubSpamRecord

UpdateFunction is a function that adjusts the GossipSub spam record of a peer. Args: - record: the GossipSubSpamRecord of the peer. Returns: - *GossipSubSpamRecord: the adjusted GossipSubSpamRecord of the peer.

type ValidationResult added in v0.29.0

type ValidationResult int
const (
	ValidationAccept ValidationResult = iota
	ValidationIgnore
	ValidationReject
)

Jump to

Keyboard shortcuts

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