network

package
v0.0.0-...-868bdbc Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2020 License: AGPL-3.0 Imports: 28 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrStrInvalidAddress returns if an invalid address was given
	ErrStrInvalidAddress       = "address: invalid address"
	ErrStrAddressEmpty         = "address: cannot dial, address was empty"
	ErrStrNoAvailableAddresses = "address: no available addresses"
)

Errors

View Source
var (
	// ErrStrDuplicatePlugin returns if the plugin has already been registered
	// with the builder
	ErrStrDuplicatePlugin = "builder: plugin %s is already registered"
	// ErrStrNoAddress returns if no address was given to the builder
	ErrStrNoAddress = "builder: network requires public server IP for peers to connect to"
	// ErrStrNoKeyPair returns if no keypair was given to the builder
	ErrStrNoKeyPair = "builder: cryptography keys not provided to Network; cannot create node ID"
)
View Source
var SupervisorListen net.Listener

Functions

func FilterPeers

func FilterPeers(address string, peers []string) (filtered []string)

FilterPeers filters out duplicate/empty addresses.

func FormatAddress

func FormatAddress(protocol string, host string, port uint16) string

FormatAddress properly marshals a destinations information into a string.

func GetRandomUnusedPort

func GetRandomUnusedPort() int

GetRandomUnusedPort returns a random unused port

func GetSignMessage

func GetSignMessage(ctx context.Context) bool

GetSignMessage returns whether the request should be signed

func SerializeMessage

func SerializeMessage(id *protobuf.ID, message []byte) []byte

SerializeMessage compactly packs all bytes of a message together for cryptographic signing purposes.

func ToUnifiedAddress

func ToUnifiedAddress(address string) (string, error)

ToUnifiedAddress resolves and normalizes a network address.

func ToUnifiedHost

func ToUnifiedHost(host string) (string, error)

ToUnifiedHost resolves a domain host.

func WithSignMessage

func WithSignMessage(ctx context.Context, sign bool) context.Context

WithSignMessage sets whether the request should be signed

Types

type AddressInfo

type AddressInfo struct {
	Protocol string
	Host     string
	Port     uint16
}

AddressInfo represents a network URL.

func NewAddressInfo

func NewAddressInfo(protocol string, host string, port uint16) *AddressInfo

NewAddressInfo creates a new AddressInfo instance.

func ParseAddress

func ParseAddress(address string) (*AddressInfo, error)

ParseAddress derives a network scheme, host and port of a destinations information. Errors should the provided destination address be malformed.

func (*AddressInfo) HostPort

func (info *AddressInfo) HostPort() string

HostPort returns the address wihout protocol, in the format `host:port`.

func (*AddressInfo) Network

func (info *AddressInfo) Network() string

Network returns the name of the network client.

func (*AddressInfo) String

func (info *AddressInfo) String() string

String prints out either the URL representation of the address info, or solely just a joined host and port should a network scheme not be defined.

type Builder

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

Builder is a Address->processors struct

func NewBuilder

func NewBuilder() *Builder

NewBuilder returns a new builder with default options.

func NewBuilderWithOptions

func NewBuilderWithOptions(opt ...BuilderOption) *Builder

NewBuilderWithOptions returns a new builder with specified options.

func (*Builder) AddPlugin

func (builder *Builder) AddPlugin(plugin PluginInterface) error

AddPlugin register a new plugin onto the network.

func (*Builder) AddPluginWithPriority

func (builder *Builder) AddPluginWithPriority(priority int, plugin PluginInterface) error

AddPluginWithPriority registers a new plugin onto the network with a set priority.

func (*Builder) Build

func (builder *Builder) Build() (*Network, error)

Build verifies all parameters of the network and returns either an error due to misconfiguration, or a *Network.

func (*Builder) ClearTransportLayers

func (builder *Builder) ClearTransportLayers()

ClearTransportLayers removes all registered transport layers from the builder.

func (*Builder) RegisterTransportLayer

func (builder *Builder) RegisterTransportLayer(name string, layer transport.Layer)

RegisterTransportLayer registers a transport layer to the network keyed by its name.

Example: builder.RegisterTransportLayer("kcp", transport.NewKCP())

func (*Builder) SetAddress

func (builder *Builder) SetAddress(address string)

SetAddress sets the host address for the network.

func (*Builder) SetKeys

func (builder *Builder) SetKeys(pair *crypto.KeyPair)

SetKeys pair created from crypto.KeyPair.

type BuilderOption

type BuilderOption func(*options)

A BuilderOption sets options such as connection timeout and cryptographic // policies for the network

func Address

func Address(address string) BuilderOption

Address address sets assress for connectionn, should include type and port tcp://127.0.0.1:port

func ConnectionTimeout

func ConnectionTimeout(d time.Duration) BuilderOption

ConnectionTimeout returns a NetworkOption that sets the timeout for establishing new connections (default: 60 seconds).

func HashPolicy

func HashPolicy(policy crypto.HashPolicy) BuilderOption

HashPolicy returns a BuilderOption that sets the hash policy for the network (default: blake2b).

func RecvWindowSize

func RecvWindowSize(recvWindowSize int) BuilderOption

RecvWindowSize returns a BuilderOption that sets the receive buffer window size (default: 4096).

func SendWindowSize

func SendWindowSize(sendWindowSize int) BuilderOption

SendWindowSize returns a BuilderOption that sets the send buffer window size (default: 4096).

func SignaturePolicy

func SignaturePolicy(policy crypto.SignaturePolicy) BuilderOption

SignaturePolicy returns a BuilderOption that sets the signature policy for the network (default: ed25519).

func WriteBufferSize

func WriteBufferSize(byteSize int) BuilderOption

WriteBufferSize returns a BuilderOption that sets the write buffer size (default: 4096 bytes).

func WriteFlushLatency

func WriteFlushLatency(d time.Duration) BuilderOption

WriteFlushLatency returns a BuilderOption that sets the write flush interval (default: 50ms).

func WriteTimeout

func WriteTimeout(d time.Duration) BuilderOption

WriteTimeout returns a BuilderOption that sets the write timeout (default: 4096).

type ConnState

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

ConnState represents a connection.

type ConnTester

type ConnTester bool

ConnTester is false if no connection to a peer is established and true if a single connection is found

func (*ConnTester) IsConnected

func (c *ConnTester) IsConnected(netw *Network, peers []string)

IsConnected tests the connection to peers. If no connection is present, the connection is retried for each peer until a connection with any single peer

type Network

type Network struct {

	// Full address to listen on. `protocol://host:port`
	Address string

	// Node's cryptographic ID.
	ID peer.ID
	// contains filtered or unexported fields
}

Network represents the current networking state for this node.

func (*Network) Accept

func (n *Network) Accept(incoming net.Conn)

Accept handles peer registration and processes incoming message streams.

func (*Network) BlockUntilListening

func (n *Network) BlockUntilListening()

BlockUntilListening blocks until this node is listening for new peers.

func (*Network) Bootstrap

func (n *Network) Bootstrap(addresses ...string)

Bootstrap with a number of peers and commence a handshake.

func (*Network) Broadcast

func (n *Network) Broadcast(ctx context.Context, message proto.Message)

Broadcast asynchronously broadcasts a message to all peer clients.

func (*Network) BroadcastByAddresses

func (n *Network) BroadcastByAddresses(ctx context.Context, message proto.Message, addresses ...string)

BroadcastByAddresses broadcasts a message to a set of peer clients denoted by their addresses.

func (*Network) BroadcastByIDs

func (n *Network) BroadcastByIDs(ctx context.Context, message proto.Message, ids ...peer.ID)

BroadcastByIDs broadcasts a message to a set of peer clients denoted by their peer IDs.

func (*Network) BroadcastChildBlock

func (n *Network) BroadcastChildBlock(ctx context.Context, message proto.Message)

BroadcastChildBlock asynchronously broadcasts the child block to all peer validators. tcp://127.0.0.1:3001

func (*Network) BroadcastChildBlockByAddresses

func (n *Network) BroadcastChildBlockByAddresses(ctx context.Context, message proto.Message, addresses ...string)

BroadcastChildBlockByAddresses broadcasts a message to a set of peer clients denoted by their addresses.

func (*Network) BroadcastRandomly

func (n *Network) BroadcastRandomly(ctx context.Context, message proto.Message, K int)

BroadcastRandomly asynchronously broadcasts a message to random selected K peers. Does not guarantee broadcasting to exactly K peers.

func (*Network) Client

func (n *Network) Client(address string) (*PeerClient, error)

Client either creates or returns a cached peer client given its host address.

func (*Network) Close

func (n *Network) Close()

Close shuts down the entire network.

func (*Network) ConnectionState

func (n *Network) ConnectionState(address string) (*ConnState, bool)

ConnectionState returns a connections state for current address.

func (*Network) ConnectionStateExists

func (n *Network) ConnectionStateExists(address string) bool

ConnectionStateExists returns true if network has a connection on a given address.

func (*Network) Dial

func (n *Network) Dial(address string) (net.Conn, error)

Dial establishes a bidirectional connection to an address, and additionally handshakes with said address.

func (*Network) GetKeys

func (n *Network) GetKeys() *crypto.KeyPair

GetKeys returns the keypair for this network

func (*Network) GetNetConnection

func (n *Network) GetNetConnection(address string) net.Conn

GetNetConnection returns a network connection object for current address.

func (*Network) Init

func (n *Network) Init()

Init starts all network I/O workers.

func (*Network) Listen

func (n *Network) Listen()

Listen starts listening for peers on a port.

func (*Network) Plugin

func (n *Network) Plugin(key interface{}) (PluginInterface, bool)

Plugin returns a plugins proxy interface should it be registered with the network. The second returning parameter is false otherwise.

Example: network.Plugin((*Plugin)(nil))

func (*Network) PrepareChildBlock

func (n *Network) PrepareChildBlock(ctx context.Context, message proto.Message) (*protobuf.ChildBlock, error)

PrepareChildBlock marshals a message into a *proto3.ChildBlock and signs it with this nodes private key. Errors if the message is null.

func (*Network) PrepareMessage

func (n *Network) PrepareMessage(ctx context.Context, message proto.Message) (*protobuf.Message, error)

PrepareMessage marshals a message into a *protobuf.Message and signs it with this nodes private key. Errors if the message is null.

func (*Network) SendByID

func (n *Network) SendByID(ctx context.Context, address string, message proto.Message)

SendByID is for testing and it should be deleted

func (*Network) SendChildBlockByAddress

func (n *Network) SendChildBlockByAddress(ctx context.Context, address string, cb protobuf.ChildBlock)

SendChildBlockByAddress ...

func (*Network) Write

func (n *Network) Write(address string, message *protobuf.Message) error

Write asynchronously sends a message to a denoted target address.

func (*Network) WriteChildBlock

func (n *Network) WriteChildBlock(address string, cb *protobuf.ChildBlock) error

WriteChildBlock asynchronously sends a message to a denoted target address.

type NetworkInterface

type NetworkInterface interface {

	// Init starts all network I/O workers.
	Init()

	// GetKeys() returns the keypair for this network
	GetKeys() *crypto.KeyPair

	// Listen starts listening for peers on a port.
	Listen()

	// Client either creates or returns a cached peer client given its host address.
	Client(address string) (*PeerClient, error)

	// BlockUntilListening blocks until this node is listening for new peers.
	BlockUntilListening()

	// Bootstrap with a number of peers and commence a handshake.
	Bootstrap(addresses ...string)

	// Dial establishes a bidirectional connection to an address, and additionally handshakes with said address.
	Dial(address string) (net.Conn, error)

	// Accept handles peer registration and processes incoming message streams.
	Accept(conn net.Conn)

	// Plugin returns a plugins proxy interface should it be registered with the
	// network. The second returning parameter is false otherwise.
	//
	// Example: network.Plugin((*Plugin)(nil))
	Plugin(key interface{}) (PluginInterface, bool)

	// PrepareMessage marshals a message into a *protobuf.Message and signs it with this
	// nodes private key. Errors if the message is null.
	PrepareMessage(ctx context.Context, message proto.Message) (*protobuf.Message, error)

	// Write asynchronously sends a message to a denoted target address.
	Write(address string, message *protobuf.Message) error

	// PrepareChildBlock marshals a message into a *proto3.ChildBlock and signs it with this
	// nodes private key. Errors if the message is null.
	PrepareChildBlock(ctx context.Context, message proto.Message) (*protobuf.ChildBlock, error)

	// WriteChildBlock asynchronously sends a child block to a denoted target address.
	WriteChildBlock(address string, cb *protobuf.ChildBlock) error

	// Broadcast asynchronously broadcasts a message to all peer clients.
	Broadcast(ctx context.Context, message proto.Message)

	SendByID(ctx context.Context, address string, message proto.Message)
	SendChildBlockByAddress(ctx context.Context, address string, message protobuf.ChildBlock)

	// Broadcast asynchronously broadcasts a child block to all validator peer clients.
	BroadcastChildBlock(ctx context.Context, message proto.Message)

	// BroadcastByAddresses broadcasts a message to a set of peer clients denoted by their addresses.
	BroadcastByAddresses(ctx context.Context, message proto.Message, addresses ...string)

	BroadcastChildBlockByAddresses(ctx context.Context, message proto.Message, addresses ...string)

	// BroadcastByIDs broadcasts a message to a set of peer clients denoted by their peer IDs.
	BroadcastByIDs(ctx context.Context, message proto.Message, ids ...peer.ID)

	// BroadcastRandomly asynchronously broadcasts a message to random selected K peers.
	// Does not guarantee broadcasting to exactly K peers.
	BroadcastRandomly(ctx context.Context, message proto.Message, K int)

	// Close shuts down the entire network.
	Close()
}

NetworkInterface represents a node in the network.

type PeerClient

type PeerClient struct {
	sync.Once

	Network *Network

	ID      *peer.ID
	Address string

	Requests     sync.Map // uint64 -> *RequestState
	RequestNonce uint64
	// contains filtered or unexported fields
}

PeerClient represents a single incoming peers client.

func (*PeerClient) Close

func (c *PeerClient) Close() error

Close stops all sessions/streams and cleans up the nodes in routing table.

func (*PeerClient) Init

func (c *PeerClient) Init()

Init initialize a client's pluging and starts executing a jobs.

func (*PeerClient) IsIncomingReady

func (c *PeerClient) IsIncomingReady() bool

IsIncomingReady returns true if the client has both incoming and outgoing sockets established.

func (*PeerClient) IsOutgoingReady

func (c *PeerClient) IsOutgoingReady() bool

IsOutgoingReady returns true if the client has an outgoing socket established.

func (*PeerClient) LocalAddr

func (c *PeerClient) LocalAddr() net.Addr

LocalAddr implements net.Conn.

func (*PeerClient) Read

func (c *PeerClient) Read(out []byte) (int, error)

Read implement net.Conn by reading packets of bytes over a stream.

func (*PeerClient) RemoteAddr

func (c *PeerClient) RemoteAddr() net.Addr

RemoteAddr implements net.Conn.

func (*PeerClient) Reply

func (c *PeerClient) Reply(ctx context.Context, nonce uint64, message proto.Message) error

Reply is equivalent to Write() with an appended nonce to signal a reply.

func (*PeerClient) Request

func (c *PeerClient) Request(ctx context.Context, req proto.Message) (proto.Message, error)

Request requests for a response for a request sent to a given peer.

func (*PeerClient) SetDeadline

func (c *PeerClient) SetDeadline(t time.Time) error

SetDeadline implements net.Conn.

func (*PeerClient) SetReadDeadline

func (c *PeerClient) SetReadDeadline(t time.Time) error

SetReadDeadline implements net.Conn.

func (*PeerClient) SetWriteDeadline

func (c *PeerClient) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements net.Conn.

func (*PeerClient) Submit

func (c *PeerClient) Submit(job func())

Submit adds a job to the execution queue.

func (*PeerClient) Tell

func (c *PeerClient) Tell(ctx context.Context, message proto.Message) error

Tell will asynchronously emit a message to a given peer.

func (*PeerClient) Write

func (c *PeerClient) Write(data []byte) (int, error)

Write implements net.Conn and sends packets of bytes over a stream.

type Plugin

type Plugin struct{}

Plugin is an abstract class which all plugins extend.

func (*Plugin) Cleanup

func (*Plugin) Cleanup(net *Network)

Cleanup is called only once after network stops listening

func (*Plugin) PeerConnect

func (*Plugin) PeerConnect(client *PeerClient)

PeerConnect is called every time a PeerClient is initialized and connected

func (*Plugin) PeerDisconnect

func (*Plugin) PeerDisconnect(client *PeerClient)

PeerDisconnect is called every time a PeerClient connection is closed

func (*Plugin) Receive

func (*Plugin) Receive(ctx *PluginContext) error

Receive is called every time when messages are received

func (*Plugin) Startup

func (*Plugin) Startup(net *Network)

Startup is called only once when the plugin is loaded

type PluginContext

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

PluginContext provides parameters and helper functions to a Plugin for interacting with/analyzing incoming messages from a select peer.

func (*PluginContext) Client

func (pctx *PluginContext) Client() *PeerClient

Client returns the peer client.

func (*PluginContext) Message

func (pctx *PluginContext) Message() proto.Message

Message returns the decoded protobuf message.

func (*PluginContext) Network

func (pctx *PluginContext) Network() *Network

Network returns the entire node's network.

func (*PluginContext) Reply

func (pctx *PluginContext) Reply(ctx context.Context, message proto.Message) error

Reply sends back a message to an incoming message's incoming stream.

func (*PluginContext) Self

func (pctx *PluginContext) Self() peer.ID

Self returns the node's ID.

func (*PluginContext) Sender

func (pctx *PluginContext) Sender() peer.ID

Sender returns the peer's ID.

type PluginInfo

type PluginInfo struct {
	Priority int
	Plugin   PluginInterface
}

PluginInfo wraps a priority level with a plugin interface.

type PluginInterface

type PluginInterface interface {
	// Callback for when the network starts listening for peers.
	Startup(net *Network)

	// Callback for when an incoming message is received. Return true
	// if the plugin will intercept messages to be processed.
	Receive(ctx *PluginContext) error

	// Callback for when the network stops listening for peers.
	Cleanup(net *Network)

	// Callback for when a peer connects to the network.
	PeerConnect(client *PeerClient)

	// Callback for when a peer disconnects from the network.
	PeerDisconnect(client *PeerClient)
}

PluginInterface is used to proxy callbacks to a particular Plugin instance.

type PluginList

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

PluginList holds a statically-typed sorted map of plugins registered on Noise.

func NewPluginList

func NewPluginList() *PluginList

NewPluginList creates a new instance of a sorted plugin list.

func (*PluginList) Each

func (m *PluginList) Each(f func(value PluginInterface))

Each goes through every plugin in ascending order of priority of the plugin list.

func (*PluginList) Get

func (m *PluginList) Get(withTy interface{}) (PluginInterface, bool)

Get returns the plugin interface given a plugin ID. Returns nil if not exists.

func (*PluginList) GetInfo

func (m *PluginList) GetInfo(withTy interface{}) (*PluginInfo, bool)

GetInfo gets the priority and plugin interface given a plugin ID. Returns nil if not exists.

func (*PluginList) Len

func (m *PluginList) Len() int

Len returns the number of plugins in the plugin list.

func (*PluginList) Put

func (m *PluginList) Put(priority int, plugin PluginInterface) bool

Put places a new plugin with a set priority onto the list.

func (*PluginList) PutInfo

func (m *PluginList) PutInfo(plugin *PluginInfo) bool

PutInfo places a new plugins info onto the list.

func (*PluginList) SortByPriority

func (m *PluginList) SortByPriority()

SortByPriority sorts the plugins list by each plugins priority.

type RecvWindow

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

RecvWindow represents a window that buffers and cuts off messages based on their priority.

func NewRecvWindow

func NewRecvWindow(size int) *RecvWindow

NewRecvWindow creates a new receive buffer window with a specific buffer size.

func (*RecvWindow) LocalNonce

func (w *RecvWindow) LocalNonce() uint64

LocalNonce gets last nonce.

func (*RecvWindow) Pop

func (w *RecvWindow) Pop() []interface{}

Pop returns a slice of values from last till not yet received nonce.

func (*RecvWindow) Push

func (w *RecvWindow) Push(nonce uint64, value interface{})

Push adds value with a given nonce to the window.

func (*RecvWindow) Range

func (w *RecvWindow) Range(fn func(uint64, interface{}) bool) []interface{}

Range will return items from the queue while `fn` returns true. If `fn` never return false, the result will be a full buffer.

func (*RecvWindow) SetLocalNonce

func (w *RecvWindow) SetLocalNonce(nonce uint64)

SetLocalNonce sets a expected nonce.

type RequestState

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

RequestState represents a state of a request.

type StreamState

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

StreamState represents a stream.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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