p2p

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2021 License: LGPL-3.0 Imports: 54 Imported by: 0

Documentation

Overview

Package p2p implements the Ethereum p2p network protocols.

Index

Constants

View Source
const (
	MetricsInboundTraffic          = "p2p_InboundTraffic"
	MetricsOutboundTraffic         = "p2p_OutboundTraffic"
	MetricsSendMsgQPS              = "p2p_SendMsgQPS"
	MetricsSendMsgQPSFailure       = "p2p_SendMsgQPSFailure"
	HistogramsAPIUsingTimes        = "p2p_APIUsingTimes"
	HistogramsAPIUsingFailureTimes = "p2p_APIUsingTimesFailure"
	HistogramsHandleUsingTimes     = "p2p_HandleUsingTimes"

	HistogramsPMHandleMsgUsingTimes   = "pm_HandleMsgUsingTimes"
	HistogramsBCInsertBlcokUsingTimes = "bc_InsertBlocksUsingTimes"
)
View Source
const DefaultMaxPeers = 50
View Source
const NodeIDBits = 512

Variables

View Source
var DefaultConfig = &Config{
	ListenAddr:      fmt.Sprintf(":%d", params.DefaultP2PListenPort),
	DiscoverAddr:    fmt.Sprintf(":%d", params.DefaultP2PDiscoverPort),
	MaxPeers:        DefaultMaxPeers,
	NAT:             nat.Any(),
	NodeType:        params.FullNode,
	EnableMsgEvents: false,
}
View Source
var (
	ErrPeerIsNotConnected = errors.New("peer is not connected")
)

Error types

View Source
var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")

ErrPipeClosed is returned from pipe operations after the pipe has been closed.

View Source
var (
	ErrShuttingDown = errors.New("shutting down")
)

Functions

func AddPeerToBlacklist

func AddPeerToBlacklist(blacklist *Blacklist, peer *Peer) error

func CheckAddrInBlacklist

func CheckAddrInBlacklist(bl *Blacklist, addr net.Addr) bool

func ClearBlacklistDB

func ClearBlacklistDB(blacklist *Blacklist)

func Encode

func Encode(msg Msg) ([]byte, error)

func ExpectMsg

func ExpectMsg(r MsgReader, code uint64, content interface{}) error

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 MessageCacheInstance

func MessageCacheInstance() *messageCache

func MsgPipe

func MsgPipe() (*MsgPipeRW, *MsgPipeRW)

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.

func OpenDB

func OpenDB(path string) (*blacklistDB, error)

open blacklist database for storing blacklist infos If no path is given an in-memory, temporary database is constructed

func PrintInfo

func PrintInfo(r metrics.Registry, freq time.Duration)

func PrintInfo2

func PrintInfo2(freq time.Duration)

func PublicBCInsertBlockUsingTime

func PublicBCInsertBlockUsingTime(start time.Time)

func PublicPMHandleMsgUsingTime

func PublicPMHandleMsgUsingTime(start time.Time)

func RegisterFilterCode

func RegisterFilterCode(code uint64)

func RemoveAddrFromBlacklist

func RemoveAddrFromBlacklist(blacklist *Blacklist, addr net.Addr) bool

func RemoveFromBlacklist

func RemoveFromBlacklist(blacklist *Blacklist, ip string, rudpPort int) bool

func Send

func Send(w MsgWriter, msgcode uint64, data interface{}) error

Send writes an RLP-encoded message with the given code. data should encode as an RLP list.

func SendItems

func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error

SendItems writes an RLP with the given code and data elements. For a call such as:

SendItems(w, code, e1, e2, e3)

the message payload will be an RLP list containing the items:

[e1, e2, e3]

func UnregisterFilterCode

func UnregisterFilterCode(code uint64)

Types

type Blacklist

type Blacklist struct {
	Version uint64

	sync.RWMutex
	sync.WaitGroup
	// contains filtered or unexported fields
}

func NewBlacklist

func NewBlacklist(dbPath string) (*Blacklist, error)

func (*Blacklist) Check

func (bl *Blacklist) Check(hash common.Hash) (bool, error)

func (*Blacklist) Close

func (bl *Blacklist) Close() (err error)

func (*Blacklist) Start

func (bl *Blacklist) Start()

type BlacklistEvent

type BlacklistEvent struct {
	Type       BlacklistEventType
	Enode      *enode.Node
	Hash       common.Hash
	ReceivedAt time.Time
}

type BlacklistEventType

type BlacklistEventType string
const (
	BlacklistEventAddPeer    BlacklistEventType = "add"
	BlacklistEventRemovePeer BlacklistEventType = "remove"
	BlacklistEventClearDB    BlacklistEventType = "clearDB"
)

type BlacklistItem

type BlacklistItem struct {
	IP         string    `json:"ip"`
	RUDP       int       `json:"port"`
	Enode      string    `json:"enode"`
	ReceivedAt time.Time `json:"time"`
}

func GetBlacklist

func GetBlacklist(blacklist *Blacklist) []BlacklistItem

type Cap

type Cap struct {
	Name    string
	Version uint
}

Cap is the structure of a peer capability.

func (Cap) String

func (cap Cap) String() string

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

	// 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

	// 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

	// 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"`

	// Blacklist database path
	BlacklistDatabase 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
	DiscoverAddr 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 //todo remove this

	//node type in config
	NodeType params.NodeType

	//nat type
	NatType enode.NATType

	// The name of the protocol supported by TLS
	ProtocolName string

	// local area network
	LocalNet bool
}

Config holds Server options.

func NewDefaultConfig

func NewDefaultConfig() Config

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 Msg

type Msg struct {
	Code       uint64
	Size       uint32 // size of the paylod
	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 Decode

func Decode(rw io.Reader) (msg Msg, err error)

func (Msg) Decode

func (msg Msg) Decode(val interface{}) error

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.

func (Msg) Discard

func (msg Msg) Discard() error

Discard reads any remaining payload data into a black hole.

func (*Msg) Hash

func (msg *Msg) Hash() common.Hash

Hash = Code + Payload

func (Msg) String

func (msg Msg) String() string

type MsgPipeRW

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

MsgPipeRW is an endpoint of a MsgReadWriter pipe.

func (*MsgPipeRW) Addr

func (p *MsgPipeRW) Addr() common.Address

func (*MsgPipeRW) AsynWriteMsg

func (p *MsgPipeRW) AsynWriteMsg(msg Msg) error

func (*MsgPipeRW) Close

func (p *MsgPipeRW) Close() error

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.

func (*MsgPipeRW) ReadMsg

func (p *MsgPipeRW) ReadMsg() (Msg, error)

ReadMsg returns a message sent on the other end of the pipe.

func (*MsgPipeRW) WriteMsg

func (p *MsgPipeRW) WriteMsg(msg Msg) error

WriteMsg sends a messsage on the pipe. It blocks until the receiver has consumed the message payload.

type MsgReadWriter

type MsgReadWriter interface {
	MsgReader
	MsgWriter
}

MsgReadWriter provides reading and writing of encoded messages. Implementations should ensure that ReadMsg and WriteMsg can be called simultaneously from multiple goroutines.

type MsgReader

type MsgReader interface {
	ReadMsg() (Msg, error)
}

type MsgWriter

type MsgWriter interface {
	// WriteMsg sends a message. It will block until the message's
	// Payload has been consumed by the other end.
	//
	// Note that messages can be sent only once because their
	// payload reader is drained.
	WriteMsg(Msg) error
	Addr() common.Address
}

type NodeDialer

type NodeDialer interface {
	Dial(*enode.Node) (quic.Session, error)
}

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 NodeID

type NodeID [NodeIDBits / 8]byte

NodeID is a unique identifier for each node. The node identifier is a marshaled elliptic curve public key.

func BytesID

func BytesID(b []byte) (NodeID, error)

BytesID converts a byte slice to a NodeID

func HexID

func HexID(in string) (NodeID, error)

HexID converts a hex string to a NodeID. The string may be prefixed with 0x.

func MustBytesID

func MustBytesID(b []byte) NodeID

MustBytesID converts a byte slice to a NodeID. It panics if the byte slice is not a valid NodeID.

func MustHexID

func MustHexID(in string) NodeID

MustHexID converts a hex string to a NodeID. It panics if the string is not a valid NodeID.

func PubkeyID

func PubkeyID(pub *ecdsa.PublicKey) NodeID

PubkeyID returns a marshaled representation of the given public key.

func (NodeID) Bytes

func (id NodeID) Bytes() []byte

Bytes returns a byte slice representation of the NodeID

func (NodeID) GoString

func (n NodeID) GoString() string

The Go syntax representation of a NodeID is a call to HexID.

func (NodeID) MarshalText

func (n NodeID) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (NodeID) Pubkey

func (id NodeID) Pubkey() (*ecdsa.PublicKey, error)

Pubkey returns the public key represented by the node ID. It returns an error if the ID is not a point on the curve.

func (NodeID) String

func (n NodeID) String() string

NodeID prints as a long hexadecimal number.

func (NodeID) TerminalString

func (n NodeID) TerminalString() string

TerminalString returns a shortened hex string for terminal logging.

func (*NodeID) UnmarshalText

func (n *NodeID) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

type NodeIP

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

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 NodeStatus

type NodeStatus struct {
	NodeIp *NodeIP // net.IPNet相关的
	ID     []byte  // 64位,IP+子网掩码,确定主机位于哪个子网,未来分片用
	Config *Config // 相关的配置
	Hosts  []multiaddr.Multiaddr
}

type Peer

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

Peer represents a connected remote node.

func NewPeer

func NewPeer(id enode.ID, name string, caps []Cap, nodetype uint16) *Peer

NewPeer returns a peer for testing purposes.

func (*Peer) Caps

func (p *Peer) Caps() []Cap

Caps returns the capabilities (supported subprotocols) of the remote peer.

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

func (p *Peer) ID() enode.ID

ID returns the node's public key.

func (*Peer) Inbound

func (p *Peer) Inbound() bool

Inbound returns true if the peer is an inbound connection

func (*Peer) Info

func (p *Peer) Info() *PeerInfo

Info gathers and returns a collection of metadata known about a peer.

func (*Peer) IsTrusted added in v1.0.0

func (p *Peer) IsTrusted() bool

IsTrusted returns true if the peer is a trusted connection.

func (*Peer) LocalAddr

func (p *Peer) LocalAddr() net.Addr

LocalAddr returns the local address of the network connection.

func (*Peer) Log

func (p *Peer) Log() logging.Logger

func (*Peer) Name

func (p *Peer) Name() string

Name returns the node name that the remote node advertised.

func (*Peer) Node

func (p *Peer) Node() *enode.Node

Node returns the peer's node descriptor.

func (*Peer) RemoteAddr

func (p *Peer) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the network connection.

func (*Peer) String

func (p *Peer) String() string

String implements fmt.Stringer.

type PeerEvent

type PeerEvent struct {
	Type     PeerEventType `json:"type"`
	Peer     enode.ID      `json:"peer"`
	IP       string        `json:"ip"`
	Enode    string        `son:"Enode"`
	Error    string        `json:"error,omitempty"`
	Protocol string        `json:"protocol,omitempty"`
	MsgCode  *uint64       `json:"msg_code,omitempty"`
	MsgSize  *uint32       `json:"msg_size,omitempty"`
	Count    int           `json:"number,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"

	PeerEventTypeReadChanCount PeerEventType = "chanCount"
)

type PeerInfo

type PeerInfo struct {
	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
	Nat      string   `json:"nat"`
	NodeType string   `json:"nodeType"`
	Caps     []string `json:"caps"` // Protocols advertised by this 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{}

	// Attributes contains protocol specific information for the node record.
	Attributes []enr.Entry
}

Protocol represents a P2P subprotocol implementation.

type RUDPDialer

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

TCPDialer implements the NodeDialer interface by using a net.Dialer to create TCP connections to nodes in the network

func (RUDPDialer) Dial

func (t RUDPDialer) Dial(dest *enode.Node) (quic.Session, error)

Dial creates a TCP connection to the node

type Server

type Server struct {
	// Config fields may not be modified while the server is running.
	Config
	// contains filtered or unexported fields
}

Server manages all peer connections.

func (*Server) AddPeer

func (srv *Server) AddPeer(node *enode.Node)

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

func (srv *Server) AddPeerToBlacklist(peer *Peer) error

func (*Server) AddTrustedPeer

func (srv *Server) AddTrustedPeer(node *enode.Node)

AddTrustedPeer adds the given node to a reserved whitelist which allows the node to always connect, even if the slot are full.

func (*Server) ClearBlacklistDB

func (srv *Server) ClearBlacklistDB()

func (*Server) GetBlacklist

func (srv *Server) GetBlacklist() []BlacklistItem

func (*Server) GetLocalIPs

func (srv *Server) GetLocalIPs() []*net.IPNet

func (*Server) NodeInfo

func (srv *Server) NodeInfo() *NodeInfo

NodeInfo gathers and returns a collection of metadata known about the host.

func (*Server) PeerCount

func (srv *Server) PeerCount() int

PeerCount returns the number of connected peers.

func (*Server) Peers

func (srv *Server) Peers() []*Peer

Peers returns all connected peers.

func (*Server) PeersInfo

func (srv *Server) PeersInfo() []*PeerInfo

PeersInfo returns an array of metadata objects describing connected peers.

func (*Server) RemovePeer

func (srv *Server) RemovePeer(node *enode.Node)

RemovePeer disconnects from the given node

func (*Server) RemovePeerFromBlacklist

func (srv *Server) RemovePeerFromBlacklist(ip string, rudpPort int) bool

func (*Server) RemoveTrustedPeer

func (srv *Server) RemoveTrustedPeer(node *enode.Node)

RemoveTrustedPeer removes the given node from the trusted peer set.

func (*Server) Self

func (srv *Server) Self() *enode.Node

Self returns the local node's endpoint information.

func (*Server) SetupConn

func (srv *Server) SetupConn(session quic.Session, flags connFlag, dialDest *enode.Node) error

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

func (srv *Server) Start() (err error)

Start starts running the server. Servers can not be re-used after stopping.

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

Directories

Path Synopsis
Package discover implements the Node Discovery Protocol.
Package discover implements the Node Discovery Protocol.
Package enr implements Ethereum Node Records as defined in EIP-778.
Package enr implements Ethereum Node Records as defined in EIP-778.
nat
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.

Jump to

Keyboard shortcuts

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