tenzro-network
P2P networking layer for Tenzro Network — the AI verification and settlement protocol.
Overview
The tenzro-network crate provides the networking infrastructure for Tenzro Network, built on libp2p. It handles peer discovery, message propagation, and network topology management across the Tenzro Network protocol. This P2P layer enables communication between nodes running Tenzro Ledger (the L1 settlement layer with TNZO governance token).
Modules
8 modules: behaviour, config, discovery, error, gossip, message, peer_manager, service, transport
behaviour- TenzroBehaviour combining Gossipsub, Kademlia, Identify, Pingconfig- NetworkConfig for local/testnet/mainnetdiscovery- Peer discovery via DHT and mDNS, BootstrapConfigerror- NetworkError and Result typesgossip- GossipTopics, MessageDeduplicator, MessageValidation, TopicSubscriptionsmessage- NetworkMessage, MessagePayload with 11 message typespeer_manager- PeerManager, ValidatorRegistry, VALIDATOR_ONLY_TOPICS, reputation scoringservice- NetworkService trait, TenzroNetworkService implementationtransport- TCP and QUIC transport with Noise encryption
Features
- Gossipsub: Pub/sub messaging for blocks, transactions, consensus messages, and more
- Kademlia DHT: Distributed peer discovery and content routing
- Identify Protocol: Peer information exchange and capability discovery
- Ping Protocol: Connection health monitoring and keep-alive
- Peer Management: Reputation scoring, peer banning, and connection limits
- Message Validation: Automatic validation with timestamp checks, size limits, and age verification
- Multi-Transport: TCP and QUIC support with Noise encryption
- Validator Authentication: ValidatorRegistry trait with topic-based authorization (consensus/block/attestation topics)
Architecture
The network service uses an event loop pattern with async channels for communication:
┌─────────────────┐
│ Application │
│ Layer │
└────────┬────────┘
│ async channels
┌────────▼────────┐
│ NetworkService │ ← API Layer (trait-based)
└────────┬────────┘
│
┌────────▼────────┐
│ Event Loop │ ← libp2p Swarm
│ (background) │
└────────┬────────┘
│
┌────────▼────────┐
│ TenzroBehaviour│ ← Combines protocols:
│ │ - Gossipsub
│ │ - Kademlia
│ │ - Identify
│ │ - Ping
└─────────────────┘
Usage
Creating a Network Service
use ;
async
Subscribing to Topics
use ;
// Subscribe to blocks
let mut blocks_rx = network.subscribe.await?;
// Handle incoming messages
spawn;
Broadcasting Messages
use ;
// Create a message
let message = new;
// Broadcast to all peers on a topic
network.broadcast.await?;
Peer Management
// Get connected peers
let peers = network.connected_peers.await?;
println!;
// Get peer information
for peer_id in peers
// Ban a misbehaving peer
network.ban_peer.await?;
Gossipsub Topics
The network uses different topics for different message types (8 topics):
| Topic | Purpose |
|---|---|
tenzro/blocks |
Block propagation |
tenzro/transactions |
Transaction broadcasting |
tenzro/consensus |
Consensus messages (proposals, votes) - validator-only |
tenzro/attestations |
TEE attestation reports |
tenzro/models |
Model registration announcements |
tenzro/inference |
Inference requests and responses |
tenzro/status |
Node status and health checks |
tenzro/agents |
Agent-to-agent messages |
For testnet and mainnet, topics are prefixed:
- Testnet:
tenzro/testnet/blocks/1.0.0 - Mainnet:
tenzro/mainnet/blocks/1.0.0
Network Configurations
Local Development
let config = local;
- Listens on localhost only
- No bootstrap nodes
- mDNS enabled for local peer discovery
- Suitable for testing on a single machine
Testnet
let config = testnet;
- Connects to testnet bootstrap nodes
- Full DHT and gossipsub enabled
- Testnet-specific topics
Mainnet
let config = mainnet;
- Connects to mainnet bootstrap nodes
- Production settings
- Mainnet-specific topics
Custom Configuration
use NetworkConfig;
use Duration;
let config = NetworkConfig ;
Peer Discovery
The network supports multiple peer discovery mechanisms:
Kademlia DHT
- Distributed hash table for peer routing
- Random walks for discovering new peers
- Provider records for finding specific node types (validators, inference providers, etc.)
mDNS
- Local network peer discovery
- Enabled by default for development
- Automatically finds peers on the same LAN
Bootstrap Nodes
- Well-known nodes for initial connections
- Configured per network (testnet/mainnet)
- Used to bootstrap the DHT
Message Validation
All incoming messages are automatically validated:
- Timestamp validation: Messages must have recent timestamps (within 5 minutes)
- Message age: Messages older than 1 hour are rejected
- Size limits: Messages must be under 10MB
- Payload validation: Type-specific validation for each message type
Invalid messages result in reputation penalties for the sender.
Peer Reputation
Peers are assigned reputation scores based on their behavior:
- Good behavior: Valid messages, successful pings → +reputation
- Bad behavior: Invalid messages, failed pings → -reputation
- Auto-ban: Peers with reputation < -50 are automatically banned
- Bans: Temporary (1 hour default) or permanent
Validator Authentication
Validators are authenticated for consensus-critical topics via ValidatorRegistry trait:
authorize_peer_for_topic()checks validator status- Validator-only topics:
tenzro/consensus,tenzro/blocks(for block proposals),tenzro/attestations - Non-validators are rejected from these topics
Message Types (15 variants)
Ping/Pong- Health checksBlock(Block)/BlockRequest(Hash)/BlockResponse(Option<Block>)- Block propagation + targeted fetchTransaction(SignedTransaction)/TransactionRequest(Hash)/TransactionResponse(Option<SignedTransaction>)- Transaction broadcast + targeted fetchAttestation(AttestationMessage)- TEE attestationsModelRegistration(ModelRegistrationMessage)- Model announcementsInferenceRequest(InferenceRequestMessage)/InferenceResponse(InferenceResponseMessage)- Inference operationsStatus(StatusMessage)- Node statusProviderAnnouncement(ProviderAnnouncementMessage)- Provider registrationAgentAnnouncement(AgentAnnouncementMessage)- Agent discovery
Dependencies
tenzro-types- Shared typestenzro-crypto- Cryptographic primitiveslibp2p- P2P networking (Gossipsub, Kademlia, Identify, Ping)tokio- Async runtimeasync-trait- Async traitsserde,serde_json- Serializationthiserror- Error handlingtracing- Loggingfutures- Async utilitiesbytes,prost- Data encodingdashmap- Concurrent mapsuuid,chrono,sha2- Utilitiesparking_lot- High-performance locks
Test Coverage
3 unit tests + 1 doc test covering:
- Config validation
- Message serialization/deserialization
- Network service creation
Examples
See the examples/ directory:
basic_network.rs: Basic network setup and messaging
Run an example:
License
Licensed under either of:
- MIT license (LICENSE or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0 (LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
at your option.