p2p

package
v0.27.2-access-fix-en-... Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2022 License: AGPL-3.0 Imports: 68 Imported by: 10

Documentation

Overview

Package p2p encapsulates the libp2p library

Index

Constants

View Source
const (

	// defines maximum message size in publish and multicast modes
	DefaultMaxPubSubMsgSize = 5 * mb // 5 mb

	// defines maximum message size in unicast mode for most messages
	DefaultMaxUnicastMsgSize = 10 * mb // 10 mb

	// defines maximum message size in unicast mode for large messages
	LargeMsgMaxUnicastMsgSize = gb // 1 gb

	// default maximum time to wait for a default unicast request to complete
	// assuming at least a 1mb/sec connection
	DefaultUnicastTimeout = 5 * time.Second

	// maximum time to wait for a unicast request to complete for large message size
	LargeMsgUnicastTimeout = 1000 * time.Second
)
View Source
const (
	// DefaultReceiveCacheSize represents size of receive cache that keeps hash of incoming messages
	// for sake of deduplication.
	DefaultReceiveCacheSize = 10e4
)
View Source
const UnstakedRole = flow.Role(0)

Variables

View Source
var DefaultPeerUpdateInterval = 10 * time.Minute

DefaultPeerUpdateInterval is default duration for which the peer manager waits in between attempts to update peer connections

View Source
var ErrNetworkShutdown = errors.New("network has already shutdown")
View Source
var NotEjectedFilter = filter.Not(filter.Ejected)

NotEjectedFilter is an identity filter that, when applied to the identity table at a given snapshot, returns all nodes that we should communicate with over the networking layer.

NOTE: The protocol state includes nodes from the previous/next epoch that should be included in network communication. We omit any nodes that have been ejected.

Functions

func AsClient added in v0.23.9

func AsClient() dht.Option

func AsServer added in v0.21.0

func AsServer() dht.Option

func ConnectednessToString

func ConnectednessToString(connectedness network.Connectedness) (string, bool)

ConnectednessToString reverse translates libp2p network connectedness to string

func CountStream

func CountStream(host host.Host, targetID peer.ID, protocol core.ProtocolID, dir network.Direction) int

CountStream finds total number of outbound stream to the target id

func DefaultLibP2PHost added in v0.21.0

func DefaultLibP2PHost(ctx context.Context, address string, key fcrypto.PrivateKey, options ...config.Option) (host.Host,
	error)

DefaultLibP2PHost returns a libp2p host initialized to listen on the given address and using the given private key and customized with options

func DefaultMessageIDFunction added in v0.23.9

func DefaultMessageIDFunction(msg *pb.Message) string

DefaultMessageIDFunction returns a default message ID function based on the message's data

func DefaultPubsubOptions added in v0.21.0

func DefaultPubsubOptions(maxPubSubMsgSize int) []pubsub.Option

func DefaultValidators added in v0.20.0

func DefaultValidators(log zerolog.Logger, flowID flow.Identifier) []network.MessageValidator

func DirectionToString

func DirectionToString(direction network.Direction) (string, bool)

DirectionToString reverse translates libp2p network direction to string

func EventId added in v0.23.9

func EventId(channel channels.Channel, payload []byte) (hash.Hash, error)

func FindOutboundStream

func FindOutboundStream(host host.Host, targetID peer.ID, protocol core.ProtocolID) (network.Stream, bool)

FindOutboundStream finds an existing outbound stream to the target id if it exists by querying libp2p

func IPPortFromMultiAddress

func IPPortFromMultiAddress(addrs ...multiaddr.Multiaddr) (string, string, error)

IPPortFromMultiAddress returns the IP/hostname and the port for the given multi-addresses associated with a libp2p host

func IsUnconvertibleIdentitiesError added in v0.14.0

func IsUnconvertibleIdentitiesError(err error) bool

IsUnconvertibleIdentitiesError returns whether the given error is an UnconvertibleIdentitiesError error

func MultiAddressStr added in v0.13.0

func MultiAddressStr(ip, port string) string

MultiAddressStr receives a node ip and port and returns its corresponding Libp2p MultiAddressStr in string format in current implementation IP part of the node address is either an IP or a dns4. https://docs.libp2p.io/concepts/addressing/

func NetworkingInfo added in v0.26.1

func NetworkingInfo(identity flow.Identity) (string, string, crypto.PubKey, error)

NetworkingInfo returns ip, port, libp2p public key of the identity.

func NewBlobService added in v0.23.9

func NewBlobService(
	host host.Host,
	r routing.ContentRouting,
	prefix string,
	ds datastore.Batching,
	opts ...network.BlobServiceOption,
) *blobService

NewBlobService creates a new BlobService.

func NewDHT added in v0.21.0

func NewDHT(ctx context.Context, host host.Host, prefix protocol.ID, logger zerolog.Logger, metrics module.DHTMetrics, options ...dht.Option) (*dht.IpfsDHT, error)

This produces a new IPFS DHT on the name, see https://github.com/libp2p/go-libp2p-kad-dht/issues/337

func NewUnconvertableIdentitiesError added in v0.14.0

func NewUnconvertableIdentitiesError(errs map[flow.Identifier]error) error

func PeerAddressInfo added in v0.13.0

func PeerAddressInfo(identity flow.Identity) (peer.AddrInfo, error)

PeerAddressInfo generates the libp2p peer.AddrInfo for the given Flow.Identity. A node in flow is defined by a flow.Identity while it is defined by a peer.AddrInfo in libp2p. flow.Identity ---> peer.AddrInfo

|-- Address          --->   |-- []multiaddr.Multiaddr
|-- NetworkPublicKey --->   |-- ID

func PeerInfosFromIDs added in v0.26.1

func PeerInfosFromIDs(ids flow.IdentityList) ([]peer.AddrInfo, map[flow.Identifier]error)

PeerInfosFromIDs converts the given flow.Identities to peer.AddrInfo. For each identity, if the conversion succeeds, the peer.AddrInfo is included in the result else it is included in the error map with the corresponding error

func WithBitswapOptions added in v0.23.9

func WithBitswapOptions(opts ...bitswap.Option) network.BlobServiceOption

WithBitswapOptions sets additional options for Bitswap exchange

func WithHashOnRead added in v0.26.2

func WithHashOnRead(enabled bool) network.BlobServiceOption

WithHashOnRead sets whether or not the blobstore will rehash the blob data on read When set, calls to GetBlob will fail with an error if the hash of the data in storage does not match its CID

func WithReprovideInterval added in v0.23.9

func WithReprovideInterval(d time.Duration) network.BlobServiceOption

WithReprovideInterval sets the interval at which DHT provider entries are refreshed

Types

type BlobServiceConfig added in v0.23.9

type BlobServiceConfig struct {
	ReprovideInterval time.Duration    // the interval at which the DHT provider entries are refreshed
	BitswapOptions    []bitswap.Option // options to pass to the Bitswap service
}

type ChannelSubscriptionManager

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

ChannelSubscriptionManager manages subscriptions of engines running on the node to channels. Each channel should be taken by at most a single engine.

func NewChannelSubscriptionManager

func NewChannelSubscriptionManager(mw network.Middleware) *ChannelSubscriptionManager

func (*ChannelSubscriptionManager) Channels added in v0.14.0

Channels returns all the channels registered in this subscription manager.

func (*ChannelSubscriptionManager) GetEngine

GetEngine returns engine associated with a channel.

func (*ChannelSubscriptionManager) Register

Register registers an engine on the channel into the subscription manager.

func (*ChannelSubscriptionManager) Unregister

func (sm *ChannelSubscriptionManager) Unregister(channel channels.Channel) error

Unregister removes the engine associated with a channel.

type ConnGater added in v0.21.0

type ConnGater struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

ConnGater is the implementation of the libp2p connmgr.ConnectionGater interface It provides node allowlisting by libp2p peer.ID which is derived from the node public networking key

func NewConnGater added in v0.21.0

func NewConnGater(log zerolog.Logger, peerFilter PeerFilter) *ConnGater

func (*ConnGater) InterceptAccept added in v0.21.0

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

InterceptAccept is not used. Currently, allowlisting is only implemented by Peer IDs and not multi-addresses

func (*ConnGater) InterceptAddrDial added in v0.21.0

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

InterceptAddrDial is not used. Currently, allowlisting is only implemented by Peer IDs and not multi-addresses

func (*ConnGater) InterceptPeerDial added in v0.21.0

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

InterceptPeerDial - a callback which allows or disallows outbound connection

func (*ConnGater) InterceptSecured added in v0.21.0

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

InterceptSecured - a callback executed after the libp2p security handshake. It tests whether to accept or reject an inbound connection based on its peer id.

func (*ConnGater) InterceptUpgraded added in v0.21.0

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

Decision to continue or drop the connection should have been made before this call

type ConnManager

type ConnManager struct {
	connmgr.NullConnMgr // a null conn mgr provided by libp2p to allow implementing only the functions needed
	// contains filtered or unexported fields
}

ConnManager provides an implementation of Libp2p's ConnManager interface (https://godoc.org/github.com/libp2p/go-libp2p-core/connmgr#ConnManager) It is called back by libp2p when certain events occur such as opening/closing a stream, opening/closing connection etc. This implementation updates networking metrics when a peer connection is added or removed

func NewConnManager

func NewConnManager(log zerolog.Logger, metrics module.NetworkMetrics) *ConnManager

func (*ConnManager) Connected

func (c *ConnManager) Connected(n network.Network, con network.Conn)

Connected is called by libp2p when a connection opened

func (*ConnManager) Disconnected

func (c *ConnManager) Disconnected(n network.Network, con network.Conn)

Disconnected is called by libp2p when a connection closed

func (*ConnManager) IsProtected added in v0.18.3

func (cm *ConnManager) IsProtected(id peer.ID, tag string) (protected bool)

func (*ConnManager) ListenCloseNotifee

func (c *ConnManager) ListenCloseNotifee(n network.Network, m multiaddr.Multiaddr)

called by libp2p when network stops listening on an addr * This is never called back by libp2p currently and may be a bug on their side

func (*ConnManager) ListenNotifee

func (c *ConnManager) ListenNotifee(n network.Network, m multiaddr.Multiaddr)

ListenNotifee is called by libp2p when network starts listening on an addr

func (*ConnManager) Notifee

func (c *ConnManager) Notifee() network.Notifiee

func (*ConnManager) Protect added in v0.23.1

func (cm *ConnManager) Protect(id peer.ID, tag string)

func (*ConnManager) Unprotect added in v0.23.1

func (cm *ConnManager) Unprotect(id peer.ID, tag string) (protected bool)

type Connector

type Connector 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)
}

Connector connects to peer and disconnects from peer using the underlying networking library

type ConnectorOption added in v0.21.1

type ConnectorOption func(connector *Libp2pConnector)

func WithConnectionPruning added in v0.21.1

func WithConnectionPruning(enable bool) ConnectorOption

type FixedTableIdentityTranslator added in v0.21.1

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

FixedTableIdentityTranslator implements an IDTranslator which translates ID's for a fixed list of identities.

func NewFixedTableIdentityTranslator added in v0.21.1

func NewFixedTableIdentityTranslator(identities flow.IdentityList) (*FixedTableIdentityTranslator, error)

func (*FixedTableIdentityTranslator) GetFlowID added in v0.21.1

func (*FixedTableIdentityTranslator) GetPeerID added in v0.21.1

type HierarchicalIDTranslator added in v0.21.1

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

HierarchicalIDTranslator implements an IDTranslator which combines the ID translation capabilities of multiple IDTranslators. When asked to translate an ID, it will iterate through all of the IDTranslators it was given and return the first successful translation.

func NewHierarchicalIDTranslator added in v0.21.1

func NewHierarchicalIDTranslator(translators ...IDTranslator) *HierarchicalIDTranslator

func (*HierarchicalIDTranslator) GetFlowID added in v0.21.1

func (t *HierarchicalIDTranslator) GetFlowID(peerID peer.ID) (flow.Identifier, error)

func (*HierarchicalIDTranslator) GetPeerID added in v0.21.1

func (t *HierarchicalIDTranslator) GetPeerID(flowID flow.Identifier) (peer.ID, error)

type IDTranslator added in v0.21.1

type IDTranslator interface {
	// GetPeerID returns the peer ID for the given Flow ID
	GetPeerID(flow.Identifier) (peer.ID, error)

	// GetFlowID returns the Flow ID for the given peer ID
	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 IdentityProviderIDTranslator added in v0.21.1

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

IdentityProviderIDTranslator implements an IDTranslator which provides ID translation capabilities for an IdentityProvider.

func NewIdentityProviderIDTranslator added in v0.21.1

func NewIdentityProviderIDTranslator(provider id.IdentityProvider) *IdentityProviderIDTranslator

func (*IdentityProviderIDTranslator) GetFlowID added in v0.21.1

func (*IdentityProviderIDTranslator) GetPeerID added in v0.21.1

type LibP2PFactoryFunc added in v0.13.0

type LibP2PFactoryFunc func(context.Context) (*Node, error)

LibP2PFactoryFunc is a factory function type for generating libp2p Node instances.

func DefaultLibP2PNodeFactory added in v0.13.0

func DefaultLibP2PNodeFactory(
	log zerolog.Logger,
	address string,
	flowKey fcrypto.PrivateKey,
	sporkId flow.Identifier,
	idProvider id.IdentityProvider,
	metrics module.NetworkMetrics,
	resolver madns.BasicResolver,
	role string,
) LibP2PFactoryFunc

DefaultLibP2PNodeFactory returns a LibP2PFactoryFunc which generates the libp2p host initialized with the default options for the host, the pubsub and the ping service.

type LibP2PNodeBuilder added in v0.23.9

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

func NewNodeBuilder added in v0.23.9

func NewNodeBuilder(
	logger zerolog.Logger,
	addr string,
	networkKey fcrypto.PrivateKey,
	sporkID flow.Identifier,
) *LibP2PNodeBuilder

func (*LibP2PNodeBuilder) Build added in v0.23.9

func (builder *LibP2PNodeBuilder) Build(ctx context.Context) (*Node, error)

func (*LibP2PNodeBuilder) SetBasicResolver added in v0.23.9

func (builder *LibP2PNodeBuilder) SetBasicResolver(br madns.BasicResolver) NodeBuilder

func (*LibP2PNodeBuilder) SetConnectionGater added in v0.23.9

func (builder *LibP2PNodeBuilder) SetConnectionGater(gater connmgr.ConnectionGater) NodeBuilder

func (*LibP2PNodeBuilder) SetConnectionManager added in v0.23.9

func (builder *LibP2PNodeBuilder) SetConnectionManager(manager connmgr.ConnManager) NodeBuilder

func (*LibP2PNodeBuilder) SetPubSub added in v0.23.9

func (builder *LibP2PNodeBuilder) SetPubSub(f func(context.Context, host.Host, ...pubsub.Option) (*pubsub.PubSub, error)) NodeBuilder

func (*LibP2PNodeBuilder) SetRoutingSystem added in v0.23.9

func (builder *LibP2PNodeBuilder) SetRoutingSystem(f func(context.Context, host.Host) (routing.Routing, error)) NodeBuilder

func (*LibP2PNodeBuilder) SetSubscriptionFilter added in v0.23.9

func (builder *LibP2PNodeBuilder) SetSubscriptionFilter(filter pubsub.SubscriptionFilter) NodeBuilder

type Libp2pConnector added in v0.21.1

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

libp2pConnector is a libp2p based Connector implementation to connect and disconnect from peers

func NewLibp2pConnector added in v0.21.1

func NewLibp2pConnector(host host.Host, log zerolog.Logger, options ...ConnectorOption) (*Libp2pConnector, error)

func (*Libp2pConnector) UpdatePeers added in v0.21.1

func (l *Libp2pConnector) UpdatePeers(ctx context.Context, peerIDs peer.IDSlice)

UpdatePeers is the implementation of the Connector.UpdatePeers function. It connects to all of the ids and disconnects from any other connection that the libp2p node might have.

type Middleware

type Middleware struct {
	sync.Mutex

	component.Component
	// contains filtered or unexported fields
}

Middleware handles the input & output on the direct connections we have to our neighbours on the peer-to-peer network.

func NewMiddleware

func NewMiddleware(
	log zerolog.Logger,
	libP2PNodeFactory LibP2PFactoryFunc,
	flowID flow.Identifier,
	metrics module.NetworkMetrics,
	rootBlockID flow.Identifier,
	unicastMessageTimeout time.Duration,
	idTranslator IDTranslator,
	codec network.Codec,
	opts ...MiddlewareOption,
) *Middleware

NewMiddleware creates a new middleware instance libP2PNodeFactory is the factory used to create a LibP2PNode flowID is this node's Flow ID metrics is the interface to report network related metrics peerUpdateInterval is the interval when the PeerManager's peer update runs unicastMessageTimeout is the timeout used for unicast messages connectionGating if set to True, restricts this node to only talk to other nodes which are part of the identity list managePeerConnections if set to True, enables the default PeerManager which continuously updates the node's peer connections validators are the set of the different message validators that each inbound messages is passed through During normal operations any error returned by Middleware.start is considered to be catastrophic and will be thrown by the irrecoverable.SignalerContext causing the node to crash.

func (*Middleware) GetIPPort

func (m *Middleware) GetIPPort() (string, string, error)

GetIPPort returns the ip address and port number associated with the middleware All errors returned from this function can be considered benign.

func (*Middleware) IsConnected

func (m *Middleware) IsConnected(nodeID flow.Identifier) (bool, error)

IsConnected returns true if this node is connected to the node with id nodeID. All errors returned from this function can be considered benign.

func (*Middleware) Me

func (m *Middleware) Me() flow.Identifier

Me returns the flow identifier of this middleware

func (*Middleware) NewBlobService added in v0.23.9

func (m *Middleware) NewBlobService(channel channels.Channel, ds datastore.Batching, opts ...network.BlobServiceOption) network.BlobService

func (*Middleware) NewPingService added in v0.23.9

func (m *Middleware) NewPingService(pingProtocol protocol.ID, provider network.PingInfoProvider) network.PingService

func (*Middleware) Publish

func (m *Middleware) Publish(msg *message.Message, channel channels.Channel) error

Publish publishes a message on the channel. It models a distributed broadcast where the message is meant for all or a many nodes subscribing to the channel. It does not guarantee the delivery though, and operates on a best effort. The following benign errors are expected during normal operations: - the msg cannot be marshalled. - the msg size exceeds DefaultMaxPubSubMsgSize. - the libP2P node fails to publish the message.

All errors returned from this function can be considered benign.

func (*Middleware) SendDirect

func (m *Middleware) SendDirect(msg *message.Message, targetID flow.Identifier) (err error)

SendDirect sends msg on a 1-1 direct connection to the target ID. It models a guaranteed delivery asynchronous direct one-to-one connection on the underlying network. No intermediate node on the overlay is utilized as the router.

Dispatch should be used whenever guaranteed delivery to a specific target is required. Otherwise, Publish is a more efficient candidate.

The following benign errors can be returned: - he peer ID for the target node ID cannot be found. - the msg size was too large. - failed to send message to peer.

All errors returned from this function can be considered benign.

func (*Middleware) SetOverlay added in v0.23.0

func (m *Middleware) SetOverlay(ov network.Overlay)

func (*Middleware) Subscribe

func (m *Middleware) Subscribe(channel channels.Channel) error

Subscribe subscribes the middleware to a channel. No errors are expected during normal operation.

func (*Middleware) Unsubscribe

func (m *Middleware) Unsubscribe(channel channels.Channel) error

Unsubscribe unsubscribes the middleware from a channel. The following benign errors are expected during normal operations from libP2P: - the libP2P node fails to unsubscribe to the topic created from the provided channel.

All errors returned from this function can be considered benign.

func (*Middleware) UpdateNodeAddresses added in v0.21.1

func (m *Middleware) UpdateNodeAddresses()

type MiddlewareOption added in v0.21.1

type MiddlewareOption func(*Middleware)

func WithMessageValidators added in v0.21.1

func WithMessageValidators(validators ...network.MessageValidator) MiddlewareOption

func WithPeerManager added in v0.21.1

func WithPeerManager(peerManagerFunc PeerManagerFactoryFunc) MiddlewareOption

func WithPreferredUnicastProtocols added in v0.23.3

func WithPreferredUnicastProtocols(unicasts []unicast.ProtocolName) MiddlewareOption

type Network

type Network struct {
	sync.RWMutex
	*component.ComponentManager
	// contains filtered or unexported fields
}

Network represents the overlay network of our peer-to-peer network, including the protocols for handshakes, authentication, gossiping and heartbeats.

func NewNetwork

func NewNetwork(
	log zerolog.Logger,
	codec network.Codec,
	me module.Local,
	mwFactory func() (network.Middleware, error),
	top network.Topology,
	sm network.SubscriptionManager,
	metrics module.NetworkMetrics,
	identityProvider id.IdentityProvider,
	receiveCache *netcache.ReceiveCache,
	options ...NetworkOptFunction,
) (*Network, error)

NewNetwork creates a new naive overlay network, using the given middleware to communicate to direct peers, using the given codec for serialization, and using the given state & cache interfaces to track volatile information. csize determines the size of the cache dedicated to keep track of received messages

func (*Network) Identities added in v0.21.1

func (n *Network) Identities() flow.IdentityList

func (*Network) Identity

func (n *Network) Identity(pid peer.ID) (*flow.Identity, bool)

func (*Network) MulticastOnChannel added in v0.25.0

func (n *Network) MulticastOnChannel(channel channels.Channel, message interface{}, num uint, targetIDs ...flow.Identifier) error

MulticastOnChannel unreliably sends the specified event over the channel to randomly selected 'num' number of recipients selected from the specified targetIDs.

func (*Network) PublishOnChannel added in v0.25.0

func (n *Network) PublishOnChannel(channel channels.Channel, message interface{}, targetIDs ...flow.Identifier) error

PublishOnChannel sends the message in an unreliable way to the given recipients. In this context, unreliable means that the message is published over a libp2p pub-sub channel and can be read by any node subscribed to that channel. The selector could be used to optimize or restrict delivery.

func (*Network) Receive

func (n *Network) Receive(nodeID flow.Identifier, msg *message.Message, decodedMsgPayload interface{}) error

func (*Network) Register

func (n *Network) Register(channel channels.Channel, messageProcessor network.MessageProcessor) (network.Conduit, error)

Register will register the given engine with the given unique engine engineID, returning a conduit to directly submit messages to the message bus of the engine.

func (*Network) RegisterBlobService added in v0.23.9

func (n *Network) RegisterBlobService(channel channels.Channel, ds datastore.Batching, opts ...network.BlobServiceOption) (network.BlobService, error)

RegisterBlobService registers a BlobService on the given channel. The returned BlobService can be used to request blobs from the network.

func (*Network) RegisterPingService added in v0.23.9

func (n *Network) RegisterPingService(pingProtocol protocol.ID, provider network.PingInfoProvider) (network.PingService, error)

func (*Network) Topology

func (n *Network) Topology() (flow.IdentityList, error)

Topology returns the identities of a uniform subset of nodes in protocol state using the topology provided earlier. Independent invocations of Topology on different nodes collectively constructs a connected network graph.

func (*Network) UnRegisterChannel added in v0.25.0

func (n *Network) UnRegisterChannel(channel channels.Channel) error

UnRegisterChannel unregisters the engine for the specified channel. The engine will no longer be able to send or receive messages from that channel.

func (*Network) UnicastOnChannel added in v0.25.0

func (n *Network) UnicastOnChannel(channel channels.Channel, message interface{}, targetID flow.Identifier) error

UnicastOnChannel sends the message in a reliable way to the given recipient. It uses 1-1 direct messaging over the underlying network to deliver the message. It returns an error if unicasting fails.

type NetworkOptFunction added in v0.25.0

type NetworkOptFunction func(*Network)

func WithConduitFactory added in v0.25.0

func WithConduitFactory(f network.ConduitFactory) NetworkOptFunction

type Node

type Node struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Node is a wrapper around the LibP2P host.

func (*Node) AddPeer

func (n *Node) AddPeer(ctx context.Context, peerInfo peer.AddrInfo) error

AddPeer adds a peer to this node by adding it to this node's peerstore and connecting to it

func (*Node) CreateStream

func (n *Node) CreateStream(ctx context.Context, peerID peer.ID) (libp2pnet.Stream, error)

CreateStream returns an existing stream connected to the peer if it exists, or creates a new stream with it.

func (*Node) GetIPPort

func (n *Node) GetIPPort() (string, string, error)

GetIPPort returns the IP and Port the libp2p node is listening on.

func (*Node) GetPeersForProtocol added in v0.23.1

func (n *Node) GetPeersForProtocol(pid protocol.ID) peer.IDSlice

func (*Node) Host

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

Host returns pointer to host object of node.

func (*Node) IsConnected

func (n *Node) IsConnected(peerID peer.ID) (bool, error)

IsConnected returns true is address is a direct peer of this node else false

func (*Node) ListPeers added in v0.26.1

func (n *Node) ListPeers(topic string) []peer.ID

func (*Node) Publish

func (n *Node) Publish(ctx context.Context, topic channels.Topic, data []byte) error

Publish publishes the given payload on the topic

func (*Node) RemovePeer

func (n *Node) RemovePeer(peerID peer.ID) error

RemovePeer closes the connection with the peer.

func (*Node) RoutingTable added in v0.26.1

func (n *Node) RoutingTable() *kbucket.RoutingTable

func (*Node) Stop

func (n *Node) Stop() (chan struct{}, error)

Stop terminates the libp2p node.

func (*Node) Subscribe

func (n *Node) Subscribe(topic channels.Topic, codec flownet.Codec, peerFilter peerFilterFunc, validators ...validator.MessageValidator) (*pubsub.Subscription, error)

Subscribe subscribes the node to the given topic and returns the subscription Currently only one subscriber is allowed per topic. NOTE: A node will receive its own published messages.

func (*Node) UnSubscribe

func (n *Node) UnSubscribe(topic channels.Topic) error

UnSubscribe cancels the subscriber and closes the topic.

func (*Node) WithDefaultUnicastProtocol added in v0.23.3

func (n *Node) WithDefaultUnicastProtocol(defaultHandler libp2pnet.StreamHandler, preferred []unicast.ProtocolName) error

type NodeBuilder added in v0.21.0

type NodeBuilder interface {
	SetBasicResolver(madns.BasicResolver) NodeBuilder
	SetSubscriptionFilter(pubsub.SubscriptionFilter) NodeBuilder
	SetConnectionManager(connmgr.ConnManager) NodeBuilder
	SetConnectionGater(connmgr.ConnectionGater) NodeBuilder
	SetRoutingSystem(func(context.Context, host.Host) (routing.Routing, error)) NodeBuilder
	SetPubSub(func(context.Context, host.Host, ...pubsub.Option) (*pubsub.PubSub, error)) NodeBuilder
	Build(context.Context) (*Node, error)
}

type Option added in v0.18.0

type Option func(*PeerManager)

Option represents an option for the peer manager.

func WithInterval added in v0.18.0

func WithInterval(period time.Duration) Option

type PeerFilter added in v0.23.9

type PeerFilter func(peer.ID) bool

type PeerManager

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

PeerManager adds and removes connections to peers periodically and on request

func NewPeerManager

func NewPeerManager(logger zerolog.Logger, peersProvider PeersProvider,
	connector Connector, options ...Option) *PeerManager

NewPeerManager creates a new peer manager which calls the peersProvider callback to get a list of peers to connect to and it uses the connector to actually connect or disconnect from peers.

func (*PeerManager) Done

func (pm *PeerManager) Done() <-chan struct{}

func (*PeerManager) ForceUpdatePeers added in v0.26.1

func (pm *PeerManager) ForceUpdatePeers()

func (*PeerManager) Ready

func (pm *PeerManager) Ready() <-chan struct{}

Ready kicks off the ambient periodic connection updates.

func (*PeerManager) RequestPeerUpdate

func (pm *PeerManager) RequestPeerUpdate()

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.

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

func PeerManagerFactory added in v0.21.1

func PeerManagerFactory(peerManagerOptions []Option, connectorOptions ...ConnectorOption) PeerManagerFactoryFunc

PeerManagerFactory generates a PeerManagerFunc that produces the default PeerManager with the given peer manager options and that uses the LibP2PConnector with the given LibP2P connector options

type PeersProvider added in v0.21.1

type PeersProvider func() (peer.IDSlice, error)

type PingInfoProviderImpl added in v0.17.0

type PingInfoProviderImpl struct {
	SoftwareVersionFun   func() string
	SealedBlockHeightFun func() (uint64, error)
	HotstuffViewFun      func() (uint64, error)
}

func (PingInfoProviderImpl) HotstuffView added in v0.22.10

func (p PingInfoProviderImpl) HotstuffView() uint64

func (PingInfoProviderImpl) SealedBlockHeight added in v0.17.1

func (p PingInfoProviderImpl) SealedBlockHeight() uint64

func (PingInfoProviderImpl) SoftwareVersion added in v0.17.0

func (p PingInfoProviderImpl) SoftwareVersion() string

type PingService added in v0.17.0

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

PingService handles the outbound and inbound ping requests and response

func NewPingService added in v0.17.0

func NewPingService(
	h host.Host,
	pingProtocolID protocol.ID,
	logger zerolog.Logger,
	pingProvider fnetwork.PingInfoProvider,
) *PingService

func (*PingService) Ping added in v0.17.0

Ping sends a Ping request to the remote node and returns the response, rtt and error if any.

type ProtocolStateIDCache added in v0.21.1

type ProtocolStateIDCache struct {
	events.Noop
	// contains filtered or unexported fields
}

ProtocolStateIDCache implements an IdentityProvider and IDTranslator for the set of authorized Flow network participants as according to the given `protocol.State`.

func NewProtocolStateIDCache added in v0.21.1

func NewProtocolStateIDCache(
	logger zerolog.Logger,
	state protocol.State,
	eventDistributer *events.Distributor,
) (*ProtocolStateIDCache, error)

func (*ProtocolStateIDCache) ByNodeID added in v0.21.1

func (p *ProtocolStateIDCache) ByNodeID(flowID flow.Identifier) (*flow.Identity, bool)

func (*ProtocolStateIDCache) ByPeerID added in v0.21.1

func (p *ProtocolStateIDCache) ByPeerID(peerID peer.ID) (*flow.Identity, bool)

func (*ProtocolStateIDCache) EpochCommittedPhaseStarted added in v0.21.1

func (p *ProtocolStateIDCache) EpochCommittedPhaseStarted(currentEpochCounter uint64, header *flow.Header)

func (*ProtocolStateIDCache) EpochSetupPhaseStarted added in v0.21.1

func (p *ProtocolStateIDCache) EpochSetupPhaseStarted(currentEpochCounter uint64, header *flow.Header)

func (*ProtocolStateIDCache) EpochTransition added in v0.21.1

func (p *ProtocolStateIDCache) EpochTransition(newEpochCounter uint64, header *flow.Header)

func (*ProtocolStateIDCache) GetFlowID added in v0.21.1

func (p *ProtocolStateIDCache) GetFlowID(peerID peer.ID) (fid flow.Identifier, err error)

func (*ProtocolStateIDCache) GetPeerID added in v0.21.1

func (p *ProtocolStateIDCache) GetPeerID(flowID flow.Identifier) (pid peer.ID, err error)

func (*ProtocolStateIDCache) Identities added in v0.21.1

type PublicNetworkIDTranslator added in v0.27.0

type PublicNetworkIDTranslator struct{}

PublicNetworkIDTranslator implements an IDTranslator which translates IDs for peers on the unstaked network. On the unstaked network, a Flow ID is derived from a peer ID by extracting the public key from the peer ID, dropping the first byte (parity byte), and using the remaining 32 bytes as the Flow ID. Network keys for unstaked nodes must be generated using the Secp256k1 curve, and must be positive. It is assumed that these requirements are enforced during key generation, and any peer ID's which don't follow these conventions are considered invalid.

func NewPublicNetworkIDTranslator added in v0.27.0

func NewPublicNetworkIDTranslator() *PublicNetworkIDTranslator

TODO Rename this one to NewPublicNetworkIDTranslator once observer changes are merged

func (*PublicNetworkIDTranslator) GetFlowID added in v0.27.0

func (t *PublicNetworkIDTranslator) GetFlowID(peerID peer.ID) (flow.Identifier, error)

func (*PublicNetworkIDTranslator) GetPeerID added in v0.27.0

func (t *PublicNetworkIDTranslator) GetPeerID(flowID flow.Identifier) (peer.ID, error)

type RoleBasedFilter added in v0.22.4

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

RoleBasedFilter implements a subscription filter that filters subscriptions based on a node's role.

func NewRoleBasedFilter added in v0.22.4

func NewRoleBasedFilter(role flow.Role, idProvider id.IdentityProvider) *RoleBasedFilter

func (*RoleBasedFilter) CanSubscribe added in v0.22.4

func (f *RoleBasedFilter) CanSubscribe(topic string) bool

func (*RoleBasedFilter) FilterIncomingSubscriptions added in v0.22.4

func (f *RoleBasedFilter) FilterIncomingSubscriptions(from peer.ID, opts []*pb.RPC_SubOpts) ([]*pb.RPC_SubOpts, error)

type UnconvertibleIdentitiesError added in v0.14.0

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

UnconvertibleIdentitiesError is an error which reports all the flow.Identifiers that could not be converted to peer.AddrInfo

func (UnconvertibleIdentitiesError) Error added in v0.14.0

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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