Agent Mesh Architecture
ZAP + RNS + Consensus + x402 — high performance mesh collective intelligence for multi-agent coordination.
Vision
High Performance Mesh Collective Intelligence
The architecture separates full nodes (hanzod) from light nodes (agents):
- 1 hanzod per system: Full blockchain consensus node with global connectivity
- N light agents per system: Fast local agents connecting to hanzod via ZAP
- Global mesh: hanzod nodes connect worldwide via PQ RNS tunnels
┌────────────────────────────────────────────────────────────────────────────────────┐
│ GLOBAL MESH NETWORK │
├────────────────────────────────────────────────────────────────────────────────────┤
│ │
│ SYSTEM A SYSTEM B SYSTEM C │
│ ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────┐ │
│ │ hanzod │◄═══════►│ hanzod │◄═══════►│ hanzod │ │
│ │ (Full Node) │ PQ RNS │ (Full Node) │ PQ RNS │ (Full Node) │ │
│ │ ┌───────────┐ │ Tunnel │ ┌───────────┐ │ Tunnel │ │ │
│ │ │ Consensus │ │ │ │ Consensus │ │ │ │ │
│ │ │ + State │ │ │ │ + State │ │ │ │ │
│ │ └───────────┘ │ │ └───────────┘ │ │ │ │
│ └────────┬────────────┘ └────────┬────────────┘ └──────┬──────┘ │
│ │ZAP │ZAP │ZAP │
│ ┌────────┴────────┐ ┌────────┴────────┐ ┌──────┴──────┐ │
│ │ LIGHT AGENTS │ │ LIGHT AGENTS │ │LIGHT AGENTS │ │
│ │ (100+ agents) │ │ (100+ agents) │ │ (N agents) │ │
│ │ │ │ │ │ │ │
│ │ ┌───┐ ┌───┐ ┌───┐│ │ ┌───┐ ┌───┐ ┌───┐│ │ ┌───┐ ┌───┐ │ │
│ │ │CTO│ │UI │ │Dev││ │ │Ops│ │QA │ │Sec││ │ │ │ │ │ │ │
│ │ └───┘ └───┘ └───┘│ │ └───┘ └───┘ └───┘│ │ └───┘ └───┘ │ │
│ │ ┌───┐ ┌───┐ ┌───┐│ │ ┌───┐ ┌───┐ ┌───┐│ │ │ │
│ │ │Arc│ │Rvw│ │...││ │ │ │ │ │ │...││ │ │ │
│ │ └───┘ └───┘ └───┘│ │ └───┘ └───┘ └───┘│ │ │ │
│ └──────────────────┘ └──────────────────┘ └─────────────┘ │
│ │
│ ARCHITECTURE: │
│ • hanzod: Full blockchain node, global consensus, PQ RNS tunnels │
│ • Agents: Light nodes via ZAP, commit state to local hanzod │
│ • ZAP: Zero-copy binary RPC (10-100x faster than JSON-RPC) │
│ • PQ RNS: Post-quantum secure mesh routing, perfect forward secrecy │
│ • x402: Agent-to-agent micropayments over public internet │
│ • PoA: Proof of Authority when all nodes share same key │
│ │
│ NETWORKS: │
│ • Multiple parallel networks with unique consensus each │
│ • Local agents (100+) commit work through hanzod │
│ • Global state sync across all hanzod nodes │
│ │
└────────────────────────────────────────────────────────────────────────────────────┘Node Architecture
hanzod - Full Node
Each system runs exactly one hanzod instance - a full blockchain consensus node:
// hanzod/src/node.rs
/// Full Hanzo node - one per system
/// Handles global consensus, state sync, and agent coordination
pub struct HanzoFullNode {
/// Node identity (RNS destination)
identity: NodeIdentity,
/// Global consensus engine (BFT)
consensus: ConsensusEngine,
/// State machine with Merkle proofs
state: StateMachine,
/// ZAP server for local agents
zap_server: ZapServer,
/// RNS transport for global mesh
rns: RnsTransport,
/// Post-quantum tunnel manager
pq_tunnels: PqTunnelManager,
/// Connected light agents
agents: HashMap<AgentId, AgentConnection>,
/// Peer hanzod nodes
peers: HashMap<NodeId, PeerConnection>,
/// x402 payment processor
payments: PaymentProcessor,
}
impl HanzoFullNode {
/// Start hanzod
pub async fn start(config: NodeConfig) -> Result<Self> {
// Load or generate node identity
let identity = NodeIdentity::load_or_generate(&config.identity_path)?;
// Initialize consensus
let consensus = ConsensusEngine::new(config.consensus)?;
// Start ZAP server for local agents
let zap_server = ZapServer::bind(&config.zap_listen).await?;
// Initialize RNS for global connectivity
let rns = RnsTransport::new(&config.rns).await?;
// Establish PQ tunnels to known peers
let pq_tunnels = PqTunnelManager::new(&config.peers).await?;
let node = Self {
identity,
consensus,
state: StateMachine::new(),
zap_server,
rns,
pq_tunnels,
agents: HashMap::new(),
peers: HashMap::new(),
payments: PaymentProcessor::new(&config.payment)?,
};
// Connect to bootstrap peers
node.bootstrap(&config.bootstrap_nodes).await?;
// Start event loops
node.spawn_listeners().await?;
Ok(node)
}
/// Handle agent connection (light node)
pub async fn handle_agent_connect(&mut self, conn: ZapConnection) -> Result<AgentId> {
let agent = AgentConnection::new(conn).await?;
let agent_id = agent.id.clone();
// Register agent
self.agents.insert(agent_id.clone(), agent);
// Sync current state to agent
self.sync_state_to_agent(&agent_id).await?;
Ok(agent_id)
}
/// Receive commit from local agent
pub async fn receive_agent_commit(&mut self, agent_id: &AgentId, commit: AgentCommit) -> Result<()> {
// Verify commit signature
self.verify_agent_commit(&commit)?;
// Propose to consensus
let proposal = self.consensus.propose(commit.into()).await?;
// Broadcast to peers
self.broadcast_to_peers(proposal).await?;
Ok(())
}
/// Forward message between agents (local or remote)
pub async fn route_agent_message(&self, msg: AgentMessage) -> Result<()> {
// Check if destination is local
if let Some(agent) = self.agents.get(&msg.to) {
agent.send(msg).await?;
} else {
// Route through global mesh
self.route_global(msg).await?;
}
Ok(())
}
}Light Agent - hanzo-dev Agent
Each agent runs as a light node, connecting to local hanzod:
// agent-mesh/src/light_agent.rs
/// Light agent node - connects to local hanzod
/// Many agents per system, fast local communication
pub struct LightAgent {
/// Agent identity
identity: AgentIdentity,
/// Connection to local hanzod
hanzod: ZapClient,
/// Local state cache
state_cache: StateCache,
/// Agent role
role: AgentRole,
/// Tool registry (MCP tools)
tools: ToolRegistry,
/// Event handlers
handlers: EventHandlers,
}
impl LightAgent {
/// Connect to local hanzod
pub async fn connect(config: AgentConfig) -> Result<Self> {
// Generate or load identity
let identity = AgentIdentity::load_or_generate(&config.identity_path)?;
// Connect to local hanzod via ZAP
let hanzod = ZapClient::connect(&config.hanzod_addr).await?;
// Register with hanzod
let registration = hanzod.register(AgentRegistration {
identity: identity.public(),
role: config.role.clone(),
capabilities: config.capabilities.clone(),
}).await?;
// Sync initial state
let state_cache = hanzod.sync_state().await?;
Ok(Self {
identity,
hanzod,
state_cache,
role: config.role,
tools: ToolRegistry::default(),
handlers: EventHandlers::new(),
})
}
/// Commit work to hanzod (will be consensus-replicated globally)
pub async fn commit(&self, work: AgentWork) -> Result<CommitId> {
let commit = AgentCommit {
id: CommitId::new(),
agent: self.identity.public(),
work,
timestamp: Utc::now(),
signature: self.identity.sign(&work)?,
};
// Send to hanzod for global consensus
self.hanzod.commit(commit).await
}
/// Send message to another agent (local or remote)
pub async fn send(&self, to: &AgentId, msg: AgentPayload) -> Result<()> {
let message = AgentMessage {
id: MessageId::new(),
from: self.identity.id(),
to: to.clone(),
payload: msg,
timestamp: Utc::now(),
signature: self.identity.sign(&msg)?,
};
// Route through hanzod
self.hanzod.route_message(message).await
}
/// Subscribe to state updates
pub async fn subscribe_state(&mut self, topics: Vec<String>) -> Result<StateStream> {
self.hanzod.subscribe_state(topics).await
}
/// Get current global state (from cache or hanzod)
pub fn global_state(&self) -> &StateCache {
&self.state_cache
}
}Network Topology
GLOBAL MESH NETWORK
═══════════════════
INTERNET / PQ RNS TUNNELS
═══════════════════════════════════════════════════════════════════
║ ║ ║
║ ML-KEM + ML-DSA ║ ║
║ Perfect Forward ║ ║
║ Secrecy ║ ║
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ hanzod │ │ hanzod │ │ hanzod │
│ (Region A) │◄══► (Region B) │◄══► (Region C) │
│ │ │ │ │ │
│ • Full consensus│ │ • Full consensus│ │ • Full consensus│
│ • Global state │ │ • Global state │ │ • Global state │
│ • PQ RNS node │ │ • PQ RNS node │ │ • PQ RNS node │
│ • x402 payments │ │ • x402 payments │ │ • x402 payments │
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
│ │ │
│ ZAP (local) │ ZAP (local) │ ZAP (local)
│ < 1ms latency │ < 1ms latency │ < 1ms latency
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Light Agents │ │ Light Agents │ │ Light Agents │
│ │ │ │ │ │
│ 100+ per system │ │ 100+ per system │ │ 100+ per system │
│ │ │ │ │ │
│ • CTO Agent │ │ • DevOps Agent │ │ • Research Agent│
│ • UI Agent │ │ • QA Agent │ │ • Data Agent │
│ • Dev Agent(s) │ │ • Security Agent│ │ • ML Agent │
│ • Architect │ │ • ... │ │ • ... │
│ • Reviewer │ │ │ │ │
│ • ... │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
CONSENSUS MODES:
• BFT: Byzantine Fault Tolerant (diverse operators)
• PoA: Proof of Authority (all nodes share same key)
• Per-network: Multiple parallel networks, each with unique consensusCore Components
Agent Identity (RNS + PQ)
Each agent has a cryptographic identity:
// hanzo-dev/agent-mesh/src/identity.rs
pub struct AgentIdentity {
/// RNS destination (Ed25519 + X25519 derived)
pub destination: [u8; 16],
/// Ed25519 signing keypair
pub signing: ed25519::SigningKey,
/// X25519 encryption keypair
pub encryption: x25519::StaticSecret,
/// ML-DSA post-quantum signing (Dilithium)
pub pq_signing: mldsa::SigningKey,
/// ML-KEM post-quantum key encapsulation
pub pq_kem: mlkem::DecapsulationKey,
/// Agent role/capabilities
pub role: AgentRole,
/// Human-readable name
pub name: String,
}
#[derive(Clone)]
pub enum AgentRole {
Architect, // Coordinates workflow
Developer, // Writes code
Reviewer, // Reviews code
Tester, // Runs tests
DevOps, // Deployment
UI, // Frontend
Backend, // Backend
Custom(String),
}ZAP Transport Layer
Zero-copy agent protocol over Cap'n Proto:
# agent-mesh.capnp
@0xabc123def456789a;
# Agent-to-Agent message
struct AgentMessage {
id @0 :Text; # Message UUID
from @1 :Data; # Sender destination (16 bytes)
to @2 :Data; # Recipient destination (16 bytes)
timestamp @3 :Int64; # Unix timestamp
payload :union {
# Direct messages
request @4 :TaskRequest;
response @5 :TaskResponse;
# Gossip protocol
gossip @6 :GossipMessage;
# Consensus
vote @7 :ConsensusVote;
proposal @8 :ConsensusProposal;
# Payment
payment @9 :PaymentRequest;
receipt @10 :PaymentReceipt;
}
# Post-quantum signature (ML-DSA)
signature @11 :Data;
}
struct TaskRequest {
taskId @0 :Text;
taskType @1 :TaskType;
description @2 :Text;
context @3 :Data; # Compressed context
deadline @4 :Int64;
payment @5 :PaymentOffer;
enum TaskType {
code @0;
review @1;
test @2;
deploy @3;
design @4;
research @5;
}
}
struct GossipMessage {
topic @0 :Text;
data @1 :Data;
ttl @2 :UInt32; # Hops remaining
seen @3 :List(Data); # Destinations that have seen this
}
struct ConsensusVote {
round @0 :UInt64;
proposalHash @1 :Data;
vote @2 :Vote;
enum Vote {
yes @0;
no @1;
abstain @2;
}
}Lightweight BFT Consensus
For agent coordination without full blockchain:
// hanzo-dev/agent-mesh/src/consensus.rs
/// Lightweight Byzantine Fault Tolerant consensus
/// Optimized for small agent networks (3-100 nodes)
pub struct AgentConsensus {
/// Current consensus round
round: u64,
/// Known agents and their stakes
agents: HashMap<Destination, AgentInfo>,
/// Current global state
state: GlobalState,
/// Pending proposals
proposals: Vec<Proposal>,
/// Votes received
votes: HashMap<ProposalHash, Vec<Vote>>,
/// Consensus threshold (2f+1 for f faulty)
threshold: usize,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct GlobalState {
/// Current project state
pub project: ProjectState,
/// Active tasks and assignments
pub tasks: HashMap<TaskId, Task>,
/// Agent capabilities and load
pub agents: HashMap<Destination, AgentStatus>,
/// Merkle root for verification
pub state_root: [u8; 32],
/// Block height equivalent
pub height: u64,
}
impl AgentConsensus {
/// Propose a state change (new task, completion, etc)
pub async fn propose(&mut self, change: StateChange) -> Result<ProposalId> {
let proposal = Proposal {
id: uuid::Uuid::new_v4(),
round: self.round,
change,
proposer: self.identity.destination,
timestamp: Utc::now(),
};
// Broadcast to all agents
self.broadcast(AgentMessage::Proposal(proposal.clone())).await?;
// Vote for own proposal
self.vote(&proposal, Vote::Yes).await?;
Ok(proposal.id)
}
/// Process incoming vote
pub async fn receive_vote(&mut self, vote: ConsensusVote) -> Result<()> {
// Verify signature
self.verify_vote(&vote)?;
// Add to votes
self.votes
.entry(vote.proposal_hash)
.or_default()
.push(vote);
// Check if threshold reached
if self.votes[&vote.proposal_hash].len() >= self.threshold {
self.commit_proposal(&vote.proposal_hash).await?;
}
Ok(())
}
/// Commit agreed proposal
async fn commit_proposal(&mut self, hash: &ProposalHash) -> Result<()> {
let proposal = self.proposals.iter()
.find(|p| p.hash() == *hash)
.ok_or(Error::ProposalNotFound)?;
// Apply state change
self.state.apply(&proposal.change)?;
// Increment round
self.round += 1;
// Broadcast commitment
self.broadcast(AgentMessage::Commit(hash.clone())).await?;
Ok(())
}
}Gossip Protocol
Efficient state propagation:
// hanzo-dev/agent-mesh/src/gossip.rs
pub struct GossipProtocol {
/// Our identity
identity: AgentIdentity,
/// Known peers
peers: HashMap<Destination, PeerInfo>,
/// Messages we've seen (bloom filter)
seen: BloomFilter,
/// Fanout (number of peers to forward to)
fanout: usize,
/// Message TTL
default_ttl: u32,
}
impl GossipProtocol {
/// Broadcast message to network
pub async fn broadcast(&self, topic: &str, data: &[u8]) -> Result<()> {
let msg = GossipMessage {
id: uuid::Uuid::new_v4(),
topic: topic.to_string(),
data: data.to_vec(),
ttl: self.default_ttl,
origin: self.identity.destination,
timestamp: Utc::now(),
};
// Select random peers
let targets = self.select_peers(self.fanout);
// Send to each
for peer in targets {
self.send_to(peer, &msg).await?;
}
Ok(())
}
/// Handle incoming gossip
pub async fn receive(&mut self, msg: GossipMessage) -> Result<Option<Vec<u8>>> {
// Check if already seen
if self.seen.contains(&msg.id) {
return Ok(None);
}
// Mark as seen
self.seen.insert(&msg.id);
// Forward if TTL > 0
if msg.ttl > 0 {
let mut forwarded = msg.clone();
forwarded.ttl -= 1;
let targets = self.select_peers_excluding(self.fanout, &msg.origin);
for peer in targets {
self.send_to(peer, &forwarded).await?;
}
}
// Return data for processing
Ok(Some(msg.data))
}
}x402 Payment Protocol
HTTP-based micropayments for agent compute:
// hanzo-dev/agent-mesh/src/payment.rs
/// x402 Payment Protocol for agent-to-agent payments
/// Implements HTTP 402 Payment Required semantics
pub struct PaymentProtocol {
/// Wallet for payments
wallet: AgentWallet,
/// Payment channels
channels: HashMap<Destination, PaymentChannel>,
/// Price list (per task type)
prices: HashMap<TaskType, u64>, // satoshis
}
#[derive(Clone, Serialize, Deserialize)]
pub struct PaymentRequest {
/// Unique payment ID
pub id: PaymentId,
/// Amount in satoshis
pub amount: u64,
/// Payment network
pub network: PaymentNetwork,
/// Recipient address/destination
pub recipient: String,
/// Invoice/payment details
pub invoice: Option<String>,
/// Expiry
pub expires_at: DateTime<Utc>,
}
#[derive(Clone)]
pub enum PaymentNetwork {
/// Lightning Network (instant, low fee)
Lightning,
/// Lux Network (native AIC token)
Lux,
/// Ethereum L2 (USDC)
EthereumL2,
/// Direct crypto payment
Bitcoin,
}
impl PaymentProtocol {
/// Request payment for task
pub async fn request_payment(&self, task: &Task) -> Result<PaymentRequest> {
let price = self.prices.get(&task.task_type)
.ok_or(Error::NoPriceSet)?;
let invoice = match &self.wallet.network {
PaymentNetwork::Lightning => {
self.wallet.create_lightning_invoice(*price).await?
}
PaymentNetwork::Lux => {
self.wallet.create_lux_invoice(*price).await?
}
_ => None,
};
Ok(PaymentRequest {
id: PaymentId::new(),
amount: *price,
network: self.wallet.network.clone(),
recipient: self.wallet.address.clone(),
invoice,
expires_at: Utc::now() + Duration::minutes(30),
})
}
/// Verify payment received
pub async fn verify_payment(&self, proof: &PaymentProof) -> Result<bool> {
match &proof.network {
PaymentNetwork::Lightning => {
self.wallet.verify_lightning_payment(&proof.preimage).await
}
PaymentNetwork::Lux => {
self.wallet.verify_lux_transaction(&proof.tx_hash).await
}
_ => self.wallet.verify_generic(&proof).await,
}
}
}
/// HTTP 402 integration
pub struct X402Middleware;
impl X402Middleware {
/// Handle HTTP request with payment requirement
pub async fn handle(&self, req: Request, payment: &PaymentProtocol) -> Response {
// Check if payment header present
if let Some(proof) = req.header("X-Payment-Proof") {
if payment.verify_payment(&proof.parse()?).await? {
// Payment verified, proceed
return self.next(req).await;
}
}
// Return 402 Payment Required
let payment_req = payment.request_payment(&req.task()).await?;
Response::builder()
.status(402)
.header("X-Payment-Request", serde_json::to_string(&payment_req)?)
.header("X-Payment-Network", payment_req.network.to_string())
.header("X-Payment-Amount", payment_req.amount.to_string())
.body("Payment Required")
}
}Integration with hanzo-dev
Light agents integrate into hanzo-dev CLI, connecting to local hanzod:
// hanzo-dev/agent-mesh/src/node.rs
/// Full agent mesh node embedded in hanzo-dev
pub struct AgentMeshNode {
/// Agent identity
identity: AgentIdentity,
/// ZAP server/client
zap: ZapTransport,
/// RNS transport (mesh/LoRa capable)
rns: RnsTransport,
/// Gossip protocol
gossip: GossipProtocol,
/// Consensus engine
consensus: AgentConsensus,
/// Payment protocol
payment: PaymentProtocol,
/// Tool registry (MCP tools via ZAP)
tools: ToolRegistry,
/// Event bus for local coordination
events: EventBus,
}
impl AgentMeshNode {
/// Start the agent mesh node
pub async fn start(config: MeshConfig) -> Result<Self> {
// Generate or load identity
let identity = AgentIdentity::load_or_generate(&config.identity_path)?;
// Initialize transports
let zap = ZapTransport::new(&config.zap).await?;
let rns = RnsTransport::new(&config.rns).await?;
// Initialize protocols
let gossip = GossipProtocol::new(identity.clone(), config.gossip);
let consensus = AgentConsensus::new(identity.clone(), config.consensus);
let payment = PaymentProtocol::new(&config.payment).await?;
// Register with network
let node = Self {
identity,
zap,
rns,
gossip,
consensus,
payment,
tools: ToolRegistry::new(),
events: EventBus::new(),
};
// Announce presence
node.announce().await?;
// Start background tasks
node.spawn_listeners().await?;
Ok(node)
}
/// Connect to peer agent
pub async fn connect(&self, destination: &Destination) -> Result<AgentConnection> {
// Try ZAP first (fastest)
if let Ok(conn) = self.zap.connect(destination).await {
return Ok(AgentConnection::Zap(conn));
}
// Fall back to RNS (works over mesh/LoRa)
let conn = self.rns.connect(destination).await?;
Ok(AgentConnection::Rns(conn))
}
/// Send task request to another agent
pub async fn request_task(
&self,
target: &Destination,
task: TaskRequest,
) -> Result<TaskResponse> {
let conn = self.connect(target).await?;
// Create payment offer
let offer = self.payment.create_offer(&task).await?;
// Send request
let msg = AgentMessage::Request(TaskRequestWithPayment {
task,
payment: offer,
});
let response = conn.request(msg).await?;
match response {
AgentMessage::Response(r) => Ok(r),
AgentMessage::PaymentRequired(req) => {
// Pay and retry
let proof = self.payment.pay(&req).await?;
conn.request_with_payment(msg, proof).await
}
_ => Err(Error::UnexpectedResponse),
}
}
/// Propose network-wide state change
pub async fn propose_change(&mut self, change: StateChange) -> Result<()> {
self.consensus.propose(change).await?;
Ok(())
}
/// Get current global state
pub fn global_state(&self) -> &GlobalState {
self.consensus.state()
}
}Configuration
hanzod Configuration (Full Node)
# /etc/hanzod/config.toml or ~/.hanzod/config.toml
[node]
name = "hanzod-primary"
data_dir = "/var/lib/hanzod"
[identity]
path = "/etc/hanzod/identity"
# Node identity for global mesh
[zap_server]
# Local ZAP server for light agents
listen = "127.0.0.1:9999"
max_agents = 1000
tls_cert = "/etc/hanzod/certs/server.pem"
tls_key = "/etc/hanzod/certs/server.key"
[rns]
# Global mesh via Reticulum Network Stack
enabled = true
config_path = "/etc/reticulum"
interfaces = ["AutoInterface", "TCPServerInterface", "TCPClientInterface"]
listen = "0.0.0.0:4242"
announce_interval = "5m"
[pq_tunnels]
# Post-quantum secure tunnels to peers
enabled = true
kem = "ml-kem-768"
signing = "ml-dsa-65"
# Perfect forward secrecy with key rotation
key_rotation_interval = "1h"
[consensus]
# BFT consensus for global state
mode = "bft" # or "poa" for Proof of Authority
threshold = "2/3"
round_timeout = "10s"
proposal_timeout = "30s"
[consensus.poa]
# PoA mode: all nodes share same authority key
# enabled when mode = "poa"
authority_key = "/etc/hanzod/authority.key"
[state]
# State machine with Merkle proofs
storage = "rocksdb"
path = "/var/lib/hanzod/state"
pruning = "archive" # or "recent" for light storage
[payment]
# x402 payment processor
enabled = true
networks = ["lightning", "lux"]
wallet_path = "/etc/hanzod/wallet"
[gossip]
fanout = 6
ttl = 10
seen_cache_size = 100000
[peers]
# Bootstrap peers for initial sync
bootstrap = [
"rns://hanzo.ai/hanzod-global-1",
"rns://hanzo.ai/hanzod-global-2",
]
[networks]
# Multiple parallel networks (unique consensus each)
default = "hanzo-main"
[[networks.definitions]]
name = "hanzo-main"
consensus = "bft"
description = "Main Hanzo network"
[[networks.definitions]]
name = "hanzo-test"
consensus = "poa"
description = "Test network with shared authority"
[metrics]
enabled = true
listen = "127.0.0.1:9090"Light Agent Configuration (hanzo-dev)
# ~/.hanzo/agent.toml
[agent]
name = "dev-agent-1"
role = "developer"
[identity]
path = "~/.hanzo/agent-identity"
# Light agent identity
[hanzod]
# Connect to local hanzod
address = "127.0.0.1:9999"
# Auto-discover if not specified
auto_discover = true
[capabilities]
# Agent capabilities for task routing
tools = ["fs", "proc", "think", "browser"]
languages = ["rust", "python", "typescript"]
specializations = ["backend", "cli"]
[payment]
# Agent payment preferences
network = "lightning"
wallet_path = "~/.hanzo/wallet"
# Prices for tasks (satoshis)
prices = { code = 100, review = 50, test = 30 }
# Auto-pay threshold
auto_pay_max = 1000
[state]
# Local state cache
cache_size = "100MB"
sync_interval = "1s"Test Cases
#[cfg(test)]
mod tests {
use super::*;
// ============== hanzod Full Node Tests ==============
#[tokio::test]
async fn test_hanzod_start() {
// Start single hanzod
let hanzod = HanzoFullNode::start(test_hanzod_config()).await.unwrap();
assert!(hanzod.is_running());
assert!(hanzod.zap_server.is_listening());
}
#[tokio::test]
async fn test_hanzod_peer_discovery() {
// Start 3 hanzod nodes
let nodes: Vec<_> = (0..3)
.map(|i| HanzoFullNode::start(test_hanzod_config_with_peers(i)))
.collect::<FuturesUnordered<_>>()
.try_collect()
.await
.unwrap();
// Wait for RNS discovery
tokio::time::sleep(Duration::from_secs(5)).await;
// Each should see the other 2 peers
for node in &nodes {
assert_eq!(node.peer_count(), 2);
}
}
#[tokio::test]
async fn test_hanzod_pq_tunnel() {
let nodes = start_two_hanzod_nodes().await;
// PQ tunnel should be established
let tunnel = nodes[0].get_tunnel(&nodes[1].identity.destination()).unwrap();
assert!(tunnel.is_pq_secure());
assert_eq!(tunnel.cipher_suite(), "ML-KEM-768 + AES-256-GCM");
assert!(tunnel.has_perfect_forward_secrecy());
}
// ============== Light Agent Tests ==============
#[tokio::test]
async fn test_light_agent_connect_to_hanzod() {
// Start hanzod
let hanzod = HanzoFullNode::start(test_hanzod_config()).await.unwrap();
// Connect light agent
let agent = LightAgent::connect(AgentConfig {
hanzod_addr: "127.0.0.1:9999".into(),
role: AgentRole::Developer,
..Default::default()
}).await.unwrap();
// Agent should be registered
assert_eq!(hanzod.agent_count(), 1);
assert!(agent.is_connected());
}
#[tokio::test]
async fn test_many_agents_single_hanzod() {
// Start hanzod
let hanzod = HanzoFullNode::start(test_hanzod_config()).await.unwrap();
// Connect 100 light agents
let agents: Vec<_> = (0..100)
.map(|i| LightAgent::connect(AgentConfig {
hanzod_addr: "127.0.0.1:9999".into(),
role: AgentRole::Developer,
name: format!("dev-{}", i),
..Default::default()
}))
.collect::<FuturesUnordered<_>>()
.try_collect()
.await
.unwrap();
// All agents registered
assert_eq!(hanzod.agent_count(), 100);
// All agents connected
for agent in &agents {
assert!(agent.is_connected());
}
}
#[tokio::test]
async fn test_agent_commit_to_hanzod() {
let (hanzod, agent) = start_hanzod_with_agent().await;
// Agent commits work
let commit_id = agent.commit(AgentWork {
task_id: TaskId::new(),
result: "Implemented feature X".into(),
files_changed: vec!["src/lib.rs".into()],
}).await.unwrap();
// Commit should be in hanzod state
assert!(hanzod.state.has_commit(&commit_id));
}
// ============== Global Consensus Tests ==============
#[tokio::test]
async fn test_consensus_across_hanzod_nodes() {
// Start 3 hanzod nodes with peer connections
let nodes = start_three_hanzod_nodes().await;
// Connect agent to node 0
let agent = LightAgent::connect_to(&nodes[0]).await.unwrap();
// Agent commits work
agent.commit(AgentWork {
task_id: TaskId::new(),
result: "Feature completed".into(),
..Default::default()
}).await.unwrap();
// Wait for consensus propagation
tokio::time::sleep(Duration::from_secs(5)).await;
// All hanzod nodes should have same state
let state_roots: Vec<_> = nodes.iter()
.map(|n| n.state.root_hash())
.collect();
assert!(state_roots.windows(2).all(|w| w[0] == w[1]));
}
#[tokio::test]
async fn test_poa_consensus_shared_key() {
// Start 3 hanzod nodes with same authority key (PoA mode)
let nodes = start_poa_hanzod_nodes(3).await;
// All should accept commits immediately (no voting needed)
let agent = LightAgent::connect_to(&nodes[0]).await.unwrap();
let start = Instant::now();
agent.commit(AgentWork::test()).await.unwrap();
let commit_time = start.elapsed();
// PoA should be faster than BFT (no voting round)
assert!(commit_time < Duration::from_millis(100));
}
// ============== Agent Messaging Tests ==============
#[tokio::test]
async fn test_agent_to_agent_local() {
let (hanzod, agents) = start_hanzod_with_agents(2).await;
let (sender, receiver) = (&agents[0], &agents[1]);
// Sender sends message to receiver
sender.send(&receiver.id(), AgentPayload::Task {
description: "Review this code".into(),
}).await.unwrap();
// Receiver should get message
let msg = receiver.recv().await.unwrap();
assert!(matches!(msg.payload, AgentPayload::Task { .. }));
}
#[tokio::test]
async fn test_agent_to_agent_cross_hanzod() {
// Two hanzod nodes
let nodes = start_two_hanzod_nodes().await;
// Agent on each
let agent_a = LightAgent::connect_to(&nodes[0]).await.unwrap();
let agent_b = LightAgent::connect_to(&nodes[1]).await.unwrap();
// Agent A sends to Agent B (routes through hanzod mesh)
agent_a.send(&agent_b.id(), AgentPayload::Task {
description: "Coordinate on feature".into(),
}).await.unwrap();
// Agent B receives (via hanzod[0] -> hanzod[1] -> agent_b)
let msg = agent_b.recv().await.unwrap();
assert_eq!(msg.from, agent_a.id());
}
// ============== Payment Tests ==============
#[tokio::test]
async fn test_x402_payment_flow() {
let (hanzod, agents) = start_hanzod_with_agents(2).await;
let (client, provider) = (&agents[0], &agents[1]);
// Provider sets price
provider.set_price(TaskType::Code, 100).await.unwrap();
// Client requests task
let result = client.request_task(&provider.id(), TaskRequest {
task_type: TaskType::Code,
description: "Write tests".into(),
}).await;
// Should get payment required
match result {
Err(Error::PaymentRequired(req)) => {
assert_eq!(req.amount, 100);
assert!(req.invoice.is_some());
}
_ => panic!("Expected payment request"),
}
}
// ============== Multi-Network Tests ==============
#[tokio::test]
async fn test_multiple_parallel_networks() {
// hanzod participating in multiple networks
let hanzod = HanzoFullNode::start(HanzodConfig {
networks: vec!["hanzo-main", "hanzo-test"],
..Default::default()
}).await.unwrap();
// Each network has independent consensus
assert!(hanzod.network("hanzo-main").is_some());
assert!(hanzod.network("hanzo-test").is_some());
// Commit to specific network
let agent = LightAgent::connect_to(&hanzod).await.unwrap();
agent.commit_to_network("hanzo-test", AgentWork::test()).await.unwrap();
// Only test network should have commit
assert!(hanzod.network("hanzo-test").unwrap().state.has_commit(&commit_id));
assert!(!hanzod.network("hanzo-main").unwrap().state.has_commit(&commit_id));
}
// ============== Scale Tests ==============
#[tokio::test]
#[ignore] // Run with --ignored for scale tests
async fn test_100_agents_concurrent_commits() {
let hanzod = HanzoFullNode::start(test_hanzod_config()).await.unwrap();
// Connect 100 agents
let agents: Vec<_> = (0..100)
.map(|i| LightAgent::connect(AgentConfig {
hanzod_addr: "127.0.0.1:9999".into(),
role: AgentRole::Developer,
name: format!("dev-{}", i),
..Default::default()
}))
.collect::<FuturesUnordered<_>>()
.try_collect()
.await
.unwrap();
// All agents commit concurrently
let start = Instant::now();
let commits: Vec<_> = agents.iter()
.map(|a| a.commit(AgentWork::test()))
.collect::<FuturesUnordered<_>>()
.try_collect()
.await
.unwrap();
let total_time = start.elapsed();
// All commits successful
assert_eq!(commits.len(), 100);
// Should be fast (< 1s for 100 agents via ZAP)
assert!(total_time < Duration::from_secs(1));
// State should reflect all commits
assert_eq!(hanzod.state.commit_count(), 100);
}
}Implementation Roadmap
Phase 1: Core Infrastructure (Week 1-2)
- Port RNS identity from Lux Go to Rust (
hanzo-rns) - Implement ZAP Cap'n Proto schema (
hanzo-zap) - Post-quantum crypto primitives (
hanzo-pq-crypto)- ML-KEM-768 key encapsulation
- ML-DSA-65 signatures
- Perfect forward secrecy
- Unit tests for identity and crypto
Phase 2: hanzod Full Node (Week 3-4)
- hanzod daemon skeleton
- ZAP server for local agents
- RNS transport for global mesh
- PQ tunnel establishment
- State machine with Merkle proofs
- hanzod tests (single node)
Phase 3: Consensus Engine (Week 5-6)
- BFT consensus implementation
- PoA consensus (shared authority key)
- Multi-network support (parallel networks)
- State replication across hanzod nodes
- Consensus tests with Byzantine nodes
Phase 4: Light Agent Library (Week 7-8)
- Light agent client (
agent-mesh) - Connect to local hanzod via ZAP
- State cache and sync
- Agent-to-agent messaging through hanzod
- Light agent tests
Phase 5: Payments & x402 (Week 9-10)
- x402 payment processor in hanzod
- Lightning Network integration
- Lux Network AIC payments
- Agent payment flow
- Payment tests
Phase 6: hanzo-dev Integration (Week 11-12)
- Embed light agent in hanzo-dev CLI
- Agent role configuration
- Auto-connect to local hanzod
- Cross-agent task delegation
- End-to-end mesh tests (100+ agents)
- Global multi-region tests
Repository Structure
hanzoai/
├── tools/ # Base tools (shared MCP/ZAP)
│ ├── src/
│ │ ├── fs.rs
│ │ ├── proc.rs
│ │ ├── think.rs
│ │ └── ...
│ └── Cargo.toml
│
├── mcp/ # MCP protocol layer (JSON-RPC)
│ ├── rust/ # Rust implementation
│ │ ├── src/
│ │ │ ├── server.rs
│ │ │ ├── tools/
│ │ │ └── ...
│ │ └── Cargo.toml
│ └── python/ # Python implementation
│
├── zap/ # ZAP protocol layer (Cap'n Proto)
│ ├── schema/
│ │ ├── zap.capnp # Core protocol
│ │ ├── agent-mesh.capnp # Mesh networking
│ │ └── ...
│ ├── src/
│ │ ├── client.rs
│ │ ├── server.rs
│ │ ├── gateway.rs # MCP<>ZAP bridge
│ │ └── ...
│ └── Cargo.toml
│
├── hanzod/ # Full node daemon (1 per system)
│ ├── src/
│ │ ├── main.rs # Entry point
│ │ ├── node.rs # Full node implementation
│ │ ├── consensus/ # BFT/PoA consensus
│ │ │ ├── bft.rs
│ │ │ ├── poa.rs
│ │ │ └── state.rs
│ │ ├── rns/ # RNS transport (ported from Lux)
│ │ │ ├── identity.rs
│ │ │ ├── transport.rs
│ │ │ └── tunnel.rs
│ │ ├── pq/ # Post-quantum crypto
│ │ │ ├── mlkem.rs
│ │ │ ├── mldsa.rs
│ │ │ └── pfs.rs # Perfect forward secrecy
│ │ ├── zap_server.rs # ZAP server for light agents
│ │ ├── payment.rs # x402 payment processor
│ │ └── ...
│ ├── Cargo.toml
│ └── README.md
│
├── agent-mesh/ # Light agent mesh library
│ ├── src/
│ │ ├── lib.rs
│ │ ├── identity.rs # Agent identity
│ │ ├── light_agent.rs # Light node client
│ │ ├── gossip.rs # Gossip protocol
│ │ ├── payment.rs # Agent payments
│ │ └── ...
│ └── Cargo.toml
│
└── dev/ # hanzo-dev CLI (embeds light agent)
├── codex-rs/ # Core runtime
│ ├── core/
│ ├── tui/
│ └── ...
├── agent-mesh/ # Light agent integration
│ ├── src/
│ │ ├── integration.rs
│ │ └── ...
│ └── Cargo.toml
└── Cargo.tomlCrate Dependencies
┌──────────────────────────────────────────────────────────────────┐
│ hanzod │
│ (Full Node - 1 per system) │
│ │
│ Dependencies: │
│ ├── hanzo-consensus (BFT/PoA consensus) │
│ ├── hanzo-rns (RNS mesh transport) │
│ ├── hanzo-pq-crypto (ML-KEM, ML-DSA) │
│ ├── hanzo-zap (ZAP server) │
│ ├── hanzo-payment (x402 processor) │
│ └── hanzo-state (Merkle state machine) │
└──────────────────────────────────────────────────────────────────┘
▲
│ ZAP
│
┌──────────────────────────────────────────────────────────────────┐
│ agent-mesh │
│ (Light Agent Library) │
│ │
│ Dependencies: │
│ ├── hanzo-zap (ZAP client) │
│ ├── hanzo-identity (Agent identity) │
│ └── hanzo-payment (Agent payments) │
└──────────────────────────────────────────────────────────────────┘
▲
│ links
│
┌──────────────────────────────────────────────────────────────────┐
│ hanzo-dev │
│ (CLI with embedded light agent) │
│ │
│ Dependencies: │
│ ├── agent-mesh (Light agent) │
│ ├── hanzo-mcp (MCP tools) │
│ └── codex-* (Core runtime) │
└──────────────────────────────────────────────────────────────────┘Quick Start
Start hanzod (Full Node)
# Install hanzod
cargo install hanzod
# Generate identity
hanzod init
# Start daemon
hanzod start
# Check status
hanzod statusStart Light Agents
# Start multiple agents (they auto-connect to local hanzod)
hanzo-dev --agent-role=cto &
hanzo-dev --agent-role=architect &
hanzo-dev --agent-role=developer &
hanzo-dev --agent-role=reviewer &
hanzo-dev --agent-role=tester &
# Or spawn many agents
for i in {1..100}; do
hanzo-dev --agent-role=developer --agent-name="dev-$i" &
doneCheck Mesh Status
# From hanzod
hanzod agents list # List connected light agents
hanzod peers list # List connected hanzod peers
hanzod state show # Show global state
hanzod consensus status # Consensus status
# From any agent
hanzo-dev mesh status # Agent's view of mesh
hanzo-dev mesh peers # Known agentsConnect Globally
# Add peer hanzod nodes
hanzod peers add rns://partner.example/hanzod
hanzod peers add rns://hanzo.ai/global-1
# Check global connectivity
hanzod peers ping rns://hanzo.ai/global-1References
Last updated on