net

package
v0.0.9-alpha Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2024 License: MIT Imports: 57 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Halflife defines the time (in seconds) by which the transient part
	// of the ban score decays to one half of it's original value.
	Halflife = 60

	// Lifetime defines the maximum age of the transient part of the ban
	// score to be considered a non-zero score (in seconds).
	Lifetime = 1800
)
View Source
const (
	// BlockTopic is the routing topic for block relay
	BlockTopic = "blocks"
	// TransactionsTopic is the routing topic for transaction relay
	TransactionsTopic = "transactions"
	// RelayKey is the routing key used to advertise and discover relay peers
	RelayKey = "/ilx/relaypeers"
	// ValidatorProtectionFlag is a flag use to keep alive connections to
	// validator peers.
	ValidatorProtectionFlag = "validator"
)

Variables

View Source
var ErrNetworkConfig = errors.New("network config error")
View Source
var ErrReadTimeout = fmt.Errorf("timed out reading response")

ErrReadTimeout is an error that occurs when no message is read within the timeout period.

Functions

func ReadMsg

func ReadMsg(ctx context.Context, r msgio.ReadCloser, mes proto.Message) error

func UseLogger

func UseLogger(logger *logger.Logger)

UseLogger uses a specified Logger to output package logging info.

func WriteMsg

func WriteMsg(w io.Writer, mes proto.Message) error

Types

type ConnectionGater

type ConnectionGater struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

ConnectionGater implements a connection gater that allows the application to perform access control on incoming and outgoing connections. The difference between this and the libp2p BasicConnectionGater is this class provides a method for incrementally increasing a peer's banscore and bans them only for a specified duration.

func NewConnectionGater

func NewConnectionGater(ds repo.Datastore, addrBook peerstore.AddrBook, banDuration time.Duration, maxBanscore uint32) (*ConnectionGater, error)

NewConnectionGater creates a new connection gater.

func (*ConnectionGater) BlockAddr

func (cg *ConnectionGater) BlockAddr(ip net.IP) error

BlockAddr adds an IP address to the set of blocked addresses. Note: active connections to the IP address are not automatically closed.

func (*ConnectionGater) BlockPeer

func (cg *ConnectionGater) BlockPeer(p peer.ID) error

BlockPeer adds a peer to the set of blocked peers. Note: active connections to the peer are not automatically closed.

func (*ConnectionGater) IncreaseBanscore

func (cg *ConnectionGater) IncreaseBanscore(p peer.ID, persistent, transient uint32, reason ...string) (bool, error)

IncreaseBanscore increases the ban score for a peer. If the score goes over maxBanscore then the peer will be banned as well as its IP addresses.

If persistent is non-zero the persistent score will never decrease. The transient score does decrease according to a decay function.

func (*ConnectionGater) InterceptAccept

func (cg *ConnectionGater) InterceptAccept(cma network.ConnMultiaddrs) (allow bool)

func (*ConnectionGater) InterceptAddrDial

func (cg *ConnectionGater) InterceptAddrDial(p peer.ID, a ma.Multiaddr) (allow bool)

func (*ConnectionGater) InterceptPeerDial

func (cg *ConnectionGater) InterceptPeerDial(p peer.ID) (allow bool)

func (*ConnectionGater) InterceptSecured

func (cg *ConnectionGater) InterceptSecured(dir network.Direction, p peer.ID, cma network.ConnMultiaddrs) (allow bool)

func (*ConnectionGater) InterceptUpgraded

func (cg *ConnectionGater) InterceptUpgraded(network.Conn) (allow bool, reason control.DisconnectReason)

func (*ConnectionGater) ListBlockedAddrs

func (cg *ConnectionGater) ListBlockedAddrs() []net.IP

ListBlockedAddrs return a list of blocked IP addresses

func (*ConnectionGater) ListBlockedPeers

func (cg *ConnectionGater) ListBlockedPeers() []peer.ID

ListBlockedPeers return a list of blocked peers

func (*ConnectionGater) UnblockAddr

func (cg *ConnectionGater) UnblockAddr(ip net.IP) error

UnblockAddr removes an IP address from the set of blocked addresses

func (*ConnectionGater) UnblockPeer

func (cg *ConnectionGater) UnblockPeer(p peer.ID) error

UnblockPeer removes a peer from the set of blocked peers

type CtxMutex

type CtxMutex chan struct{}

func NewCtxMutex

func NewCtxMutex() CtxMutex

func (CtxMutex) Lock

func (m CtxMutex) Lock(ctx context.Context) error

func (CtxMutex) Unlock

func (m CtxMutex) Unlock()

type DynamicBanScore

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

DynamicBanScore provides dynamic ban scores consisting of a persistent and a decaying component. The persistent score could be utilized to create simple additive banning policies similar to those found in other bitcoin node implementations.

The decaying score enables the creation of evasive logic which handles misbehaving peers (especially application layer DoS attacks) gracefully by disconnecting and banning peers attempting various kinds of flooding. DynamicBanScore allows these two approaches to be used in tandem.

Zero value: Values of type DynamicBanScore are immediately ready for use upon declaration.

func (*DynamicBanScore) Increase

func (s *DynamicBanScore) Increase(persistent, transient uint32) uint32

Increase increases both the persistent and decaying scores by the values passed as parameters. The resulting score is returned.

This function is safe for concurrent access.

func (*DynamicBanScore) Int

func (s *DynamicBanScore) Int() uint32

Int returns the current ban score, the sum of the persistent and decaying scores.

This function is safe for concurrent access.

func (*DynamicBanScore) Reset

func (s *DynamicBanScore) Reset()

Reset set both persistent and decaying scores to zero.

This function is safe for concurrent access.

func (*DynamicBanScore) String

func (s *DynamicBanScore) String() string

String returns the ban score as a human-readable string.

type MessageSender

type MessageSender interface {
	// SendRequest sends a peer a message and waits for its response
	SendRequest(ctx context.Context, p peer.ID, req proto.Message, resp proto.Message) error
	// SendMessage sends a peer a message without waiting on a response
	SendMessage(ctx context.Context, p peer.ID, pmes proto.Message) error
}

MessageSender handles sending wire protocol messages to a given peer

func NewMessageSender

func NewMessageSender(h host.Host, protos ...protocol.ID) MessageSender

type Network

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

Network manages the libp2p network connections to other peers

func NewNetwork

func NewNetwork(ctx context.Context, opts ...Option) (*Network, error)

NewNetwork returns a new network configured with the provided options

func (*Network) BroadcastBlock

func (n *Network) BroadcastBlock(blk *blocks.XThinnerBlock) error

BroadcastBlock submits a block to the blocks pubsub channel

func (*Network) BroadcastTransaction

func (n *Network) BroadcastTransaction(tx *transactions.Transaction) error

BroadcastTransaction submits a transaction to the transactions pubsub channel

func (*Network) Close

func (n *Network) Close() error

Close shuts down the network

func (*Network) ConnGater

func (n *Network) ConnGater() *ConnectionGater

ConnGater returns the network's ConnGater

func (*Network) ConnManager

func (n *Network) ConnManager() coreconmgr.ConnManager

ConnManager returns the network's ConnManager

func (*Network) Dht

func (n *Network) Dht() *dht.IpfsDHT

Dht returns the network's DHT instance

func (*Network) Host

func (n *Network) Host() host.Host

Host returns the network's libp2p Host

func (*Network) IncreaseBanscore

func (n *Network) IncreaseBanscore(p peer.ID, persistent, transient uint32, reason ...string)

IncreaseBanscore increases the banscore for a peer and bans the peer if it goes over the configured threshold.

func (*Network) Pubsub

func (n *Network) Pubsub() *pubsub.PubSub

Pubsub returns the network's Pubsub instance

func (*Network) Reachability

func (n *Network) Reachability() inet.Reachability

Reachability returns whether the node can be dialed from external nodes or if a firewall is blocking incoming connections.

func (*Network) SubscribeBlocks

func (n *Network) SubscribeBlocks() (*pubsub.Subscription, error)

SubscribeBlocks returns a subscription to the blocks pubsub channel

func (*Network) SubscribeTransactions

func (n *Network) SubscribeTransactions() (*pubsub.Subscription, error)

SubscribeTransactions returns a subscription to the transactions pubsub channel

type Option

type Option func(cfg *config) error

Option is configuration option function for the Network

func BanDuration

func BanDuration(duration time.Duration) Option

func BlockValidator

func BlockValidator(validateBlock func(blk *blocks.XThinnerBlock, p peer.ID) error) Option

func Datastore

func Datastore(ds repo.Datastore) Option

func DisableNatPortMap

func DisableNatPortMap() Option

func ForceDHTServerMode

func ForceDHTServerMode() Option

ForceDHTServerMode forces the DHT to start in server mode. This is necessary if the node is a validator as they need to be publicly reachable.

func ListenAddrs

func ListenAddrs(addrs []string) Option

func MaxBanscore

func MaxBanscore(max uint32) Option

func MaxMessageSize

func MaxMessageSize(maxMessageSize int) Option

func MempoolValidator

func MempoolValidator(acceptToMempool func(tx *transactions.Transaction) error) Option

func Params

func Params(params *params.NetworkParams) Option

func PrivateKey

func PrivateKey(privKey crypto.PrivKey) Option

func SeedAddrs

func SeedAddrs(addrs []string) Option

func TorBinary

func TorBinary(binaryPath string) Option

TorBinary is the path to a tor binary file. If this option is used the tor transport is activated and the tor binary is started and managed by this process.

func TorDataDir

func TorDataDir(dir string) Option

TorDataDir is the path to the directory to store tor data.

func TorDualStack

func TorDualStack() Option

TorDualStack configures the network to make connections over both Tor AND the clear internet.

Tor must be configured to use this mode.

func TorrcFile

func TorrcFile(torrcPath string) Option

TorrcFile is the path to a custom tor torrc file. This allows you to set custom options for the running tor instance.

func UserAgent

func UserAgent(s string) Option

func WithHost

func WithHost(host host.Host) Option

type Peerstoreds

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

Peerstoreds adds a layer of caching to the peerstore addresses. The reason we want this is on each startup we are reliant exclusively on the hardcoded bootstrap peers for connectivity to the network. Instead, we can load a number of peers from the database and connect to them.

Each datastore entry tracks the last seen time of the peer and garbage collects peers that haven't been seen in over a month.

func NewPeerstoreds

func NewPeerstoreds(ds repo.Datastore, pstore peerstore.Peerstore) *Peerstoreds

NewPeerstoreds returns a new Peerstoreds

func (*Peerstoreds) AddrInfos

func (pds *Peerstoreds) AddrInfos() ([]peer.AddrInfo, error)

AddrInfos returns a list of AddrInfos (peer, multiaddrs) from the database.

func (*Peerstoreds) Close

func (pds *Peerstoreds) Close()

Close shuts down the Peerstoreds

type ValidatorConnector

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

ValidatorConnector does two things. First, it strives to maintain active connections to all validators in the validator set. Second, it tracks the percentage of the weighted stake that we are connected to.

func NewValidatorConnector

func NewValidatorConnector(host host.Host, ownID peer.ID,
	getValidatorFunc func(validatorID peer.ID) (*blockchain.Validator, error),
	getValidatorsFunc func() []*blockchain.Validator,
	blockchainSubscribeFunc func(cb blockchain.NotificationCallback)) *ValidatorConnector

NewValidatorConnector returns a new ValidatorConnector

func (*ValidatorConnector) ConnectedStakePercentage

func (vc *ValidatorConnector) ConnectedStakePercentage() float64

ConnectedStakePercentage returns the percentage of the weighted stake that we are connected to.

func (*ValidatorConnector) RegisterDialFailure

func (vc *ValidatorConnector) RegisterDialFailure(p peer.ID)

RegisterDialFailure registers a failed query for the purpose of tracking validator uptime and behavior.

func (*ValidatorConnector) RegisterDialSuccess

func (vc *ValidatorConnector) RegisterDialSuccess(p peer.ID)

RegisterDialSuccess registers a successful query for the purpose of tracking validator uptime and behavior.

func (*ValidatorConnector) ValidatorDialSuccessRate

func (vc *ValidatorConnector) ValidatorDialSuccessRate(p peer.ID) float64

ValidatorDialSuccessRate returns the dial success rate for the validator for the prior epoch.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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