p2p

package
v0.1.19-profiler Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2020 License: MIT Imports: 28 Imported by: 2

Documentation

Overview

Package p2p provides a networking api for creating p2p protocols by enabling sending direct messages to a set of provided neighbors or broadcasting a message to all of them. the discovery, connectivity and encryption is completely transparent to consumers. NOTE: gossip protocols must take care of their own message validation.

Index

Constants

View Source
const ConnectingTimeout = 20 * time.Second //todo: add to the config

ConnectingTimeout is the timeout we wait when trying to connect a neighborhood

View Source
const NoResultsInterval = 1 * time.Second

NoResultsInterval is the timeout we wait between requesting more peers repeatedly

View Source
const UPNPRetries = 20

UPNPRetries is the number of times to retry obtaining a port due to a UPnP failure

Variables

View Source
var (
	// ErrBadFormat1 could'nt deserialize the payload
	ErrBadFormat1 = errors.New("bad msg format, couldn't deserialize 1")
	// ErrBadFormat2 could'nt deserialize the protocol message payload
	ErrBadFormat2 = errors.New("bad msg format, couldn't deserialize 2")
	// ErrOutOfSync is returned when message timestamp was out of sync
	ErrOutOfSync = errors.New("received out of sync msg")
	// ErrFailDecrypt session cant decrypt
	ErrFailDecrypt = errors.New("can't decrypt message payload with session key")
	// ErrNoProtocol we don't have the protocol message
	ErrNoProtocol = errors.New("received msg to an unsupported protocol")
	// ErrNoSession we don't have this session
	ErrNoSession = errors.New("connection is missing a session")
)

Functions

func ExtractData

func ExtractData(pm *Payload) (service.Data, error)

ExtractData is a helper function to extract the payload data from a message payload.

func StringIdentifiers

func StringIdentifiers(boot ...*Switch) []string

StringIdentifiers turns Switch into string representation node for use as bootnodes.

Types

type IntegrationTestSuite

type IntegrationTestSuite struct {
	suite.Suite

	BootstrapNodesCount   int
	BootstrappedNodeCount int
	NeighborsCount        int

	BeforeHook func(idx int, s NodeTestInstance)
	AfterHook  func(idx int, s NodeTestInstance)

	Instances []*Switch
	// contains filtered or unexported fields
}

IntegrationTestSuite is a suite which bootstraps a network according to the given params and lets you run actions on this network. You must set the params before running the suite.

func (*IntegrationTestSuite) ForAll

func (its *IntegrationTestSuite) ForAll(f func(idx int, s NodeTestInstance) error, filter []int) []error

ForAll executes f on all the node and returns error if it failed

func (*IntegrationTestSuite) ForAllAsync

func (its *IntegrationTestSuite) ForAllAsync(ctx context.Context, f func(idx int, s NodeTestInstance) error) ([]error, error)

ForAllAsync executes f on all the nodes concurrently, it stops if ctx is cancelled.

func (*IntegrationTestSuite) SetupSuite

func (its *IntegrationTestSuite) SetupSuite()

SetupSuite setups the configured nodes, bootstraps and connects them.

func (*IntegrationTestSuite) TearDownSuite

func (its *IntegrationTestSuite) TearDownSuite()

TearDownSuite shutdowns all nodes.

func (*IntegrationTestSuite) WaitForGossip

func (its *IntegrationTestSuite) WaitForGossip(ctx context.Context) error

WaitForGossip waits that all nodes initialized gossip connections

type Lookuper

type Lookuper func(key p2pcrypto.PublicKey) (*node.Info, error)

Lookuper is a service used to lookup for nodes we know already

type NodeTestInstance

type NodeTestInstance interface {
	Service
	LocalNode() node.LocalNode // this holds the keys
}

NodeTestInstance is an instance of a p2p node for testing

type Payload

type Payload struct {
	Payload []byte
	Wrapped *service.DataMsgWrapper
}

Payload holds either a byte array or a wrapped req-res message.

func CreatePayload

func CreatePayload(data service.Data) (*Payload, error)

CreatePayload is a helper function to format a payload for sending.

type ProtocolMessage

type ProtocolMessage struct {
	Metadata *ProtocolMessageMetadata
	Payload  *Payload
}

ProtocolMessage is a pair of metadata and a a payload.

type ProtocolMessageMetadata

type ProtocolMessageMetadata struct {
	NextProtocol  string
	ClientVersion string
	Timestamp     int64
	AuthPubkey    []byte
	NetworkID     int32
}

ProtocolMessageMetadata is a general p2p message wrapper

type Service

type Service service.Service

Service is a wrapper for service.Service to expose the Service interface to `p2p` package clients

type Switch added in v0.1.11

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

Switch is the heart of the p2p package. it runs and orchestrates all services within it. It provides the external interface for protocols to access peers or receive incoming messages.

func New

func New(ctx context.Context, config config.Config, logger log.Log, path string) (*Switch, error)

New creates a new P2P service a.k.a `Switch` it loads existing node information from the disk or creates a new one.

func (*Switch) Broadcast added in v0.1.11

func (s *Switch) Broadcast(protocol string, payload []byte) error

Broadcast creates a gossip message signs it and disseminate it to neighbors. this message must be validated by our own node first just as any other message.

func (*Switch) Disconnect added in v0.1.11

func (s *Switch) Disconnect(peer p2pcrypto.PublicKey)

Disconnect removes a peer from the neighborhood. It requests more peers if our outbound peer count is less than configured

func (*Switch) LocalNode added in v0.1.11

func (s *Switch) LocalNode() node.LocalNode

LocalNode is the local p2p identity.

func (*Switch) ProcessDirectProtocolMessage added in v0.1.11

func (s *Switch) ProcessDirectProtocolMessage(sender p2pcrypto.PublicKey, protocol string, data service.Data, metadata service.P2PMetadata) error

ProcessDirectProtocolMessage passes an already decrypted message to a protocol. if protocol does not exist, return and error.

func (*Switch) ProcessGossipProtocolMessage added in v0.1.11

func (s *Switch) ProcessGossipProtocolMessage(sender p2pcrypto.PublicKey, protocol string, data service.Data, validationCompletedChan chan service.MessageValidation) error

ProcessGossipProtocolMessage passes an already decrypted message to a protocol. It is expected that the protocol will send the message syntactic validation result on the validationCompletedChan ASAP

func (*Switch) RegisterDirectProtocol added in v0.1.11

func (s *Switch) RegisterDirectProtocol(protocol string) chan service.DirectMessage

RegisterDirectProtocol registers an handler for a direct messaging based protocol.

func (*Switch) RegisterDirectProtocolWithChannel added in v0.1.11

func (s *Switch) RegisterDirectProtocolWithChannel(protocol string, ingressChannel chan service.DirectMessage) chan service.DirectMessage

RegisterDirectProtocolWithChannel registers a direct protocol with a given channel. NOTE: eventually should replace RegisterDirectProtocol

func (*Switch) RegisterGossipProtocol added in v0.1.11

func (s *Switch) RegisterGossipProtocol(protocol string, prio priorityq.Priority) chan service.GossipMessage

RegisterGossipProtocol registers an handler for a gossip based protocol. priority must be provided.

func (*Switch) SendMessage added in v0.1.11

func (s *Switch) SendMessage(peerPubkey p2pcrypto.PublicKey, protocol string, payload []byte) error

SendMessage sends a p2p message to a peer using it's public key. the provided public key must belong to one of our connected neighbors. otherwise an error will return.

func (*Switch) SendWrappedMessage added in v0.1.11

func (s *Switch) SendWrappedMessage(nodeID p2pcrypto.PublicKey, protocol string, payload *service.DataMsgWrapper) error

SendWrappedMessage sends a wrapped message in order to differentiate between request response and sub protocol messages. It is used by `MessageServer`.

func (*Switch) Shutdown added in v0.1.11

func (s *Switch) Shutdown()

Shutdown sends a shutdown signal to all running services of Switch and then runs an internal shutdown to cleanup.

func (*Switch) Start added in v0.1.11

func (s *Switch) Start() error

Start starts the p2p service. if configured, bootstrap is started in the background. returns error if the Switch is already running or there was an error starting one of the needed services.

func (*Switch) SubscribePeerEvents added in v0.1.11

func (s *Switch) SubscribePeerEvents() (conn, disc chan p2pcrypto.PublicKey)

SubscribePeerEvents lets clients listen on events inside the Switch about peers. first chan is new peers, second is deleted peers.

type UDPMux

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

UDPMux is a server for receiving and sending udp messages through protocols.

func NewUDPMux

func NewUDPMux(localNode node.LocalNode, lookuper Lookuper, udpNet udpNetwork, networkid int8, logger log.Log) *UDPMux

NewUDPMux creates a new udp protocol server

func (*UDPMux) ProcessDirectProtocolMessage

func (mux *UDPMux) ProcessDirectProtocolMessage(sender p2pcrypto.PublicKey, protocol string, data service.Data, metadata service.P2PMetadata) error

ProcessDirectProtocolMessage passes a message to the protocol.

func (*UDPMux) RegisterDirectProtocolWithChannel

func (mux *UDPMux) RegisterDirectProtocolWithChannel(name string, c chan service.DirectMessage) chan service.DirectMessage

RegisterDirectProtocolWithChannel registers a protocol on a channel, should be done before `Start` was called. not thread-safe

func (*UDPMux) SendMessage

func (mux *UDPMux) SendMessage(peerPubkey p2pcrypto.PublicKey, protocol string, payload []byte) error

SendMessage is a proxy method to the sendMessageImpl.

func (*UDPMux) SendWrappedMessage

func (mux *UDPMux) SendWrappedMessage(nodeID p2pcrypto.PublicKey, protocol string, payload *service.DataMsgWrapper) error

SendWrappedMessage is a proxy method to the sendMessageImpl. it sends a wrapped message and used within MessageServer

func (*UDPMux) Shutdown

func (mux *UDPMux) Shutdown()

Shutdown closes the server

func (*UDPMux) Start

func (mux *UDPMux) Start() error

Start starts the UDPMux

Directories

Path Synopsis
Package config defines configuration used in the p2p package
Package config defines configuration used in the p2p package
Package connectionpool functions as a connection cache that takes care of connecting and reusing connected sockets.
Package connectionpool functions as a connection cache that takes care of connecting and reusing connected sockets.
Package discovery implements uses bitcoin-based addrbook to store network addresses and collects them by crawling the network using a simple protocol.
Package discovery implements uses bitcoin-based addrbook to store network addresses and collects them by crawling the network using a simple protocol.
Package gossip implements simple protocol to send new validated messages to all peers and ignore old or not valid messages.
Package gossip implements simple protocol to send new validated messages to all peers and ignore old or not valid messages.
Package metrics defines metric reporting for the p2p component.
Package metrics defines metric reporting for the p2p component.
net
Package net manages the accepting network connections/messages and routing the data upward for the protocols to consume.
Package net manages the accepting network connections/messages and routing the data upward for the protocols to consume.
wire/delimited
Package delimited implements a reader and writer for simple streams of length-delimited byte records.
Package delimited implements a reader and writer for simple streams of length-delimited byte records.
Package node defines simple data structures to represent p2p node identities.
Package node defines simple data structures to represent p2p node identities.
Package p2pcrypto defines the cryptographic primitives used to communicate and identify in the p2p network, it uses go stdlib's NaCL box implementation.
Package p2pcrypto defines the cryptographic primitives used to communicate and identify in the p2p network, it uses go stdlib's NaCL box implementation.
Package server is used to wrap the p2p services to define multiple req-res messages under one protocol.
Package server is used to wrap the p2p services to define multiple req-res messages under one protocol.
Package service defines basic interfaces to for protocols to consume p2p functionality.
Package service defines basic interfaces to for protocols to consume p2p functionality.
Package version includes methods to compare versions between nodes.
Package version includes methods to compare versions between nodes.

Jump to

Keyboard shortcuts

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