Documentation
¶
Index ¶
- type BestBlockRequestMessage
- type BlockMessage
- type Config
- type Handler
- type HandshakeMessage
- type MessageType
- type MiningOnMessage
- type Node
- func (s *Node) BytesReceived() uint64
- func (s *Node) BytesSent() uint64
- func (s *Node) ConnectedPeers() []PeerInfo
- func (s *Node) CurrentlyConnectedPeers() []PeerInfo
- func (s *Node) DisconnectPeer(_ context.Context, peerID peer.ID) error
- func (s *Node) GetPeerIPs(peerID peer.ID) []string
- func (s *Node) GetProcessName() string
- func (s *Node) GetTopic(topicName string) *pubsub.Topic
- func (s *Node) HostID() peer.ID
- func (s *Node) LastRecv() time.Time
- func (s *Node) LastSend() time.Time
- func (s *Node) Publish(ctx context.Context, topicName string, msgBytes []byte) error
- func (s *Node) SendToPeer(ctx context.Context, peerID peer.ID, msg []byte) (err error)
- func (s *Node) SetPeerConnectedCallback(callback func(context.Context, peer.ID))
- func (s *Node) SetTopicHandler(ctx context.Context, topicName string, handler Handler) error
- func (s *Node) Start(ctx context.Context, streamHandler func(network.Stream), topicNames ...string) error
- func (s *Node) Stop(_ context.Context) error
- func (s *Node) UpdateBytesReceived(bytesCount uint64)
- func (s *Node) UpdateLastReceived()
- func (s *Node) UpdatePeerHeight(peerID peer.ID, height int32)
- type NodeI
- type PeerInfo
- type RejectedTxMessage
- type SubtreeMessage
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BestBlockRequestMessage ¶
type BestBlockRequestMessage struct {
PeerID string // Identifier of the peer making the request
}
BestBlockRequestMessage represents a request for the best block information from a peer. This message is used in the P2P handshake process to query peers about their current best block, enabling blockchain synchronization and peer height comparison.
The message contains the requesting peer's identifier to allow the recipient to respond appropriately and track the source of the request.
type BlockMessage ¶
type BlockMessage struct {
Hash string // Unique hash identifier of the block
Height uint32 // Position of the block in the blockchain
DataHubURL string // URL where the complete block data can be retrieved
PeerID string // Identifier of the peer announcing the block
}
BlockMessage announces the availability of a new block to the P2P network. This message is used for block propagation, allowing nodes to efficiently distribute new blocks across the network. It contains essential block metadata and a reference to where the full block data can be retrieved.
The message enables efficient block distribution by providing metadata first, allowing peers to decide whether they need the full block data before downloading it.
type Config ¶
type Config struct {
ProcessName string // Identifier for this node in logs and metrics
BootstrapAddresses []string // Initial peer addresses to connect to for network discovery
ListenAddresses []string // Network addresses to listen on for incoming connections
AdvertiseAddresses []string // Addresses to advertise to other peers (may differ from listen addresses)
Port int // Port number for P2P communication
DHTProtocolID string // Protocol ID for the DHT used by this node
PrivateKey string // Node's private key for secure communication
UsePrivateDHT bool // Whether to use a private DHT instead of the public IPFS DHT
OptimiseRetries bool // Whether to optimize connection retry behavior
Advertise bool // Whether to advertise this node's presence on the network
StaticPeers []string // List of peer addresses to always attempt to connect to
}
Config defines the configuration parameters for a P2P node. It encapsulates all settings needed to establish and maintain a functional peer-to-peer network presence.
type Handler ¶
Handler defines the function signature for topic message handlers. Each topic in the P2P network can have a dedicated handler that processes incoming messages.
Parameters:
- ctx: Context for the handler execution, allowing for cancellation and timeouts
- msg: Raw message bytes received from the network
- from: Identifier of the peer that sent the message
Handlers should process messages efficiently as they may be called frequently in high-traffic scenarios. Any long-running operations should be delegated to separate goroutines.
type HandshakeMessage ¶
type HandshakeMessage struct {
Type MessageType `json:"type"`
PeerID string `json:"peerID"`
BestHeight uint32 `json:"bestHeight"`
BestHash string `json:"bestHash"`
DataHubURL string `json:"dataHubURL"`
UserAgent string `json:"userAgent"`
Services uint64 `json:"services"`
}
HandshakeMessage carries version/verack information between peers during connection establishment. This message is the core of the P2P handshake protocol, allowing peers to exchange their current blockchain state, capabilities, and connection information. It supports both initial version announcements and acknowledgment responses.
The handshake process works as follows:
- Connecting peer sends a "version" message with their current state
- Receiving peer responds with a "verack" message to acknowledge
- Both peers now have each other's capabilities and can begin normal communication
Fields are JSON-tagged to support serialization for network transmission.
type MessageType ¶
type MessageType string
MessageType represents the type of handshake message in the P2P protocol. These constants define the standard message types used during the peer handshake process to establish communication and exchange version information.
const ( // Version is the initial handshake message type sent by a peer to announce its capabilities and blockchain state. Version MessageType = "version" // Verack is the acknowledgment message type sent by a peer to confirm receipt of a version message. Verack MessageType = "verack" )
type MiningOnMessage ¶
type MiningOnMessage struct {
Hash string // Hash of the block being mined
PreviousHash string // Hash of the previous block in the chain
DataHubURL string // URL where block data can be retrieved
PeerID string // Identifier of the mining peer
Height uint32 // Block height in the blockchain
Miner string // Identifier or address of the miner
SizeInBytes uint64 // Size of the block in bytes
TxCount uint64 // Number of transactions in the block
}
MiningOnMessage announces that a peer has started mining on a specific block. This message is broadcast to inform the network about mining activity and helps coordinate mining efforts across the network. It contains comprehensive information about the block being mined and the mining peer's capabilities.
The message enables other nodes to:
- Track mining activity across the network
- Coordinate their own mining efforts
- Monitor network hash rate and mining distribution
- Validate mining announcements against known block data
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node implements the NodeI interface and provides the core functionality for peer-to-peer networking in BSV blockchain applications using libp2p. It manages peer connections, topic subscriptions, message routing, and network discovery.
The Node encapsulates several critical components: - libp2p host for network transport and connection management - PubSub for topic-based message distribution - Peer height tracking for blockchain synchronization - Bandwidth and activity metrics for monitoring
Thread safety is maintained for all concurrent operations across multiple goroutines.
func NewNode ¶ added in v1.1.0
NewNode creates and initializes a new P2P network node with the provided configuration. This constructor performs the core setup of the libp2p networking stack, including:
- Setting up the node's cryptographic identity (private key)
- Configuring network transports and listeners
- Initializing the DHT (Distributed Hash Table) for peer discovery
- Preparing topic handlers and message routing systems
Parameters:
- ctx: Context for controlling the initialization process
- logger: Logger for recording initialization and operational events
- config: P2P-specific configuration parameters defining network behavior
Returns a fully initialized P2P node ready for starting, or an error if initialization fails.
func (*Node) BytesReceived ¶
BytesReceived returns the total number of bytes received by this node.
func (*Node) ConnectedPeers ¶
ConnectedPeers returns information about all connected peers.
func (*Node) CurrentlyConnectedPeers ¶
CurrentlyConnectedPeers returns information about currently connected peers.
func (*Node) DisconnectPeer ¶
DisconnectPeer disconnects from the specified peer.
func (*Node) GetPeerIPs ¶
GetPeerIPs returns the IP addresses for a specific peer.
func (*Node) GetProcessName ¶
GetProcessName returns the name of the current process.
func (*Node) SendToPeer ¶
SendToPeer sends a message to a peer. It will attempt to connect to the peer if not already connected.
func (*Node) SetPeerConnectedCallback ¶
SetPeerConnectedCallback sets a callback function to be called when a new peer connects
func (*Node) SetTopicHandler ¶
SetTopicHandler sets a message handler for the specified topic.
func (*Node) Start ¶
func (s *Node) Start(ctx context.Context, streamHandler func(network.Stream), topicNames ...string) error
Start activates the P2P node and begins network operations. This method initializes peer discovery, topic subscriptions, and stream handlers. It performs several key operations: - Launches static peer connector to maintain connections with configured static peers - Starts peer discovery in a background goroutine to find and connect to network peers - Initializes the GossipSub protocol for pub/sub messaging - Sets up stream handlers for direct peer-to-peer communication
Parameters: - ctx: Context for controlling the start process and subsequent operations - streamHandler: Handler for incoming protocol streams (can be nil if not using direct streams) - topicNames: List of topic names to subscribe to for pub/sub messaging
The method is non-blocking for peer discovery but waits for GossipSub initialization to complete. Returns an error if any critical component fails to initialize.
func (*Node) UpdateBytesReceived ¶
UpdateBytesReceived updates the count of bytes received.
func (*Node) UpdateLastReceived ¶
func (s *Node) UpdateLastReceived()
UpdateLastReceived updates the timestamp of the last received message.
type NodeI ¶
type NodeI interface {
// Core lifecycle methods
Start(ctx context.Context, streamHandler func(network.Stream), topicNames ...string) error
Stop(ctx context.Context) error
// Topic-related methods
SetTopicHandler(ctx context.Context, topicName string, handler Handler) error
GetTopic(topicName string) *pubsub.Topic
Publish(ctx context.Context, topicName string, msgBytes []byte) error
// Peer management methods
HostID() peer.ID
ConnectedPeers() []PeerInfo
CurrentlyConnectedPeers() []PeerInfo
DisconnectPeer(ctx context.Context, peerID peer.ID) error
SendToPeer(ctx context.Context, pid peer.ID, msg []byte) error
SetPeerConnectedCallback(callback func(context.Context, peer.ID))
UpdatePeerHeight(peerID peer.ID, height int32)
// Stats methods
LastSend() time.Time
LastRecv() time.Time
BytesSent() uint64
BytesReceived() uint64
// Additional accessors needed by Server
GetProcessName() string
UpdateBytesReceived(bytesCount uint64)
UpdateLastReceived()
GetPeerIPs(peerID peer.ID) []string
}
NodeI defines the interface for P2P node functionality. This interface abstracts the concrete implementation to allow for better testability. It provides methods for managing core peer-to-peer networking operations, including node lifecycle management, topic subscription, peer discovery, and message propagation.
The interface is designed to be robust for both standard network operation and specialized testing scenarios. It encapsulates all libp2p functionality behind a clean API that integrates with BSV blockchain applications.
type PeerInfo ¶
type PeerInfo struct {
ID peer.ID
Addrs []multiaddr.Multiaddr
CurrentHeight int32
ConnTime *time.Time // Connection time (nil if not connected)
}
PeerInfo contains information about a connected peer.
type RejectedTxMessage ¶
type RejectedTxMessage struct {
TxID string // Identifier of the rejected transaction
Reason string // Reason for the transaction rejection
PeerID string // Identifier of the peer reporting the rejection
}
RejectedTxMessage notifies peers about a rejected transaction. This message is used to inform the network about transactions that have been rejected due to validation errors or other reasons, helping to prevent unnecessary retransmissions and optimize network traffic.
The message contains the transaction ID and the reason for rejection, enabling peers to update their transaction sets and avoid retransmitting the rejected transaction.
type SubtreeMessage ¶
type SubtreeMessage struct {
Hash string // Unique hash identifier of the subtree
DataHubURL string // URL where the subtree data can be retrieved
PeerID string // Identifier of the peer announcing the subtree
}
SubtreeMessage announces the availability of a subtree (transaction batch) to the network. In Teranode's architecture, subtrees represent collections of transactions that are processed and validated together. This message enables efficient distribution of transaction data across the P2P network.
The message allows nodes to:
- Discover new transaction batches
- Coordinate transaction processing
- Maintain network-wide transaction visibility
- Optimize bandwidth usage through selective downloading
Directories
¶
| Path | Synopsis |
|---|---|
|
Package main demonstrates basic usage of the go-p2p library
|
Package main demonstrates basic usage of the go-p2p library |
|
Package mocks provides mock implementations for P2P node interfaces used in testing.
|
Package mocks provides mock implementations for P2P node interfaces used in testing. |
