Documentation ¶
Overview ¶
Package p2p implements the Ethereum p2p network protocols.
Index ¶
- Variables
- func ExpectMsg(r MsgReader, code uint64, content interface{}) error
- func MsgPipe() (*MsgPipeRW, *MsgPipeRW)
- 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 Info
- type KnownNodeInfos
- type Msg
- type MsgPipeRW
- type MsgReadWriter
- type MsgReader
- type MsgWriter
- type NodeDialer
- type NodeInfo
- type Peer
- func (p *Peer) Caps() []Cap
- func (p *Peer) ConnFlags() connFlag
- func (p *Peer) ConnInfoCtx() []interface{}
- func (p *Peer) Disconnect(reason DiscReason)
- func (p *Peer) Duration() float64
- func (p *Peer) ID() discover.NodeID
- func (p *Peer) Info() *PeerInfo
- func (p *Peer) IsInbound() bool
- func (p *Peer) ListenPort() uint16
- func (p *Peer) LocalAddr() net.Addr
- func (p *Peer) Log() log.Logger
- func (p *Peer) Name() string
- func (p *Peer) RemoteAddr() net.Addr
- func (p *Peer) Rtt() float64
- func (p *Peer) String() string
- func (p *Peer) TCPPort() uint16
- func (p *Peer) Version() uint64
- type PeerEvent
- type PeerEventType
- type PeerInfo
- type Protocol
- type Server
- func (srv *Server) AddBlacklist(cidrs string) error
- func (srv *Server) AddPeer(node *discover.Node)
- func (srv *Server) NodeInfo() *NodeInfo
- func (srv *Server) PeerCount() int
- func (srv *Server) Peers() []*Peer
- func (srv *Server) PeersInfo() []*PeerInfo
- func (srv *Server) RedialList() []string
- func (srv *Server) RemovePeer(node *discover.Node)
- func (srv *Server) Self() *discover.Node
- func (srv *Server) SetPushFreq(pushFreq float64)
- func (srv *Server) SetRedialCheckFreq(redialCheckFreq float64)
- func (srv *Server) SetRedialExp(redialExp float64)
- func (srv *Server) SetRedialFreq(redialFreq float64)
- func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node)
- func (srv *Server) Start() (err error)
- func (srv *Server) Stop()
- func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription
- type SqlStrings
- type TCPDialer
- type Td
- type UnixTime
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
ErrPipeClosed is returned from pipe operations after the pipe has been closed.
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.
func MsgPipe ¶
MsgPipe creates a message pipe. Reads on one end are matched with writes on the other. The pipe is full-duplex, both ends implement MsgReadWriter.
Example ¶
rw1, rw2 := MsgPipe() go func() { Send(rw1, 8, [][]byte{{0, 0}}) Send(rw1, 5, [][]byte{{1, 1}}) rw1.Close() }() for { msg, err := rw2.ReadMsg() if err != nil { break } var data [][]byte msg.Decode(&data) fmt.Printf("msg: %d, %x\n", msg.Code, data[0]) }
Output: msg: 8, 0000 msg: 5, 0101
Types ¶
type Config ¶
type Config struct { // MaxDial is the maximum number of concurrently dialing outbound connections. MaxDial int // MaxRedial is the maximum number of concurrently redialing outbound connections. MaxRedial int // NoMaxPeers ignores/overwrites MaxPeers, allowing unlimited number of peer connections. NoMaxPeers bool // Blacklist is the list of IP networks that we should not connect to Blacklist *netutil.Netlist `toml:",omitempty"` // RedialFreq is the frequency of re-dialing static nodes (in seconds). RedialFreq float64 // RedialCheckFreq is the frequency of checking static nodes ready for redial (in seconds). RedialCheckFreq float64 // RedialExp is the maximum number of hours re-dial nodes can remain unresponsive to avoid eviction. RedialExp float64 // PushFreq is the frequency of pushing updates to MySQL database (in seconds). PushFreq float64 // MaxSqlChunk is the maximum number of updates in a single batch insert. MaxSqlChunk int // MaxSqlQueue is the maximum number of updates allowed in queues. When reached, the instance goes through shutdown and all updates are pushed. MaxSqlQueue int // MySQLName is the MySQL node database connection information MySQLName string // BackupSQL makes a backup of the current MySQL db tables. BackupSQL bool // ResetSQL makes a backup of the current MySQL db tables and resets them. // If set true, BackupSQL should be set true as well. ResetSQL bool // 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 // 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"` // NoDiscovery can be used to disable the peer discovery mechanism. // Disabling is useful for protocol debugging (manual topology). NoDiscovery bool // DiscoveryV5 specifies whether the the new topic-discovery based V5 discovery // protocol should be started or not. DiscoveryV5 bool `toml:",omitempty"` // Listener address for the V5 discovery protocol UDP traffic. DiscoveryV5Addr string `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 []*discover.Node // BootstrapNodesV5 are used to establish connectivity // with the rest of the network using the V5 discovery // protocol. BootstrapNodesV5 []*discv5.Node `toml:",omitempty"` // Static nodes are used as pre-configured connections which are always // maintained and re-connected on disconnects. StaticNodes []*discover.Node // Trusted nodes are used as pre-configured connections which are always // allowed to connect, even above the peer limit. TrustedNodes []*discover.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 }
Config holds Server options.
type DiscReason ¶
type DiscReason uint
const ( DiscRequested DiscReason = iota DiscNetworkError DiscProtocolError DiscUselessPeer DiscTooManyPeers 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 Info ¶
type Info struct { sync.RWMutex Keccak256Hash string `json:"keccak256Hash"` // Keccak256 hash of node ID IP string `json:"ip"` // IP address of the node TCPPort uint16 `json:"tcpPort"` // TCP listening port for RLPx RemotePort uint16 `json:"remotePort"` // Remote TCP port of the most recent connection // DEVp2p Hello info P2PVersion uint64 `json:"p2pVersion,omitempty"` // DEVp2p protocol version ClientId string `json:"clientId,omitempty"` // Name of the node, including client type, version, OS, custom data Caps string `json:"caps,omitempty"` // Node's capabilities ListenPort uint16 `json:"listenPort,omitempty"` // Listening port reported in the node's DEVp2p Hello FirstHelloAt *UnixTime `json:"firstHelloAt,omitempty"` // First time the node sent Hello LastHelloAt *UnixTime `json:"lastHelloAt,omitempty"` // Last time the node sent Hello // Ethereum Status info ProtocolVersion uint64 `json:"protocolVersion,omitempty"` // Ethereum sub-protocol version NetworkId uint64 `json:"networkId,omitempty"` // Ethereum network ID FirstReceivedTd *Td `json:"firstReceivedTd,omitempty"` // First reported total difficulty of the node's blockchain LastReceivedTd *Td `json:"lastReceivedTd,omitempty"` // Last reported total difficulty of the node's blockchain BestHash string `json:"bestHash,omitempty"` // Hex string of SHA3 hash of the node's best owned block GenesisHash string `json:"genesisHash,omitempty"` // Hex string of SHA3 hash of the node's genesis block FirstStatusAt *UnixTime `json:"firstStatusAt,omitempty"` // First time the node sent Status LastStatusAt *UnixTime `json:"lastStatusAt,omitempty"` // Last time the node sent Status DAOForkSupport int8 `json:"daoForkSupport,omitempty"` // Whether the node supports or opposes the DAO hard-fork }
Info represents a short summary of the information known about a known node.
func (*Info) MarshalJSON ¶
type KnownNodeInfos ¶
func NewKnownNodeInfos ¶
func NewKnownNodeInfos() *KnownNodeInfos
type Msg ¶
type Msg struct { Code uint64 Size uint32 // size of the paylod Payload io.Reader ReceivedAt time.Time PeerRtt float64 PeerDuration float64 }
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 MsgPipeRW ¶
type MsgPipeRW struct {
// contains filtered or unexported fields
}
MsgPipeRW is an endpoint of a MsgReadWriter pipe.
func (*MsgPipeRW) Close ¶
Close unblocks any pending ReadMsg and WriteMsg calls on both ends of the pipe. They will return ErrPipeClosed. Close also interrupts any reads from a message payload.
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 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 {
// contains filtered or unexported fields
}
Peer represents a connected remote node.
func (*Peer) ConnInfoCtx ¶
func (p *Peer) ConnInfoCtx() []interface{}
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) ListenPort ¶
ListenPort returns the port number that the remote peer advertised.
func (*Peer) RemoteAddr ¶
RemoteAddr returns the remote address of the network connection.
type PeerEvent ¶
type PeerEvent struct { Type PeerEventType `json:"type"` Peer discover.NodeID `json:"peer"` Error string `json:"error,omitempty"` Protocol string `json:"protocol,omitempty"` MsgCode *uint64 `json:"msg_code,omitempty"` MsgSize *uint32 `json:"msg_size,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 { 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 Caps []string `json:"caps"` // Sum-protocols advertised by this particular peer Rtt float64 `json:"rtt"` Duration float64 `json:"duration"` Network struct { LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection } `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 groutine 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 discover.NodeID) interface{} }
Protocol represents a P2P subprotocol implementation.
type Server ¶
type Server struct { NeighborChan chan []interface{} EthInfoChan chan []interface{} KnownNodeInfos *KnownNodeInfos // information on known nodes StrReplacer *strings.Replacer // Config fields may not be modified while the server is running. Config DiscV5 *discv5.Network // contains filtered or unexported fields }
Server manages all peer connections.
func (*Server) AddBlacklist ¶
func (*Server) AddPeer ¶
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) NodeInfo ¶
NodeInfo gathers and returns a collection of metadata known about the host.
func (*Server) PeersInfo ¶
PeersInfo returns an array of metadata objects describing connected peers.
func (*Server) RedialList ¶
func (*Server) RemovePeer ¶
RemovePeer disconnects from the given node
func (*Server) SetPushFreq ¶
func (*Server) SetRedialCheckFreq ¶
func (*Server) SetRedialExp ¶
func (*Server) SetRedialFreq ¶
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
SubscribePeers subscribes the given channel to peer events
type SqlStrings ¶
type TCPDialer ¶
TCPDialer implements the NodeDialer interface by using a net.Dialer to create TCP connections to nodes in the network
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package discover implements the Node Discovery Protocol.
|
Package discover implements the Node Discovery Protocol. |
Package discv5 implements the RLPx v5 Topic Discovery Protocol.
|
Package discv5 implements the RLPx v5 Topic Discovery Protocol. |
Package nat provides access to common network port mapping protocols.
|
Package nat provides access to common network port mapping protocols. |
Package netutil contains extensions to the net package.
|
Package netutil contains extensions to the net package. |