Documentation ¶
Index ¶
- Constants
- Variables
- func ExpectMsg(r MsgReader, code uint64, content interface{}) error
- func Send(w MsgWriter, msgcode uint64, data interface{}) error
- func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error
- type Cap
- type Config
- type DiscReason
- type Msg
- type MsgReadWriter
- type MsgReader
- type MsgWriter
- type NodeDialer
- type NodeInfo
- type Peer
- func (p *Peer) AddPurpose(purpose PurposeFlag)
- func (p *Peer) Caps() []Cap
- func (p *Peer) Disconnect(reason DiscReason)
- func (p *Peer) HasPurpose(purpose PurposeFlag) bool
- func (p *Peer) ID() enode.ID
- func (p *Peer) Inbound() bool
- func (p *Peer) Info() *PeerInfo
- func (p *Peer) LocalAddr() net.Addr
- func (p *Peer) Log() log.Logger
- func (p *Peer) Name() string
- func (p *Peer) Node() *enode.Node
- func (p *Peer) RemoteAddr() net.Addr
- func (p *Peer) RemovePurpose(purpose PurposeFlag)
- func (p *Peer) RunningCap(protocol string, versions []uint) bool
- func (p *Peer) String() string
- type PeerEvent
- type PeerEventType
- type PeerInfo
- type Protocol
- type PurposeFlag
- type Server
- func (srv *Server) AddPeer(node *enode.Node, purpose PurposeFlag)
- func (srv *Server) AddTrustedPeer(node *enode.Node, purpose PurposeFlag)
- func (srv *Server) CheckPeerCounts(peer *Peer) error
- func (srv *Server) LocalNode() *enode.LocalNode
- func (srv *Server) NodeInfo() *NodeInfo
- func (srv *Server) PeerCount() int
- func (srv *Server) Peers() []*Peer
- func (srv *Server) PeersInfo() []*PeerInfo
- func (srv *Server) RemovePeer(node *enode.Node, purpose PurposeFlag)
- func (srv *Server) RemoveTrustedPeer(node *enode.Node, purpose PurposeFlag)
- func (srv *Server) Self() *enode.Node
- func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *enode.Node) error
- func (srv *Server) Start() (err error)
- func (srv *Server) Stop()
- func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription
- type SharedUDPConn
Constants ¶
const ( NoPurpose PurposeFlag = 0 ExplicitStaticPurpose = 1 << 0 ExplicitTrustedPurpose = 1 << 1 ValidatorPurpose = 1 << 2 ProxyPurpose = 1 << 3 AnyPurpose = ExplicitStaticPurpose | ExplicitTrustedPurpose | ValidatorPurpose | ProxyPurpose // This value should be the bitwise OR of all possible PurposeFlag values )
const (
// HandleHistName is the prefix of the per-packet serving time histograms.
HandleHistName = "p2p/handle"
)
Variables ¶
var (
ErrShuttingDown = errors.New("shutting down")
)
Functions ¶
func ExpectMsg ¶
ExpectMsg reads a message from r and verifies that its code and encoded RLP content match the provided values. If content is nil, the payload is discarded and not verified.
Types ¶
type Config ¶
type Config struct { // This field must be set to a valid secp256k1 private key. PrivateKey *ecdsa.PrivateKey `toml:"-"` // MaxPeers is the maximum number of peers that can be // connected. It must be greater than zero. MaxPeers int // MaxLightClients is the maximum number of light clients that can be connected. // It is zero if the LES server isn't running (includes the case that we are an LES client). MaxLightClients int // MaxPendingPeers is the maximum number of peers that can be pending in the // handshake phase, counted separately for inbound and outbound connections. // Zero defaults to preset values. MaxPendingPeers int `toml:",omitempty"` // DialRatio controls the ratio of inbound to dialed connections. // Example: a DialRatio of 2 allows 1/2 of connections to be dialed. // Setting DialRatio to zero defaults it to 3. DialRatio int `toml:",omitempty"` // NoDiscovery can be used to disable the peer discovery mechanism. // Disabling is useful for protocol debugging (manual topology). NoDiscovery bool // DiscoveryV5 specifies whether the new topic-discovery based V5 discovery // protocol should be started or not. DiscoveryV5 bool `toml:",omitempty"` // Name sets the node name of this server. // Use common.MakeName to create a name that follows existing conventions. Name string `toml:"-"` // BootstrapNodes are used to establish connectivity // with the rest of the network. BootstrapNodes []*enode.Node // BootstrapNodesV5 are used to establish connectivity // with the rest of the network using the V5 discovery // protocol. BootstrapNodesV5 []*enode.Node `toml:",omitempty"` // Static nodes are used as pre-configured connections which are always // maintained and re-connected on disconnects. StaticNodes []*enode.Node // Trusted nodes are used as pre-configured connections which are always // allowed to connect, even above the peer limit. TrustedNodes []*enode.Node // Connectivity can be restricted to certain IP networks. // If this option is set to a non-nil value, only hosts which match one of the // IP networks contained in the list are considered. NetRestrict *netutil.Netlist `toml:",omitempty"` // NodeDatabase is the path to the database containing the previously seen // live nodes in the network. NodeDatabase string `toml:",omitempty"` // Protocols should contain the protocols supported // by the server. Matching protocols are launched for // each peer. Protocols []Protocol `toml:"-"` // If ListenAddr is set to a non-nil address, the server // will listen for incoming connections. // // If the port is zero, the operating system will pick a port. The // ListenAddr field will be updated with the actual address when // the server is started. ListenAddr string // If set to a non-nil value, the given NAT port mapper // is used to make the listening port available to the // Internet. NAT nat.Interface `toml:",omitempty"` // If Dialer is set to a non-nil value, the given Dialer // is used to dial outbound peer connections. Dialer NodeDialer `toml:"-"` // If NoDial is true, the server will not dial any peers. NoDial bool `toml:",omitempty"` // If EnableMsgEvents is set then the server will emit PeerEvents // whenever a message is sent to or received from a peer EnableMsgEvents bool // Logger is a custom logger to use with the p2p.Server. Logger log.Logger `toml:",omitempty"` // contains filtered or unexported fields }
Config holds Server options.
type DiscReason ¶
type DiscReason uint
const ( DiscRequested DiscReason = iota DiscNetworkError DiscProtocolError DiscUselessPeer DiscTooManyPeers DiscTooManyInboundPeers DiscAlreadyConnected DiscIncompatibleVersion DiscInvalidIdentity DiscQuitting DiscUnexpectedIdentity DiscSelf DiscReadTimeout DiscSubprotocolError = 0x10 )
func (DiscReason) Error ¶
func (d DiscReason) Error() string
func (DiscReason) String ¶
func (d DiscReason) String() string
type Msg ¶
type Msg struct { Code uint64 Size uint32 // Size of the raw payload Payload io.Reader ReceivedAt time.Time // contains filtered or unexported fields }
Msg defines the structure of a p2p message.
Note that a Msg can only be sent once since the Payload reader is consumed during sending. It is not possible to create a Msg and send it any number of times. If you want to reuse an encoded structure, encode the payload into a byte array and create a separate Msg with a bytes.Reader as Payload for each send.
func (Msg) Decode ¶
Decode parses the RLP content of a message into the given value, which must be a pointer.
For the decoding rules, please see package rlp.
type MsgReadWriter ¶
MsgReadWriter provides reading and writing of encoded messages. Implementations should ensure that ReadMsg and WriteMsg can be called simultaneously from multiple goroutines.
type NodeDialer ¶
NodeDialer is used to connect to nodes in the network, typically by using an underlying net.Dialer but also using net.Pipe in tests.
type NodeInfo ¶
type NodeInfo struct { ID string `json:"id"` // Unique node identifier (also the encryption key) Name string `json:"name"` // Name of the node, including client type, version, OS, custom data Enode string `json:"enode"` // Enode URL for adding this peer from remote peers ENR string `json:"enr"` // Ethereum Node Record IP string `json:"ip"` // IP address of the node Ports struct { Discovery int `json:"discovery"` // UDP listening port for discovery protocol Listener int `json:"listener"` // TCP listening port for RLPx } `json:"ports"` ListenAddr string `json:"listenAddr"` Protocols map[string]interface{} `json:"protocols"` }
NodeInfo represents a short summary of the information known about the host.
type Peer ¶
type Peer struct { Server *Server // contains filtered or unexported fields }
Peer represents a connected remote node.
func (*Peer) AddPurpose ¶
func (p *Peer) AddPurpose(purpose PurposeFlag)
func (*Peer) Disconnect ¶
func (p *Peer) Disconnect(reason DiscReason)
Disconnect terminates the peer connection with the given reason. It returns immediately and does not wait until the connection is closed.
func (*Peer) HasPurpose ¶
func (p *Peer) HasPurpose(purpose PurposeFlag) bool
func (*Peer) RemoteAddr ¶
RemoteAddr returns the remote address of the network connection.
func (*Peer) RemovePurpose ¶
func (p *Peer) RemovePurpose(purpose PurposeFlag)
func (*Peer) RunningCap ¶
RunningCap returns true if the peer is actively connected using any of the enumerated versions of a specific protocol, meaning that at least one of the versions is supported by both this node and the peer p.
type PeerEvent ¶
type PeerEvent struct { Type PeerEventType `json:"type"` Peer enode.ID `json:"peer"` Error string `json:"error,omitempty"` Protocol string `json:"protocol,omitempty"` MsgCode *uint64 `json:"msg_code,omitempty"` MsgSize *uint32 `json:"msg_size,omitempty"` LocalAddress string `json:"local,omitempty"` RemoteAddress string `json:"remote,omitempty"` }
PeerEvent is an event emitted when peers are either added or dropped from a p2p.Server or when a message is sent or received on a peer connection
type PeerEventType ¶
type PeerEventType string
PeerEventType is the type of peer events emitted by a p2p.Server
const ( // PeerEventTypeAdd is the type of event emitted when a peer is added // to a p2p.Server PeerEventTypeAdd PeerEventType = "add" // PeerEventTypeDrop is the type of event emitted when a peer is // dropped from a p2p.Server PeerEventTypeDrop PeerEventType = "drop" // PeerEventTypeMsgSend is the type of event emitted when a // message is successfully sent to a peer PeerEventTypeMsgSend PeerEventType = "msgsend" // PeerEventTypeMsgRecv is the type of event emitted when a // message is received from a peer PeerEventTypeMsgRecv PeerEventType = "msgrecv" )
type PeerInfo ¶
type PeerInfo struct { ENR string `json:"enr,omitempty"` // Ethereum Node Record Enode string `json:"enode"` // Node URL ID string `json:"id"` // Unique node identifier Name string `json:"name"` // Name of the node, including client type, version, OS, custom data Caps []string `json:"caps"` // Protocols advertised by this peer Purposes string `json:"purposes"` // Purposes for the peer Network struct { LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection Inbound bool `json:"inbound"` Trusted bool `json:"trusted"` Static bool `json:"static"` } `json:"network"` Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields }
PeerInfo represents a short summary of the information known about a connected peer. Sub-protocol independent fields are contained and initialized here, with protocol specifics delegated to all connected sub-protocols.
type Protocol ¶
type Protocol struct { // Name should contain the official protocol name, // often a three-letter word. Name string // Version should contain the version number of the protocol. Version uint // Length should contain the number of message codes used // by the protocol. Length uint64 // Run is called in a new goroutine when the protocol has been // negotiated with a peer. It should read and write messages from // rw. The Payload for each message must be fully consumed. // // The peer connection is closed when Start returns. It should return // any protocol-level error (such as an I/O error) that is // encountered. Run func(peer *Peer, rw MsgReadWriter) error // NodeInfo is an optional helper method to retrieve protocol specific metadata // about the host node. NodeInfo func() interface{} // PeerInfo is an optional helper method to retrieve protocol specific metadata // about a certain peer in the network. If an info retrieval function is set, // but returns nil, it is assumed that the protocol handshake is still running. PeerInfo func(id enode.ID) interface{} // DialCandidates, if non-nil, is a way to tell Server about protocol-specific nodes // that should be dialed. The server continuously reads nodes from the iterator and // attempts to create connections to them. DialCandidates enode.Iterator // Attributes contains protocol specific information for the node record. Attributes []enr.Entry }
Protocol represents a P2P subprotocol implementation.
type PurposeFlag ¶
type PurposeFlag uint32
Note that this type is NOT threadsafe. The reason that it is not is that it's read and written only by the p2p server's single threaded event loop.
func (PurposeFlag) Add ¶
func (pf PurposeFlag) Add(f PurposeFlag) PurposeFlag
func (PurposeFlag) HasNoPurpose ¶
func (pf PurposeFlag) HasNoPurpose() bool
func (PurposeFlag) HasPurpose ¶
func (pf PurposeFlag) HasPurpose() bool
func (PurposeFlag) IsSet ¶
func (pf PurposeFlag) IsSet(f PurposeFlag) bool
func (PurposeFlag) Remove ¶
func (pf PurposeFlag) Remove(f PurposeFlag) PurposeFlag
func (PurposeFlag) String ¶
func (pf PurposeFlag) String() string
type Server ¶
type Server struct { // Config fields may not be modified while the server is running. Config DiscV5 *discover.UDPv5 // discv5.Network // contains filtered or unexported fields }
Server manages all peer connections.
func (*Server) AddPeer ¶
func (srv *Server) AddPeer(node *enode.Node, purpose PurposeFlag)
AddPeer connects to the given node and maintains the connection until the server is shut down. If the connection fails for any reason, the server will attempt to reconnect the peer.
func (*Server) AddTrustedPeer ¶
func (srv *Server) AddTrustedPeer(node *enode.Node, purpose PurposeFlag)
AddTrustedPeer adds the given node to a reserved whitelist which allows the node to always connect, even if the slot are full.
func (*Server) CheckPeerCounts ¶
CheckPeerCounts performs some checks for a peer that has already been included in the peer counts
func (*Server) NodeInfo ¶
NodeInfo gathers and returns a collection of metadata known about the host.
func (*Server) PeersInfo ¶
PeersInfo returns an array of metadata objects describing all connected peers.
func (*Server) RemovePeer ¶
func (srv *Server) RemovePeer(node *enode.Node, purpose PurposeFlag)
RemovePeer disconnects from the given node
func (*Server) RemoveTrustedPeer ¶
func (srv *Server) RemoveTrustedPeer(node *enode.Node, purpose PurposeFlag)
RemoveTrustedPeer removes the given node from the trusted peer set.
func (*Server) SetupConn ¶
SetupConn runs the handshakes and attempts to add the connection as a peer. It returns when the connection has been added as a peer or the handshakes have failed.
func (*Server) Stop ¶
func (srv *Server) Stop()
Stop terminates the server and all active peer connections. It blocks until all active connections have been closed.
func (*Server) SubscribeEvents ¶
func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription
SubscribeEvents subscribes the given channel to peer events
type SharedUDPConn ¶
type SharedUDPConn struct {}
SharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns messages that were found unprocessable and sent to the unhandled channel by the primary listener.
func (*SharedUDPConn) ReadFromUDP ¶
ReadFromUDP implements discv5.conn