network

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2018 License: MIT Imports: 25 Imported by: 0

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"
)

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 added in v1.1.0

func GetRandomUnusedPort() int

GetRandomUnusedPort returns a random unused port

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.

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 added in v1.1.0

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 added in v1.1.0

func (builder *Builder) ClearTransportLayers()

ClearTransportLayers removes all registered transport layers from the builder.

func (*Builder) RegisterTransportLayer added in v1.1.0

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 added in v1.1.0

type BuilderOption func(*options)

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

func ConnectionTimeout added in v1.1.0

func ConnectionTimeout(d time.Duration) BuilderOption

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

func HashPolicy added in v1.1.0

func HashPolicy(policy crypto.HashPolicy) BuilderOption

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

func RecvWindowSize added in v1.1.0

func RecvWindowSize(recvWindowSize int) BuilderOption

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

func SendWindowSize added in v1.1.0

func SendWindowSize(sendWindowSize int) BuilderOption

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

func SignaturePolicy added in v1.1.0

func SignaturePolicy(policy crypto.SignaturePolicy) BuilderOption

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

func WriteBufferSize added in v1.1.0

func WriteBufferSize(byteSize int) BuilderOption

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

func WriteFlushLatency added in v1.1.0

func WriteFlushLatency(d time.Duration) BuilderOption

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

func WriteTimeout added in v1.1.0

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
}

type Network

type Network struct {

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

	// Map of plugins registered to the network.
	// map[string]Plugin
	Plugins *PluginList

	// Node's cryptographic ID.
	ID peer.ID

	// Map of connection addresses (string) <-> *network.PeerClient
	// so that the Network doesn't dial multiple times to the same ip
	Peers *sync.Map

	// Map of connection addresses (string) <-> *ConnState
	Connections *sync.Map

	// Map of protocol addresses (string) <-> *transport.Layer
	Transports *sync.Map

	// <-Listening will block a goroutine until this node is listening for peers.
	Listening chan struct{}
	// 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(message proto.Message)

Broadcast asynchronously broadcasts a message to all peer clients.

func (*Network) BroadcastByAddresses

func (n *Network) BroadcastByAddresses(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(message proto.Message, ids ...peer.ID)

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

func (*Network) BroadcastRandomly

func (n *Network) BroadcastRandomly(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) 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 added in v1.1.0

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

GetKeys returns the keypair for this network

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) PrepareMessage

func (n *Network) PrepareMessage(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) Write

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

Write asynchronously sends a message to a denoted target address.

type NetworkInterface added in v1.1.0

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(message proto.Message) (*protobuf.Message, error)

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

	// Broadcast asynchronously broadcasts a message to all peer clients.
	Broadcast(message proto.Message)

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

	// BroadcastByIDs broadcasts a message to a set of peer clients denoted by their peer IDs.
	BroadcastByIDs(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(message proto.Message, K int)

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

type PeerClient

type PeerClient struct {
	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 routing table. Errors if session fails to close.

func (*PeerClient) IncomingReady

func (c *PeerClient) IncomingReady() bool

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

func (*PeerClient) Init

func (c *PeerClient) Init()

func (*PeerClient) LocalAddr

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

LocalAddr implements net.Conn.

func (*PeerClient) OutgoingReady

func (c *PeerClient) OutgoingReady() bool

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

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(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(req *rpc.Request) (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(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 (ctx *PluginContext) Client() *PeerClient

Client returns the peer client.

func (*PluginContext) Message

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

Message returns the decoded protobuf message.

func (*PluginContext) Network

func (ctx *PluginContext) Network() *Network

Network returns the entire node's network.

func (*PluginContext) Reply

func (ctx *PluginContext) Reply(message proto.Message) error

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

func (*PluginContext) Self

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

Self returns the node's ID.

func (*PluginContext) Sender

func (ctx *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) Pop added in v1.1.0

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

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

func (*RecvWindow) Push added in v1.1.0

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

Push adds value with a given nonce to the window.

func (*RecvWindow) SetLocalNonce added in v1.1.0

func (w *RecvWindow) SetLocalNonce(nonce uint64)

SetLocalNonce sets a expected nonce.

type RequestState added in v1.1.0

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

type RingBuffer

type RingBuffer struct {
	Data     []interface{}
	Position int
}

RingBuffer is a circular list.

func NewRingBuffer

func NewRingBuffer(size int) *RingBuffer

NewRingBuffer returns a new ring buffer with a fixed size.

func (*RingBuffer) Index

func (b *RingBuffer) Index(pos int) *interface{}

Index returns an item at Position % len(Ringbuffer) in O(1) time.

func (*RingBuffer) MoveForward

func (b *RingBuffer) MoveForward(n int)

MoveForward shifts all items in the ring buffer N steps.

type StreamState

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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