p2p

package
v0.1.94 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2025 License: AGPL-3.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Dial

func Dial(n *enode.Node, opts DialOpts) (*rlpxConn, error)

Dial attempts to Dial the given node and perform a handshake, returning the created Conn if successful.

func Listen

func Listen(ln *enode.LocalNode) (*net.UDPConn, error)

func NewEthProtocol

func NewEthProtocol(version uint, opts EthProtocolOptions) ethp2p.Protocol

NewEthProtocol creates the new eth protocol. This will handle writing the status exchange, message handling, and writing blocks/txs to the database.

func ParseBootnodes

func ParseBootnodes(bootnodes string) ([]*enode.Node, error)

ParseBootnodes parses the bootnodes string and returns a node slice.

func ParseNode

func ParseNode(source string) (*enode.Node, error)

ParseNode parses a node record and verifies its signature.

func ParsePrivateKey added in v0.1.90

func ParsePrivateKey(file string, key string) (*ecdsa.PrivateKey, error)

ParsePrivateKey loads a private key from a file path or hex string. If file is provided, it attempts to load from the file path first. If the file doesn't exist, it generates a new key and saves it to the file. If key is provided instead, it parses the hex-encoded private key string. If neither file nor key is provided, it generates and returns a new private key.

func ReadNodeSet

func ReadNodeSet(file string) ([]*enode.Node, error)

ReadNodeSet parses a list of discovery node URLs loaded from a JSON file.

func WriteDNSTreeNodes added in v0.1.61

func WriteDNSTreeNodes(file string, tree *dnsdisc.Tree) error

func WriteNodeSet

func WriteNodeSet(file string, ns NodeSet, writeErrors bool) error

func WritePeers

func WritePeers(file string, urls []string) error

func WriteURLs

func WriteURLs(file string, ns NodeSet) error

Types

type AccountRange

type AccountRange snap.AccountRangePacket

func (AccountRange) Code

func (msg AccountRange) Code() int

func (AccountRange) ReqID

func (msg AccountRange) ReqID() uint64

type BlockBodies

type BlockBodies eth.BlockBodiesPacket

BlockBodies is the network packet for block content distribution.

func (BlockBodies) Code

func (msg BlockBodies) Code() int

func (BlockBodies) ReqID

func (msg BlockBodies) ReqID() uint64

type BlockCache added in v0.1.94

type BlockCache struct {
	Header *types.Header
	Body   *eth.BlockBody
	TD     *big.Int
}

BlockCache stores the actual block data to avoid duplicate fetches and database queries.

type BlockHeaders

type BlockHeaders eth.BlockHeadersPacket

func (BlockHeaders) Code

func (msg BlockHeaders) Code() int

func (BlockHeaders) ReqID

func (msg BlockHeaders) ReqID() uint64

type ByteCodes

type ByteCodes snap.ByteCodesPacket

func (ByteCodes) Code

func (msg ByteCodes) Code() int

func (ByteCodes) ReqID

func (msg ByteCodes) ReqID() uint64

type Cache added in v0.1.93

type Cache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Cache is a thread-safe LRU cache with optional TTL-based expiration.

func NewCache added in v0.1.93

func NewCache[K comparable, V any](maxSize int, ttl time.Duration) *Cache[K, V]

NewCache creates a new cache with the given max size and optional TTL. If maxSize <= 0, the cache has no size limit. If ttl is 0, entries never expire based on time.

func (*Cache[K, V]) Add added in v0.1.93

func (c *Cache[K, V]) Add(key K, value V)

Add adds or updates a value in the cache.

func (*Cache[K, V]) Contains added in v0.1.93

func (c *Cache[K, V]) Contains(key K) bool

Contains checks if a key exists in the cache and is not expired. Uses a read lock and doesn't update LRU ordering.

func (*Cache[K, V]) Get added in v0.1.93

func (c *Cache[K, V]) Get(key K) (V, bool)

Get retrieves a value from the cache and updates LRU ordering.

func (*Cache[K, V]) Keys added in v0.1.93

func (c *Cache[K, V]) Keys() []K

Keys returns all keys in the cache.

func (*Cache[K, V]) Len added in v0.1.93

func (c *Cache[K, V]) Len() int

Len returns the number of items in the cache.

func (*Cache[K, V]) Peek added in v0.1.94

func (c *Cache[K, V]) Peek(key K) (V, bool)

Peek retrieves a value from the cache without updating LRU ordering. Uses a read lock for better concurrency.

func (*Cache[K, V]) Purge added in v0.1.93

func (c *Cache[K, V]) Purge()

Purge clears all items from the cache.

func (*Cache[K, V]) Remove added in v0.1.93

func (c *Cache[K, V]) Remove(key K)

Remove removes a key from the cache.

func (*Cache[K, V]) Update added in v0.1.94

func (c *Cache[K, V]) Update(key K, updateFn func(V) V)

Update atomically updates a value in the cache using the provided update function. The update function receives the current value (or zero value if not found) and returns the new value to store. This is thread-safe and prevents race conditions in get-modify-add patterns.

type Conns added in v0.1.89

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

Conns manages a collection of active peer connections for transaction broadcasting. It also maintains a global cache of blocks written to the database.

func NewConns added in v0.1.89

func NewConns(opts ConnsOptions) *Conns

NewConns creates a new connection manager with a blocks cache.

func (*Conns) Add added in v0.1.89

func (c *Conns) Add(cn *conn)

Add adds a connection to the manager.

func (*Conns) Blocks added in v0.1.94

func (c *Conns) Blocks() *Cache[common.Hash, BlockCache]

Blocks returns the global blocks cache.

func (*Conns) BroadcastTx added in v0.1.89

func (c *Conns) BroadcastTx(tx *types.Transaction) int

BroadcastTx broadcasts a single transaction to all connected peers. Returns the number of peers the transaction was successfully sent to.

func (*Conns) BroadcastTxs added in v0.1.89

func (c *Conns) BroadcastTxs(txs types.Transactions) int

BroadcastTxs broadcasts multiple transactions to all connected peers. Returns the number of peers the transactions were successfully sent to.

func (*Conns) GetPeerConnectedAt added in v0.1.91

func (c *Conns) GetPeerConnectedAt(peerID string) time.Time

GetPeerConnectedAt returns the connection time for a peer by their ID. Returns zero time if the peer is not found.

func (*Conns) Nodes added in v0.1.89

func (c *Conns) Nodes() []*enode.Node

Nodes returns all currently connected peer nodes.

func (*Conns) Remove added in v0.1.89

func (c *Conns) Remove(cn *conn)

Remove removes a connection from the manager when a peer disconnects.

type ConnsOptions added in v0.1.94

type ConnsOptions struct {
	// MaxBlocks is the maximum number of blocks to track in the cache.
	MaxBlocks int
	// BlocksCacheTTL is the time to live for block cache entries.
	BlocksCacheTTL time.Duration
}

ConnsOptions contains configuration options for creating a new Conns manager.

type DialOpts added in v0.1.90

type DialOpts struct {
	EnableWit  bool
	Port       int
	Addr       net.IP
	PrivateKey *ecdsa.PrivateKey
}

func NewDialOpts added in v0.1.90

func NewDialOpts() DialOpts

type Direction added in v0.1.91

type Direction string

Direction represents the direction of a message (sent or received).

const (
	// MsgReceived represents messages received from peers.
	MsgReceived Direction = "received"
	// MsgSent represents messages sent to peers.
	MsgSent Direction = "sent"

	// PacketSuffix is appended to message names to create packet count metrics.
	PacketSuffix = "Packet"
)

type Disconnect

type Disconnect struct {
	Reason p2p.DiscReason
}

Disconnect is the RLP structure for a disconnect message.

func (Disconnect) Code

func (msg Disconnect) Code() int

func (Disconnect) ReqID

func (msg Disconnect) ReqID() uint64

type Disconnects

type Disconnects []p2p.DiscReason

Disconnects is the RLP structure for disconnect messages.

func (Disconnects) Code

func (msg Disconnects) Code() int

func (Disconnects) ReqID

func (msg Disconnects) ReqID() uint64

type Error

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

func (*Error) Code

func (e *Error) Code() int

func (*Error) Error

func (e *Error) Error() string

func (*Error) ReqID

func (e *Error) ReqID() uint64

func (*Error) String

func (e *Error) String() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type EthProtocolOptions

type EthProtocolOptions struct {
	Context     context.Context
	Database    database.Database
	GenesisHash common.Hash
	RPC         string
	SensorID    string
	NetworkID   uint64
	Conns       *Conns
	ForkID      forkid.ID
	MsgCounter  *prometheus.CounterVec

	// Head keeps track of the current head block of the chain. This is required
	// when doing the status exchange.
	Head      *HeadBlock
	HeadMutex *sync.RWMutex

	// Requests cache configuration
	MaxRequests      int
	RequestsCacheTTL time.Duration
}

EthProtocolOptions is the options used when creating a new eth protocol.

type GetAccountRange

type GetAccountRange snap.GetAccountRangePacket

GetAccountRange represents an account range query.

func (GetAccountRange) Code

func (msg GetAccountRange) Code() int

func (GetAccountRange) ReqID

func (msg GetAccountRange) ReqID() uint64

type GetBlockBodies

type GetBlockBodies eth.GetBlockBodiesPacket

GetBlockBodies represents a GetBlockBodies request

func (GetBlockBodies) Code

func (msg GetBlockBodies) Code() int

func (GetBlockBodies) ReqID

func (msg GetBlockBodies) ReqID() uint64

type GetBlockHeaders

type GetBlockHeaders eth.GetBlockHeadersPacket

GetBlockHeaders represents a block header query.

func (GetBlockHeaders) Code

func (msg GetBlockHeaders) Code() int

func (GetBlockHeaders) ReqID

func (msg GetBlockHeaders) ReqID() uint64

type GetByteCodes

type GetByteCodes snap.GetByteCodesPacket

func (GetByteCodes) Code

func (msg GetByteCodes) Code() int

func (GetByteCodes) ReqID

func (msg GetByteCodes) ReqID() uint64

type GetPooledTransactions

type GetPooledTransactions eth.GetPooledTransactionsPacket

func (GetPooledTransactions) Code

func (msg GetPooledTransactions) Code() int

func (GetPooledTransactions) ReqID

func (msg GetPooledTransactions) ReqID() uint64

type GetStorageRanges

type GetStorageRanges snap.GetStorageRangesPacket

func (GetStorageRanges) Code

func (msg GetStorageRanges) Code() int

func (GetStorageRanges) ReqID

func (msg GetStorageRanges) ReqID() uint64

type GetTrieNodes

type GetTrieNodes snap.GetTrieNodesPacket

func (GetTrieNodes) Code

func (msg GetTrieNodes) Code() int

func (GetTrieNodes) ReqID

func (msg GetTrieNodes) ReqID() uint64

type GetWitnessPacket added in v0.1.90

type GetWitnessPacket struct {
	RequestId uint64
	*GetWitnessRequest
}

GetWitnessPacket represents a witness query with request ID wrapping.

func (GetWitnessPacket) Code added in v0.1.90

func (msg GetWitnessPacket) Code() int

func (GetWitnessPacket) ReqID added in v0.1.90

func (msg GetWitnessPacket) ReqID() uint64

type GetWitnessRequest added in v0.1.90

type GetWitnessRequest struct {
	WitnessPages []WitnessPageRequest // Request by list of witness pages
}

GetWitnessRequest represents a list of witnesses query by witness pages.

type HeadBlock

type HeadBlock struct {
	Hash            common.Hash
	TotalDifficulty *big.Int
	Number          uint64
	Time            uint64
}

HeadBlock contains the necessary head block data for the status message.

type Hello

type Hello struct {
	Version    uint64
	Name       string
	Caps       []p2p.Cap
	ListenPort uint64
	ID         []byte // secp256k1 public key

	// Ignore additional fields (for forward compatibility).
	Rest []rlp.RawValue `rlp:"tail"`
}

Hello is the RLP structure of the protocol handshake.

func (Hello) Code

func (msg Hello) Code() int

func (Hello) ReqID

func (msg Hello) ReqID() uint64

type Message

type Message interface {
	Code() int
	ReqID() uint64
}

type MessageCount

type MessageCount struct {
	BlockHeaders        int64 `json:"block_headers,omitempty"`
	BlockBodies         int64 `json:"block_bodies,omitempty"`
	Blocks              int64 `json:"blocks,omitempty"`
	BlockHashes         int64 `json:"block_hashes,omitempty"`
	BlockHeaderRequests int64 `json:"block_header_requests,omitempty"`
	BlockBodiesRequests int64 `json:"block_bodies_requests,omitempty"`
	Transactions        int64 `json:"transactions,omitempty"`
	TransactionHashes   int64 `json:"transaction_hashes,omitempty"`
	TransactionRequests int64 `json:"transaction_requests,omitempty"`
	Pings               int64 `json:"pings,omitempty"`
	Errors              int64 `json:"errors,omitempty"`
	Disconnects         int64 `json:"disconnects,omitempty"`
	NewWitness          int64 `json:"new_witness,omitempty"`
	NewWitnessHashes    int64 `json:"new_witness_hashes,omitempty"`
	GetWitnessRequest   int64 `json:"get_witness_request,omitempty"`
	Witness             int64 `json:"witness,omitempty"`
}

MessageCount is used to help the outer goroutine to receive summary of the number and type of messages that were sent. This is used for distributed logging. It can be used to count the different types of messages received across all peer connections to provide a summary.

func (*MessageCount) Clear

func (count *MessageCount) Clear()

Clear clears all of the counts from the message counter.

func (*MessageCount) IsEmpty

func (c *MessageCount) IsEmpty() bool

IsEmpty checks whether the sum of all the counts is empty. Make sure to call Load before this method to get an accurate count.

func (*MessageCount) Load

func (count *MessageCount) Load() MessageCount

Load takes a snapshot of all the counts in a thread-safe manner. Make sure you call this and read from the returned object.

type NewBlock

type NewBlock eth.NewBlockPacket

NewBlock is the network packet for the block propagation message.

func (NewBlock) Code

func (msg NewBlock) Code() int

func (NewBlock) ReqID

func (msg NewBlock) ReqID() uint64

type NewBlockHashes

type NewBlockHashes eth.NewBlockHashesPacket

NewBlockHashes is the network packet for the block announcements.

func (NewBlockHashes) Code

func (msg NewBlockHashes) Code() int

func (NewBlockHashes) ReqID

func (msg NewBlockHashes) ReqID() uint64

type NewPooledTransactionHashes

type NewPooledTransactionHashes struct {
	Types  []byte
	Sizes  []uint32
	Hashes []common.Hash
}

NewPooledTransactionHashes is the network packet for the tx hash propagation message.

func (NewPooledTransactionHashes) Code

func (msg NewPooledTransactionHashes) Code() int

func (NewPooledTransactionHashes) ReqID

func (msg NewPooledTransactionHashes) ReqID() uint64

type NewPooledTransactionHashes66

type NewPooledTransactionHashes66 []common.Hash

NewPooledTransactionHashes66 is the network packet for the tx hash propagation message.

func (NewPooledTransactionHashes66) Code

func (msg NewPooledTransactionHashes66) Code() int

func (NewPooledTransactionHashes66) ReqID

type NewWitnessHashesPacket added in v0.1.90

type NewWitnessHashesPacket struct {
	Hashes  []common.Hash
	Numbers []uint64
}

func (NewWitnessHashesPacket) Code added in v0.1.90

func (msg NewWitnessHashesPacket) Code() int

func (NewWitnessHashesPacket) ReqID added in v0.1.90

func (msg NewWitnessHashesPacket) ReqID() uint64

type NewWitnessPacket added in v0.1.90

type NewWitnessPacket struct {
	Witness *stateless.Witness
}

func (NewWitnessPacket) Code added in v0.1.90

func (msg NewWitnessPacket) Code() int

func (NewWitnessPacket) ReqID added in v0.1.90

func (msg NewWitnessPacket) ReqID() uint64

type NodeJSON

type NodeJSON struct {
	URL    string  `json:"url"`
	Hello  *Hello  `json:"hello,omitempty"`
	Status *Status `json:"status,omitempty"`
	Error  string  `json:"error,omitempty"`
	Time   int64   `json:"time,omitempty"`
	Nodes  int     `json:"nodes,omitempty"`
}

type NodeSet

type NodeSet map[enode.ID][]NodeJSON

type Ping

type Ping struct{}

func (Ping) Code

func (msg Ping) Code() int

func (Ping) ReqID

func (msg Ping) ReqID() uint64

type Pong

type Pong struct{}

func (Pong) Code

func (msg Pong) Code() int

func (Pong) ReqID

func (msg Pong) ReqID() uint64

type PooledTransactions

type PooledTransactions eth.PooledTransactionsPacket

func (PooledTransactions) Code

func (msg PooledTransactions) Code() int

func (PooledTransactions) ReqID

func (msg PooledTransactions) ReqID() uint64

type Status

type Status eth.StatusPacket

Status is the network packet for the status message for eth/64 and later.

func (Status) Code

func (msg Status) Code() int

func (Status) ReqID

func (msg Status) ReqID() uint64

type StorageRanges

type StorageRanges snap.StorageRangesPacket

func (StorageRanges) Code

func (msg StorageRanges) Code() int

func (StorageRanges) ReqID

func (msg StorageRanges) ReqID() uint64

type Transactions

type Transactions eth.TransactionsPacket

func (Transactions) Code

func (msg Transactions) Code() int

func (Transactions) ReqID

func (msg Transactions) ReqID() uint64

type TrieNodes

type TrieNodes snap.TrieNodesPacket

func (TrieNodes) Code

func (msg TrieNodes) Code() int

func (TrieNodes) ReqID

func (msg TrieNodes) ReqID() uint64

type WitnessPacketRLPPacket added in v0.1.90

type WitnessPacketRLPPacket struct {
	RequestId uint64
	WitnessPacketResponse
}

WitnessPacketRLPPacket represents a witness response with request ID wrapping.

func (WitnessPacketRLPPacket) Code added in v0.1.90

func (msg WitnessPacketRLPPacket) Code() int

func (WitnessPacketRLPPacket) ReqID added in v0.1.90

func (msg WitnessPacketRLPPacket) ReqID() uint64

type WitnessPacketResponse added in v0.1.90

type WitnessPacketResponse []WitnessPageResponse

WitnessPacketResponse represents a witness response, to use when we already have the witness rlp encoded.

type WitnessPageRequest added in v0.1.90

type WitnessPageRequest struct {
	Hash common.Hash // BlockHash
	Page uint64      // Starts on 0
}

type WitnessPageResponse added in v0.1.90

type WitnessPageResponse struct {
	Data       []byte
	Hash       common.Hash
	Page       uint64 // Starts on 0; If Page >= TotalPages means the request was invalid and the response is an empty data array
	TotalPages uint64 // Length of pages
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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