p2p

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2019 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultExternalPort = 8770
)
View Source
const Version = "0.5.0"

Variables

View Source
var (
	//DefaultNewTableFunc is default function to new table to save nodes's netinfo
	DefaultNewTableFunc = defaultNewTable
)
View Source
var (
	//HandShakeFunc is the gloable fuction of p2p handshake
	HandShakeFunc = defaultHandshakeTimeout
)
View Source
var (
	//ListenerBindFunc is the gloable fuction
	ListenerBindFunc = DefaultBindListener
)

Functions

func GetLocalAllAddress

func GetLocalAllAddress() []string

GetLocalAllAddress get all of local address

func MaxNodeInfoSize

func MaxNodeInfoSize() int

MaxNodeInfoSize return Max size of the NodeInfo struct

func SplitHostPort

func SplitHostPort(addr string) (host string, port int)

func TransNodeToEndpoint

func TransNodeToEndpoint(nodes []*common.Node) []string

TransNodeToEndpoint translate nodes to array of ip:port

Types

type BaseReactor

type BaseReactor struct {
	cmn.BaseService
}

BaseReactor Provides Start, Stop, .Quit

func NewBaseReactor

func NewBaseReactor(name string, impl Reactor) *BaseReactor

NewBaseReactor new BaseReactor

func (*BaseReactor) AddPeer

func (*BaseReactor) AddPeer(peer Peer)

func (*BaseReactor) GetChannels

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

func (*BaseReactor) Receive

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

func (*BaseReactor) RemovePeer

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

type ChannelDescriptor

type ChannelDescriptor = conn.ChannelDescriptor

type ConManager

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

ConManager is the con manager of P2P

func NewConManager

func NewConManager(sw *Switch, log log.Logger) *ConManager

NewConManager return the ConManager

func (*ConManager) SetCandidate

func (conma *ConManager) SetCandidate(candidates []*types.CandidateState)

SetCandidate is called when candidate ndoe changed

func (*ConManager) Start

func (conma *ConManager) Start()

Start start the service of dialout

func (*ConManager) Stop

func (conma *ConManager) Stop()

Stop stop the service of ConManager

type ConnectionStatus

type ConnectionStatus = conn.ConnectionStatus

type DefaultListener

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

DefaultListener is a cmn.Service, running net.Listener underneath. Optionally, UPnP is used upon calling NewDefaultListener to resolve external address.

func (*DefaultListener) Connections

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

Connections returns a channel of inbound connections. It gets closed when the listener closes. It is the callers responsibility to close any connections received over this channel.

func (*DefaultListener) ExternalAddress

func (l *DefaultListener) ExternalAddress() *NetAddress

ExternalAddress returns the external NetAddress (publicly available, determined using either UPnP or local resolver).

func (*DefaultListener) ExternalAddressHost

func (l *DefaultListener) ExternalAddressHost() string

ExternalAddressHost returns the external NetAddress IP string. If an IP is IPv6, it's wrapped in brackets ("[2001:db8:1f70::999:de8:7648:6e8]").

func (*DefaultListener) OnStart

func (l *DefaultListener) OnStart() error

OnStart implements cmn.Service by spinning a goroutine, listening for new connections.

func (*DefaultListener) OnStop

func (l *DefaultListener) OnStop()

OnStop implements cmn.Service by closing the listener.

func (*DefaultListener) String

func (l *DefaultListener) String() string

type ErrNetAddressInvalid

type ErrNetAddressInvalid struct {
	Addr string
	Err  error
}

func (ErrNetAddressInvalid) Error

func (e ErrNetAddressInvalid) Error() string

type ErrNetAddressLookup

type ErrNetAddressLookup struct {
	Addr string
	Err  error
}

func (ErrNetAddressLookup) Error

func (e ErrNetAddressLookup) Error() string

type ErrSwitchConnectToSelf

type ErrSwitchConnectToSelf struct {
	Addr *NetAddress
}

ErrSwitchConnectToSelf to be raised when trying to connect to itself.

func (ErrSwitchConnectToSelf) Error

func (e ErrSwitchConnectToSelf) Error() string

type ErrSwitchDuplicatePeerID

type ErrSwitchDuplicatePeerID struct {
	ID string
}

ErrSwitchDuplicatePeerID to be raised when a peer is connecting with a known ID.

func (ErrSwitchDuplicatePeerID) Error

func (e ErrSwitchDuplicatePeerID) Error() string

type IPeerSet

type IPeerSet interface {
	HasID(id string) bool
	HasIP(ip string) bool
	GetByID(id string) Peer
	GetByIP(ip 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
	ExternalAddress() *NetAddress
	ExternalAddressHost() string
	String() string
	Stop() error
}

Listener is a network listener for stream-oriented protocols, providing convenient methods to get listener's internal and external addresses. Clients are supposed to read incoming connections from a channel, returned by Connections() method.

func NewDefaultListener

func NewDefaultListener(
	nodeType types.NodeType,
	fullListenAddrString string,
	externalAddrString string,
	logger log.Logger) (Listener, *net.UDPConn, bool)

NewDefaultListener creates a new DefaultListener on lAddr

type NetAddress

type NetAddress struct {
	IP   net.IP `json:"ip"`
	Port uint16 `json:"port"`
	// contains filtered or unexported fields
}

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

func DefaultBindListener

func DefaultBindListener(nodeType types.NodeType, fullListenAddrString string, externalAddrString string, logger log.Logger) (tcpListener net.Listener, extAddr *NetAddress, udpConn *net.UDPConn, isUpnpSuccess bool)

func GetNaiveExternalAddress

func GetNaiveExternalAddress(defaultToIPv4 bool, port int, settleForLocal bool, logger log.Logger) *NetAddress

TODO: use syscalls: see issue #712

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. Errors are of type ErrNetAddressXxx where Xxx is in (Invalid, Lookup)

func NewNetAddressStrings

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

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

func StartUpnpLoop

func StartUpnpLoop(oldTcpListener net.Listener, log log.Logger) (net.Listener, *NetAddress)

func (*NetAddress) Dial

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

Dial calls net.Dial on the address.

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

func (*NetAddress) RFC3849

func (na *NetAddress) RFC3849() bool

func (*NetAddress) RFC3927

func (na *NetAddress) RFC3927() bool

func (*NetAddress) RFC3964

func (na *NetAddress) RFC3964() bool

func (*NetAddress) RFC4193

func (na *NetAddress) RFC4193() bool

func (*NetAddress) RFC4380

func (na *NetAddress) RFC4380() bool

func (*NetAddress) RFC4843

func (na *NetAddress) RFC4843() bool

func (*NetAddress) RFC4862

func (na *NetAddress) RFC4862() bool

func (*NetAddress) RFC6052

func (na *NetAddress) RFC6052() bool

func (*NetAddress) RFC6145

func (na *NetAddress) RFC6145() bool

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: <IP>:<PORT>

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"`
	CachePeerID string
	ListenAddr  string `json:"listen_addr"` // listen tcp addr,accepting tcp protocol incoming

	// Check compatibility.
	// Channels are HexBytes so easier to read as JSON
	Network  string       `json:"network"`  // network/chain ID
	Version  string       `json:"version"`  // major.minor.revision
	Channels cmn.HexBytes `json:"channels"` // channels this node knows about

	// ASCIIText fields
	Moniker string   `json:"moniker"` // arbitrary moniker
	Other   []string `json:"other"`   // other application specific data

	Type       types.NodeType `json:"type"`  // node type
	LocalAddrs []string       `json:"addrs"` // all address of node
}

NodeInfo is the basic node information exchanged between two peers during the P2P handshake.

func (NodeInfo) CompatibleWith

func (info NodeInfo) CompatibleWith(other NodeInfo) error

CompatibleWith checks if two NodeInfo are compatible with eachother. CONTRACT: two nodes are compatible if the major version matches and network match and they have at least one channel in common.

func (*NodeInfo) ID

func (info *NodeInfo) ID() string

ID returns the peer's Uniquely identifies

func (NodeInfo) NetAddress

func (info NodeInfo) NetAddress() *NetAddress

NetAddress returns a NetAddress derived from the NodeInfo - ListenAddr Note that the ListenAddr is not authenticated and may not match that address actually dialed if its an outbound peer.

func (NodeInfo) String

func (info NodeInfo) String() string

func (NodeInfo) Validate

func (info NodeInfo) Validate() error

Validate checks the self-reported NodeInfo is safe. It returns an error if there are too many Channels, if there are any duplicate Channels, if the ListenAddr is malformed, or if the ListenAddr is a host name that can not be resolved to some IP. TODO: constraints for Moniker/Other? Or is that for the UI ? JAE: It needs to be done on the client, but to prevent ambiguous unicode characters, maybe it's worth sanitizing it here. In the future we might want to validate these, once we have a name-resolution system up. International clients could then use punycode (or we could use url-encoding), and we just need to be careful with how we handle that in our clients. (e.g. off by default).

type P2PManager

type P2PManager interface {
	cmn.Service
	GetByID(peerID string) Peer
	StopPeerForError(peer Peer, reason interface{})
	Reactor(name string) Reactor
	AddReactor(name string, reactor Reactor) Reactor
	Broadcast(chID byte, msgEncodeBytes []byte) chan bool //broadcast  msgEncodeBytes from chID channel to all nodes that already connected
	BroadcastE(chID byte, peerID string, msgEncodeBytes []byte) chan bool
	Peers() IPeerSet //all peers that already connected
	LocalNodeInfo() NodeInfo
	NumPeers() (outbound, inbound, dialing int) //return the num of  out\in\dialing connections
	MarkBadNode(nodeInfo NodeInfo)              //mark bad node,when badnode connect us next time,we will disconnect it
	CloseAllConnection()                        //close all the connection that my node already connected
}

P2PManager to control all the p2p connections

type Peer

type Peer interface {
	cmn.Service
	ID() string // peer's ID
	RemoteAddr() net.Addr
	NodeInfo() NodeInfo // peer's info
	IsOutbound() bool   //IsOutbound returns true if the connection is outbound, false otherwise.
	Status() ConnectionStatus
	Send(channelID byte, msgEncodeBytes []byte) bool //try send  msgEncodeBytes blocked until send success or timeout
	TrySend(chID byte, msgEncodeBytes []byte) bool   //try send  msgEncodeBytes unblocked
	Close() error                                    //support close many times(if already closed,when call Close again,return error)
	Set(key string, data interface{})
	Get(key string) interface{}
}

Peer is the single connection with other node

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. It returns an error carrying the reason, if the peer is already present.

func (*PeerSet) AddOurAddress

func (ps *PeerSet) AddOurAddress(listenaddr string, otheraddr []string)

AddOurAddress add oneself node address.

func (*PeerSet) GetByID

func (ps *PeerSet) GetByID(id string) Peer

GetByID looks up a peer by the provided id. Returns nil if peer is not found.

func (*PeerSet) GetByIP

func (ps *PeerSet) GetByIP(ip string) Peer

GetByIP looks up a peer by the provided ip. Returns nil if peer is not found.

func (*PeerSet) HasID

func (ps *PeerSet) HasID(id string) bool

HasID returns true if the set contains the peer referred to by this id, otherwise false.

func (*PeerSet) HasIP

func (ps *PeerSet) HasIP(ip string) bool

HasIP returns true if the set contains the peer referred to by this ip, otherwise false.

func (*PeerSet) List

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

List returns the threadsafe list of peers.

func (*PeerSet) Remove

func (ps *PeerSet) Remove(peer Peer)

Remove discards peer by its Key, 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
	RemovePeer(peer Peer, reason interface{})            //peer alraedy disconnect peer,just a notifacation
	AddPeer(peer Peer)                                   //recieve new connection
	Receive(chID byte, peer Peer, msgEncodeBytes []byte) //recieve data from  peer's chID channel,it should not blocked
	GetChannels() []*ChannelDescriptor
}

Reactor is the interface to achieve different business logic processing by control the same conneciton

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 NewP2pManager

func NewP2pManager(logger log.Logger, myPrivKey crypto.PrivKey, cfg *config.P2PConfig,
	localNodeInfo NodeInfo, seeds []*common.Node, db dbm.DB) (*Switch, error)

NewP2pManager creates a new Switch with the given config.

func (*Switch) AddDial added in v0.1.1

func (sw *Switch) AddDial(node *common.Node) bool

AddDial try to dials the given peer and return the result

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

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

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

func (*Switch) BootNodeAddr

func (sw *Switch) BootNodeAddr() string

func (*Switch) Broadcast

func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool

Broadcast runs a go routine for each attempted send, which will block trying to send for defaultSendTimeoutSeconds. Returns a channel which receives success values for each attempted send (false if times out). Channel will be closed once msg bytes are sent to all peers (or time out).

NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.

func (*Switch) BroadcastE

func (sw *Switch) BroadcastE(chID byte, peerID string, msgBytes []byte) chan bool

BroadcastE runs a go routine for each attempted send expept peerID,which will block trying to send for defaultSendTimeoutSeconds. Returns a channel which receives success values for each attempted send (false if times out). Channel will be closed once msg bytes are sent to all peers (or time out).

func (*Switch) CloseAllConnection

func (sw *Switch) CloseAllConnection()

func (*Switch) DBManager

func (sw *Switch) DBManager() common.P2pDBManager

func (*Switch) DHTPeers added in v0.1.1

func (sw *Switch) DHTPeers() []*common.Node

func (*Switch) DefaultNewTable added in v0.1.1

func (sw *Switch) DefaultNewTable(seeds []*common.Node, needDht bool, needReNewUDPCon bool) error

func (*Switch) DialPeerWithAddress

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

DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects and authenticates successfully.

func (*Switch) FilterConnByAddr

func (sw *Switch) FilterConnByAddr(addr net.Addr) error

FilterConnByAddr returns an error if connecting to the given address is forbidden.

func (*Switch) GetByID

func (sw *Switch) GetByID(id string) Peer

GetByID retrun the peer con by id

func (*Switch) GetConManager

func (sw *Switch) GetConManager() *ConManager

GetConManager return manager of Switch obj

func (*Switch) GetConfig

func (sw *Switch) GetConfig() *config.P2PConfig

GetConfig retrun p2p config

func (*Switch) GetNumPeersByRole

func (sw *Switch) GetNumPeersByRole() (int, int, int)

GetNumPeersByRole return the num of validators、peers、listeners

func (*Switch) GetTable added in v0.1.1

func (sw *Switch) GetTable() common.DiscoverTable

func (*Switch) IsDialing

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

IsDialing returns true if the switch is currently dialing the given address.

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

func (sw *Switch) LocalNodeInfo() NodeInfo

LocalNodeInfo return the localnode info

func (*Switch) MarkBadNode

func (sw *Switch) MarkBadNode(nodeInfo NodeInfo)

MarkBadNode mark node to blacklist for a long time until blackListTimeout

func (*Switch) NodeInfo

func (sw *Switch) NodeInfo() NodeInfo

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

func (*Switch) NodeKey

func (sw *Switch) NodeKey() crypto.PrivKey

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() IPeerSet

Peers returns the set of peers that are connected to the switch.

func (*Switch) Reactor

func (sw *Switch) Reactor(name string) Reactor

Reactor returns the reactor with the given name. NOTE: Not goroutine safe.

func (*Switch) Reactors

func (sw *Switch) Reactors() map[string]Reactor

Reactors returns a map of reactors registered on the switch. NOTE: Not goroutine safe.

func (*Switch) SetAddrFilter

func (sw *Switch) SetAddrFilter(f func(net.Addr) error)

SetAddrFilter sets the function for filtering connections by address.

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

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

StopPeerForError disconnects from a peer due to external error. TODO: make record depending on reason.

func (*Switch) UDPCon added in v0.1.2

func (sw *Switch) UDPCon() *net.UDPConn

Directories

Path Synopsis
Package math provides integer math utilities.
Package math provides integer math utilities.
Uses nacl's secret_box to encrypt a net.Conn.
Uses nacl's secret_box to encrypt a net.Conn.
Package discover implements the Node Discovery Protocol.
Package discover implements the Node Discovery Protocol.
Package netutil contains extensions to the net package.
Package netutil contains extensions to the net package.

Jump to

Keyboard shortcuts

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