p2p

package
v0.0.0-...-77dcbbd Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2024 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package p2p implements P2P protocol using libp2p library.

Index

Constants

View Source
const (
	// ValidationAccept is a validation decision that indicates a valid message that should be accepted and
	// delivered to the application and forwarded to the network.
	ValidationAccept = ValidationResult(0)
	// ValidationReject is a validation decision that indicates an invalid message that should not be
	// delivered to the application or forwarded to the application. Furthermore the peer that forwarded
	// the message should be penalized.
	ValidationReject = ValidationResult(1)
	// ValidationIgnore is a validation decision that indicates a message that should be ignored: it will
	// be neither delivered to the application nor forwarded to the network.
	ValidationIgnore = ValidationResult(2)
)
View Source
const (
	ConnectionSecurityNone  = "none"  // Do not support any security.
	ConnectionSecurityTLS   = "tls"   // Support TLS connections.
	ConnectionSecurityNoise = "noise" // Support Noise connections.
)

Connection security option type.

View Source
const (
	MaxPenaltyScore = 100 // When a peer exceeded the MaxPenaltyScore, it should be banned.
)

Variables

View Source
var (
	ErrGossipSubIsNotRunnig = errors.New("gossipSub is not running")
	ErrGossipSubIsRunning   = errors.New("gossipSub is running the action is not possible")
	ErrDuplicateHandler     = errors.New("eventHandler is already registered")
	ErrTopicNotFound        = errors.New("topic not found")
)

Functions

This section is empty.

Types

type AddrInfo

type AddrInfo = peer.AddrInfo

func AddrInfoFromMultiAddr

func AddrInfoFromMultiAddr(s string) (*AddrInfo, error)

AddrInfoFromMultiAddr returns a peer info from multi address as string.

type Config

type Config struct {
	Version                 string
	Addresses               []string
	ConnectionSecurity      string
	EnableNATService        bool
	EnableUsingRelayService bool
	EnableRelayService      bool
	EnableHolePunching      bool
	SeedPeers               []string
	FixedPeers              []string
	BlacklistedIPs          []string
	MinNumOfConnections     int
	MaxNumOfConnections     int
	// GossipSub configuration
	IsSeedPeer bool
	ChainID    codec.Hex
}

type Connection

type Connection struct {
	*MessageProtocol
	*Peer
	*GossipSub
	// contains filtered or unexported fields
}

Connection - a connection to p2p network.

func NewConnection

func NewConnection(logger log.Logger, cfg *Config) *Connection

NewConnection creates a new P2P instance.

func (*Connection) ApplyPenalty

func (conn *Connection) ApplyPenalty(pid PeerID, score int)

ApplyPenalty updates the score of the given PeerID (all its IP addresses) and bans the peer if the score exceeded. Also disconnected the peer immediately.

func (*Connection) BanPeer

func (conn *Connection) BanPeer(pid PeerID)

BanPeer bans the given PeerID (all its IP addresses) and disconnects the peer immediately.

func (*Connection) Start

func (conn *Connection) Start(seed []byte) error

Start the P2P and all other related services and handlers.

func (*Connection) Stop

func (conn *Connection) Stop() error

Stop the connection to the P2P network.

func (*Connection) Version

func (conn *Connection) Version() string

Version returns network version set for the protocol.

type Discovery

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

func (Discovery) Advertise

func (d Discovery) Advertise(ctx context.Context, ns string, opts ...discovery.Option) (time.Duration, error)

func (Discovery) FindPeers

func (d Discovery) FindPeers(ctx context.Context, ns string, opts ...discovery.Option) (<-chan peer.AddrInfo, error)

type Event

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

Event holds event message from a peer.

func NewEvent

func NewEvent(peerID PeerID, topic string, data []byte) *Event

NewEvent creates a new event.

func (*Event) Data

func (e *Event) Data() []byte

Data returns event payload.

func (*Event) PeerID

func (e *Event) PeerID() PeerID

PeerID returns sender peer ID.

func (*Event) Topic

func (e *Event) Topic() string

Topic returns topic of the event.

type EventHandler

type EventHandler func(event *Event)

EventHandler is a handler function for event received from a peer.

type ExtendedConnection

type ExtendedConnection struct {
	*Connection
}

ExtendedConnection extends the Connection for some extra utilities functions.

func NewExtendedConnection

func NewExtendedConnection(logger log.Logger, cfg *Config) *ExtendedConnection

NewExtendedConnection returns a new ExtendedConnection.

func (*ExtendedConnection) ConnsToPeer

func (ec *ExtendedConnection) ConnsToPeer(pid PeerID) []network.Conn

ConnToPeer returns the connections in the Network of the host/node for given peerID.

func (*ExtendedConnection) Info

func (ec *ExtendedConnection) Info() *AddrInfo

Info returns an AddrInfo struct with the ID of the host/node and all of its Addrs.

func (*ExtendedConnection) Listen

func (ec *ExtendedConnection) Listen(addrs []ma.Multiaddr) error

Listen tells the network of the host/node to start listening on given multiaddrs. It will be available with an empty addresses of the config in NewRawConnection.

func (*ExtendedConnection) NewStream

func (ec *ExtendedConnection) NewStream(ctx context.Context, pid PeerID, pids ...protocol.ID) (network.Stream, error)

NewSteam opens a new stream to given peer in the host/node.

func (*ExtendedConnection) SetStreamHandler

func (ec *ExtendedConnection) SetStreamHandler(protocolID protocol.ID, hander network.StreamHandler)

SetStreamHandler sets a new handler for given protocolID in the host/node.

func (*ExtendedConnection) StartGossipSub

func (ec *ExtendedConnection) StartGossipSub(ctx context.Context, options ...pubsub.Option) error

StartGossipSub starts a new gossipsub based on input options.

func (*ExtendedConnection) SwarmClear

func (ec *ExtendedConnection) SwarmClear(pid PeerID) bool

SwarmClear returns true and removes a backoff record if the Network of the host/node has the given peerID.

type GossipSub

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

GossipSub type.

func (*GossipSub) Publish

func (gs *GossipSub) Publish(ctx context.Context, topicName string, data []byte) error

Publish publishes a message to a topic.

func (*GossipSub) RegisterEventHandler

func (gs *GossipSub) RegisterEventHandler(name string, handler EventHandler, validator Validator) error

RegisterEventHandler registers an event handler for an event type.

type Message

type Message struct {
	Timestamp int64  `json:"timestamp"`            // Unix time when the message was received.
	Data      []byte `fieldNumber:"1" json:"data"` // Message data (payload).
}

Message is a message type sent to other peers in the network over GossipSub.

func NewMessage

func NewMessage(data []byte) *Message

NewMessage creates a new message.

func (*Message) Decode

func (e *Message) Decode(data []byte) error

func (*Message) DecodeFromReader

func (e *Message) DecodeFromReader(reader *codec.Reader) error

func (*Message) DecodeStrict

func (e *Message) DecodeStrict(data []byte) error

func (*Message) DecodeStrictFromReader

func (e *Message) DecodeStrictFromReader(reader *codec.Reader) error

func (*Message) Encode

func (e *Message) Encode() []byte

func (*Message) MustDecode

func (e *Message) MustDecode(data []byte)

type MessageProtocol

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

MessageProtocol type.

func (*MessageProtocol) Broadcast

func (mp *MessageProtocol) Broadcast(ctx context.Context, procedure string, data []byte) error

Broadcast sends a request message to all connected peers using a message protocol.

func (*MessageProtocol) RegisterRPCHandler

func (mp *MessageProtocol) RegisterRPCHandler(name string, handler RPCHandler, opts ...RPCHandlerOption) error

RegisterRPCHandler registers a new RPC handler function.

func (*MessageProtocol) RequestFrom

func (mp *MessageProtocol) RequestFrom(ctx context.Context, peerID PeerID, procedure string, data []byte) Response

RequestFrom sends a request message to a peer using a message protocol.

type Peer

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

Peer type - a p2p node.

func (*Peer) BlacklistedPeers

func (p *Peer) BlacklistedPeers() []AddrInfo

BlacklistedPeers returns a list of blacklisted peers and their addresses.

func (*Peer) Connect

func (p *Peer) Connect(ctx context.Context, peer AddrInfo) error

Connect to a peer using AddrInfo. Direct connection is discouraged. Manually connected peer must be manually disconnected.

func (*Peer) ConnectedPeers

func (p *Peer) ConnectedPeers() PeerIDs

ConnectedPeers returns a list of all connected peers IDs.

func (*Peer) Disconnect

func (p *Peer) Disconnect(peer PeerID) error

Disconnect from a peer.

func (*Peer) ID

func (p *Peer) ID() PeerID

ID returns a peers's identifier.

func (*Peer) MultiAddress

func (p *Peer) MultiAddress() ([]string, error)

MultiAddress returns a peers's listen addresses.

func (*Peer) Ping

func (p *Peer) Ping(ctx context.Context, peer PeerID) (rtt time.Duration, err error)

Ping tries to send a ping request to a peer.

func (*Peer) PingMultiTimes

func (p *Peer) PingMultiTimes(ctx context.Context, peer PeerID) (rtt []time.Duration, err error)

PingMultiTimes tries to send ping request to a peer for five times.

type PeerID

type PeerID = peer.ID

type PeerIDs

type PeerIDs = peer.IDSlice

type RPCHandler

type RPCHandler func(w ResponseWriter, req *Request)

RPCHandler is a handler function for RPC request received from a peer.

type RPCHandlerOption

type RPCHandlerOption func(*MessageProtocol, string) error

func WithRPCMessageCounter

func WithRPCMessageCounter(limit, penalty int) RPCHandlerOption

WithRPCMessageCounter sets a rate limit for a specific RPC message handler.

type Request

type Request struct {
	ID        string `fieldNumber:"1" json:"id"`        // Message ID.
	Procedure string `fieldNumber:"2" json:"procedure"` // Procedure to be called.
	Data      []byte `fieldNumber:"3" json:"data"`      // Request data.
	Timestamp int64  `json:"timestamp"`                 // Unix time when the message was received.
	PeerID    PeerID `json:"peerID"`                    // ID of peer that created the request message.
}

Request is a request message type sent to other peer.

func (*Request) Decode

func (e *Request) Decode(data []byte) error

func (*Request) DecodeFromReader

func (e *Request) DecodeFromReader(reader *codec.Reader) error

func (*Request) DecodeStrict

func (e *Request) DecodeStrict(data []byte) error

func (*Request) DecodeStrictFromReader

func (e *Request) DecodeStrictFromReader(reader *codec.Reader) error

func (*Request) Encode

func (e *Request) Encode() []byte

func (*Request) MustDecode

func (e *Request) MustDecode(data []byte)

type Response

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

Event holds event message from a peer.

func NewResponse

func NewResponse(timestamp int64, peerID PeerID, data []byte, err error) *Response

NewResponse creates a new Response struct.

func (*Response) Data

func (r *Response) Data() []byte

Data returns response payload.

func (*Response) Error

func (r *Response) Error() error

Error returns response error.

func (*Response) PeerID

func (r *Response) PeerID() PeerID

PeerID returns sender peer ID.

func (*Response) Timestamp

func (r *Response) Timestamp() int64

Timestamp returns response timestamp.

type ResponseWriter

type ResponseWriter interface {
	Write([]byte)
	Error(error)
}

ResponseWriter is an interface for handler to write.

type ValidationResult

type ValidationResult = pubsub.ValidationResult

ValidationResult represents the decision of a validator.

type Validator

type Validator = func(context.Context, *Message) ValidationResult

Validator should be implemented for each type that we want to validate it.

Jump to

Keyboard shortcuts

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