Documentation ¶
Index ¶
- Constants
- func AddPeerToSwitchPeerSet(sw *Switch, peer Peer)
- func Connect2Switches(switches []*Switch, i, j int)
- func FuzzConn(conn net.Conn) net.Conn
- func FuzzConnAfter(conn net.Conn, d time.Duration) net.Conn
- func FuzzConnAfterFromConfig(conn net.Conn, d time.Duration, config *config.FuzzConnConfig) net.Conn
- func FuzzConnFromConfig(conn net.Conn, config *config.FuzzConnConfig) net.Conn
- func IDAddressString(id ID, protocolHostPort string) string
- func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig
- func MakePoWTarget(difficulty, targetBits uint) []byte
- func MaxNodeInfoSize() int
- func StartSwitches(switches []*Switch) error
- type AddrBook
- type BaseReactor
- func (*BaseReactor) AddPeer(peer Peer)
- func (*BaseReactor) GetChannels() []*conn.ChannelDescriptor
- func (*BaseReactor) InitPeer(peer Peer) Peer
- func (*BaseReactor) Receive(chID byte, peer Peer, msgBytes []byte)
- func (*BaseReactor) RemovePeer(peer Peer, reason interface{})
- func (br *BaseReactor) SetSwitch(sw *Switch)
- type ChannelDescriptor
- type ConnFilterFunc
- type ConnSet
- type ConnectionStatus
- type DefaultNodeInfo
- func (info DefaultNodeInfo) CompatibleWith(otherInfo NodeInfo) error
- func (info DefaultNodeInfo) ID() ID
- func (info *DefaultNodeInfo) Marshal() ([]byte, error)
- func (info *DefaultNodeInfo) MarshalTo(data []byte) (int, error)
- func (info DefaultNodeInfo) NetAddress() (*NetAddress, error)
- func (info *DefaultNodeInfo) Size() int
- func (info *DefaultNodeInfo) Unmarshal(bs []byte) error
- func (info DefaultNodeInfo) Validate() error
- type DefaultNodeInfoOther
- type ErrCurrentlyDialingOrExistingAddress
- type ErrFilterTimeout
- type ErrNetAddressInvalid
- type ErrNetAddressLookup
- type ErrNetAddressNoID
- type ErrRejected
- func (e ErrRejected) Addr() NetAddress
- func (e ErrRejected) Error() string
- func (e ErrRejected) IsAuthFailure() bool
- func (e ErrRejected) IsDuplicate() bool
- func (e ErrRejected) IsFiltered() bool
- func (e ErrRejected) IsIncompatible() bool
- func (e ErrRejected) IsNodeInfoInvalid() bool
- func (e ErrRejected) IsSelf() bool
- type ErrSwitchAuthenticationFailure
- type ErrSwitchConnectToSelf
- type ErrSwitchDuplicatePeerID
- type ErrSwitchDuplicatePeerIP
- type ErrTransportClosed
- type FuzzedConnection
- func (fc *FuzzedConnection) Close() error
- func (fc *FuzzedConnection) Config() *config.FuzzConnConfig
- func (fc *FuzzedConnection) LocalAddr() net.Addr
- func (fc *FuzzedConnection) Read(data []byte) (n int, err error)
- func (fc *FuzzedConnection) RemoteAddr() net.Addr
- func (fc *FuzzedConnection) SetDeadline(t time.Time) error
- func (fc *FuzzedConnection) SetReadDeadline(t time.Time) error
- func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error
- func (fc *FuzzedConnection) Write(data []byte) (n int, err error)
- type ID
- type IPResolver
- type IPeerSet
- type Metrics
- type MultiplexTransport
- func (mt *MultiplexTransport) Accept(cfg peerConfig) (Peer, error)
- func (mt *MultiplexTransport) Cleanup(p Peer)
- func (mt *MultiplexTransport) Close() error
- func (mt *MultiplexTransport) Dial(addr NetAddress, cfg peerConfig) (Peer, error)
- func (mt *MultiplexTransport) Listen(addr NetAddress) error
- func (mt *MultiplexTransport) NetAddress() NetAddress
- type MultiplexTransportOption
- func MultiplexTransportConnFilters(filters ...ConnFilterFunc) MultiplexTransportOption
- func MultiplexTransportFilterTimeout(timeout time.Duration) MultiplexTransportOption
- func MultiplexTransportMaxIncomingConnections(n int) MultiplexTransportOption
- func MultiplexTransportResolver(resolver IPResolver) MultiplexTransportOption
- type NetAddress
- func CreateRoutableAddr() (addr string, netAddr *NetAddress)
- func NewNetAddress(id ID, addr net.Addr) *NetAddress
- func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress
- func NewNetAddressString(addr string) (*NetAddress, error)
- func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error)
- func (na *NetAddress) Dial() (net.Conn, error)
- func (na *NetAddress) DialString() string
- func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error)
- func (na *NetAddress) Equals(other interface{}) bool
- func (na *NetAddress) HasID() bool
- func (na *NetAddress) Local() bool
- func (na *NetAddress) OnionCatTor() bool
- func (na *NetAddress) RFC1918() bool
- func (na *NetAddress) RFC3849() bool
- func (na *NetAddress) RFC3927() bool
- func (na *NetAddress) RFC3964() bool
- func (na *NetAddress) RFC4193() bool
- func (na *NetAddress) RFC4380() bool
- func (na *NetAddress) RFC4843() bool
- func (na *NetAddress) RFC4862() bool
- func (na *NetAddress) RFC6052() bool
- func (na *NetAddress) RFC6145() bool
- func (na *NetAddress) ReachabilityTo(o *NetAddress) int
- func (na *NetAddress) Routable() bool
- func (na *NetAddress) Same(other interface{}) bool
- func (na *NetAddress) String() string
- func (na *NetAddress) Valid() error
- type NodeInfo
- type NodeKey
- type Peer
- type PeerFilterFunc
- type PeerOption
- type PeerSet
- type ProtocolVersion
- type Reactor
- type Switch
- func (sw *Switch) AddPersistentPeers(addrs []string) error
- func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor
- func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error
- func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool
- func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error
- func (sw *Switch) DialPeersAsync(peers []string) error
- func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool
- func (sw *Switch) IsPeerPersistent(na *NetAddress) bool
- func (sw *Switch) IsPeerUnconditional(id ID) bool
- func (sw *Switch) MarkPeerAsGood(peer Peer)
- func (sw *Switch) MaxNumOutboundPeers() int
- func (sw *Switch) NetAddress() *NetAddress
- func (sw *Switch) NodeInfo() NodeInfo
- func (sw *Switch) NumPeers() (outbound, inbound, dialing int)
- func (sw *Switch) OnStart() error
- func (sw *Switch) OnStop()
- func (sw *Switch) Peers() IPeerSet
- func (sw *Switch) Reactor(name string) Reactor
- func (sw *Switch) Reactors() map[string]Reactor
- func (sw *Switch) RemoveReactor(name string, reactor Reactor)
- func (sw *Switch) SetAddrBook(addrBook AddrBook)
- func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo)
- func (sw *Switch) SetNodeKey(nodeKey *NodeKey)
- func (sw *Switch) StopPeerForError(peer Peer, reason interface{})
- func (sw *Switch) StopPeerGracefully(peer Peer)
- type SwitchOption
- type Transport
Constants ¶
const IDByteLength = crypto.AddressSize
IDByteLength 是crypto.Address的长度. 当前只能为20. TODO: support other length addresses ?
const ( // MetricsSubsystem is a subsystem shared by all metrics exposed by this // package. MetricsSubsystem = "p2p" )
const TestHost = "localhost"
Variables ¶
This section is empty.
Functions ¶
func AddPeerToSwitchPeerSet ¶
func Connect2Switches ¶
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 FuzzConnAfter ¶
FuzzConnAfter creates a new FuzzedConnection. Fuzzing starts when the duration elapses.
func FuzzConnAfterFromConfig ¶
func FuzzConnAfterFromConfig( conn net.Conn, d time.Duration, config *config.FuzzConnConfig, ) net.Conn
FuzzConnAfterFromConfig creates a new FuzzedConnection from a config. Fuzzing starts when the duration elapses.
func FuzzConnFromConfig ¶
FuzzConnFromConfig creates a new FuzzedConnection from a config. Fuzzing starts immediately.
func IDAddressString ¶
IDAddressString returns id@hostPort. It strips the leading protocol from protocolHostPort if it exists.
func MConnConfig ¶
func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig
MConnConfig 返回一个从配置文件中获取数值的MConnConfig对象
func MakePoWTarget ¶
MakePoWTarget returns the big-endian encoding of 2^(targetBits - difficulty) - 1. It can be used as a Proof of Work target. NOTE: targetBits must be a multiple of 8 and difficulty must be less than targetBits.
func StartSwitches ¶
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 AddOurAddress(*NetAddress) OurAddress(*NetAddress) bool MarkGood(ID) RemoveAddress(*NetAddress) HasAddress(*NetAddress) bool Save() }
AddrBook 代表一个来自pex包的地址簿,用来保存peer地址
type BaseReactor ¶
type BaseReactor struct { service.BaseService // 提供了启动、停止和退出等方法 Switch *Switch }
-------------------------------------- 提供reactor的基本实现,其他reactor通过继承它来实现reactor接口。
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 ¶
func (*BaseReactor) InitPeer(peer Peer) Peer
func (*BaseReactor) RemovePeer ¶
func (*BaseReactor) RemovePeer(peer Peer, reason interface{})
func (*BaseReactor) SetSwitch ¶
func (br *BaseReactor) SetSwitch(sw *Switch)
type ChannelDescriptor ¶
type ChannelDescriptor = conn.ChannelDescriptor
type ConnFilterFunc ¶
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.
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 在Tendermint P2P握手期间两个peer互相交换的基本node信息。
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) Marshal ¶
func (info *DefaultNodeInfo) Marshal() ([]byte, error)
Marshal returns the amino encoding.
func (*DefaultNodeInfo) MarshalTo ¶
func (info *DefaultNodeInfo) MarshalTo(data []byte) (int, error)
MarshalTo calls Marshal and copies to the given buffer.
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) Size ¶
func (info *DefaultNodeInfo) Size() int
Size returns the size of the amino encoding, in bytes.
func (*DefaultNodeInfo) Unmarshal ¶
func (info *DefaultNodeInfo) Unmarshal(bs []byte) error
Unmarshal deserializes from amino encoded form.
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 是杂项。 特定于应用程序的数据
type ErrCurrentlyDialingOrExistingAddress ¶
type ErrCurrentlyDialingOrExistingAddress struct {
Addr string
}
ErrCurrentlyDialingOrExistingAddress indicates that we're currently dialing this address or it belongs to an existing peer.
func (ErrCurrentlyDialingOrExistingAddress) Error ¶
func (e ErrCurrentlyDialingOrExistingAddress) Error() string
type ErrFilterTimeout ¶
type ErrFilterTimeout struct{}
ErrFilterTimeout indicates that a filter operation timed out.
func (ErrFilterTimeout) Error ¶
func (e ErrFilterTimeout) Error() string
type ErrNetAddressInvalid ¶
func (ErrNetAddressInvalid) Error ¶
func (e ErrNetAddressInvalid) Error() string
type ErrNetAddressLookup ¶
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.
type ErrSwitchAuthenticationFailure ¶
type ErrSwitchAuthenticationFailure struct { Dialed *NetAddress Got ID }
func (ErrSwitchAuthenticationFailure) Error ¶
func (e ErrSwitchAuthenticationFailure) 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 ID
}
ErrSwitchDuplicatePeerID to be raised when a peer is connecting with a known ID.
func (ErrSwitchDuplicatePeerID) Error ¶
func (e ErrSwitchDuplicatePeerID) Error() string
type ErrSwitchDuplicatePeerIP ¶
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 FuzzedConnection ¶
type FuzzedConnection struct {
// contains filtered or unexported fields
}
FuzzedConnection wraps any net.Conn and depending on the mode either delays reads/writes or randomly drops reads/writes/connections.
func (*FuzzedConnection) Close ¶
func (fc *FuzzedConnection) Close() error
Close implements net.Conn.
func (*FuzzedConnection) Config ¶
func (fc *FuzzedConnection) Config() *config.FuzzConnConfig
Config returns the connection's config.
func (*FuzzedConnection) LocalAddr ¶
func (fc *FuzzedConnection) LocalAddr() net.Addr
LocalAddr implements net.Conn.
func (*FuzzedConnection) Read ¶
func (fc *FuzzedConnection) Read(data []byte) (n int, err error)
Read implements net.Conn.
func (*FuzzedConnection) RemoteAddr ¶
func (fc *FuzzedConnection) RemoteAddr() net.Addr
RemoteAddr implements net.Conn.
func (*FuzzedConnection) SetDeadline ¶
func (fc *FuzzedConnection) SetDeadline(t time.Time) error
SetDeadline implements net.Conn.
func (*FuzzedConnection) SetReadDeadline ¶
func (fc *FuzzedConnection) SetReadDeadline(t time.Time) error
SetReadDeadline implements net.Conn.
func (*FuzzedConnection) SetWriteDeadline ¶
func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error
SetWriteDeadline implements net.Conn.
type ID ¶
type ID string
ID 是一个hex编码的crypto.Address
func PubKeyToID ¶
PubKeyToID 返回与给定PubKey对应的ID。 它是pubKey.Address()的hex编码。
type IPResolver ¶
IPResolver是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 PrometheusMetrics ¶
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 ¶
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 ¶
func MultiplexTransportMaxIncomingConnections(n int) MultiplexTransportOption
MultiplexTransportMaxIncomingConnections 设置同时连接的最大数量(传入). 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"` // contains filtered or unexported fields }
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 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 ¶
DialTimeout 调用了net.DialTimeout,在规定时间内创建连接
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) OnionCatTor ¶
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) 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. NodeInfo 暴露一个node的基本信息,并决定是否兼容
type NodeKey ¶
NodeKey 是一个持久化的peer钥匙。 它保存了peer的私钥用于身份验证。
func LoadNodeKey ¶
func LoadOrGenNodeKey ¶
LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If the file does not exist, it generates and saves a new NodeKey. LoadOrGenNodeKey 尝试者从指定的路径读取nodeKey, 如果文件不存在 就在指定路径生成一个新的nodeKey
type Peer ¶
type Peer interface { service.Service FlushStop() ID() ID // peer的加密ID RemoteIP() net.IP // 连接的远程IP RemoteAddr() net.Addr // 连接的远程地址 IsOutbound() bool // true-->主动去连接其他peer的peer,否则是被连接 IsPersistent() bool // 持久化peer,断开后会去重连 CloseConn() error // 关闭原始链接 NodeInfo() NodeInfo // peer的信息 Status() tmconn.ConnectionStatus SocketAddr() *NetAddress // 套接字的实际地址 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 ¶
type PeerFilterFunc ¶
PeerFilterFunc to be implemented by filter hooks after a new Peer has been fully setup.
type PeerOption ¶
type PeerOption func(*peer)
func PeerMetrics ¶
func PeerMetrics(metrics *Metrics) PeerOption
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 ¶
Add adds the peer to the PeerSet. It returns an error carrying the reason, if the peer is already present.
func (*PeerSet) Get ¶
Get looks up a peer by the provided peerKey. Returns nil if peer is not found.
func (*PeerSet) Has ¶
Has returns true if the set contains the peer referred to by this peerKey, otherwise false.
func (*PeerSet) HasIP ¶
HasIP returns true if the set contains the peer referred to by this IP address, otherwise false.
type ProtocolVersion ¶
type ProtocolVersion struct { P2P version.Protocol `json:"p2p"` Block version.Protocol `json:"block"` App version.Protocol `json:"app"` }
ProtocolVersion 包含软件的协议版本
func NewProtocolVersion ¶
func NewProtocolVersion(p2p, block, app version.Protocol) ProtocolVersion
NewProtocolVersion returns a fully populated ProtocolVersion.
type Reactor ¶
type Reactor interface { service.Service // 继承service接口,实现启停。 // SetSwitch 让reactor和switch可以互相调用。 SetSwitch(*Switch) // GetChannels 返回MConnection.ChannelDescriptor集合。 // 确保每个MConnection.ChannelDescriptor的ID都是唯一的。 GetChannels() []*conn.ChannelDescriptor // InitPeer 在peer启动前被switch调用。使用它来初始化peer的一些数据(例如peer的状态) // // 注意:如果switch无法启动peer,则它不会调用AddPeer或RemovePeer。 // 除非您不想拥有永远不会被清除的状态,否则请勿在reactor本身中存储与peer关联的任何数据。 InitPeer(peer Peer) Peer // AddPeer 在添加peer并成功启动之后,被switch调用。使用它来启动goroutine于peer交流。 AddPeer(peer Peer) // RemovePeer 当peer停止时被switch调用(由于错误或者其他原因) RemovePeer(peer Peer, reason interface{}) // Receive 当从peer收到消息时被调用。 // // 注意:在Receive方法完成后,reactor如果不拷贝消息,无法保留消息。 // // 消息不能为空 Receive(chID byte, peer Peer, msgBytes []byte) }
Reactor 负责处理一个或多个channel中的消息。当reactor被添加到Switch时,会调用GetChannels方法。 当一个新的peer加入节点时,InitPeer和AddPeer被调用。当一个peer被停止时,RemovePeer被调用。 当reactor相关的channel收到一条消息后,Receive方法被调用。
Peer#Send或Peer#TrySend应该被用来发送消息到peer
type Switch ¶
type Switch struct { // 继承基本服务 方便统一启动和停止 service.BaseService // contains filtered or unexported fields }
Switch 处理peer连接并暴露API来接受reactors的传入消息。 每个Reactor负责处理一个或多个Channel的传入消息。 因此peer通常用于发送消息,而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 NewSwitch ¶
func NewSwitch( cfg *config.P2PConfig, transport Transport, options ...SwitchOption, ) *Switch
NewSwitch 通过给定的配置创建一个新的switch
func (*Switch) AddPersistentPeers ¶
AddPersistentPeers 添加持久化peer,持久化peer在config文件中被设置
func (*Switch) AddReactor ¶
AddReactor 添加一个给定的reactor到switch 注意: 非goroutine安全.
func (*Switch) AddUnconditionalPeerIDs ¶
func (*Switch) Broadcast ¶
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: 广播使用goroutines,因此可能不会保留广播的顺序。
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 ¶
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 ¶
func (sw *Switch) IsPeerPersistent(na *NetAddress) bool
func (*Switch) IsPeerUnconditional ¶
func (*Switch) MarkPeerAsGood ¶
MarkPeerAsGood marks the given peer as good when it did something useful like contributed to consensus.
func (*Switch) MaxNumOutboundPeers ¶
MaxNumOutboundPeers 返回最大客户端peer数量
func (*Switch) NetAddress ¶
func (sw *Switch) NetAddress() *NetAddress
NetAddress returns the address the switch is listening on.
func (*Switch) NumPeers ¶
NumPeers 返回outbound/inbound和outbound-dialing peer的数量 unconditional peer不包含在这里
func (*Switch) RemoveReactor ¶
RemoveReactor 把给定的reactor从switch中删除 注意: 非goroutine安全.
func (*Switch) SetAddrBook ¶
SetAddrBook allows to set address book on Switch.
func (*Switch) SetNodeInfo ¶
SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes. NOTE: Not goroutine safe.
func (*Switch) SetNodeKey ¶
SetNodeKey sets the switch's private key for authenticated encryption. NOTE: Not goroutine safe.
func (*Switch) StopPeerForError ¶
StopPeerForError 发生错误,断开与peer的连接 如果peer是持久化的,它将尝试重新连接
func (*Switch) StopPeerGracefully ¶
StopPeerGracefully 优雅~~~的断开与peer的连接 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.
type Transport ¶
type Transport interface { // 监听地址 NetAddress() NetAddress // Accept 生成一个服务端peer Accept(peerConfig) (Peer, error) // Dial 生成一个客户端peer Dial(NetAddress, peerConfig) (Peer, error) // 清理与此peer相关的资源 Cleanup(Peer) }
Transport 发送并连接peer。Peer的实现留给transport。、 每个transport还负责过滤特定于其域的对等端。