p2p

package
v0.34.1-dev1 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2020 License: Apache-2.0 Imports: 38 Imported by: 0

README

p2p

The p2p package provides an abstraction around peer-to-peer communication.

Docs:

  • Connection for details on how connections and multiplexing work
  • Peer for details on peer ID, handshakes, and peer exchange
  • Node for details about different types of nodes and how they should work
  • Pex for details on peer discovery and exchange
  • Config for details on some config option

Documentation

Index

Constants

View Source
const (
	PeerStatusNew     = PeerStatus("new")     // New peer which we haven't tried to contact yet.
	PeerStatusUp      = PeerStatus("up")      // Peer which we have an active connection to.
	PeerStatusDown    = PeerStatus("down")    // Peer which we're temporarily disconnected from.
	PeerStatusRemoved = PeerStatus("removed") // Peer which has been removed.
	PeerStatusBanned  = PeerStatus("banned")  // Peer which is banned for misbehavior.
)
View Source
const EmptyNetAddress = "<nil-NetAddress>"

EmptyNetAddress defines the string representation of an empty NetAddress

View Source
const IDByteLength = crypto.AddressSize

IDByteLength is the length of a crypto.Address. Currently only 20. TODO: support other length addresses ?

View Source
const (
	// MetricsSubsystem is a subsystem shared by all metrics exposed by this
	// package.
	MetricsSubsystem = "p2p"
)
View Source
const TestHost = "localhost"

Variables

This section is empty.

Functions

func AddPeerToSwitchPeerSet added in v0.31.6

func AddPeerToSwitchPeerSet(sw *Switch, peer Peer)

func Connect2Switches

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

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

func IDAddressString

func IDAddressString(id ID, protocolHostPort string) string

IDAddressString returns id@hostPort. It strips the leading protocol from protocolHostPort if it exists.

func MConnConfig

func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig

MConnConfig returns an MConnConfig with fields updated from the P2PConfig.

func MaxNodeInfoSize

func MaxNodeInfoSize() int

Max size of the NodeInfo struct

func NetAddressesToProto added in v0.34.0

func NetAddressesToProto(nas []*NetAddress) []tmp2p.NetAddress

NetAddressesToProto converts a slice of NetAddresses into a Protobuf slice.

func StartSwitches

func StartSwitches(switches []*Switch) error

StartSwitches calls sw.Start() for each given switch. It returns the first encountered error.

Types

type AddrBook

type AddrBook interface {
	AddAddress(addr *NetAddress, src *NetAddress) error
	AddPrivateIDs([]string)
	AddOurAddress(*NetAddress)
	OurAddress(*NetAddress) bool
	MarkGood(ID)
	RemoveAddress(*NetAddress)
	HasAddress(*NetAddress) bool
	Save()
}

An AddrBook represents an address book from the pex package, which is used to store peer addresses.

type AddrBookMock added in v0.34.0

type AddrBookMock struct {
	Addrs        map[string]struct{}
	OurAddrs     map[string]struct{}
	PrivateAddrs map[string]struct{}
}

func (*AddrBookMock) AddAddress added in v0.34.0

func (book *AddrBookMock) AddAddress(addr *NetAddress, src *NetAddress) error

func (*AddrBookMock) AddOurAddress added in v0.34.0

func (book *AddrBookMock) AddOurAddress(addr *NetAddress)

func (*AddrBookMock) AddPrivateIDs added in v0.34.0

func (book *AddrBookMock) AddPrivateIDs(addrs []string)

func (*AddrBookMock) HasAddress added in v0.34.0

func (book *AddrBookMock) HasAddress(addr *NetAddress) bool

func (*AddrBookMock) MarkGood added in v0.34.0

func (book *AddrBookMock) MarkGood(ID)

func (*AddrBookMock) OurAddress added in v0.34.0

func (book *AddrBookMock) OurAddress(addr *NetAddress) bool

func (*AddrBookMock) RemoveAddress added in v0.34.0

func (book *AddrBookMock) RemoveAddress(addr *NetAddress)

func (*AddrBookMock) Save added in v0.34.0

func (book *AddrBookMock) Save()

type BaseReactor

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

func NewBaseReactor

func NewBaseReactor(name string, impl Reactor) *BaseReactor

func (*BaseReactor) AddPeer

func (*BaseReactor) AddPeer(peer Peer)

func (*BaseReactor) GetChannels

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

func (*BaseReactor) InitPeer added in v0.31.6

func (*BaseReactor) InitPeer(peer Peer) Peer

func (*BaseReactor) Receive

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

func (*BaseReactor) RemovePeer

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

func (*BaseReactor) SetSwitch

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

type Channel added in v0.10.0

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

Channel is a bidirectional channel for Protobuf message exchange with peers. A Channel is safe for concurrent use by multiple goroutines.

func NewChannel

func NewChannel(id ChannelID, mType proto.Message, in, out chan Envelope, errCh chan PeerError) *Channel

NewChannel returns a reference to a new p2p Channel. It is the reactor's responsibility to close the Channel. After a channel is closed, the router may safely and explicitly close the internal In channel.

func (*Channel) Close

func (c *Channel) Close()

Close closes the outbound channel and marks the Channel as done. Internally, the outbound outCh and peer error errCh channels are closed. It is the reactor's responsibility to invoke Close. Any send on the Out or Error channel will panic after the Channel is closed.

NOTE: After a Channel is closed, the router may safely assume it can no longer send on the internal inCh, however it should NEVER explicitly close it as that could result in panics by sending on a closed channel.

func (*Channel) Done

func (c *Channel) Done() <-chan struct{}

Done returns the Channel's internal channel that should be used by a router to signal when it is safe to send on the internal inCh go channel.

func (*Channel) Error

func (c *Channel) Error() chan<- PeerError

Error returns a write-only outbound go channel designated for peer errors only. This go channel should be used by reactors to send peer errors when consuming Envelopes sent from other peers.

func (*Channel) ID

func (c *Channel) ID() ChannelID

ID returns the Channel's ID.

func (*Channel) In

func (c *Channel) In() <-chan Envelope

In returns a read-only inbound go channel. This go channel should be used by reactors to consume Envelopes sent from peers.

func (*Channel) Out

func (c *Channel) Out() chan<- Envelope

Out returns a write-only outbound go channel. This go channel should be used by reactors to route Envelopes to other peers.

type ChannelDescriptor

type ChannelDescriptor = conn.ChannelDescriptor

type ChannelDescriptorShim

type ChannelDescriptorShim struct {
	MsgType    proto.Message
	Descriptor *ChannelDescriptor
}

ChannelDescriptorShim defines a shim wrapper around a legacy p2p channel and the proto.Message the new p2p Channel is responsible for handling. A ChannelDescriptorShim is not contained in ReactorShim, but is rather used to construct a ReactorShim.

type ChannelID

type ChannelID uint16

ChannelID is an arbitrary channel ID.

type ChannelShim

type ChannelShim struct {
	Descriptor *ChannelDescriptor
	Channel    *Channel
}

ChannelShim defines a generic shim wrapper around a legacy p2p channel and the new p2p Channel. It also includes the raw bi-directional Go channels so we can proxy message delivery.

func NewChannelShim

func NewChannelShim(cds *ChannelDescriptorShim, buf uint) *ChannelShim

type ConnFilterFunc

type ConnFilterFunc func(ConnSet, net.Conn, []net.IP) error

ConnFilterFunc to be implemented by filter hooks after a new connection has been established. The set of exisiting connections is passed along together with all resolved IPs for the new connection.

func ConnDuplicateIPFilter

func ConnDuplicateIPFilter() ConnFilterFunc

ConnDuplicateIPFilter resolves and keeps all ips for an incoming connection and refuses new ones if they come from a known ip.

type ConnSet

type ConnSet interface {
	Has(net.Conn) bool
	HasIP(net.IP) bool
	Set(net.Conn, []net.IP)
	Remove(net.Conn)
	RemoveAddr(net.Addr)
}

ConnSet is a lookup table for connections and all their ips.

func NewConnSet

func NewConnSet() ConnSet

NewConnSet returns a ConnSet implementation.

type ConnectionStatus

type ConnectionStatus = conn.ConnectionStatus

type DefaultNodeInfo

type DefaultNodeInfo struct {
	ProtocolVersion ProtocolVersion `json:"protocol_version"`

	// Authenticate
	// TODO: replace with NetAddress
	DefaultNodeID ID     `json:"id"`          // authenticated identifier
	ListenAddr    string `json:"listen_addr"` // accepting 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 bytes.HexBytes `json:"channels"` // channels this node knows about

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

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

func DefaultNodeInfoFromToProto added in v0.34.0

func DefaultNodeInfoFromToProto(pb *tmp2p.DefaultNodeInfo) (DefaultNodeInfo, error)

func (DefaultNodeInfo) CompatibleWith

func (info DefaultNodeInfo) CompatibleWith(otherInfo NodeInfo) error

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

func (DefaultNodeInfo) ID

func (info DefaultNodeInfo) ID() ID

ID returns the node's peer ID.

func (DefaultNodeInfo) NetAddress

func (info DefaultNodeInfo) NetAddress() (*NetAddress, error)

NetAddress returns a NetAddress derived from the DefaultNodeInfo - it includes the authenticated peer ID and the self-reported ListenAddr. Note that the ListenAddr is not authenticated and may not match that address actually dialed if its an outbound peer.

func (DefaultNodeInfo) ToProto added in v0.34.0

func (info DefaultNodeInfo) ToProto() *tmp2p.DefaultNodeInfo

func (DefaultNodeInfo) Validate

func (info DefaultNodeInfo) Validate() error

Validate checks the self-reported DefaultNodeInfo 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 DefaultNodeInfoOther

type DefaultNodeInfoOther struct {
	TxIndex    string `json:"tx_index"`
	RPCAddress string `json:"rpc_address"`
}

DefaultNodeInfoOther is the misc. applcation specific data

type Envelope added in v0.34.23

type Envelope struct {
	From      PeerID        // Message sender, or empty for outbound messages.
	To        PeerID        // Message receiver, or empty for inbound messages.
	Broadcast bool          // Send message to all connected peers, ignoring To.
	Message   proto.Message // Payload.
}

Envelope specifies the message receiver and sender.

type ErrCurrentlyDialingOrExistingAddress added in v0.31.4

type ErrCurrentlyDialingOrExistingAddress struct {
	Addr string
}

ErrCurrentlyDialingOrExistingAddress indicates that we're currently dialing this address or it belongs to an existing peer.

func (ErrCurrentlyDialingOrExistingAddress) Error added in v0.31.4

type ErrFilterTimeout

type ErrFilterTimeout struct{}

ErrFilterTimeout indicates that a filter operation timed out.

func (ErrFilterTimeout) Error

func (e ErrFilterTimeout) Error() 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 ErrNetAddressNoID

type ErrNetAddressNoID struct {
	Addr string
}

func (ErrNetAddressNoID) Error

func (e ErrNetAddressNoID) Error() string

type ErrRejected

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

ErrRejected indicates that a Peer was rejected carrying additional information as to the reason.

func (ErrRejected) Addr

func (e ErrRejected) Addr() NetAddress

Addr returns the NetAddress for the rejected Peer.

func (ErrRejected) Error

func (e ErrRejected) Error() string

func (ErrRejected) IsAuthFailure

func (e ErrRejected) IsAuthFailure() bool

IsAuthFailure when Peer authentication was unsuccessful.

func (ErrRejected) IsDuplicate

func (e ErrRejected) IsDuplicate() bool

IsDuplicate when Peer ID or IP are present already.

func (ErrRejected) IsFiltered

func (e ErrRejected) IsFiltered() bool

IsFiltered when Peer ID or IP was filtered.

func (ErrRejected) IsIncompatible

func (e ErrRejected) IsIncompatible() bool

IsIncompatible when Peer NodeInfo is not compatible with our own.

func (ErrRejected) IsNodeInfoInvalid

func (e ErrRejected) IsNodeInfoInvalid() bool

IsNodeInfoInvalid when the sent NodeInfo is not valid.

func (ErrRejected) IsSelf

func (e ErrRejected) IsSelf() bool

IsSelf when Peer is our own node.

type ErrSwitchAuthenticationFailure

type ErrSwitchAuthenticationFailure struct {
	Dialed *NetAddress
	Got    ID
}

func (ErrSwitchAuthenticationFailure) Error

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 ID
}

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

func (ErrSwitchDuplicatePeerID) Error

func (e ErrSwitchDuplicatePeerID) Error() string

type ErrSwitchDuplicatePeerIP

type ErrSwitchDuplicatePeerIP struct {
	IP net.IP
}

ErrSwitchDuplicatePeerIP to be raised whena a peer is connecting with a known IP.

func (ErrSwitchDuplicatePeerIP) Error

func (e ErrSwitchDuplicatePeerIP) Error() string

type ErrTransportClosed

type ErrTransportClosed struct{}

ErrTransportClosed is raised when the Transport has been closed.

func (ErrTransportClosed) Error

func (e ErrTransportClosed) Error() string

type ID

type ID string

ID is a hex-encoded crypto.Address

func PubKeyToID

func PubKeyToID(pubKey crypto.PubKey) ID

PubKeyToID returns the ID corresponding to the given PubKey. It's the hex-encoding of the pubKey.Address().

type IPResolver

type IPResolver interface {
	LookupIPAddr(context.Context, string) ([]net.IPAddr, error)
}

IPResolver is a behaviour subset of net.Resolver.

type IPeerSet

type IPeerSet interface {
	Has(key ID) bool
	HasIP(ip net.IP) bool
	Get(key ID) Peer
	List() []Peer
	Size() int
}

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

type Metrics

type Metrics struct {
	// Number of peers.
	Peers metrics.Gauge
	// Number of bytes received from a given peer.
	PeerReceiveBytesTotal metrics.Counter
	// Number of bytes sent to a given peer.
	PeerSendBytesTotal metrics.Counter
	// Pending bytes to be sent to a given peer.
	PeerPendingSendBytes metrics.Gauge
	// Number of transactions submitted by each peer.
	NumTxs metrics.Gauge
}

Metrics contains metrics exposed by this package.

func NopMetrics

func NopMetrics() *Metrics

NopMetrics returns no-op Metrics.

func PrometheusMetrics

func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics

PrometheusMetrics returns Metrics build using Prometheus client library. Optionally, labels can be provided along with their values ("foo", "fooValue").

type MultiplexTransport

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

MultiplexTransport accepts and dials tcp connections and upgrades them to multiplexed peers.

func NewMultiplexTransport

func NewMultiplexTransport(
	nodeInfo NodeInfo,
	nodeKey NodeKey,
	mConfig conn.MConnConfig,
) *MultiplexTransport

NewMultiplexTransport returns a tcp connected multiplexed peer.

func (*MultiplexTransport) Accept

func (mt *MultiplexTransport) Accept(cfg peerConfig) (Peer, error)

Accept implements Transport.

func (*MultiplexTransport) Cleanup

func (mt *MultiplexTransport) Cleanup(p Peer)

Cleanup removes the given address from the connections set and closes the connection.

func (*MultiplexTransport) Close

func (mt *MultiplexTransport) Close() error

Close implements transportLifecycle.

func (*MultiplexTransport) Dial

func (mt *MultiplexTransport) Dial(
	addr NetAddress,
	cfg peerConfig,
) (Peer, error)

Dial implements Transport.

func (*MultiplexTransport) Listen

func (mt *MultiplexTransport) Listen(addr NetAddress) error

Listen implements transportLifecycle.

func (*MultiplexTransport) NetAddress added in v0.30.3

func (mt *MultiplexTransport) NetAddress() NetAddress

NetAddress implements Transport.

type MultiplexTransportOption

type MultiplexTransportOption func(*MultiplexTransport)

MultiplexTransportOption sets an optional parameter on the MultiplexTransport.

func MultiplexTransportConnFilters

func MultiplexTransportConnFilters(
	filters ...ConnFilterFunc,
) MultiplexTransportOption

MultiplexTransportConnFilters sets the filters for rejection new connections.

func MultiplexTransportFilterTimeout

func MultiplexTransportFilterTimeout(
	timeout time.Duration,
) MultiplexTransportOption

MultiplexTransportFilterTimeout sets the timeout waited for filter calls to return.

func MultiplexTransportMaxIncomingConnections added in v0.31.12

func MultiplexTransportMaxIncomingConnections(n int) MultiplexTransportOption

MultiplexTransportMaxIncomingConnections sets the maximum number of simultaneous connections (incoming). Default: 0 (unlimited)

func MultiplexTransportResolver

func MultiplexTransportResolver(resolver IPResolver) MultiplexTransportOption

MultiplexTransportResolver sets the Resolver used for ip lokkups, defaults to net.DefaultResolver.

type NetAddress

type NetAddress struct {
	ID   ID     `json:"id"`
	IP   net.IP `json:"ip"`
	Port uint16 `json:"port"`
}

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

func CreateRoutableAddr

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

func NetAddressFromProto added in v0.34.0

func NetAddressFromProto(pb tmp2p.NetAddress) (*NetAddress, error)

NetAddressFromProto converts a Protobuf NetAddress into a native struct.

func NetAddressesFromProto added in v0.34.0

func NetAddressesFromProto(pbs []tmp2p.NetAddress) ([]*NetAddress, error)

NetAddressesFromProto converts a slice of Protobuf NetAddresses into a native slice.

func NewNetAddress

func NewNetAddress(id ID, 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. Panics if ID is invalid. 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 "ID@IP:Port". Also resolves the host if host is not an IP. Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup)

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

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, including their ID, IP, and Port.

func (*NetAddress) HasID

func (na *NetAddress) HasID() bool

HasID returns true if the address has an ID. NOTE: It does not check whether the ID is valid or not.

func (*NetAddress) Local

func (na *NetAddress) Local() bool

Local returns true if it is a local address.

func (*NetAddress) OnionCatTor added in v0.32.12

func (na *NetAddress) OnionCatTor() bool

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

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

Same returns true is na has the same non-empty ID or DialString as other.

func (*NetAddress) String

func (na *NetAddress) String() string

String representation: <ID>@<IP>:<PORT>

func (*NetAddress) ToProto added in v0.34.0

func (na *NetAddress) ToProto() tmp2p.NetAddress

ToProto converts a NetAddress to Protobuf.

func (*NetAddress) Valid

func (na *NetAddress) Valid() error

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 interface {
	ID() ID
	// contains filtered or unexported methods
}

NodeInfo exposes basic info of a node and determines if we're compatible.

type NodeKey

type NodeKey struct {
	// Canonical ID - hex-encoded pubkey's address (IDByteLength bytes)
	ID ID `json:"id"`
	// Private key
	PrivKey crypto.PrivKey `json:"priv_key"`
}

NodeKey is the persistent peer key. It contains the nodes private key for authentication.

func GenNodeKey

func GenNodeKey() NodeKey

GenNodeKey generates a new node key.

func LoadNodeKey

func LoadNodeKey(filePath string) (NodeKey, error)

LoadNodeKey loads NodeKey located in filePath.

func LoadOrGenNodeKey

func LoadOrGenNodeKey(filePath string) (NodeKey, error)

LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If the file does not exist, it generates and saves a new NodeKey.

func (NodeKey) PubKey

func (nodeKey NodeKey) PubKey() crypto.PubKey

PubKey returns the peer's PubKey

func (NodeKey) SaveAs added in v0.34.0

func (nodeKey NodeKey) SaveAs(filePath string) error

SaveAs persists the NodeKey to filePath.

type Peer

type Peer interface {
	service.Service
	FlushStop()

	ID() ID               // peer's cryptographic ID
	RemoteIP() net.IP     // remote IP of the connection
	RemoteAddr() net.Addr // remote address of the connection

	IsOutbound() bool   // did we dial the peer
	IsPersistent() bool // do we redial this peer when we disconnect

	CloseConn() error // close original connection

	NodeInfo() NodeInfo // peer's info
	Status() tmconn.ConnectionStatus
	SocketAddr() *NetAddress // actual address of the socket

	Send(byte, []byte) bool
	TrySend(byte, []byte) bool

	Set(string, interface{})
	Get(string) interface{}
}

Peer is an interface representing a peer connected on a reactor.

func CreateRandomPeer

func CreateRandomPeer(outbound bool) Peer

type PeerError

type PeerError struct {
	PeerID   PeerID
	Err      error
	Severity PeerErrorSeverity
}

PeerError is a peer error reported by a reactor via the Error channel. The severity may cause the peer to be disconnected or banned depending on policy.

type PeerErrorSeverity

type PeerErrorSeverity string

PeerErrorSeverity determines the severity of a peer error.

const (
	PeerErrorSeverityLow      PeerErrorSeverity = "low"      // Mostly ignored.
	PeerErrorSeverityHigh     PeerErrorSeverity = "high"     // May disconnect.
	PeerErrorSeverityCritical PeerErrorSeverity = "critical" // Ban.
)

type PeerFilterFunc

type PeerFilterFunc func(IPeerSet, Peer) error

PeerFilterFunc to be implemented by filter hooks after a new Peer has been fully setup.

type PeerID

type PeerID []byte

PeerID is a unique peer ID, generally expressed in hex form.

func PeerIDFromString

func PeerIDFromString(s string) (PeerID, error)

PeerIDFromString returns a PeerID from an encoded string or an error upon decode failure.

func (PeerID) Empty

func (pid PeerID) Empty() bool

Empty returns true if the PeerID is considered empty.

func (PeerID) Equal

func (pid PeerID) Equal(other PeerID) bool

Equal reports whether two PeerID are equal.

func (PeerID) String

func (pid PeerID) String() string

String implements the fmt.Stringer interface for the PeerID type.

type PeerOption

type PeerOption func(*peer)

func PeerMetrics

func PeerMetrics(metrics *Metrics) PeerOption

type PeerPriority

type PeerPriority int

PeerPriority specifies peer priorities.

const (
	PeerPriorityNormal PeerPriority = iota + 1
	PeerPriorityValidator
	PeerPriorityPersistent
)

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

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

Get looks up a peer by the provided peerKey. Returns nil if peer is not found.

func (*PeerSet) Has

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

Has returns true if the set contains the peer referred to by this peerKey, otherwise false.

func (*PeerSet) HasIP

func (ps *PeerSet) HasIP(peerIP net.IP) bool

HasIP returns true if the set contains the peer referred to by this IP address, 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) bool

Remove discards peer by its Key, if the peer was previously memoized. Returns true if the peer was removed, and false if it was not found. in the set.

func (*PeerSet) Size

func (ps *PeerSet) Size() int

Size returns the number of unique items in the peerSet.

type PeerStatus

type PeerStatus string

PeerStatus specifies peer statuses.

type PeerUpdate

type PeerUpdate struct {
	PeerID PeerID
	Status PeerStatus
}

PeerUpdate is a peer status update for reactors.

type PeerUpdatesCh

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

PeerUpdatesCh defines a wrapper around a PeerUpdate go channel that allows a reactor to listen for peer updates and safely close it when stopping.

func NewPeerUpdates

func NewPeerUpdates() *PeerUpdatesCh

NewPeerUpdates returns a reference to a new PeerUpdatesCh.

func (*PeerUpdatesCh) Close

func (puc *PeerUpdatesCh) Close()

Close closes the PeerUpdatesCh channel. It should only be closed by the respective reactor when stopping and ensure nothing is listening for updates.

NOTE: After a PeerUpdatesCh is closed, the router may safely assume it can no longer send on the internal updatesCh, however it should NEVER explicitly close it as that could result in panics by sending on a closed channel.

func (*PeerUpdatesCh) Done

func (puc *PeerUpdatesCh) Done() <-chan struct{}

Done returns a read-only version of the PeerUpdatesCh's internal doneCh go channel that should be used by a router to signal when it is safe to explicitly not send any peer updates.

func (*PeerUpdatesCh) Updates

func (puc *PeerUpdatesCh) Updates() <-chan PeerUpdate

Updates returns a read-only go channel where a consuming reactor can listen for peer updates sent from the router.

type ProtocolVersion

type ProtocolVersion struct {
	P2P   uint64 `json:"p2p"`
	Block uint64 `json:"block"`
	App   uint64 `json:"app"`
}

ProtocolVersion contains the protocol versions for the software.

func NewProtocolVersion

func NewProtocolVersion(p2p, block, app uint64) ProtocolVersion

NewProtocolVersion returns a fully populated ProtocolVersion.

type Reactor

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

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

	// GetChannels returns the list of MConnection.ChannelDescriptor. Make sure
	// that each ID is unique across all the reactors added to the switch.
	GetChannels() []*conn.ChannelDescriptor

	// InitPeer is called by the switch before the peer is started. Use it to
	// initialize data for the peer (e.g. peer state).
	//
	// NOTE: The switch won't call AddPeer nor RemovePeer if it fails to start
	// the peer. Do not store any data associated with the peer in the reactor
	// itself unless you don't want to have a state, which is never cleaned up.
	InitPeer(peer Peer) Peer

	// AddPeer is called by the switch after the peer is added and successfully
	// started. Use it to start goroutines communicating with the peer.
	AddPeer(peer Peer)

	// 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 by the switch when msgBytes is received from the peer.
	//
	// NOTE reactor can not keep msgBytes around after Receive completes without
	// copying.
	//
	// CONTRACT: msgBytes are not nil.
	//
	// XXX: do not call any methods that can block or incur heavy processing.
	// https://github.com/tendermint/tendermint/issues/2888
	Receive(chID byte, peer Peer, msgBytes []byte)
}

Reactor is responsible for handling incoming messages on one or more Channel. Switch calls GetChannels when reactor is added to it. When a new peer joins our node, InitPeer and AddPeer are called. RemovePeer is called when the peer is stopped. Receive is called when a message is received on a channel associated with this reactor.

Peer#Send or Peer#TrySend should be used to send the message to a peer.

type ReactorShim

type ReactorShim struct {
	BaseReactor

	Name        string
	PeerUpdates *PeerUpdatesCh
	Channels    map[ChannelID]*ChannelShim
}

ReactorShim defines a generic shim wrapper around a BaseReactor. It is responsible for wiring up legacy p2p behavior to the new p2p semantics (e.g. proxying Envelope messages to legacy peers).

func NewReactorShim

func NewReactorShim(name string, descriptors map[ChannelID]*ChannelDescriptorShim) *ReactorShim

func (*ReactorShim) AddPeer

func (rs *ReactorShim) AddPeer(peer Peer)

AddPeer sends a PeerUpdate with status PeerStatusUp on the PeerUpdateCh. The embedding reactor must be sure to listen for messages on this channel to handle adding a peer.

func (*ReactorShim) GetChannel

func (rs *ReactorShim) GetChannel(cID ChannelID) *Channel

GetChannel returns a p2p Channel reference for a given ChannelID. If no Channel exists, nil is returned.

func (*ReactorShim) GetChannels

func (rs *ReactorShim) GetChannels() []*ChannelDescriptor

GetChannels implements the legacy Reactor interface for getting a slice of all the supported ChannelDescriptors.

func (*ReactorShim) OnStart

func (rs *ReactorShim) OnStart() error

OnStart executes the reactor shim's OnStart hook where we start all the necessary go-routines in order to proxy peer envelopes and errors per p2p Channel.

func (*ReactorShim) Receive

func (rs *ReactorShim) Receive(chID byte, src Peer, msgBytes []byte)

Receive implements a generic wrapper around implementing the Receive method on the legacy Reactor p2p interface. If the reactor is running, Receive will find the corresponding new p2p Channel, create and decode the appropriate proto.Message from the msgBytes, execute any validation and finally construct and send a p2p Envelope on the appropriate p2p Channel.

func (*ReactorShim) RemovePeer

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

RemovePeer sends a PeerUpdate with status PeerStatusDown on the PeerUpdateCh. The embedding reactor must be sure to listen for messages on this channel to handle removing a peer.

type Switch

type Switch struct {
	service.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.P2PConfig,
	n int,
	initSwitch func(int, *Switch) *Switch,
	connect func([]*Switch, int, int),
) []*Switch

MakeConnectedSwitches returns n switches, connected according to the connect func. If connect==Connect2Switches, the switches will be fully connected. initSwitch defines how the i'th switch should be initialized (ie. with what reactors). NOTE: panics if any switch fails to start.

func MakeSwitch

func MakeSwitch(
	cfg *config.P2PConfig,
	i int,
	network, version string,
	initSwitch func(int, *Switch) *Switch,
	opts ...SwitchOption,
) *Switch

func NewSwitch

func NewSwitch(
	cfg *config.P2PConfig,
	transport Transport,
	options ...SwitchOption,
) *Switch

NewSwitch creates a new Switch with the given config.

func (*Switch) AddPersistentPeers added in v0.31.6

func (sw *Switch) AddPersistentPeers(addrs []string) error

AddPersistentPeers allows you to set persistent peers. It ignores ErrNetAddressLookup. However, if there are other errors, first encounter is returned.

func (*Switch) AddPrivatePeerIDs added in v0.34.0

func (sw *Switch) AddPrivatePeerIDs(ids []string) error

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) AddUnconditionalPeerIDs added in v0.33.0

func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error

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

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

DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects and authenticates successfully. If we're currently dialing this address or it belongs to an existing peer, ErrCurrentlyDialingOrExistingAddress is returned.

func (*Switch) DialPeersAsync

func (sw *Switch) DialPeersAsync(peers []string) error

DialPeersAsync dials a list of peers asynchronously in random order. Used to dial peers from config on startup or from unsafe-RPC (trusted sources). It ignores ErrNetAddressLookup. However, if there are other errors, first encounter is returned. Nop if there are no peers.

func (*Switch) IsDialingOrExistingAddress

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

IsDialingOrExistingAddress returns true if switch has a peer with the given address or dialing it at the moment.

func (*Switch) IsPeerPersistent added in v0.33.0

func (sw *Switch) IsPeerPersistent(na *NetAddress) bool

func (*Switch) IsPeerUnconditional added in v0.33.0

func (sw *Switch) IsPeerUnconditional(id ID) bool

func (*Switch) MarkPeerAsGood

func (sw *Switch) MarkPeerAsGood(peer Peer)

MarkPeerAsGood marks the given peer as good when it did something useful like contributed to consensus.

func (*Switch) MaxNumOutboundPeers

func (sw *Switch) MaxNumOutboundPeers() int

MaxNumOutboundPeers returns a maximum number of outbound peers.

func (*Switch) NetAddress added in v0.30.3

func (sw *Switch) NetAddress() *NetAddress

NetAddress returns the address the switch is listening on.

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. unconditional peers are not counted here.

func (*Switch) OnStart

func (sw *Switch) OnStart() error

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

func (*Switch) OnStop

func (sw *Switch) OnStop()

OnStop implements BaseService. It stops all 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) RemoveReactor added in v0.32.2

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

RemoveReactor removes the given Reactor from the Switch. NOTE: Not goroutine safe.

func (*Switch) SetAddrBook

func (sw *Switch) SetAddrBook(addrBook AddrBook)

SetAddrBook allows to set address book on Switch.

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

func (sw *Switch) SetNodeKey(nodeKey NodeKey)

SetNodeKey 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. If the peer is persistent, it will attempt to reconnect. TODO: make record depending on reason.

func (*Switch) StopPeerGracefully

func (sw *Switch) StopPeerGracefully(peer Peer)

StopPeerGracefully disconnects from a peer gracefully. TODO: handle graceful disconnects.

type SwitchOption

type SwitchOption func(*Switch)

SwitchOption sets an optional parameter on the Switch.

func SwitchFilterTimeout

func SwitchFilterTimeout(timeout time.Duration) SwitchOption

SwitchFilterTimeout sets the timeout used for peer filters.

func SwitchPeerFilters

func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption

SwitchPeerFilters sets the filters for rejection of new peers.

func WithMetrics

func WithMetrics(metrics *Metrics) SwitchOption

WithMetrics sets the metrics.

type Transport

type Transport interface {
	// Listening address.
	NetAddress() NetAddress

	// Accept returns a newly connected Peer.
	Accept(peerConfig) (Peer, error)

	// Dial connects to the Peer for the address.
	Dial(NetAddress, peerConfig) (Peer, error)

	// Cleanup any resources associated with Peer.
	Cleanup(Peer)
}

Transport emits and connects to Peers. The implementation of Peer is left to the transport. Each transport is also responsible to filter establishing peers specific to its domain.

type Wrapper added in v0.34.23

type Wrapper interface {
	// Wrap will take a message and wrap it in this one.
	Wrap(proto.Message) error

	// Unwrap will unwrap the inner message contained in this message.
	Unwrap() (proto.Message, error)
}

Wrapper is a Protobuf message that can contain a variety of inner messages. If a Channel's message type implements Wrapper, the channel will automatically (un)wrap passed messages using the container type, such that the channel can transparently support multiple message types.

Directories

Path Synopsis
Taken from taipei-torrent.
Taken from taipei-torrent.

Jump to

Keyboard shortcuts

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