Rust SDK

High-performance Rust SDK with QUIC transport, async/await patterns, and zero-cost abstractions for system-level agent integration.

Why Rust?

Performance: Native speed with zero runtime overhead - up to 10x faster than interpreted languages
🔒 Memory Safety: No garbage collector, no data races - compile-time guarantees prevent common bugs
⚙️ Concurrency: Fearless concurrency with async/await and Tokio runtime - handle thousands of connections
📦 Small Binaries: Self-contained executables with no runtime dependencies - easy deployment

Installation

Add Opacus to your Cargo.toml:

[dependencies]
opacus-sdk = "1.0"
tokio = { version = "1.36", features = ["full"] }

Quick Start

Basic Client Example

use opacus_sdk::{OpacusClient, AgentMetadata};
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box> {
    // Initialize client
    let client = OpacusClient::new(
        "https://evmrpc-testnet.0g.ai",
        "0x5FbDB2315678afecb367f032d93F642f64180aa3",
        std::env::var("PRIVATE_KEY")?
    ).await?;
    
    // Register agent
    let metadata = AgentMetadata {
        name: "RustAgent".to_string(),
        version: "1.0.0".to_string(),
        capabilities: vec![
            "data-processing".to_string(),
            "ml-inference".to_string()
        ],
    };
    
    let agent_id = client.register_agent(metadata).await?;
    println!("✅ Agent registered: {}", agent_id);
    
    Ok(())
}

QUIC Transport Architecture

🚀 What is QUIC?

QUIC (Quick UDP Internet Connections) is a modern transport protocol that combines the reliability of TCP with the speed of UDP. Built into HTTP/3, it offers:

  • 0-RTT connection establishment (instant reconnects)
  • Multiplexed streams without head-of-line blocking
  • Built-in TLS 1.3 encryption
  • Connection migration (survive IP changes)
QUIC vs Traditional TCP Comparison Traditional TCP Connection Setup 1. TCP Handshake (SYN, SYN-ACK, ACK) 2. TLS Handshake (ClientHello, etc.) ⏱️ Total: 2-3 RTT Data Transfer ❌ Single stream ❌ Head-of-line blocking ❌ Connection drops on IP change Performance Throughput: Good Latency: High (multiple RTTs) Packet Loss Impact: Severe QUIC (Opacus) Connection Setup 1. Combined crypto + transport handshake 2. 0-RTT for known servers ⚡ Total: 0-1 RTT (up to 3x faster) Data Transfer ✅ Multiple independent streams ✅ Per-stream flow control ✅ Connection migration (same ID) Performance Throughput: Excellent (multiplexing) Latency: Minimal (0-RTT) Packet Loss Impact: Isolated per-stream

Core API Reference

OpacusClient

Main client for interacting with Opacus Protocol:

pub struct OpacusClient {
    // Internal fields...
}

impl OpacusClient {
    /// Create new client instance
    pub async fn new(
        rpc_url: &str,
        contract_address: &str,
        private_key: String
    ) -> Result;
    
    /// Register a new AI agent
    pub async fn register_agent(
        &self,
        metadata: AgentMetadata
    ) -> Result;
    
    /// Get agent information
    pub async fn get_agent(
        &self,
        agent_id: &str
    ) -> Result;
    
    /// Send encrypted message to another agent
    pub async fn send_message(
        &self,
        to: &str,
        data: Vec
    ) -> Result<(), OpacusError>;
}

QUIC Transport Example

Establish high-performance QUIC connection:

use opacus_sdk::transport::QuicTransport;
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> Result<(), Box> {
    // Create QUIC transport
    let transport = QuicTransport::new(
        "0.0.0.0:4433".parse::()?,
        None // Auto-generate certificates
    ).await?;
    
    // Connect to relay server
    let conn = transport.connect(
        "relay.opacus.io:4433".parse()?
    ).await?;
    
    println!("✅ QUIC connection established");
    
    // Open bidirectional stream
    let (mut send, mut recv) = conn.open_bi().await?;
    
    // Send data
    send.write_all(b"Hello from Rust!").await?;
    send.finish().await?;
    
    // Receive response
    let response = recv.read_to_end(1024).await?;
    println!("Received: {:?}", String::from_utf8(response)?);
    
    Ok(())
}

Advanced Features

Relay Server

Run your own QUIC relay for agent communication:

use opacus_sdk::relay::RelayServer;

#[tokio::main]
async fn main() -> Result<(), Box> {
    // Create relay server
    let mut relay = RelayServer::new(4433);
    
    // Start listening
    relay.start().await?;
    
    println!("🚀 Relay server listening on port 4433");
    
    // Server runs until Ctrl+C
    tokio::signal::ctrl_c().await?;
    println!("Shutting down...");
    
    Ok(())
}

Cryptographic Operations

Key Generation

use opacus_sdk::crypto::KeyManager;

// Generate Ed25519 keypair (signing)
let key_manager = KeyManager::new();
let ed_keypair = key_manager.generate_ed25519();
let ed_public = ed_keypair.verifying_key().to_bytes();

println!("Ed25519 Public Key: {}", hex::encode(ed_public));

// Generate X25519 keypair (encryption)
let x_keypair = key_manager.generate_x25519();
let x_public = x_keypair.public_key().as_bytes();

println!("X25519 Public Key: {}", hex::encode(x_public));

Message Signing & Verification

use opacus_sdk::crypto::SecurityManager;
use ed25519_dalek::SigningKey;

let security = SecurityManager::new();

// Sign message
let message = b"Important agent data";
let signing_key = SigningKey::from_bytes(&private_key);
let signature = security.sign_message(message, &signing_key)?;

println!("Signature: {}", hex::encode(signature.to_bytes()));

// Verify signature
let is_valid = security.verify_signature(
    message,
    &signature,
    &signing_key.verifying_key()
)?;

assert!(is_valid);
println!("✅ Signature verified!");

End-to-End Encryption

use opacus_sdk::crypto::SecurityManager;

let security = SecurityManager::new();

// Alice wants to send encrypted message to Bob
let alice_secret = x25519_dalek::StaticSecret::random();
let bob_public = x25519_dalek::PublicKey::from([/* Bob's public key */]);

// Derive shared secret (ECDH)
let shared = alice_secret.diffie_hellman(&bob_public);

// Encrypt message
let plaintext = b"Secret agent communication";
let encrypted = security.encrypt_message(
    plaintext,
    shared.as_bytes()
)?;

println!("Encrypted: {}", hex::encode(&encrypted));

// Bob decrypts with his private key
let bob_secret = x25519_dalek::StaticSecret::random();
let alice_public = x25519_dalek::PublicKey::from(
    alice_secret.to_bytes()
);

let shared_bob = bob_secret.diffie_hellman(&alice_public);
let decrypted = security.decrypt_message(
    &encrypted,
    shared_bob.as_bytes()
)?;

assert_eq!(plaintext, decrypted.as_slice());
println!("✅ Message decrypted: {}", String::from_utf8(decrypted)?);

Performance Optimization

🔧

Build Flags

Optimize for production:
cargo build --release
Enables LTO and max optimization

⚙️

Async Runtime

Tokio multi-threaded:
Handles 10,000+ concurrent connections
Work-stealing scheduler

📊

Memory Usage

Zero-copy operations:
Bytes for efficient buffer management
~10MB base footprint

🚀

Benchmarks

Message throughput:
50,000+ msg/sec
0.02ms average latency

Error Handling

Opacus uses Result types with custom error enum:

#[derive(Debug, thiserror::Error)]
pub enum OpacusError {
    #[error("Network error: {0}")]
    Network(#[from] std::io::Error),
    
    #[error("Cryptography error: {0}")]
    Crypto(String),
    
    #[error("Contract error: {0}")]
    Contract(String),
    
    #[error("Invalid agent ID: {0}")]
    InvalidAgent(String),
}

// Usage
match client.register_agent(metadata).await {
    Ok(agent_id) => println!("Success: {}", agent_id),
    Err(OpacusError::Network(e)) => {
        eprintln!("Network issue: {}", e);
    }
    Err(OpacusError::Crypto(msg)) => {
        eprintln!("Crypto problem: {}", msg);
    }
    Err(e) => eprintln!("Other error: {}", e),
}

Testing

Unit Tests

#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_agent_registration() {
        let client = OpacusClient::new(
            "http://localhost:8545",
            "0x...",
            "test_key".to_string()
        ).await.unwrap();
        
        let metadata = AgentMetadata {
            name: "TestAgent".to_string(),
            version: "0.1.0".to_string(),
            capabilities: vec![],
        };
        
        let result = client.register_agent(metadata).await;
        assert!(result.is_ok());
    }
}

Integration Tests

// tests/integration_test.rs
use opacus_sdk::OpacusClient;

#[tokio::test]
async fn test_full_flow() {
    // Setup
    let client_a = OpacusClient::new(/*...*/).await.unwrap();
    let client_b = OpacusClient::new(/*...*/).await.unwrap();
    
    // Register agents
    let agent_a = client_a.register_agent(/*...*/).await.unwrap();
    let agent_b = client_b.register_agent(/*...*/).await.unwrap();
    
    // Send message
    client_a.send_message(&agent_b, b"test").await.unwrap();
    
    // Verify receipt
    // ... assertions
}

✅ Production Ready

The Rust SDK is battle-tested and production-ready. It powers high-throughput agent communication in real-world deployments, handling millions of messages per day with sub-millisecond latency.

Examples

Check out complete examples in the repository:

Run examples with:

cargo run --example client
cargo run --example relay