network

package
v0.0.0-...-7e562c3 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2024 License: AGPL-3.0 Imports: 53 Imported by: 0

Documentation

Index

Constants

View Source
const AddressHeader = "X-Algorand-Location"

AddressHeader HTTP header by which an inbound connection reports its public address

View Source
const (
	ErrorKey = "Error" // used for passing an error message
)

Constant strings used as keys for topics

View Source
const GenesisHeader = "X-Algorand-Genesis"

GenesisHeader HTTP header for genesis id to make sure we're on the same chain

View Source
const GossipNetworkPath = "/v1/{genesisID}/gossip"

GossipNetworkPath is the URL path to connect to the websocket gossip node at. Contains {genesisID} param to be handled by gorilla/mux

View Source
const HealthServiceStatusPath = "/status"

HealthServiceStatusPath is the path to register HealthService as a handler for when using gorilla/mux

View Source
const IdentityChallengeHeader = "X-Algorand-IdentityChallenge"

IdentityChallengeHeader is used to exchange IdentityChallenges

View Source
const InstanceNameHeader = "X-Algorand-InstanceName"

InstanceNameHeader HTTP header by which an inbound connection reports an ID to distinguish multiple local nodes.

View Source
const MaxDecompressedMessageSize = 20 * 1024 * 1024 // some large enough value

MaxDecompressedMessageSize defines a maximum decompressed data size to prevent zip bombs. This depends on MaxTxnBytesPerBlock consensus parameter and should be larger.

View Source
const MaxMessageLength = 6 * 1024 * 1024 // Currently the biggest message is VB vote bundles.

MaxMessageLength is the maximum length of a message that can be sent or received, exported to be used in the node.TestMaxSizesCorrect test

View Source
const NodeRandomHeader = "X-Algorand-NodeRandom"

NodeRandomHeader HTTP header that a node uses to make sure it's not talking to itself

View Source
const PeerFeatureProposalCompression = "ppzstd"

PeerFeatureProposalCompression is a value for PeerFeaturesHeader indicating peer supports proposal payload compression with zstd

View Source
const PeerFeaturesHeader = "X-Algorand-Peer-Features"

PeerFeaturesHeader is the HTTP header listing features

View Source
const PingLength = 8

PingLength is the fixed length of ping message, exported to be used in the node.TestMaxSizesCorrect test

View Source
const PriorityChallengeHeader = "X-Algorand-PriorityChallenge"

PriorityChallengeHeader HTTP header informs a client about the challenge it should sign to increase network priority.

View Source
const ProtocolAcceptVersionHeader = "X-Algorand-Accept-Version"

ProtocolAcceptVersionHeader HTTP header for accept protocol version. Client use this to advertise supported protocol versions.

View Source
const ProtocolVersion = "2.2"

ProtocolVersion is the current version attached to the ProtocolVersionHeader header

Version history:
*  1   Catchup service over websocket connections with unicast messages between peers
*  2.1 Introduced topic key/data pairs and enabled services over the gossip connections
*  2.2 Peer features
View Source
const ProtocolVersionHeader = "X-Algorand-Version"

ProtocolVersionHeader HTTP header for protocol version.

View Source
const ReservedHealthServiceConnections = 10

ReservedHealthServiceConnections reserves additional connections for the health check endpoint. This reserves capacity to query the health check service when a node is serving maximum peers. The file descriptors will be used from the ReservedFDs pool, as this pool is meant for short-lived usage (dns queries, disk i/o, etc.)

View Source
const TelemetryIDHeader = "X-Algorand-TelId"

TelemetryIDHeader HTTP header for telemetry-id for logging

View Source
const TooManyRequestsRetryAfterHeader = "Retry-After"

TooManyRequestsRetryAfterHeader HTTP header let the client know when to make the next connection attempt

View Source
const UserAgentHeader = "User-Agent"

UserAgentHeader is the HTTP header identify the user agent.

Variables

View Source
var ErrIncomingMsgTooLarge = errors.New("read limit exceeded")

ErrIncomingMsgTooLarge is returned when an incoming message is too large

View Source
var SupportedProtocolVersions = []string{"2.2"}

SupportedProtocolVersions contains the list of supported protocol versions by this node ( in order of preference ).

Functions

func DisconnectReasonMaxSize

func DisconnectReasonMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func IdentityChallengeMaxSize

func IdentityChallengeMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func IdentityChallengeResponseMaxSize

func IdentityChallengeResponseMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func IdentityChallengeResponseSignedMaxSize

func IdentityChallengeResponseSignedMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func IdentityChallengeSignedMaxSize

func IdentityChallengeSignedMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func IdentityChallengeValueMaxSize

func IdentityChallengeValueMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func IdentityVerificationMessageMaxSize

func IdentityVerificationMessageMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func IdentityVerificationMessageSignedMaxSize

func IdentityVerificationMessageSignedMaxSize() (s int)

MaxSize returns a maximum valid message size for this message type

func MessageOfInterestMaxSize

func MessageOfInterestMaxSize() int

MessageOfInterestMaxSize returns the maximum size of a MI message sent over the network by encoding all of the tags currenttly in use.

func NewIdentityChallengeScheme

func NewIdentityChallengeScheme(opts ...IdentityChallengeSchemeOption) *identityChallengePublicKeyScheme

NewIdentityChallengeScheme will create a default Identification Scheme

func NewIdentityTracker

func NewIdentityTracker() *publicKeyIdentTracker

NewIdentityTracker returns a new publicKeyIdentTracker

func SetUserAgentHeader

func SetUserAgentHeader(header http.Header)

SetUserAgentHeader adds the User-Agent header to the provided heades map.

func SubstituteGenesisID

func SubstituteGenesisID(net GossipNode, rawURL string) string

SubstituteGenesisID substitutes the "{genesisID}" with their network-specific genesisID.

Types

type DisconnectablePeer

type DisconnectablePeer interface {
	GetNetwork() GossipNode
}

DisconnectablePeer is a Peer with a long-living connection to a network that can be disconnected

type ForwardingPolicy

type ForwardingPolicy int

ForwardingPolicy is an enum indicating to whom we should send a message

const (
	// Ignore - discard (don't forward)
	Ignore ForwardingPolicy = iota

	// Disconnect - disconnect from the peer that sent this message
	Disconnect

	// Broadcast - forward to everyone (except the sender)
	Broadcast

	// Respond - reply to the sender
	Respond

	// Accept - accept for further processing after successful validation
	Accept
)

type GossipNode

type GossipNode interface {
	Address() (string, bool)
	Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error
	Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error
	Disconnect(badnode DisconnectablePeer)
	DisconnectPeers() // only used by testing

	// RegisterHTTPHandler and RegisterHTTPHandlerFunc: path accepts gorilla/mux path annotations
	RegisterHTTPHandler(path string, handler http.Handler)
	RegisterHTTPHandlerFunc(path string, handler func(http.ResponseWriter, *http.Request))

	// RequestConnectOutgoing asks the system to actually connect to peers.
	// `replace` optionally drops existing connections before making new ones.
	// `quit` chan allows cancellation. TODO: use `context`
	RequestConnectOutgoing(replace bool, quit <-chan struct{})

	// Get a list of Peers we could potentially send a direct message to.
	GetPeers(options ...PeerOption) []Peer

	// Start threads, listen on sockets.
	Start() error

	// Close sockets. Stop threads.
	Stop()

	// RegisterHandlers adds to the set of given message handlers.
	RegisterHandlers(dispatch []TaggedMessageHandler)

	// ClearHandlers deregisters all the existing message handlers.
	ClearHandlers()

	// RegisterValidatorHandlers adds to the set of given message validation handlers.
	// A difference with regular handlers is validation ones perform synchronous validation.
	// Currently used as p2p pubsub topic validators.
	RegisterValidatorHandlers(dispatch []TaggedMessageValidatorHandler)

	// ClearValidatorHandlers deregisters all the existing message processors.
	ClearValidatorHandlers()

	// GetHTTPClient returns a http.Client with a suitable for the network Transport
	// that would also limit the number of outgoing connections.
	GetHTTPClient(address string) (*http.Client, error)

	// OnNetworkAdvance notifies the network library that the agreement protocol was able to make a notable progress.
	// this is the only indication that we have that we haven't formed a clique, where all incoming messages
	// arrive very quickly, but might be missing some votes. The usage of this call is expected to have similar
	// characteristics as with a watchdog timer.
	OnNetworkAdvance()

	// GetGenesisID returns the network-specific genesisID.
	GetGenesisID() string
	// contains filtered or unexported methods
}

GossipNode represents a node in the gossip network

func NewWebsocketGossipNode

func NewWebsocketGossipNode(log logging.Logger, config config.Local, phonebookAddresses []string, genesisID string, networkID protocol.NetworkID) (gn GossipNode, err error)

NewWebsocketGossipNode constructs a websocket network node and returns it as a GossipNode interface implementation

type HTTPPAddressBoundTransport

type HTTPPAddressBoundTransport struct {
	Addr           string
	InnerTransport http.RoundTripper
}

HTTPPAddressBoundTransport is a http.RoundTripper that sets the scheme and host of the request URL to the given address

func (*HTTPPAddressBoundTransport) RoundTrip

func (t *HTTPPAddressBoundTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper by adding the schema, host, port, path prefix from the parsed address to the request URL and then calling the inner transport.

type HTTPPeer

type HTTPPeer interface {
	GetAddress() string
	GetHTTPClient() *http.Client
}

HTTPPeer is what the opaque Peer might be. If you get an opaque Peer handle from a GossipNode, maybe try a .(HTTPPeer) type assertion on it.

type HandlerFunc

type HandlerFunc func(message IncomingMessage) OutgoingMessage

HandlerFunc represents an implementation of the MessageHandler interface

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(message IncomingMessage) OutgoingMessage

Handle implements MessageHandler.Handle, calling the handler with the IncomingMessage and returning the OutgoingMessage

type HybridP2PNetwork

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

HybridP2PNetwork runs both P2PNetwork and WebsocketNetwork to implement the GossipNode interface

func NewHybridP2PNetwork

func NewHybridP2PNetwork(log logging.Logger, cfg config.Local, datadir string, phonebookAddresses []string, genesisID string, networkID protocol.NetworkID, nodeInfo NodeInfo) (*HybridP2PNetwork, error)

NewHybridP2PNetwork constructs a GossipNode that combines P2PNetwork and WebsocketNetwork Hybrid mode requires both P2P and WS to be running in server (NetAddress set) or client (NetAddress empty) mode.

func (*HybridP2PNetwork) Address

func (n *HybridP2PNetwork) Address() (string, bool)

Address implements GossipNode

func (*HybridP2PNetwork) BridgeP2PToWS

func (n *HybridP2PNetwork) BridgeP2PToWS(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

BridgeP2PToWS skips Relay/Broadcast to both networks and only sends to WS

func (*HybridP2PNetwork) Broadcast

func (n *HybridP2PNetwork) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Broadcast implements GossipNode

func (*HybridP2PNetwork) ClearHandlers

func (n *HybridP2PNetwork) ClearHandlers()

ClearHandlers deregisters all the existing message handlers.

func (*HybridP2PNetwork) ClearValidatorHandlers

func (n *HybridP2PNetwork) ClearValidatorHandlers()

ClearValidatorHandlers deregisters all the existing message processors.

func (*HybridP2PNetwork) Disconnect

func (n *HybridP2PNetwork) Disconnect(badnode DisconnectablePeer)

Disconnect implements GossipNode

func (*HybridP2PNetwork) DisconnectPeers

func (n *HybridP2PNetwork) DisconnectPeers()

DisconnectPeers implements GossipNode

func (*HybridP2PNetwork) GetGenesisID

func (n *HybridP2PNetwork) GetGenesisID() string

GetGenesisID returns the network-specific genesisID.

func (*HybridP2PNetwork) GetHTTPClient

func (n *HybridP2PNetwork) GetHTTPClient(address string) (*http.Client, error)

GetHTTPClient returns a http.Client with a suitable for the network Transport that would also limit the number of outgoing connections.

func (*HybridP2PNetwork) GetPeers

func (n *HybridP2PNetwork) GetPeers(options ...PeerOption) []Peer

GetPeers implements GossipNode

func (*HybridP2PNetwork) OnNetworkAdvance

func (n *HybridP2PNetwork) OnNetworkAdvance()

OnNetworkAdvance notifies the network library that the agreement protocol was able to make a notable progress. this is the only indication that we have that we haven't formed a clique, where all incoming messages arrive very quickly, but might be missing some votes. The usage of this call is expected to have similar characteristics as with a watchdog timer.

func (*HybridP2PNetwork) RegisterHTTPHandler

func (n *HybridP2PNetwork) RegisterHTTPHandler(path string, handler http.Handler)

RegisterHTTPHandler implements GossipNode

func (*HybridP2PNetwork) RegisterHTTPHandlerFunc

func (n *HybridP2PNetwork) RegisterHTTPHandlerFunc(path string, handlerFunc func(http.ResponseWriter, *http.Request))

RegisterHTTPHandlerFunc implements GossipNode

func (*HybridP2PNetwork) RegisterHandlers

func (n *HybridP2PNetwork) RegisterHandlers(dispatch []TaggedMessageHandler)

RegisterHandlers adds to the set of given message handlers.

func (*HybridP2PNetwork) RegisterValidatorHandlers

func (n *HybridP2PNetwork) RegisterValidatorHandlers(dispatch []TaggedMessageValidatorHandler)

RegisterValidatorHandlers adds to the set of given message processors.

func (*HybridP2PNetwork) Relay

func (n *HybridP2PNetwork) Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Relay implements GossipNode

func (*HybridP2PNetwork) RequestConnectOutgoing

func (n *HybridP2PNetwork) RequestConnectOutgoing(replace bool, quit <-chan struct{})

RequestConnectOutgoing implements GossipNode

func (*HybridP2PNetwork) Start

func (n *HybridP2PNetwork) Start() error

Start implements GossipNode

func (*HybridP2PNetwork) Stop

func (n *HybridP2PNetwork) Stop()

Stop implements GossipNode

type IPAddressable

type IPAddressable interface {
	RoutingAddr() []byte
}

IPAddressable is addressable with either IPv4 or IPv6 address

type IdentityChallengeSchemeOption

type IdentityChallengeSchemeOption func(*identityChallengeSchemeConfig)

IdentityChallengeSchemeOption is a function that can be passed to NewIdentityChallengeScheme

func NetIdentityDedupNames

func NetIdentityDedupNames(dn ...string) IdentityChallengeSchemeOption

NetIdentityDedupNames is an option to set the deduplication names for the identity challenge scheme

func NetIdentitySigner

func NetIdentitySigner(s identityChallengeSigner) IdentityChallengeSchemeOption

NetIdentitySigner is an option to set the signer for the identity challenge scheme

type IncomingMessage

type IncomingMessage struct {
	Sender DisconnectablePeer
	Tag    Tag
	Data   []byte
	Err    error
	Net    GossipNode

	// Received is time.Time.UnixNano()
	Received int64
	// contains filtered or unexported fields
}

IncomingMessage represents a message arriving from some peer in our p2p network

type LimitedReaderSlurper

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

LimitedReaderSlurper collects bytes from an io.Reader, but stops if a limit is reached.

func MakeLimitedReaderSlurper

func MakeLimitedReaderSlurper(baseAllocation, maxAllocation uint64) *LimitedReaderSlurper

MakeLimitedReaderSlurper creates a LimitedReaderSlurper instance with the provided base and max memory allocations.

func (*LimitedReaderSlurper) Bytes

func (s *LimitedReaderSlurper) Bytes() []byte

Bytes returns a copy of all the collected data

func (*LimitedReaderSlurper) Read

func (s *LimitedReaderSlurper) Read(reader io.Reader) error

Read does repeated Read()s on the io.Reader until it gets io.EOF. Returns underlying error or ErrIncomingMsgTooLarge if limit reached. Returns a nil error if the underlying io.Reader returned io.EOF.

func (*LimitedReaderSlurper) Reset

func (s *LimitedReaderSlurper) Reset(n uint64)

Reset clears the buffered data and sets a limit for the upcoming message

func (*LimitedReaderSlurper) Size

func (s *LimitedReaderSlurper) Size() (size uint64)

Size returs the current total size of contained chunks read from io.Reader

type MessageHandler

type MessageHandler interface {
	Handle(message IncomingMessage) OutgoingMessage
}

MessageHandler takes a IncomingMessage (e.g., vote, transaction), processes it, and returns what (if anything) to send to the network in response. The ForwardingPolicy field of the returned OutgoingMessage indicates whether to reply directly to the sender (unicast), propagate to everyone except the sender (broadcast), or do nothing (ignore).

type MessageValidatorHandler

type MessageValidatorHandler interface {
	ValidateHandle(message IncomingMessage) OutgoingMessage
}

MessageValidatorHandler takes a IncomingMessage (e.g., vote, transaction), processes it, and returns what (if anything) to send to the network in response. it supposed to perform synchronous validation and return the result of the validation so that network knows immediately if the message should be be broadcasted or not.

type Multiplexer

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

Multiplexer is a message handler that sorts incoming messages by Tag and passes them along to the relevant message handler for that type of message.

func MakeMultiplexer

func MakeMultiplexer() *Multiplexer

MakeMultiplexer creates an empty Multiplexer

func (*Multiplexer) ClearHandlers

func (m *Multiplexer) ClearHandlers(excludeTags []Tag)

ClearHandlers deregisters all the existing message handlers other than the one provided in the excludeTags list

func (*Multiplexer) ClearValidatorHandlers

func (m *Multiplexer) ClearValidatorHandlers(excludeTags []Tag)

ClearValidatorHandlers deregisters all the existing message handlers other than the one provided in the excludeTags list

func (*Multiplexer) Handle

Handle is the "input" side of the multiplexer. It dispatches the message to the previously defined handler.

func (*Multiplexer) RegisterHandlers

func (m *Multiplexer) RegisterHandlers(dispatch []TaggedMessageHandler)

RegisterHandlers registers the set of given message handlers.

func (*Multiplexer) RegisterValidatorHandlers

func (m *Multiplexer) RegisterValidatorHandlers(dispatch []TaggedMessageValidatorHandler)

RegisterValidatorHandlers registers the set of given message handlers.

func (*Multiplexer) ValidateHandle

func (m *Multiplexer) ValidateHandle(msg IncomingMessage) OutgoingMessage

ValidateHandle is an alternative "input" side of the multiplexer. It dispatches the message to the previously defined validator.

type NetPrioScheme

type NetPrioScheme interface {
	NewPrioChallenge() string
	MakePrioResponse(challenge string) []byte
	VerifyPrioResponse(challenge string, response []byte) (basics.Address, error)
	GetPrioWeight(addr basics.Address) uint64
}

NetPrioScheme is an implementation of network connection priorities based on a challenge-response protocol.

type NodeInfo

type NodeInfo interface {
	// IsParticipating returns true if this node has stake and may vote on blocks or propose blocks.
	IsParticipating() bool
	// Capabilities returns a list of capabilities this node has.
	Capabilities() []p2p.Capability
}

NodeInfo helps the network get information about the node it is running on

type OutgoingMessage

type OutgoingMessage struct {
	Action  ForwardingPolicy
	Tag     Tag
	Payload []byte
	Topics  Topics

	// OnRelease is a function called when outgoing message, resulting from this incoming message, is released
	// either by being sent or discarded.
	OnRelease func()
	// contains filtered or unexported fields
}

OutgoingMessage represents a message we want to send.

func Propagate

func Propagate(msg IncomingMessage) OutgoingMessage

Propagate is a convenience function to save typing in the common case of a message handler telling us to propagate an incoming message "return network.Propagate(msg)" instead of "return network.OutgoingMsg{network.Broadcast, msg.Tag, msg.Data}"

type P2PNetwork

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

P2PNetwork implements the GossipNode interface

func NewP2PNetwork

func NewP2PNetwork(log logging.Logger, cfg config.Local, datadir string, phonebookAddresses []string, genesisID string, networkID protocol.NetworkID, node NodeInfo, identityOpts *identityOpts) (*P2PNetwork, error)

NewP2PNetwork returns an instance of GossipNode that uses the p2p.Service

func (*P2PNetwork) Address

func (n *P2PNetwork) Address() (string, bool)

Address returns a string and whether that is a 'final' address or guessed.

func (*P2PNetwork) Broadcast

func (n *P2PNetwork) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Broadcast sends a message.

func (*P2PNetwork) ClearHandlers

func (n *P2PNetwork) ClearHandlers()

ClearHandlers deregisters all the existing message handlers.

func (*P2PNetwork) ClearValidatorHandlers

func (n *P2PNetwork) ClearValidatorHandlers()

ClearValidatorHandlers deregisters all the existing message handlers.

func (*P2PNetwork) Disconnect

func (n *P2PNetwork) Disconnect(badpeer DisconnectablePeer)

Disconnect from a peer, probably due to protocol errors.

func (*P2PNetwork) DisconnectPeers

func (n *P2PNetwork) DisconnectPeers()

DisconnectPeers is used by testing

func (*P2PNetwork) GetGenesisID

func (n *P2PNetwork) GetGenesisID() string

GetGenesisID implements GossipNode

func (*P2PNetwork) GetHTTPClient

func (n *P2PNetwork) GetHTTPClient(address string) (*http.Client, error)

GetHTTPClient returns a http.Client with a suitable for the network Transport that would also limit the number of outgoing connections.

func (*P2PNetwork) GetPeers

func (n *P2PNetwork) GetPeers(options ...PeerOption) []Peer

GetPeers returns a list of Peers we could potentially send a direct message to.

func (*P2PNetwork) OnNetworkAdvance

func (n *P2PNetwork) OnNetworkAdvance()

OnNetworkAdvance notifies the network library that the agreement protocol was able to make a notable progress. this is the only indication that we have that we haven't formed a clique, where all incoming messages arrive very quickly, but might be missing some votes. The usage of this call is expected to have similar characteristics as with a watchdog timer.

func (*P2PNetwork) PeerID

func (n *P2PNetwork) PeerID() p2p.PeerID

PeerID returns this node's peer ID.

func (*P2PNetwork) PeerIDSigner

func (n *P2PNetwork) PeerIDSigner() identityChallengeSigner

PeerIDSigner returns an identityChallengeSigner that uses the libp2p peer ID's private key.

func (*P2PNetwork) RegisterHTTPHandler

func (n *P2PNetwork) RegisterHTTPHandler(path string, handler http.Handler)

RegisterHTTPHandler path accepts gorilla/mux path annotations

func (*P2PNetwork) RegisterHTTPHandlerFunc

func (n *P2PNetwork) RegisterHTTPHandlerFunc(path string, handler func(http.ResponseWriter, *http.Request))

RegisterHTTPHandlerFunc is like RegisterHTTPHandler but accepts a callback handler function instead of a method receiver.

func (*P2PNetwork) RegisterHandlers

func (n *P2PNetwork) RegisterHandlers(dispatch []TaggedMessageHandler)

RegisterHandlers adds to the set of given message handlers.

func (*P2PNetwork) RegisterValidatorHandlers

func (n *P2PNetwork) RegisterValidatorHandlers(dispatch []TaggedMessageValidatorHandler)

RegisterValidatorHandlers adds to the set of given message handlers.

func (*P2PNetwork) Relay

func (n *P2PNetwork) Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Relay message

func (*P2PNetwork) RequestConnectOutgoing

func (n *P2PNetwork) RequestConnectOutgoing(replace bool, quit <-chan struct{})

RequestConnectOutgoing asks the system to actually connect to peers. `replace` optionally drops existing connections before making new ones. `quit` chan allows cancellation.

func (*P2PNetwork) Start

func (n *P2PNetwork) Start() error

Start threads, listen on sockets.

func (*P2PNetwork) Stop

func (n *P2PNetwork) Stop()

Stop closes sockets and stop threads.

type Peer

type Peer interface{}

Peer opaque interface for referring to a neighbor in the network

type PeerOption

type PeerOption int

PeerOption allows users to specify a subset of peers to query

const (
	// PeersConnectedOut specifies all peers with outgoing connections
	PeersConnectedOut PeerOption = iota
	// PeersConnectedIn specifies all peers with inbound connections
	PeersConnectedIn PeerOption = iota
	// PeersPhonebookRelays specifies all relays in the phonebook
	PeersPhonebookRelays PeerOption = iota
	// PeersPhonebookArchivalNodes specifies all archival nodes (relay or p2p)
	PeersPhonebookArchivalNodes PeerOption = iota
)

type RequestLogger

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

RequestLogger is a middleware helps logging all the incoming http requests. The intended use is to place it at the bottom of the http processing. It will capture the status codes set by the upstream handlers and write the request info/response to the logger.

func (*RequestLogger) ServeHTTP

func (rl *RequestLogger) ServeHTTP(writer http.ResponseWriter, request *http.Request)

this is the http entry point for the request logger.

func (*RequestLogger) SetStatusCode

func (rl *RequestLogger) SetStatusCode(writer http.ResponseWriter, statusCode int)

SetStatusCode sets the status code of a given response writer without writing it to the underlaying writer object.

type RequestTracker

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

RequestTracker tracks the incoming request connections

func (*RequestTracker) Accept

func (rt *RequestTracker) Accept() (conn net.Conn, err error)

Accept waits for and returns the next connection to the listener.

func (*RequestTracker) Addr

func (rt *RequestTracker) Addr() net.Addr

Addr returns the listener's network address.

func (*RequestTracker) Close

func (rt *RequestTracker) Close() error

Close closes the listener. Any blocked Accept operations will be unblocked and return errors.

func (*RequestTracker) GetTrackedRequest

func (rt *RequestTracker) GetTrackedRequest(request *http.Request) (trackedRequest *TrackerRequest)

GetTrackedRequest return the tracked request

func (*RequestTracker) Listener

func (rt *RequestTracker) Listener(listener net.Listener) net.Listener

Listener initialize the underlaying listener, and return the request tracker wrapping listener

func (*RequestTracker) ServeHTTP

func (rt *RequestTracker) ServeHTTP(response http.ResponseWriter, request *http.Request)

type Response

type Response struct {
	Topics Topics
}

Response is the structure holding the response from the server

type TCPInfoUnicastPeer

type TCPInfoUnicastPeer interface {
	UnicastPeer
	GetUnderlyingConnTCPInfo() (*util.TCPInfo, error)
}

TCPInfoUnicastPeer exposes information about the underlying connection if available on the platform

type Tag

type Tag = protocol.Tag

Tag is a short string (2 bytes) marking a type of message

type TaggedMessageHandler

type TaggedMessageHandler = taggedMessageDispatcher[MessageHandler]

TaggedMessageHandler receives one type of broadcast messages

type TaggedMessageValidatorHandler

type TaggedMessageValidatorHandler = taggedMessageDispatcher[MessageValidatorHandler]

TaggedMessageValidatorHandler receives one type of broadcast messages and performs two stage processing: validating and handling

type Topic

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

Topic is a key-value pair

func MakeNonceTopic

func MakeNonceTopic(nonce uint64) Topic

MakeNonceTopic returns a topic with the nonce as the data exported for testing purposes

func MakeTopic

func MakeTopic(key string, data []byte) Topic

MakeTopic Creates a Topic

type Topics

type Topics []Topic

Topics is an array of type Topic The maximum number of topics allowed is 32 Each topic key can be 64 characters long and cannot be size 0

func UnmarshallTopics

func UnmarshallTopics(buffer []byte) (ts Topics, err error)

UnmarshallTopics unmarshalls the topics from the byte array

func (*Topics) GetValue

func (ts *Topics) GetValue(key string) (val []byte, found bool)

GetValue returns the value of the key if the key is found in the topics

func (Topics) MarshallTopics

func (ts Topics) MarshallTopics() (b []byte)

MarshallTopics serializes the topics into a byte array

type TrackerRequest

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

TrackerRequest hold the tracking data associated with a single request. It supposed by an upstream http.Handler called before the wsNetwork's ServeHTTP and wsNetwork's Listener (see Accept() method)

type UnicastPeer

type UnicastPeer interface {
	GetAddress() string
	// Unicast sends the given bytes to this specific peer. Does not wait for message to be sent.
	Unicast(ctx context.Context, data []byte, tag protocol.Tag) error
	// Version returns the matching version from network.SupportedProtocolVersions
	Version() string
	Request(ctx context.Context, tag Tag, topics Topics) (resp *Response, e error)
	Respond(ctx context.Context, reqMsg IncomingMessage, outMsg OutgoingMessage) (e error)
}

UnicastPeer is another possible interface for the opaque Peer. It is possible that we can only initiate a connection to a peer over websockets.

type ValidateHandleFunc

type ValidateHandleFunc func(message IncomingMessage) OutgoingMessage

ValidateHandleFunc represents an implementation of the MessageProcessor interface

func (ValidateHandleFunc) ValidateHandle

func (f ValidateHandleFunc) ValidateHandle(message IncomingMessage) OutgoingMessage

ValidateHandle implements MessageValidatorHandler.ValidateHandle, calling the validator with the IncomingMessage and returning the action.

type WebsocketNetwork

type WebsocketNetwork struct {
	GenesisID string
	NetworkID protocol.NetworkID
	RandomID  string
	// contains filtered or unexported fields
}

WebsocketNetwork implements GossipNode

func NewWebsocketNetwork

func NewWebsocketNetwork(log logging.Logger, config config.Local, phonebookAddresses []string, genesisID string, networkID protocol.NetworkID, nodeInfo NodeInfo, identityOpts *identityOpts) (wn *WebsocketNetwork, err error)

NewWebsocketNetwork constructor for websockets based gossip network

func (*WebsocketNetwork) Address

func (wn *WebsocketNetwork) Address() (string, bool)

Address returns a string and whether that is a 'final' address or guessed. Part of GossipNode interface

func (*WebsocketNetwork) Broadcast

func (wn *WebsocketNetwork) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Broadcast sends a message. If except is not nil then we will not send it to that neighboring Peer. if wait is true then the call blocks until the packet has actually been sent to all neighbors.

func (*WebsocketNetwork) ClearHandlers

func (wn *WebsocketNetwork) ClearHandlers()

ClearHandlers deregisters all the existing message handlers.

func (*WebsocketNetwork) ClearValidatorHandlers

func (wn *WebsocketNetwork) ClearValidatorHandlers()

ClearValidatorHandlers deregisters all the existing message handlers.

func (*WebsocketNetwork) DeregisterMessageInterest

func (wn *WebsocketNetwork) DeregisterMessageInterest(t protocol.Tag)

DeregisterMessageInterest will tell peers to no longer send us traffic with a protocol Tag

func (*WebsocketNetwork) Disconnect

func (wn *WebsocketNetwork) Disconnect(node DisconnectablePeer)

Disconnect from a peer, probably due to protocol errors.

func (*WebsocketNetwork) DisconnectPeers

func (wn *WebsocketNetwork) DisconnectPeers()

DisconnectPeers shuts down all connections

func (*WebsocketNetwork) GetGenesisID

func (wn *WebsocketNetwork) GetGenesisID() string

GetGenesisID returns the network-specific genesisID.

func (*WebsocketNetwork) GetHTTPClient

func (wn *WebsocketNetwork) GetHTTPClient(address string) (*http.Client, error)

GetHTTPClient returns a http.Client with a suitable for the network Transport that would also limit the number of outgoing connections.

func (*WebsocketNetwork) GetPeerData

func (wn *WebsocketNetwork) GetPeerData(peer Peer, key string) interface{}

GetPeerData returns the peer data associated with a particular key.

func (*WebsocketNetwork) GetPeers

func (wn *WebsocketNetwork) GetPeers(options ...PeerOption) []Peer

GetPeers returns a snapshot of our Peer list, according to the specified options. Peers may be duplicated and refer to the same underlying node.

func (*WebsocketNetwork) NumPeers

func (wn *WebsocketNetwork) NumPeers() int

NumPeers returns number of peers we connect to (all peers incoming and outbound).

func (*WebsocketNetwork) OnNetworkAdvance

func (wn *WebsocketNetwork) OnNetworkAdvance()

OnNetworkAdvance notifies the network library that the agreement protocol was able to make a notable progress. this is the only indication that we have that we haven't formed a clique, where all incoming messages arrive very quickly, but might be missing some votes. The usage of this call is expected to have similar characteristics as with a watchdog timer.

func (*WebsocketNetwork) PublicAddress

func (wn *WebsocketNetwork) PublicAddress() string

PublicAddress what we tell other nodes to connect to. Might be different than our locally perceived network address due to NAT/etc. Returns config "PublicAddress" if available, otherwise local addr.

func (*WebsocketNetwork) Ready

func (wn *WebsocketNetwork) Ready() chan struct{}

Ready returns a chan that will be closed when we have a minimum number of peer connections active

func (*WebsocketNetwork) RegisterHTTPHandler

func (wn *WebsocketNetwork) RegisterHTTPHandler(path string, handler http.Handler)

RegisterHTTPHandler path accepts gorilla/mux path annotations

func (*WebsocketNetwork) RegisterHTTPHandlerFunc

func (wn *WebsocketNetwork) RegisterHTTPHandlerFunc(path string, handler func(http.ResponseWriter, *http.Request))

RegisterHTTPHandlerFunc path accepts gorilla/mux path annotations

func (*WebsocketNetwork) RegisterHandlers

func (wn *WebsocketNetwork) RegisterHandlers(dispatch []TaggedMessageHandler)

RegisterHandlers registers the set of given message handlers.

func (*WebsocketNetwork) RegisterValidatorHandlers

func (wn *WebsocketNetwork) RegisterValidatorHandlers(dispatch []TaggedMessageValidatorHandler)

RegisterValidatorHandlers registers the set of given message handlers.

func (*WebsocketNetwork) Relay

func (wn *WebsocketNetwork) Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Relay message

func (*WebsocketNetwork) RelayArray

func (wn *WebsocketNetwork) RelayArray(ctx context.Context, tags []protocol.Tag, data [][]byte, wait bool, except Peer) error

RelayArray relays array of messages

func (*WebsocketNetwork) RequestConnectOutgoing

func (wn *WebsocketNetwork) RequestConnectOutgoing(replace bool, quit <-chan struct{})

RequestConnectOutgoing tries to actually do the connect to new peers. `replace` drop all connections first and find new peers.

func (*WebsocketNetwork) ServeHTTP

func (wn *WebsocketNetwork) ServeHTTP(response http.ResponseWriter, request *http.Request)

ServerHTTP handles the gossip network functions over websockets

func (*WebsocketNetwork) SetPeerData

func (wn *WebsocketNetwork) SetPeerData(peer Peer, key string, value interface{})

SetPeerData sets the peer data associated with a particular key.

func (*WebsocketNetwork) SetPrioScheme

func (wn *WebsocketNetwork) SetPrioScheme(s NetPrioScheme)

SetPrioScheme specifies the network priority scheme for a network node

func (*WebsocketNetwork) Start

func (wn *WebsocketNetwork) Start() error

Start makes network connections and threads

func (*WebsocketNetwork) Stop

func (wn *WebsocketNetwork) Stop()

Stop closes network connections and stops threads. Stop blocks until all activity on this node is done.

Directories

Path Synopsis
p2p
dht

Jump to

Keyboard shortcuts

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