Skip to content

C# implementation of various LibP2P standards

License

Notifications You must be signed in to change notification settings

ponzienjoyer/PonziTech.LibP2P

Repository files navigation

PonziTech.LibP2P

Build Status License: MIT

A .NET 10.0 implementation of core libp2p protocols for building robust peer-to-peer applications.

Overview

libp2p is a modular network stack for peer-to-peer applications. This repository provides high-performance, production-ready implementations of key libp2p protocols in C#/.NET.

Implemented Protocols

✅ GossipSub v1.0 (PubSub)

NuGet

An extensible baseline pubsub protocol for efficient message propagation in distributed networks.

  • Topic Meshes: Overlay networks for each topic with controlled peer degrees
  • Gossip Propagation: Efficient message spreading through controlled amplification
  • Peer Scoring: Dynamic peer quality assessment to maintain network health
  • Heartbeat Protocol: Periodic maintenance for mesh optimization

📖 Specification | 📦 NuGet Package

✅ Kademlia DHT

NuGet

Distributed hash table for peer routing and content discovery with XOR-based distance metric.

  • Peer Routing: Iterative lookup to find peers by ID with alpha concurrency
  • Value Storage: Distributed key-value store with replication
  • Content Discovery: Provider records for content-addressable data
  • K-Bucket Routing: XOR distance-based routing table with LRU eviction

📖 Specification | 📦 NuGet Package

Future Work

🔄 Under Consideration

  • pnet: Private network support
  • relay/dcutr: Circuit relay and direct connection upgrade
  • yamux: Stream multiplexer
  • mdns: Local peer discovery

Features

General

  • ✅ Built on modern .NET 10.0 LTS with async/await patterns
  • ✅ Comprehensive logging support via Microsoft.Extensions.Logging
  • ✅ High-performance implementations optimized for throughput and latency
  • ✅ Modular architecture - use only the protocols you need
  • ✅ Extensive test coverage
  • ✅ Production-ready and actively maintained

GossipSub Specific

  • ✅ Full GossipSub v1.0 protocol implementation
  • ✅ Peer scoring and reputation management
  • ✅ Message validation and deduplication
  • ✅ Topic-based subscription management
  • ✅ Configurable parameters for different network profiles
  • ✅ High-performance asynchronous message processing

Kademlia DHT Specific

  • ✅ Full Kademlia DHT implementation with XOR distance metric
  • ✅ K-bucket routing table with dynamic splitting
  • ✅ Iterative peer and value lookups with alpha concurrency
  • ✅ Distributed value storage with replication
  • ✅ Provider records for content discovery
  • ✅ Client and server mode support
  • ✅ Thread-safe concurrent operations

Installation

Full Suite (Recommended)

Install all libp2p protocols with a single command:

# Stable release
dotnet add package PonziTech.LibP2P

# Pre-release (latest from main)
dotnet add package PonziTech.LibP2P --prerelease

Individual Protocols

Install only the protocols you need:

# GossipSub only
dotnet add package PonziTech.LibP2P.GossipSub

# Kademlia DHT only
dotnet add package PonziTech.LibP2P.Kademlia

📖 See VERSIONING.md for details on our release strategy and how versions work.

GitHub Packages Configuration

You'll need to configure GitHub Packages as a NuGet source. Add this to your nuget.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="github" value="https://nuget.pkg.github.com/PonziEnjoyer/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <github>
      <add key="Username" value="YOUR_GITHUB_USERNAME" />
      <add key="ClearTextPassword" value="YOUR_GITHUB_PAT" />
    </github>
  </packageSourceCredentials>
</configuration>

Quick Start

GossipSub PubSub Example

using PonziTech.LibP2P.GossipSub;
using Microsoft.Extensions.Logging;

// Create a logger factory
var loggerFactory = LoggerFactory.Create(builder =>
    builder.AddConsole());

// Configure GossipSub options
var options = new GossipSubOptions
{
    // Customize parameters as needed
};

// Create a GossipSub router
var router = new GossipSubRouter(options, loggerFactory);

// Subscribe to a topic
await router.SubscribeAsync("my-topic");

// Publish a message
var message = new GossipSubMessage
{
    Topic = "my-topic",
    Data = Encoding.UTF8.GetBytes("Hello, GossipSub!")
};
await router.PublishAsync(message);

// Handle incoming messages
router.OnMessage += (sender, msg) =>
{
    var data = Encoding.UTF8.GetString(msg.Data);
    Console.WriteLine($"Received on {msg.Topic}: {data}");
};

Kademlia DHT Example

using PonziTech.LibP2P.Kademlia;

// Create a DHT node
var localId = KademliaId.Random();
var options = new KademliaOptions
{
    K = 20,          // Replication factor
    Alpha = 10,      // Concurrency
};

var dht = new KademliaDht(localId, options);

// Store a value in the DHT
var key = Encoding.UTF8.GetBytes("my-key");
var value = Encoding.UTF8.GetBytes("my-value");
await dht.PutValueAsync(key, value);

// Retrieve a value from the DHT
var retrievedValue = await dht.GetValueAsync(key);

// Advertise that you provide content
var contentHash = KademliaId.FromKey("content-identifier").ToBytes();
await dht.ProvideAsync(contentHash);

// Find providers of content
var providers = await dht.FindProvidersAsync(contentHash);
foreach (var provider in providers)
{
    Console.WriteLine($"Provider: {provider.PeerId}");
}

// Find a specific peer by ID
var targetPeerId = KademliaId.Random();
var closestPeers = await dht.FindNodeAsync(targetPeerId);

Repository Structure

PonziTech.LibP2P/
├── src/
│   ├── PonziTech.LibP2P/                 # Metapackage (contains all protocols)
│   ├── PonziTech.LibP2P.GossipSub/       # GossipSub v1.0 implementation
│   ├── PonziTech.LibP2P.Kademlia/        # Kademlia DHT implementation
│   └── [future protocols...]             # relay, pnet, yamux, etc.
├── tests/
│   ├── PonziTech.LibP2P.GossipSub.Tests/
│   ├── PonziTech.LibP2P.Kademlia.Tests/
│   └── [future test projects...]
├── specs/                                # Protocol specifications
├── .github/workflows/                    # CI/CD pipelines
└── docs/                                 # Documentation

GossipSub Architecture

  • GossipSubRouter: Core routing logic and protocol orchestration
  • MessageProcessor: Message validation, deduplication, and processing
  • TopicManager: Topic subscription and mesh management
  • ConnectionManager: Peer connection lifecycle management
  • PeerScoreCalculator: Peer reputation and scoring system
  • HeartbeatProcessor: Periodic mesh maintenance and optimization
  • MessageCache: Recent message storage for gossip propagation

Kademlia DHT Architecture

  • KademliaDht: Main DHT router and public API
  • RoutingTable: K-bucket based routing table with XOR distance
  • KBucket: Individual routing table bucket with LRU eviction
  • DataStore: Local record and provider storage
  • PeerLookup: Iterative lookup algorithm with alpha concurrency
  • DhtMessage: Protocol message types and serialization
  • KademliaId: 256-bit peer/content identifiers with XOR distance

Configuration

Customize the protocol behavior through GossipSubOptions:

var options = new GossipSubOptions
{
    // Mesh configuration
    D = 6,              // Desired mesh degree
    DLow = 4,           // Lower bound for mesh degree
    DHigh = 12,         // Upper bound for mesh degree

    // Timing parameters
    HeartbeatInterval = TimeSpan.FromSeconds(1),

    // Gossip parameters
    Gossip = 3,         // Number of peers to gossip to

    // And more...
};

See the configuration documentation for details on all available parameters.

Protocol Specification

This implementation follows the GossipSub v1.0 specification from the libp2p project. Key protocol features include:

  • Mesh-based Topology: Each topic maintains a mesh overlay with degree between D_low and D_high
  • Gossip Propagation: Metadata gossip to peers outside the mesh for message discovery
  • Peer Exchange: IHAVE/IWANT control messages for efficient message retrieval
  • Graft/Prune: Dynamic mesh membership management
  • Peer Scoring: Reputation system to incentivize good behavior and penalize misbehavior

Performance

The implementation is optimized for:

  • High Throughput: Efficient message processing with minimal allocations
  • Low Latency: Fast message propagation through optimized mesh topology
  • Scalability: Handles large numbers of topics and peers efficiently
  • Memory Efficiency: Bounded message caches with automatic cleanup

Development

Prerequisites

  • .NET 10.0 SDK or later
  • Git

Building

git clone https://github.com/PonziEnjoyer/PonziTech.LibP2P.git
cd PonziTech.LibP2P
dotnet build

Testing

dotnet test

Contributing

We welcome contributions! Please see our Contributing Guide for details on:

  • Reporting issues
  • Submitting pull requests
  • Coding standards
  • Development workflow

Roadmap

Near Term

  • Kademlia DHT implementation for peer and content routing ✅
  • GossipSub v1.1 support (improved scoring and attack resistance)
  • Message signing and validation for GossipSub
  • Performance benchmarks and optimizations
  • Interoperability testing with go-libp2p and js-libp2p

Future Protocols (Based on Need)

  • pnet: Private network support
  • relay/dcutr: Circuit relay and direct connection upgrade
  • yamux: Stream multiplexer
  • mdns: Local peer discovery
  • Additional protocols as needed

General Improvements

  • Integration examples with popular libp2p implementations
  • Cross-implementation interoperability tests
  • Comprehensive documentation and guides

Resources

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • The libp2p community for the GossipSub specification
  • Protocol Labs for pioneering work in P2P networking
  • Contributors to this implementation

There is no meme, I love you 🤍

About

C# implementation of various LibP2P standards

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages