p2p

package
v0.0.0-...-dee6c83 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2021 License: GPL-3.0, LGPL-3.0 Imports: 36 Imported by: 0

Documentation

Overview

Package p2p implements the Shx p2p network protocols.

Index

Constants

View Source
const (
	StatusMsg         uint64 = 0x1010
	ExchangeMsg       uint64 = 0x1011
	ReqNodesMsg       uint64 = 0x1020
	ResNodesMsg       uint64 = 0x1021
	ReqRemoteStateMsg uint64 = 0x1040
	ResRemoteStateMsg uint64 = 0x1041

	NewBlockHashesMsg  uint64 = 0x2012
	TxMsg              uint64 = 0x2013
	GetBlockHeadersMsg uint64 = 0x2014
	BlockHeadersMsg    uint64 = 0x2015
	GetBlockBodiesMsg  uint64 = 0x2016
	BlockBodiesMsg     uint64 = 0x2017
	NewBlockMsg        uint64 = 0x2018
	GetNodeDataMsg     uint64 = 0x2019
	NodeDataMsg        uint64 = 0x201a
	GetReceiptsMsg     uint64 = 0x201b
	ReceiptsMsg        uint64 = 0x201c

	NewHashBlockMsg uint64 = 0x2020
	WorkProofMsg    uint64 = 0x2022
	ProofConfirmMsg uint64 = 0x2024
	GetStateMsg     uint64 = 0x2025
	ResStateMsg     uint64 = 0x2026
)

message of shx protocol

View Source
const (
	PeerEventAdd     event.EventType = 0x01
	PeerEventDrop    event.EventType = 0x02
	PeerEventMsgSend event.EventType = 0x03
	PeerEventMsgRecv event.EventType = 0x04
)
View Source
const (
	ErrMsgTooLarge = iota
	ErrDecode
	ErrProtocolVersionMismatch
	ErrNetworkIdMismatch
	ErrGenesisBlockMismatch
	ErrNoStatusMsg
	ErrNoExchangeMsg
)
View Source
const (
	MaxMsgSize = 50 * 1024 * 1024
)
View Source
const ProtoName = "hpb"
View Source
const ProtoVersion100 uint = 100
View Source
const RandNonceSize = 32

Variables

View Source
var INSTANCE = atomic.Value{}
View Source
var ProtocolVersions = []uint{ProtoVersion100}

Functions

func ErrResp

func ErrResp(code errCode, format string, v ...interface{}) 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 HandleReqNodesMsg

func HandleReqNodesMsg(p *Peer, msg Msg) error

func HandleReqRemoteStateMsg

func HandleReqRemoteStateMsg(p *Peer, msg Msg) error

func HandleResNodesMsg

func HandleResNodesMsg(p *Peer, msg Msg) error

func HandleResRemoteStateMsg

func HandleResRemoteStateMsg(p *Peer, msg Msg) error

func SendData

func SendData(p *Peer, msgCode uint64, data interface{}) error

Types

type Cap

type Cap struct {
	Name    string
	Version uint
}

func (Cap) String

func (cap Cap) String() string

type ChanStatusCB

type ChanStatusCB func() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash)

type Config

type Config struct {
	PrivateKey     *ecdsa.PrivateKey `toml:"-"`
	Name           string            `toml:"-"`
	BootstrapNodes []*discover.Node
	StaticNodes    []*discover.Node
	NetRestrict    *netutil.Netlist `toml:",omitempty"`
	NodeDatabase   string           `toml:",omitempty"`
	Protocols      []Protocol       `toml:"-"`
	ListenAddr     string
	NAT            nat.Interface `toml:",omitempty"`

	EnableMsgEvents bool
	NetworkId       uint64
	CoinBase        common.Address
}

Config holds Server options.

type DiscReason

type DiscReason uint
const (
	DiscRequested DiscReason = iota
	DiscNetworkError
	DiscProtocolError
	DiscUselessPeer
	DiscPeerBySyn
	DiscAlreadyConnected
	DiscIncompatibleVersion
	DiscInvalidIdentity
	DiscQuitting
	DiscUnexpectedIdentity
	DiscSelf
	DiscReadTimeout
	DiscUnknownNode
	DiscUnexpectedConnected
	DiscHwSignError
	DiscSubprotocolError = 0x10
)

func (DiscReason) Error

func (d DiscReason) Error() string

func (DiscReason) String

func (d DiscReason) String() string

type ModuleType

type ModuleType uint

type Msg

type Msg struct {
	Code       uint64
	Size       uint32 // size of the paylod
	Payload    io.Reader
	ReceivedAt time.Time
}

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

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

func (msg Msg) String() string

type MsgProcessCB

type MsgProcessCB func(p *Peer, msg Msg) error

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
}

type NodeDialer

type NodeDialer interface {
	Dial(*discover.Node) (net.Conn, 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 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
	Local string `json:"local"` // Local node type
	IP    string `json:"ip"`    // IP address of the node
	Ports struct {
		UDP int `json:"udp"` // UDP listening port for discovery protocol
		TCP int `json:"tcp"` // TCP listening port for RLPx
	} `json:"ports"`
	ListenAddr string `json:"listenAddr"`
}

type OnAddPeerCB

type OnAddPeerCB func(p *Peer) error

type OnDropPeerCB

type OnDropPeerCB func(p *Peer) error

type Peer

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

func NewPeer

func NewPeer(version uint, pr *PeerBase, rw MsgReadWriter) *Peer

func (*Peer) Exchange

func (p *Peer) Exchange(our *exchangeData) (*exchangeData, error)

func (*Peer) GetID

func (p *Peer) GetID() string

func (*Peer) GetVersion

func (p *Peer) GetVersion() uint

func (*Peer) Handshake

func (p *Peer) Handshake(network uint64, td *big.Int, head common.Hash, genesis common.Hash) error

Handshake executes the eth protocol handshake, negotiating version number, network IDs, difficulties, head and genesis blocks.

func (*Peer) Head

func (p *Peer) Head() (hash common.Hash, td *big.Int)

Head retrieves a copy of the current head hash and total difficulty of the peer.

func (*Peer) KnownBlockAdd

func (p *Peer) KnownBlockAdd(hash common.Hash)

func (*Peer) KnownBlockHas

func (p *Peer) KnownBlockHas(hash common.Hash) bool

func (*Peer) KnownBlockSize

func (p *Peer) KnownBlockSize() int

func (*Peer) KnownTxsAdd

func (p *Peer) KnownTxsAdd(hash common.Hash)

func (*Peer) KnownTxsHas

func (p *Peer) KnownTxsHas(hash common.Hash) bool

func (*Peer) KnownTxsSize

func (p *Peer) KnownTxsSize() int

func (*Peer) SetHead

func (p *Peer) SetHead(hash common.Hash, td *big.Int)

SetHead updates the head hash and total difficulty of the peer.

func (*Peer) String

func (p *Peer) String() string

String implements fmt.Stringer.

type PeerBase

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

Peer represents a connected remote node.

func (*PeerBase) Address

func (p *PeerBase) Address() common.Address

func (*PeerBase) Caps

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

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

func (*PeerBase) Disconnect

func (p *PeerBase) 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 (*PeerBase) ID

func (p *PeerBase) ID() discover.NodeID

ID returns the node's public key.

func (*PeerBase) LocalAddr

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

LocalAddr returns the local address of the network connection.

func (*PeerBase) LocalType

func (p *PeerBase) LocalType() discover.NodeType

LocalType returns the local type of the node.

func (*PeerBase) Name

func (p *PeerBase) Name() string

Name returns the node name that the remote node advertised.

func (*PeerBase) RemoteAddr

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

RemoteAddr returns the remote address of the network connection.

func (*PeerBase) RemoteIP

func (p *PeerBase) RemoteIP() string

func (*PeerBase) RemoteIperfPort

func (p *PeerBase) RemoteIperfPort() int

func (*PeerBase) RemoteListenPort

func (p *PeerBase) RemoteListenPort() int

func (*PeerBase) RemoteType

func (p *PeerBase) RemoteType() discover.NodeType

RemoteType returns the remote type of the node.

func (*PeerBase) SetRemoteType

func (p *PeerBase) SetRemoteType(nt discover.NodeType) bool

func (*PeerBase) String

func (p *PeerBase) String() string

String implements fmt.Stringer.

func (*PeerBase) Version

func (p *PeerBase) Version() string

type PeerEvent

type PeerEvent struct {
	Type     event.EventType `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"`
}

type PeerEventType

type PeerEventType string

PeerEventType is the type of peer events emitted by a p2p.Server

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
	Version  string `json:"version"`  // Gshx version
	Remote   string `json:"remote"`   // Remote node type
	CoinBase string `json:"coinbase"` //Remote Node's CoinBase
	Cap      string `json:"cap"`      // Sum-protocols advertised by this particular peer
	Network  struct {
		Local  string `json:"local"`  // Local endpoint of the TCP data connection
		Remote string `json:"remote"` // Remote endpoint of the TCP data connection
	} `json:"network"`
	Start  string      `json:"start"`  //
	Beat   string      `json:"beat"`   //
	Mining string      `json:"mining"` //
	SHX    interface{} `json:"shx"`    // Sub-protocol specific metadata fields
}

type PeerManager

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

func PeerMgrInst

func PeerMgrInst() *PeerManager

func (*PeerManager) BestPeer

func (prm *PeerManager) BestPeer() *Peer

BestPeer retrieves the known peer with the currently highest total difficulty.

func (*PeerManager) DefaultAddr

func (prm *PeerManager) DefaultAddr() common.Address

func (*PeerManager) GetLocalType

func (prm *PeerManager) GetLocalType() discover.NodeType

func (*PeerManager) Len

func (prm *PeerManager) Len() int

Len returns if the current number of peers in the set.

func (*PeerManager) NodeInfo

func (prm *PeerManager) NodeInfo() *NodeInfo

func (*PeerManager) P2pSvr

func (prm *PeerManager) P2pSvr() *Server

func (*PeerManager) Peer

func (prm *PeerManager) Peer(id string) *Peer

Peer retrieves the registered peer with the given id.

func (*PeerManager) PeerWithAddr

func (prm *PeerManager) PeerWithAddr(addr common.Address) *Peer

func (*PeerManager) PeersAll

func (prm *PeerManager) PeersAll() []*Peer

func (*PeerManager) PeersInfo

func (prm *PeerManager) PeersInfo() []*PeerInfo

func (*PeerManager) PeersWithoutBlock

func (prm *PeerManager) PeersWithoutBlock(hash common.Hash) []*Peer

PeersWithoutBlock retrieves a list of peers that do not have a given block in their set of known hashes.

func (*PeerManager) PeersWithoutTx

func (prm *PeerManager) PeersWithoutTx(hash common.Hash) []*Peer

PeersWithoutTx retrieves a list of peers that do not have a given transaction in their set of known hashes.

func (*PeerManager) Protocol

func (prm *PeerManager) Protocol() []Protocol

func (*PeerManager) RegChanStatus

func (prm *PeerManager) RegChanStatus(cb ChanStatusCB)

func (*PeerManager) RegMsgProcess

func (prm *PeerManager) RegMsgProcess(msg uint64, cb MsgProcessCB)

//////////////////////////////////////////////////////////////////

func (*PeerManager) RegOnAddPeer

func (prm *PeerManager) RegOnAddPeer(cb OnAddPeerCB)

func (*PeerManager) RegOnDropPeer

func (prm *PeerManager) RegOnDropPeer(cb OnDropPeerCB)

func (*PeerManager) RegStatMining

func (prm *PeerManager) RegStatMining(cb StatMining)

func (*PeerManager) Register

func (prm *PeerManager) Register(p *Peer) error

Register injects a new peer into the working set, or returns an error if the peer is already known.

func (*PeerManager) SetLocalType

func (prm *PeerManager) SetLocalType(nt discover.NodeType) bool

func (*PeerManager) Start

func (prm *PeerManager) Start(coinbase common.Address) error

func (*PeerManager) Stop

func (prm *PeerManager) Stop()

type Protocol

type Protocol struct {
	Name    string
	Version uint
	Run     func(p *PeerBase, rw MsgReadWriter) error
}

Protocol represents a P2P subprotocol implementation.

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 *discover.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) PeerCount

func (srv *Server) PeerCount() int

PeerCount returns the number of connected peers.

func (*Server) Peers

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

Peers returns all connected peers.

func (*Server) RemovePeer

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

RemovePeer disconnects from the given node

func (*Server) Self

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

Self returns the local node's endpoint information.

func (*Server) SetupConn

func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node)

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(et event.EventType) event.Subscriber

SubscribePeers subscribes the given channel to peer events

type ShxInfo

type ShxInfo struct {
	TD   *big.Int `json:"handshakeTD"` // Total difficulty of the peer's blockchain
	Head string   `json:"handshakeHD"` // SHA3 hash of the peer's best owned block
}

type ShxProto

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

//////////////////////////////////////////////////////

func NewProtos

func NewProtos() *ShxProto

func (*ShxProto) Protocols

func (s *ShxProto) Protocols() []Protocol

type StatDetail

type StatDetail struct {
	ID     uint
	Detail string
}

//////////////////////////////////////////////////////

type StatMining

type StatMining func() bool

type TCPDialer

type TCPDialer struct {
	*net.Dialer
}

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

func (TCPDialer) Dial

func (t TCPDialer) Dial(dest *discover.Node) (net.Conn, error)

Dial creates a TCP connection to the node

Directories

Path Synopsis
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