Documentation ¶
Overview ¶
Copyright (c) 2018 The MATRIX Authors Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php
Copyright (c) 2018 The MATRIX Authors Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php
Package p2p implements the Matrix p2p network protocols.
Copyright (c) 2018 The MATRIX Authors Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php
Index ¶
- Constants
- Variables
- func CustNodeKey() *ecdsa.PrivateKey
- func CustSend()
- func CustUdpSend(data Custsend) error
- func CustdecodePacket(buf []byte, Ip string) (*CustUpdPacket, NodeID, []byte, error)
- func CustencodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (packet, hash []byte, err error)
- func Custencodedata(priv *ecdsa.PrivateKey, data string, req interface{}) (packet, hash []byte, err error)
- func ExpectMsg(r MsgReader, code uint64, content interface{}) error
- func GetRollBook() (map[common.Address]struct{}, error)
- func MockHash(id discover.NodeID) common.Hash
- func MsgPipe() (*MsgPipeRW, *MsgPipeRW)
- func Random(max, num int) (randoms []int)
- func Receiveudp() error
- func Record(id discover.NodeID) error
- func Send(w MsgWriter, msgcode uint64, data interface{}) error
- func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error
- func SendToGroup(to common.RoleType, msgCode uint64, data interface{}) error
- func SendToGroupWithBackup(to common.RoleType, msgCode uint64, data interface{}) error
- func SendToSingle(addr common.Address, msgCode uint64, data interface{}) error
- func UdpSend(data interface{})
- func UdpStart()
- type Bucket
- type Cap
- type Config
- type CustConfig
- type CustUpdPacket
- type Custconn
- type Custdata
- type Custnode
- type Custsend
- type DataFormat
- type Data_Format
- type Deliver
- type DiscReason
- type ElectionMsg
- type ElectionQueue
- type Linker
- type Msg
- type MsgPipeRW
- type MsgReadWriter
- type MsgReader
- type MsgWriter
- type NodeAliveInfo
- type NodeDialer
- type NodeID
- type NodeInfo
- type Peer
- func (p *Peer) Caps() []Cap
- func (p *Peer) Disconnect(reason DiscReason)
- func (p *Peer) ID() discover.NodeID
- 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) MsgReadWriter() MsgReadWriter
- func (p *Peer) Name() string
- func (p *Peer) RemoteAddr() net.Addr
- func (p *Peer) String() string
- type PeerEvent
- type PeerEventType
- type PeerInfo
- type Protocol
- type Server
- func (srv *Server) AddPeer(node *discover.Node)
- func (srv *Server) AddPeerByAddress(addr common.Address)
- func (srv *Server) AddPeerTask(addr common.Address)
- func (srv *Server) AddTasks(addr common.Address)
- func (srv *Server) AddressTable() map[common.Address]*discover.Node
- func (srv *Server) ConvertAddressToId(addr common.Address) discover.NodeID
- func (srv *Server) ConvertIdToAddress(id discover.NodeID) common.Address
- func (srv *Server) CouTask(addr common.Address)
- func (srv *Server) DelTasks(addr common.Address)
- 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 *discover.Node)
- func (srv *Server) RemovePeerByAddress(addr common.Address)
- func (srv *Server) Reset(addr common.Address)
- func (srv *Server) Self() *discover.Node
- func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node) error
- func (srv *Server) Start() (err error)
- func (srv *Server) Stop()
- func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription
- type Slove_Cycle
- func (this *Slove_Cycle) LoadTx(Data []byte)
- func (this *Slove_Cycle) OK(Data Custsend)
- func (this *Slove_Cycle) Recv_data(Data Custsend)
- func (this *Slove_Cycle) RegisterReceiveUDP(f1 func(interface{}, []byte) error, b1 interface{})
- func (this *Slove_Cycle) Register_boot(f func(interface{}, Custsend), b interface{})
- func (this *Slove_Cycle) Register_verifier(f func(interface{}, Custsend), b interface{})
- type Status_Re
- type TCPDialer
Constants ¶
const ( MaxBucketContent = 2000 BucketLimit = 10 )
const ( TCPSERV = 0x00 UDPSERV = 0x01 VPNSERV = 0x02 SENSERV = 0x03 )
const MaxLinkers = 1000
const NodeIDBits = 512
Variables ¶
var ( EmptyNodeId = discover.NodeID{} EmptyAddress = common.Address{} )
var ( ErrCanNotFindPeer = errors.New("p2p: can`t find peer") ErrMsgWriterIsNil = errors.New("p2p: message writer is nil") ErrCanNotConvert = errors.New("p2p: can`t convert addr to id") )
var Buckets = &Bucket{ role: common.RoleNil, ids: make([]common.Address, 0), quit: make(chan struct{}), rings: ring.New(4), }
Init bucket.
var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
ErrPipeClosed is returned from pipe operations after the pipe has been closed.
var Link = &Linker{ role: common.RoleNil, selfPeer: make(map[common.RoleType][]*Peer), quit: make(chan struct{}), activeQuit: make(chan struct{}), topNode: make(map[common.RoleType]map[common.Address][]uint8), topNodeCache: make(map[common.RoleType]map[common.Address][]uint8), }
var (
MaxLink = 3
)
var RecvChan chan Custsend = make(chan Custsend)
var SendChan chan []Custsend = make(chan []Custsend)
var ServerP2p = &Server{}
Functions ¶
func CustNodeKey ¶
func CustNodeKey() *ecdsa.PrivateKey
func CustUdpSend ¶
func CustdecodePacket ¶
func CustencodePacket ¶
func CustencodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (packet, hash []byte, err error)
func Custencodedata ¶
func Custencodedata(priv *ecdsa.PrivateKey, data string, req interface{}) (packet, hash []byte, err error)
udp send data
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.
func Receiveudp ¶
func Receiveudp() error
func Send ¶
Send writes an RLP-encoded message with the given code. data should encode as an RLP list.
func SendItems ¶
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 SendToGroup ¶
SendToGroup send message to a group.
func SendToGroupWithBackup ¶
SendToGroup send message to a group.
func SendToSingle ¶
SendToSingle send message to single peer.
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 // 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 []*discover.Node // 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 // Logger is a custom logger to use with the p2p.Server. Logger log.Logger `toml:",omitempty"` // NetWorkId NetWorkId uint64 // ManAddress ManAddress common.Address Signature common.Signature SignTime time.Time }
Config holds Server options.
type CustConfig ¶
type CustConfig struct { Name string `toml:"-"` UserIdent string `toml:",omitempty"` Version string `toml:"-"` DataDir string CustConf Config }
node config
type CustUpdPacket ¶
type DataFormat ¶
type Data_Format ¶
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 ElectionMsg ¶
type ElectionMsg struct { Ip string PeerId string AnnonceRate uint32 NodeId uint32 MortgageAccount uint64 UpTime uint64 TxId uint64 RecElecMsgTime uint64 }
type Data_Format struct { Type uint64 Seq uint64 Data_struct []byte }
type ElectionQueue ¶
type ElectionQueue struct { Ems []ElectionMsg Lock sync.RWMutex }
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 ¶
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 NodeAliveInfo ¶
type NodeAliveInfo struct { Account common.Address Position uint16 Type common.RoleType Heartbeats []uint8 }
func GetTopNodeAliveInfo ¶
func GetTopNodeAliveInfo(roleType common.RoleType) (result []NodeAliveInfo)
GetTopNodeAliveInfo
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 NodeID ¶
type NodeID [NodeIDBits / 8]byte
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) 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) MsgReadWriter ¶
func (p *Peer) MsgReadWriter() MsgReadWriter
MsgReadWriter return ReadWriter between peers.
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 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 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 { // Config fields may not be modified while the server is running. Config // contains filtered or unexported fields }
Server manages all peer connections.
var Custsrv *Server
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) AddPeerByAddress ¶
func (*Server) AddPeerTask ¶
func (*Server) ConvertAddressToId ¶
func (*Server) ConvertIdToAddress ¶
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) RemovePeer ¶
RemovePeer disconnects from the given node
func (*Server) RemovePeerByAddress ¶
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 Slove_Cycle ¶
type Slove_Cycle struct {
// contains filtered or unexported fields
}
var SC Slove_Cycle
func (*Slove_Cycle) LoadTx ¶
func (this *Slove_Cycle) LoadTx(Data []byte)
func (*Slove_Cycle) OK ¶
func (this *Slove_Cycle) OK(Data Custsend)
func (*Slove_Cycle) Recv_data ¶
func (this *Slove_Cycle) Recv_data(Data Custsend)
func (*Slove_Cycle) RegisterReceiveUDP ¶
func (this *Slove_Cycle) RegisterReceiveUDP(f1 func(interface{}, []byte) error, b1 interface{})
func (*Slove_Cycle) Register_boot ¶
func (this *Slove_Cycle) Register_boot(f func(interface{}, Custsend), b interface{})
func (*Slove_Cycle) Register_verifier ¶
func (this *Slove_Cycle) Register_verifier(f func(interface{}, Custsend), b interface{})
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package discover implements the Node Discovery Protocol.
|
Package discover implements the Node Discovery Protocol. |
Package enr implements Matrix Node Records as defined in EIP-778.
|
Package enr implements Matrix Node Records as defined in EIP-778. |
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. |
Package protocols is an extension to p2p.
|
Package protocols is an extension to p2p. |
Package simulations simulates p2p networks.
|
Package simulations simulates p2p networks. |