Help us shape the future of Go! Take the 2026 Go Developer Survey

p2p

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2025 License: MIT Imports: 27 Imported by: 2

README

🚀 go-p2p

CI / CD Quality & Security Docs & Meta Community
Latest Release
Build Status
CodeQL
SonarCloud
Go Report Card
Code Coverage
OpenSSF Scorecard
Security policy
Go version
Go docs
AGENTS.md rules
Makefile Supported
Dependabot
Contributors
Last commit
Sponsor

🗂️ Table of Contents


🧩 What's Inside

go-p2p is a comprehensive peer-to-peer networking library for BSV blockchain nodes, built on top of libp2p. It provides robust networking capabilities for distributed blockchain applications with support for both public and private networks.

Core Components
  • P2PNode - The main networking node implementation that manages peer connections, message routing, and network discovery
  • P2PNodeI - Interface defining the complete P2P networking API for testability and modularity
  • P2PConfig - Configuration structure for network parameters, bootstrap peers, and security settings
  • Handler - Function type for processing incoming topic messages in pub/sub communications
Key Features
  • Peer Discovery - Automatic peer discovery using Kademlia DHT (Distributed Hash Table)
  • Pub/Sub Messaging - Topic-based message distribution using GossipSub protocol
  • Direct Peer Communication - Stream-based messaging for direct peer-to-peer communication
  • Private Networks - Support for isolated private networks using pre-shared keys
  • Connection Management - Automatic connection handling, retry logic, and peer lifecycle management
  • Metrics & Monitoring - Built-in bandwidth tracking, peer statistics, and connection monitoring
  • Security - Message signing/verification, peer authentication, and encrypted communications
Network Modes
  • Public Network - Connect to the global IPFS DHT for open peer discovery
  • Private Network - Create isolated networks using shared keys for controlled environments
  • Hybrid Mode - Static peer connections combined with dynamic discovery

📦 Installation

go-p2p requires a supported release of Go.

go get -u github.com/bsv-blockchain/go-p2p

📚 Documentation

Good to know: go-p2p ships with zero runtime dependencies.
The only external package we use is testify—and that's strictly for tests.


Repository Features
  • Continuous Integration on Autopilot with GitHub Actions – every push is built, tested, and reported in minutes.
  • Pull‑Request Flow That Merges Itself thanks to auto‑merge and hands‑free Dependabot auto‑merge.
  • One‑Command Builds powered by battle‑tested Make targets for linting, testing, releases, and more.
  • First‑Class Dependency Management using native Go Modules.
  • Uniform Code Style via gofumpt plus zero‑noise linting with golangci‑lint.
  • Confidence‑Boosting Tests with testify, the Go race detector, crystal‑clear HTML coverage snapshots, and automatic uploads to Codecov.
  • Hands‑Free Releases delivered by GoReleaser whenever you create a new Tag.
  • Relentless Dependency & Vulnerability Scans via Dependabot, Nancy, and govulncheck.
  • Security Posture by Default with CodeQL, OpenSSF Scorecard, and secret‑leak detection via gitleaks.
  • Automatic Syndication to pkg.go.dev on every release for instant godoc visibility.
  • Polished Community Experience using rich templates for Issues & PRs.
  • All the Right Meta Files (LICENSE, CONTRIBUTING.md, CODE_OF_CONDUCT.md, SUPPORT.md, SECURITY.md) pre‑filled and ready.
  • Code Ownership clarified through a CODEOWNERS file, keeping reviews fast and focused.
  • Zero‑Noise Dev Environments with tuned editor settings (.editorconfig) plus curated ignore files for VS Code, Docker, and Git.
  • Label Sync Magic: your repo labels stay in lock‑step with .github/labels.yml.
  • Friendly First PR Workflow – newcomers get a warm welcome thanks to a dedicated workflow.
  • Standards‑Compliant Docs adhering to the standard‑readme spec.
  • Instant Cloud Workspaces via Gitpod – spin up a fully configured dev environment with automatic linting and tests.
  • Out‑of‑the‑Box VS Code Happiness with a preconfigured Go workspace and .vscode folder with all the right settings.
  • Optional Release Broadcasts to your community via Slack, Discord, or Twitter – plug in your webhook.
  • AI Compliance Playbook – machine‑readable guidelines (AGENTS.md, CLAUDE.md, .cursorrules, sweep.yaml) keep ChatGPT, Claude, Cursor & Sweep aligned with your repo’s rules.
  • Pre-commit Hooks for Consistency powered by pre-commit and the .pre-commit-config.yaml file—run the same formatting, linting, and tests before every commit, just like CI.
  • Automated Hook Updates keep the .pre-commit-config.yaml current via a weekly workflow.
  • DevContainers for Instant Onboarding – Launch a ready-to-code environment in seconds with VS Code DevContainers and the included .devcontainer.json config.
Repository File Glossary

This glossary describes each tracked file in the repository and notes if it is required for GitHub or another external service.

File Path Description Service
.cursorrules Rules for Cursor AI integrations Cursor
.devcontainer.json VS Code dev or GitHub container configuration VS Code & GitHub
.dockerignore Paths ignored by Docker builds Docker
.editorconfig Editor configuration defaults Editor
.gitattributes Git attributes and export settings Git
.github/.env.shared Shared environment variables for GitHub Actions GitHub Actions
.github/AGENTS.md Contribution rules and guidelines GitHub
.github/CLAUDE.md Claude agent instructions Claude
.github/CODEOWNERS Code ownership declarations for GitHub GitHub
.github/CODE_OF_CONDUCT.md Community behavior standards GitHub
.github/CODE_STANDARDS.md Coding style guide GitHub
.github/CONTRIBUTING.md How to contribute to the project GitHub
.github/FUNDING.yml Funding links displayed by GitHub GitHub
.github/ISSUE_TEMPLATE/bug_report.yml Issue template for bug reports GitHub
.github/ISSUE_TEMPLATE/feature_request.yml Issue template for feature requests GitHub
.github/ISSUE_TEMPLATE/question.yml Issue template for questions GitHub
.github/SECURITY.md Security policy GitHub
.github/SUPPORT.md Support guidelines GitHub
.github/actions/warm-cache/action.yml Action to warm GitHub Actions cache GitHub Actions
.github/dependabot.yml Dependabot configuration GitHub
.github/labels.yml Repository label definitions GitHub
.github/pull_request_template.md Pull request description template GitHub
.github/sweep.yaml Sweep AI configuration Sweep AI
.github/workflows/auto-merge-on-approval.yml Workflow for automatic merges GitHub Actions
.github/workflows/codeql-analysis.yml CodeQL security analysis workflow GitHub Actions
.github/workflows/dependabot-auto-merge.yml Auto merge Dependabot PRs GitHub Actions
.github/workflows/fortress.yml Fortress security & testing workflow GitHub Actions
.github/workflows/pull-request-management.yml Pull request triage workflow GitHub Actions
.github/workflows/scorecard.yml OpenSSF Scorecard workflow GitHub Actions
.github/workflows/stale.yml Close stale issues and PRs GitHub Actions
.github/workflows/sync-labels.yml Sync repository labels GitHub Actions
.github/workflows/update-python-dependencies.yml Update Python dependencies for pre-commit hooks GitHub Actions
.github/workflows/update-pre-commit-hooks.yml Automatically update pre-commit hooks GitHub Actions
.gitignore Files and directories Git should ignore Git
.gitpod.yml Gitpod workspace configuration Gitpod
.golangci.json GolangCI-Lint configuration GolangCI-Lint
.goreleaser.yml GoReleaser configuration for release automation GoReleaser
.make/common.mk Shared make tasks Make
.make/go.mk Go-specific make tasks Make
.make/temp.mk Temporary makefile for internal use Make
.pre-commit-config.yaml Pre-commit hooks configuration Pre-commit
.vscode/extensions.json Recommended VS Code extensions VS Code
.vscode/launch.json VS Code debugging configuration VS Code
.vscode/settings.json VS Code workspace settings VS Code
.vscode/tasks.json VS Code tasks configuration VS Code
Dockerfile Docker image build instructions Docker
LICENSE Project license Yours!
Makefile Build and lint automation Make
README.md Project overview and usage Yours!
codecov.yml Codecov upload configuration Codecov
examples/example.go Example usage of the P2P library None
go.mod Go module definition Go
go.sum Dependency checksums generated by Go Go
interface.go P2P node interface definition Yours!
node.go Main P2P node implementation Yours!
p2p.go P2P package entry point Yours!
types.go P2P configuration and data types Yours!
Library Deployment

This project uses goreleaser for streamlined binary and library deployment to GitHub. To get started, install it via:

brew install goreleaser

The release process is defined in the .goreleaser.yml configuration file.

To generate a snapshot (non-versioned) release for testing purposes, run:

make release-snap

Then create and push a new Git tag using:

make tag version=x.y.z

This process ensures consistent, repeatable releases with properly versioned artifacts and citation metadata.

Makefile Commands

View all makefile commands

make help

List of all current commands:

bench                 ## Run all benchmarks in the Go application
build-go              ## Build the Go application (locally)
citation              ## Update version in CITATION.cff (use version=X.Y.Z)
clean-mods            ## Remove all the Go mod cache
coverage              ## Show test coverage
diff                  ## Show git diff and fail if uncommitted changes exist
fumpt                 ## Run fumpt to format Go code
generate              ## Run go generate in the base of the repo
godocs                ## Trigger GoDocs tag sync
govulncheck-install   ## Install govulncheck (pass VERSION= to override)
govulncheck           ## Scan for vulnerabilities
help                  ## Display this help message
install-go            ## Install using go install with specific version
install-releaser      ## Install GoReleaser
install-stdlib        ## Install the Go standard library for the host platform
install-template      ## Kick-start a fresh copy of go-p2p (run once!)
install               ## Install the application binary
lint-version          ## Show the golangci-lint version
lint                  ## Run the golangci-lint application (install if not found)
loc                   ## Total lines of code table
mod-download          ## Download Go module dependencies
mod-tidy              ## Clean up go.mod and go.sum
pre-build             ## Pre-build all packages to warm cache
release-snap          ## Build snapshot binaries
release-test          ## Run release dry-run (no publish)
release               ## Run production release (requires github_token)
tag-remove            ## Remove local and remote tag (use version=X.Y.Z)
tag-update            ## Force-update tag to current commit (use version=X.Y.Z)
tag                   ## Create and push a new tag (use version=X.Y.Z)
test-ci-no-race       ## CI test suite without race detector
test-ci               ## CI test runs tests with race detection and coverage (no lint - handled separately)
test-cover-race       ## Runs unit tests with race detector and outputs coverage
test-cover            ## Unit tests with coverage (no race)
test-fuzz             ## Run fuzz tests only (no unit tests)
test-no-lint          ## Run only tests (no lint)
test-parallel         ## Run tests in parallel (faster for large repos)
test-race             ## Unit tests with race detector (no coverage)
test-short            ## Run tests excluding integration tests (no lint)
test                  ## Default testing uses lint + unit tests (fast)
uninstall             ## Uninstall the Go binary
update-linter         ## Upgrade golangci-lint (macOS only)
update-releaser       ## Reinstall GoReleaser
update                ## Update dependencies
vet-parallel          ## Run go vet in parallel (faster for large repos)
vet                   ## Run go vet only on your module packages
GitHub Workflows
🎛️ The Workflow Control Center

All GitHub Actions workflows in this repository are powered by a single configuration file: .env.shared – your one-stop shop for tweaking CI/CD behavior without touching a single YAML file! 🎯

This magical file controls everything from:

  • 🚀 Go version matrix (test on multiple versions or just one)
  • 🏃 Runner selection (Ubuntu or macOS, your wallet decides)
  • 🔬 Feature toggles (coverage, fuzzing, linting, race detection)
  • 🛡️ Security tool versions (gitleaks, nancy, govulncheck)
  • 🤖 Auto-merge behaviors (how aggressive should the bots be?)
  • 🏷️ PR management rules (size labels, auto-assignment, welcome messages)

Pro tip: Want to disable code coverage? Just flip ENABLE_CODE_COVERAGE=false in .env.shared and push. No YAML archaeology required!


Workflow Name Description
auto-merge-on-approval.yml Automatically merges PRs after approval and all required checks, following strict rules.
codeql-analysis.yml Analyzes code for security vulnerabilities using GitHub CodeQL.
dependabot-auto-merge.yml Automatically merges Dependabot PRs that meet all requirements.
fortress.yml Runs the GoFortress security and testing workflow, including linting, testing, releasing, and vulnerability checks.
pull-request-management.yml Labels PRs by branch prefix, assigns a default user if none is assigned, and welcomes new contributors with a comment.
scorecard.yml Runs OpenSSF Scorecard to assess supply chain security.
stale.yml Warns about (and optionally closes) inactive issues and PRs on a schedule or manual trigger.
sync-labels.yml Keeps GitHub labels in sync with the declarative manifest at .github/labels.yml.
update-python-dependencies.yml Updates Python dependencies for pre-commit hooks in the repository.
update-pre-commit-hooks.yml Automatically update versions for pre-commit hooks
Updating Dependencies

To update all dependencies (Go modules, linters, and related tools), run:

make update

This command ensures all dependencies are brought up to date in a single step, including Go modules and any tools managed by the Makefile. It is the recommended way to keep your development environment and CI in sync with the latest versions.

Pre-commit Hooks

Set up the optional pre-commit hooks to run the same formatting, linting, and tests defined in AGENTS.md before every commit:

pip install pre-commit
pre-commit install

The hooks are configured in .pre-commit-config.yaml and mirror the CI pipeline.


🧪 Examples & Tests

All unit tests and examples run via GitHub Actions and use Go version 1.24.x. View the configuration file.

Run all tests (fast):

make test

Run all tests with race detector (slower):

make test-race

⚡ Benchmarks

P2P networking benchmarks can be run using:

make bench

Note: Comprehensive benchmarks for P2P operations (peer discovery, message throughput, connection establishment) are planned for future releases. The current focus is on correctness and stability of the networking implementation.


🛠️ Code Standards

Read more about this Go project's code standards.


🤖 AI Compliance

This project documents expectations for AI assistants using a few dedicated files:

  • AGENTS.md — canonical rules for coding style, workflows, and pull requests used by Codex.
  • CLAUDE.md — quick checklist for the Claude agent.
  • .cursorrules — machine-readable subset of the policies for Cursor and similar tools.
  • sweep.yaml — rules for Sweep, a tool for code review and pull request management.

Edit AGENTS.md first when adjusting these policies, and keep the other files in sync within the same pull request.


👥 Maintainers

Siggi
Siggi

🤝 Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏

Stars


📝 License

License

Documentation

Index

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
	SharedKey          string   // Shared key for private network 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

type Handler func(ctx context.Context, msg []byte, from string)

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:

  1. Connecting peer sends a "version" message with their current state
  2. Receiving peer responds with a "verack" message to acknowledge
  3. 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 NewP2PNode

func NewP2PNode(ctx context.Context, logger *logrus.Logger, config Config) (*Node, error)

NewP2PNode 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

func (s *Node) BytesReceived() uint64

BytesReceived returns the total number of bytes received by this node.

func (*Node) BytesSent

func (s *Node) BytesSent() uint64

BytesSent returns the total number of bytes sent by this node.

func (*Node) ConnectedPeers

func (s *Node) ConnectedPeers() []PeerInfo

ConnectedPeers returns information about all connected peers.

func (*Node) CurrentlyConnectedPeers

func (s *Node) CurrentlyConnectedPeers() []PeerInfo

CurrentlyConnectedPeers returns information about currently connected peers.

func (*Node) DisconnectPeer

func (s *Node) DisconnectPeer(_ context.Context, peerID peer.ID) error

DisconnectPeer disconnects from the specified peer.

func (*Node) GetPeerIPs

func (s *Node) GetPeerIPs(peerID peer.ID) []string

GetPeerIPs returns the IP addresses for a specific peer.

func (*Node) GetProcessName

func (s *Node) GetProcessName() string

GetProcessName returns the name of the current process.

func (*Node) GetTopic

func (s *Node) GetTopic(topicName string) *pubsub.Topic

GetTopic returns the topic instance for the given topic name.

func (*Node) HostID

func (s *Node) HostID() peer.ID

HostID returns the peer ID of this node.

func (*Node) LastRecv

func (s *Node) LastRecv() time.Time

LastRecv returns the timestamp of the last message received.

func (*Node) LastSend

func (s *Node) LastSend() time.Time

LastSend returns the timestamp of the last message sent.

func (*Node) Publish

func (s *Node) Publish(ctx context.Context, topicName string, msgBytes []byte) error

Publish sends a message to all subscribers of the specified topic.

func (*Node) SendToPeer

func (s *Node) SendToPeer(ctx context.Context, peerID peer.ID, msg []byte) (err error)

SendToPeer sends a message to a peer. It will attempt to connect to the peer if not already connected.

func (*Node) SetPeerConnectedCallback

func (s *Node) SetPeerConnectedCallback(callback func(context.Context, peer.ID))

SetPeerConnectedCallback sets a callback function to be called when a new peer connects

func (*Node) SetTopicHandler

func (s *Node) SetTopicHandler(ctx context.Context, topicName string, handler Handler) error

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) Stop

func (s *Node) Stop(_ context.Context) error

Stop gracefully shuts down the P2P node and closes all connections.

func (*Node) UpdateBytesReceived

func (s *Node) UpdateBytesReceived(bytesCount uint64)

UpdateBytesReceived updates the count of bytes received.

func (*Node) UpdateLastReceived

func (s *Node) UpdateLastReceived()

UpdateLastReceived updates the timestamp of the last received message.

func (*Node) UpdatePeerHeight

func (s *Node) UpdatePeerHeight(peerID peer.ID, height int32)

UpdatePeerHeight updates the blockchain height for a specific peer.

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.

Jump to

Keyboard shortcuts

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