Documentation
¶
Overview ¶
Package p2p implement the core spacemesh p2p protocol and provide types for higher-level protcols such as handshake. See Ping for an example higher-level protocol
Index ¶
- Constants
- func CheckNodeVersion(reqVersion string, minVersion string) (bool, error)
- func GenerateRandomNodeData() node.RemoteNodeData
- func GenerateRandomNodesData(n int) []node.RemoteNodeData
- func GenerateTestNode(t *testing.T) (LocalNode, Peer)
- func GenerateTestNodeWithConfig(t *testing.T, config nodeconfig.Config) (LocalNode, Peer)
- func GetHostName(address string) string
- func GetPort(address string) (string, error)
- func GetPublicIPAddress() (string, error)
- type Callbacks
- type Demuxer
- type FindNodeCallbacks
- type FindNodeProtocol
- type FindNodeResp
- type HandshakeData
- type HandshakeProtocol
- type IncomingMessage
- type IncomingMessageImpl
- type LocalNode
- type MessagesChan
- type NetworkSession
- type NetworkSessionImpl
- func (n *NetworkSessionImpl) Created() time.Time
- func (n *NetworkSessionImpl) Decrypt(in []byte) ([]byte, error)
- func (n *NetworkSessionImpl) Encrypt(in []byte) ([]byte, error)
- func (n *NetworkSessionImpl) ID() []byte
- func (n *NetworkSessionImpl) IsAuthenticated() bool
- func (n *NetworkSessionImpl) KeyE() []byte
- func (n *NetworkSessionImpl) KeyM() []byte
- func (n *NetworkSessionImpl) LocalNodeID() string
- func (n *NetworkSessionImpl) PubKey() []byte
- func (n *NetworkSessionImpl) RemoteNodeID() string
- func (n *NetworkSessionImpl) SetAuthenticated(val bool)
- func (n *NetworkSessionImpl) String() string
- type NodeData
- type NodeEvent
- type NodeEventCallback
- type NodeResp
- type NodeState
- type Peer
- type Ping
- type ProtocolRegistration
- type RespCallbackRequest
- type SendError
- type SendMessageReq
- type SendPingResp
- type Swarm
Constants ¶
const HandshakeReq = "/handshake/1.0/handshake-req/"
HandshakeReq specifies the handshake protocol request message identifier. pattern is [protocol][version][method-name].
const HandshakeResp = "/handshake/1.0/handshake-resp/"
HandshakeResp specifies the handshake protocol response message identifier.
Variables ¶
This section is empty.
Functions ¶
func CheckNodeVersion ¶
CheckNodeVersion checks if a request version is more recent then the given min version. Returns a bool and an error
func GenerateRandomNodeData ¶
func GenerateRandomNodeData() node.RemoteNodeData
GenerateRandomNodeData generates a remote random node data for testing.
func GenerateRandomNodesData ¶
func GenerateRandomNodesData(n int) []node.RemoteNodeData
GenerateRandomNodesData generates remote nodes data for testing.
func GenerateTestNode ¶
GenerateTestNode generates a local test node without persisting data to local store and with default config value.
func GenerateTestNodeWithConfig ¶
GenerateTestNodeWithConfig creates a local test node without persisting data to local store.
func GetHostName ¶
GetHostName returns the host name part of an ip address.
func GetPort ¶
GetPort returns the port name part of an ip address which includes a port number part.
func GetPublicIPAddress ¶
GetPublicIPAddress returns this host public ip address. Method is implemented using the ipify.org service.
Types ¶
type Callbacks ¶
type Callbacks chan chan SendPingResp
Callbacks is a channel of SendPingResp channels.
type Demuxer ¶
type Demuxer interface { RegisterProtocolHandler(handler ProtocolRegistration) RouteIncomingMessage(msg IncomingMessage) }
Demuxer is responsible for routing incoming network messages back to protocol handlers based on message protocols.
Limitations - type only supports 1 handler per protocol for now.
type FindNodeCallbacks ¶
type FindNodeCallbacks chan RespCallbackRequest
FindNodeCallbacks is a channel of RespCallbackRequests.
type FindNodeProtocol ¶
type FindNodeProtocol interface { // FindNode sends a find_node request for data about a remote node, known only by id, // to a specific known remote node. // Results will include 0 or more nodes and up to count nodes which may or may not include // data about id (as serverNodeId may not know about it). // // reqID: allows the client to match responses with requests by id. // serverNodeId - node to send the find request to. // id - node id to find // // TODO(devs): this should really be named FindClosestNodes FindNode(reqID []byte, serverNodeID string, id string, callback chan FindNodeResp) error }
FindNodeProtocol provides the dht protocol FIND-NODE message.
func NewFindNodeProtocol ¶
func NewFindNodeProtocol(s Swarm) FindNodeProtocol
NewFindNodeProtocol creates a new FindNodeProtocol instance.
type FindNodeResp ¶
type FindNodeResp struct { *pb.FindNodeResp // contains filtered or unexported fields }
FindNodeResp specifies the data returned by FindNode.
type HandshakeData ¶
type HandshakeData interface { LocalNode() LocalNode Peer() Peer Session() NetworkSession GetError() error SetError(err error) }
HandshakeData defines the handshake protocol capabilities.
func NewHandshakeData ¶
func NewHandshakeData(localNode LocalNode, peer Peer, session NetworkSession, err error) HandshakeData
NewHandshakeData creates new HandshakeData with the provided data.
type HandshakeProtocol ¶
type HandshakeProtocol interface { CreateSession(peer Peer) // RegisterNewSessionCallback registers a channel to receive session state changes RegisterNewSessionCallback(callback chan HandshakeData) }
HandshakeProtocol specifies the handshake protocol.
Node1 -> Node 2: Req(HandshakeData)
Node2 -> Node 1: Resp(HandshakeData)
After response is processed by node1 both sides have an auth session with a secret ephemeral aes sym key.
func NewHandshakeProtocol ¶
func NewHandshakeProtocol(s Swarm) HandshakeProtocol
NewHandshakeProtocol Creates a new Handshake protocol for the provided swarm.
type IncomingMessage ¶
IncomingMessage defines an incoming a p2p protocol message components.
func NewIncomingMessage ¶
func NewIncomingMessage(sender Peer, protocol string, payload []byte) IncomingMessage
NewIncomingMessage creates a new IncomingMessage from provided components.
type IncomingMessageImpl ¶
type IncomingMessageImpl struct {
// contains filtered or unexported fields
}
IncomingMessageImpl implements IncomingMessage.
func (*IncomingMessageImpl) Payload ¶
func (i *IncomingMessageImpl) Payload() []byte
Payload returns the binary message payload.
func (*IncomingMessageImpl) Protocol ¶
func (i *IncomingMessageImpl) Protocol() string
Protocol returns the message protocol string.
func (*IncomingMessageImpl) Sender ¶
func (i *IncomingMessageImpl) Sender() Peer
Sender returns the message sender peer.
type LocalNode ¶
type LocalNode interface { ID() []byte String() string Pretty() string PrivateKey() crypto.PrivateKey PublicKey() crypto.PublicKey DhtID() dht.ID TCPAddress() string // ipv4 tcp address that the node is listing on PubTCPAddress() string // node's public ip address - advertised by this node RefreshPubTCPAddress() bool // attempt to refresh the node's public ip address Sign(data proto.Message) ([]byte, error) SignToString(data proto.Message) (string, error) NewProtocolMessageMetadata(protocol string, reqID []byte, gossip bool) *pb.Metadata GetSwarm() Swarm GetPing() Ping Config() nodeconfig.Config GetRemoteNodeData() node.RemoteNodeData Shutdown() NotifyOnShutdown(chan bool) Info(format string, args ...interface{}) Debug(format string, args ...interface{}) Error(format string, args ...interface{}) Warning(format string, args ...interface{}) // local store persistence EnsureNodeDataDirectory() (string, error) // contains filtered or unexported methods }
LocalNode specifies local spacemesh node capabilities and services.
func NewLocalNode ¶
NewLocalNode creates a local node with a provided tcp address. Attempts to set node identity from persisted data in local store. Creates a new identity if none was loaded.
func NewNodeIdentity ¶
NewNodeIdentity creates a new local node without attempting to restore identity from local store.
type MessagesChan ¶
type MessagesChan chan IncomingMessage
MessagesChan is a channel of IncomingMessages.
type NetworkSession ¶
type NetworkSession interface { ID() []byte // Unique session id String() string // globally unique session id for p2p debugging and key store purposes KeyE() []byte // session shared sym key for enc - 32 bytes KeyM() []byte // session shared sym key for mac - 32 bytes PubKey() []byte // 65 bytes session-only pub key uncompressed Created() time.Time // time when session was established LocalNodeID() string // string encoded session local node id RemoteNodeID() string // string encoded session remote node id IsAuthenticated() bool SetAuthenticated(val bool) Decrypt(in []byte) ([]byte, error) // decrypt data using session dec key Encrypt(in []byte) ([]byte, error) // encrypt data using session enc key }
NetworkSession is an authenticated network session between 2 peers. Sessions may be used between 'connections' until they expire. Session provides the encryptor/decryptor for all messages exchanged between 2 peers. enc/dec is using an ephemeral sym key exchanged securely between the peers via the handshake protocol. The handshake protocol goal is to create an authenticated network session.
func NewNetworkSession ¶
func NewNetworkSession(id, keyE, keyM, pubKey []byte, localNodeID, remoteNodeID string) (NetworkSession, error)
NewNetworkSession creates a new network session based on provided data.
type NetworkSessionImpl ¶
type NetworkSessionImpl struct {
// contains filtered or unexported fields
}
NetworkSessionImpl implements NetworkSession.
func (*NetworkSessionImpl) Created ¶
func (n *NetworkSessionImpl) Created() time.Time
Created returns the session creation time.
func (*NetworkSessionImpl) Decrypt ¶
func (n *NetworkSessionImpl) Decrypt(in []byte) ([]byte, error)
Decrypt decrypts in binary data that was encrypted with the session's sym enc key.
func (*NetworkSessionImpl) Encrypt ¶
func (n *NetworkSessionImpl) Encrypt(in []byte) ([]byte, error)
Encrypt encrypts in binary data with the session's sym enc key.
func (*NetworkSessionImpl) ID ¶
func (n *NetworkSessionImpl) ID() []byte
ID returns the session's unique id
func (*NetworkSessionImpl) IsAuthenticated ¶
func (n *NetworkSessionImpl) IsAuthenticated() bool
IsAuthenticated returns true iff the session is authenticated.
func (*NetworkSessionImpl) KeyE ¶
func (n *NetworkSessionImpl) KeyE() []byte
KeyE returns the sessions sym encryption key.
func (*NetworkSessionImpl) KeyM ¶
func (n *NetworkSessionImpl) KeyM() []byte
KeyM returns the session's MAC encryption key.
func (*NetworkSessionImpl) LocalNodeID ¶
func (n *NetworkSessionImpl) LocalNodeID() string
LocalNodeID returns the session's local node id.
func (*NetworkSessionImpl) PubKey ¶
func (n *NetworkSessionImpl) PubKey() []byte
PubKey returns the session's public key.
func (*NetworkSessionImpl) RemoteNodeID ¶
func (n *NetworkSessionImpl) RemoteNodeID() string
RemoteNodeID returns the session's remote node id.
func (*NetworkSessionImpl) SetAuthenticated ¶
func (n *NetworkSessionImpl) SetAuthenticated(val bool)
SetAuthenticated updates the session's authentication state.
func (*NetworkSessionImpl) String ¶
func (n *NetworkSessionImpl) String() string
String returns the session's identifier string.
type NodeData ¶
type NodeData struct { PubKey string `json:"pubKey"` PrivKey string `json:"priKey"` CoinBaseID string `json:"coinbase"` // coinbase account id }
NodeData defines persistent node data.
type NodeEventCallback ¶
type NodeEventCallback chan NodeEvent
NodeEventCallback is a channel of NodeEvents.
type NodeResp ¶
type NodeResp struct {
// contains filtered or unexported fields
}
NodeResp defines node response data.
type NodeState ¶
type NodeState int32
NodeState specifies the node's connectivity state.
type Peer ¶
type Peer interface { ID() []byte // node id is public key bytes String() string // node public key string Pretty() string TCPAddress() string // tcp address advertised by node e.g. 127.0.0.1:3058 PublicKey() crypto.PublicKey GetConnections() map[string]net.Connection DeleteAllConnections() GetSessions() map[string]NetworkSession // GetAuthenticatedSession returns an authenticated session with // the node if one exists. GetAuthenticatedSession() NetworkSession // GetActiveConnection returns an active connection with the node if we have one. GetActiveConnection() net.Connection // GetRemoteNodeData returns RemoteNodeData for this peer. GetRemoteNodeData() node.RemoteNodeData }
Peer is a remote network node. At minimum local node knows its id (public key) and announced tcp address/port. Peers are maintained by the swarm and are not visible to higher-level types on the network stack. All Peer methods are NOT thread-safe - they are designed to be used only from a singleton Swarm type. Peer handles swarm sessions and net connections with a remote node.
type Ping ¶
type Ping interface { // Send sends a ping request to a remote node. // // reqIdD: allows the client to match responses with requests by id. Send(msg string, reqID []byte, remoteNodeID string) // Register a callback for typed incoming ping responses (pongs) or send errors. Register(callback chan SendPingResp) }
Ping protocol: An example of a simple app-level p2p protocol.
func NewPingProtocol ¶
NewPingProtocol creates a new Ping protocol implementation.
type ProtocolRegistration ¶
type ProtocolRegistration struct { Protocol string Handler MessagesChan }
ProtocolRegistration defines required protocol demux registration data.
type RespCallbackRequest ¶
type RespCallbackRequest struct {
// contains filtered or unexported fields
}
RespCallbackRequest specifies callback for a request ID.
type SendError ¶
type SendError struct { ReqID []byte // unique request id // contains filtered or unexported fields }
SendError specifies message sending error data.
type SendMessageReq ¶
type SendMessageReq struct { PeerID string // base58 message destination peer id ReqID []byte // unique request id Payload []byte // this should be a marshaled protocol msg e.g. PingReqData Callback chan SendError // optional callback to receive send errors or timeout }
SendMessageReq specifies data required for sending a p2p message to a remote peer.
type SendPingResp ¶
type SendPingResp struct { *pb.PingRespData // contains filtered or unexported fields }
SendPingResp contains pong response data or error.
type Swarm ¶
type Swarm interface { // SendMessage sends a message to a specific remote node based just on its id // without knowing its ip address. // In this case we will try to locate the node via dht node search, // and send the message if we obtained node ip address and were able to connect to it. // // req.msg should be marshaled protocol message. e.g. something like pb.PingReqData; // // This is designed for standard messages that require a session. // This method is designed to be used by protocols implementations to send message // to any destination. SendMessage(req SendMessageReq) // RegisterNode registers a node with the swarm based on its id and tcp address but don't // attempt to connect to it. RegisterNode(data node.RemoteNodeData) // ConnectTo attempts to establish a session with a remote node with a known // id and tcp address. // Used for bootstrapping known bootstrap nodes. ConnectTo(req node.RemoteNodeData) // ConnectToRandomNodes connects to count random nodes - used for bootstrapping // the swarm. ConnectToRandomNodes(count int) // Forcefully disconnect form a node - close any connections and sessions with it. DisconnectFrom(req node.RemoteNodeData) // Register a callback channel for state changes related to remote nodes. // Currently used for testing network bootstrapping. RegisterNodeEventsCallback(callback NodeEventCallback) // Todo(devs): allow client to register callback to get notified when swarm has shut down Shutdown() // Services getters. GetDemuxer() Demuxer GetLocalNode() LocalNode // contains filtered or unexported methods }
Swarm is p2p virtual network of spacemesh nodes as viewed by a local node.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package delimited implements a reader and writer for simple streams of length-delimited byte records.
|
Package delimited implements a reader and writer for simple streams of length-delimited byte records. |
Package pb is a generated protocol buffer package.
|
Package pb is a generated protocol buffer package. |
Package timesync is used to check system time reliability by communicating with NTP time servers.
|
Package timesync is used to check system time reliability by communicating with NTP time servers. |