p2p

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2021 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDuplicatePeer     = errors.New("Duplicate peer")
	ErrConnectSelf       = errors.New("Connect self")
	ErrConnectBannedPeer = errors.New("Connect banned peer")
	ErrConnectBannedIP   = errors.New("Connect banned ip")
	ErrConnectSpvPeer    = errors.New("Outbound connect spv peer")
)

pre-define errors for connecting fail

View Source
var PanicOnAddPeerErr = false

PanicOnAddPeerErr add peer error

Functions

func Connect2Switches

func Connect2Switches(switches []*Switch, i, j int)

Connect2Switches will connect switches i and j via net.Pipe() Blocks until a conection is established. NOTE: caller ensures i and j are within bounds

Types

type BaseReactor

type BaseReactor struct {
	cmn.BaseService // Provides Start, Stop, .Quit
	Switch          *Switch
}

BaseReactor base service of a reactor

func NewBaseReactor

func NewBaseReactor(name string, impl Reactor) *BaseReactor

NewBaseReactor create new base Reactor

func (*BaseReactor) AddPeer

func (*BaseReactor) AddPeer(peer *Peer)

AddPeer is called by the switch when a new peer is added

func (*BaseReactor) GetChannels

func (*BaseReactor) GetChannels() []*connection.ChannelDescriptor

GetChannels returns the list of channel descriptors

func (*BaseReactor) Receive

func (*BaseReactor) Receive(chID byte, peer *Peer, msgBytes []byte)

Receive is called when msgBytes is received from peer

func (*BaseReactor) RemovePeer

func (*BaseReactor) RemovePeer(peer *Peer, reason interface{})

RemovePeer is called by the switch when the peer is stopped (due to error or other reason)

func (*BaseReactor) SetSwitch

func (br *BaseReactor) SetSwitch(sw *Switch)

SetSwitch setting a switch for reactor

type DefaultListener

type DefaultListener struct {
	cmn.BaseService
	// contains filtered or unexported fields
}

DefaultListener Implements mass server Listener

func (*DefaultListener) Connections

func (l *DefaultListener) Connections() <-chan net.Conn

Connections a channel of inbound connections. It gets closed when the listener closes.

func (*DefaultListener) ExternalAddress

func (l *DefaultListener) ExternalAddress() *NetAddress

ExternalAddress listener external address for remote peer dial

func (*DefaultListener) InternalAddress

func (l *DefaultListener) InternalAddress() *NetAddress

InternalAddress listener internal address

func (*DefaultListener) NetListener

func (l *DefaultListener) NetListener() net.Listener

NetListener the returned listener is already Accept()'ing. So it's not suitable to pass into http.Serve().

func (*DefaultListener) OnStart

func (l *DefaultListener) OnStart() error

OnStart start listener

func (*DefaultListener) OnStop

func (l *DefaultListener) OnStop()

OnStop stop listener

func (*DefaultListener) String

func (l *DefaultListener) String() string

String string of default listener

type IPResult

type IPResult struct {
	Success bool
	IP      string
}

IPResult is the ip check response

func GetIP

func GetIP() *IPResult

GetIP return the ip of the current host

type IPeerSet

type IPeerSet interface {
	Has(key string) bool
	Get(key string) *Peer
	List() []*Peer
	Size() int
}

IPeerSet has a (immutable) subset of the methods of PeerSet.

type Listener

type Listener interface {
	Connections() <-chan net.Conn
	InternalAddress() *NetAddress
	ExternalAddress() *NetAddress
	String() string
	Stop() bool
}

Listener subset of the methods of DefaultListener

func NewDefaultListener

func NewDefaultListener(cfg *config.Config) (Listener, bool)

NewDefaultListener create a default listener

type NetAddress

type NetAddress struct {
	IP   net.IP
	Port uint16
	// contains filtered or unexported fields
}

NetAddress defines information about a peer on the network including its IP address, and port.

func CreateRoutableAddr

func CreateRoutableAddr() (addr string, netAddr *NetAddress)

func NewNetAddress

func NewNetAddress(addr net.Addr) *NetAddress

NewNetAddress returns a new NetAddress using the provided TCP address. When testing, other net.Addr (except TCP) will result in using 0.0.0.0:0. When normal run, other net.Addr (except TCP) will panic. TODO: socks proxies?

func NewNetAddressIPPort

func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress

NewNetAddressIPPort returns a new NetAddress using the provided IP and port number.

func NewNetAddressString

func NewNetAddressString(addr string) (*NetAddress, error)

NewNetAddressString returns a new NetAddress using the provided address in the form of "IP:Port". Also resolves the host if host is not an IP.

func NewNetAddressStrings

func NewNetAddressStrings(addrs []string) ([]*NetAddress, error)

NewNetAddressStrings returns an array of NetAddress'es build using the provided strings.

func (*NetAddress) Dial

func (na *NetAddress) Dial() (net.Conn, error)

Dial calls net.Dial on the address.

func (*NetAddress) DialString

func (na *NetAddress) DialString() string

DialString dial address string representation

func (*NetAddress) DialTimeout

func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error)

DialTimeout calls net.DialTimeout on the address.

func (*NetAddress) Equals

func (na *NetAddress) Equals(other interface{}) bool

Equals reports whether na and other are the same addresses.

func (*NetAddress) Local

func (na *NetAddress) Local() bool

Local returns true if it is a local address.

func (*NetAddress) RFC1918

func (na *NetAddress) RFC1918() bool

RFC1918 IPv4 Private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)

func (*NetAddress) RFC3849

func (na *NetAddress) RFC3849() bool

RFC3849 IPv6 Documentation address (2001:0DB8::/32)

func (*NetAddress) RFC3927

func (na *NetAddress) RFC3927() bool

RFC3927 IPv4 Autoconfig (169.254.0.0/16)

func (*NetAddress) RFC3964

func (na *NetAddress) RFC3964() bool

RFC3964 IPv6 6to4 (2002::/16)

func (*NetAddress) RFC4193

func (na *NetAddress) RFC4193() bool

RFC4193 IPv6 unique local (FC00::/7)

func (*NetAddress) RFC4380

func (na *NetAddress) RFC4380() bool

RFC4380 IPv6 Teredo tunneling (2001::/32)

func (*NetAddress) RFC4843

func (na *NetAddress) RFC4843() bool

RFC4843 IPv6 ORCHID: (2001:10::/28)

func (*NetAddress) RFC4862

func (na *NetAddress) RFC4862() bool

RFC4862 IPv6 Autoconfig (FE80::/64)

func (*NetAddress) RFC6052

func (na *NetAddress) RFC6052() bool

RFC6052 IPv6 well known prefix (64:FF9B::/96)

func (*NetAddress) RFC6145

func (na *NetAddress) RFC6145() bool

RFC6145 IPv6 IPv4 translated address ::FFFF:0:0:0/96

func (*NetAddress) ReachabilityTo

func (na *NetAddress) ReachabilityTo(o *NetAddress) int

ReachabilityTo checks whenever o can be reached from na.

func (*NetAddress) Routable

func (na *NetAddress) Routable() bool

Routable returns true if the address is routable.

func (*NetAddress) String

func (na *NetAddress) String() string

String representation.

func (*NetAddress) Valid

func (na *NetAddress) Valid() bool

Valid For IPv4 these are either a 0 or all bits set address. For IPv6 a zero address or one that matches the RFC3849 documentation address format.

type NodeInfo

type NodeInfo struct {
	PubKey     crypto.PubKeyEd25519 `json:"pub_key"`
	Moniker    string               `json:"moniker"`
	Network    string               `json:"network"`
	RemoteAddr string               `json:"remote_addr"`
	ListenAddr string               `json:"listen_addr"`
	Version    string               `json:"version"` // major.minor.revision
	Other      []string             `json:"other"`   // other application specific data
}

NodeInfo peer node info

func (*NodeInfo) CompatibleWith

func (info *NodeInfo) CompatibleWith(other *NodeInfo) error

CompatibleWith checks if two NodeInfo are compatible with each other.

func (*NodeInfo) ListenHost

func (info *NodeInfo) ListenHost() string

ListenHost peer listener ip address

func (*NodeInfo) ListenPort

func (info *NodeInfo) ListenPort() int

ListenPort peer listener port

func (*NodeInfo) RemoteAddrHost

func (info *NodeInfo) RemoteAddrHost() string

RemoteAddrHost peer external ip address

func (NodeInfo) String

func (info NodeInfo) String() string

String representation

type Peer

type Peer struct {
	cmn.BaseService
	*NodeInfo

	Key string
	// contains filtered or unexported fields
}

Peer represent a mass network node

func CreateRandomPeer

func CreateRandomPeer(outbound bool) *Peer

func (*Peer) Addr

func (p *Peer) Addr() net.Addr

Addr returns peer's remote network address.

func (*Peer) CanSend

func (p *Peer) CanSend(chID byte) bool

CanSend returns true if the send queue is not full, false otherwise.

func (Peer) CloseConn

func (pc Peer) CloseConn()

CloseConn should be used when the peer was created, but never started.

func (*Peer) Equals

func (p *Peer) Equals(other *Peer) bool

Equals reports whenever 2 peers are actually represent the same node.

func (Peer) HandshakeTimeout

func (pc Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) (*NodeInfo, error)

HandshakeTimeout performs a handshake between a given node and the peer. NOTE: blocking

func (*Peer) ID

func (p *Peer) ID() string

func (*Peer) IsOutbound

func (p *Peer) IsOutbound() bool

IsOutbound returns true if the connection is outbound, false otherwise.

func (*Peer) IsTrustworthy

func (p *Peer) IsTrustworthy() bool

func (*Peer) OnStart

func (p *Peer) OnStart() error

OnStart implements BaseService.

func (*Peer) OnStop

func (p *Peer) OnStop()

OnStop implements BaseService.

func (*Peer) PubKey

func (p *Peer) PubKey() gocrypto.PubKeyEd25519

PubKey returns peer's public key.

func (*Peer) Send

func (p *Peer) Send(chID byte, msg interface{}) bool

Send msg to the channel identified by chID byte. Returns false if the send queue is full after timeout, specified by MConnection.

func (*Peer) ServiceFlag

func (p *Peer) ServiceFlag() consensus.ServiceFlag

func (*Peer) String

func (p *Peer) String() string

String representation.

func (*Peer) TrySend

func (p *Peer) TrySend(chID byte, msg interface{}) bool

TrySend msg to the channel identified by chID byte. Immediately returns false if the send queue is full.

type PeerConfig

type PeerConfig struct {
	HandshakeTimeout time.Duration           `mapstructure:"handshake_timeout"` // times are in seconds
	DialTimeout      time.Duration           `mapstructure:"dial_timeout"`
	MConfig          *connection.MConnConfig `mapstructure:"connection"`
}

PeerConfig is a Peer configuration.

func DefaultPeerConfig

func DefaultPeerConfig(config *config.Config) *PeerConfig

DefaultPeerConfig returns the default config.

type PeerSet

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

PeerSet is a special structure for keeping a table of peers. Iteration over the peers is super fast and thread-safe.

func NewPeerSet

func NewPeerSet() *PeerSet

NewPeerSet creates a new peerSet with a list of initial capacity of 256 items.

func (*PeerSet) Add

func (ps *PeerSet) Add(peer *Peer) error

Add adds the peer to the PeerSet. Returns false if peer with key (PubKeyEd25519) is already set

func (*PeerSet) Get

func (ps *PeerSet) Get(peerKey string) *Peer

Get looks up a peer by the provided peerKey.

func (*PeerSet) Has

func (ps *PeerSet) Has(peerKey string) bool

Has returns true if the PeerSet contains the peer referred to by this peerKey.

func (*PeerSet) List

func (ps *PeerSet) List() []*Peer

List threadsafe list of peers.

func (*PeerSet) Remove

func (ps *PeerSet) Remove(peer *Peer)

Remove discards peer if the peer was previously memoized.

func (*PeerSet) Size

func (ps *PeerSet) Size() int

Size returns the number of unique items in the peerSet.

type Reactor

type Reactor interface {
	cmn.Service // Start, Stop

	// SetSwitch allows setting a switch.
	SetSwitch(*Switch)

	// GetChannels returns the list of channel descriptors.
	GetChannels() []*connection.ChannelDescriptor

	// AddPeer is called by the switch when a new peer is added.
	AddPeer(peer *Peer) error

	// RemovePeer is called by the switch when the peer is stopped (due to error
	// or other reason).
	RemovePeer(peer *Peer, reason interface{})

	// Receive is called when msgBytes is received from peer.
	//
	// NOTE reactor can not keep msgBytes around after Receive completes without
	// copying.
	//
	// CONTRACT: msgBytes are not nil.
	Receive(chID byte, peer *Peer, msgBytes []byte)
}

Reactor is responsible for handling incoming messages of one or more `Channels`

type Switch

type Switch struct {
	cmn.BaseService
	// contains filtered or unexported fields
}

Switch handles peer connections and exposes an API to receive incoming messages on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one or more `Channels`. So while sending outgoing messages is typically performed on the peer, incoming messages are received on the reactor.

func MakeConnectedSwitches

func MakeConnectedSwitches(cfg *config.Config, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch

MakeConnectedSwitches switches connected via arbitrary net.Conn; useful for testing Returns n switches, connected according to the connect func. If connect==Connect2Switches, the switches will be fully connected. initSwitch defines how the ith switch should be initialized (ie. with what reactors). NOTE: panics if any switch fails to start.

func MakeSwitch

func MakeSwitch(cfg *config.Config, i int, network, version string, initSwitch func(int, *Switch) *Switch) (*Switch, error)

func NewSwitch

func NewSwitch(conf *config.Config) (*Switch, error)

NewSwitch creates a new Switch with the given config.

func (*Switch) AddBannedPeer

func (sw *Switch) AddBannedPeer(peerID, ip string) error

AddBannedPeer add peer to blacklist

func (*Switch) AddListener

func (sw *Switch) AddListener(l Listener)

AddListener adds the given listener to the switch for listening to incoming peer connections. NOTE: Not goroutine safe.

func (*Switch) AddPeer

func (sw *Switch) AddPeer(pc *peerConn) error

AddPeer performs the P2P handshake with a peer that already has a SecretConnection. If all goes well, it starts the peer and adds it to the switch. NOTE: This performs a blocking handshake before the peer is added. CONTRACT: If error is returned, peer is nil, and conn is immediately closed.

func (*Switch) AddReactor

func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor

AddReactor adds the given reactor to the switch. NOTE: Not goroutine safe.

func (*Switch) DialPeerWithAddress

func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error

DialPeerWithAddress dial node from net address

func (*Switch) IsDialing

func (sw *Switch) IsDialing(addr *NetAddress) bool

IsDialing prevent duplicate dialing

func (*Switch) IsListening

func (sw *Switch) IsListening() bool

IsListening returns true if the switch has at least one listener. NOTE: Not goroutine safe.

func (*Switch) Listeners

func (sw *Switch) Listeners() []Listener

Listeners returns the list of listeners the switch listens on. NOTE: Not goroutine safe.

func (*Switch) NodeInfo

func (sw *Switch) NodeInfo() *NodeInfo

NodeInfo returns the switch's NodeInfo. NOTE: Not goroutine safe.

func (*Switch) NumPeers

func (sw *Switch) NumPeers() (outbound, inbound, dialing int)

NumPeers Returns the count of outbound/inbound and outbound-dialing peers.

func (*Switch) OnStart

func (sw *Switch) OnStart() error

OnStart implements BaseService. It starts all the reactors, peers, and listeners.

func (*Switch) OnStop

func (sw *Switch) OnStop()

OnStop implements BaseService. It stops all listeners, peers, and reactors.

func (*Switch) Peers

func (sw *Switch) Peers() *PeerSet

Peers return switch peerset

func (*Switch) SetNodeInfo

func (sw *Switch) SetNodeInfo(nodeInfo *NodeInfo)

SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes. NOTE: Not goroutine safe.

func (*Switch) SetNodePrivKey

func (sw *Switch) SetNodePrivKey(nodePrivKey crypto.PrivKeyEd25519)

SetNodePrivKey sets the switch's private key for authenticated encryption. NOTE: Not goroutine safe.

func (*Switch) StopPeerForError

func (sw *Switch) StopPeerForError(peer *Peer, reason interface{})

StopPeerForError disconnects from a peer due to external error.

func (*Switch) StopPeerGracefully

func (sw *Switch) StopPeerGracefully(peerID string)

StopPeerGracefully disconnect from a peer gracefully.

Directories

Path Synopsis
Package discv5 implements the RLPx v5 Topic Discovery Protocol.
Package discv5 implements the RLPx v5 Topic Discovery Protocol.
Package netutil contains extensions to the net package.
Package netutil contains extensions to the net package.
Taken from taipei-torrent Just enough UPnP to be able to forward ports
Taken from taipei-torrent Just enough UPnP to be able to forward ports

Jump to

Keyboard shortcuts

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