Back to Home

L3 Abstractions for Agentic Prediction Markets

Building zero-attack-surface mesh consensus with local GPU inference and HTTP/3 transport

December 9, 2024 · 20 min read

Abstract

We present a novel architecture for decentralized prediction markets powered by agentic AI, built on Layer 3 (L3) abstractions over IP that enable Layer 0 (L0) application stacks for distributed consensus. By connecting local GPU inference backends to our HTTP/3 transport stack, we create mesh-federated consensus networks with no external attack surface—enabling unbiased, distributed resolution of global state for conditional markets without centralized oracles or trusted third parties.

Introduction: The Oracle Problem in Prediction Markets

Prediction markets have long promised to be "the ultimate information aggregation mechanism"—using market dynamics to surface collective intelligence about future events. From political elections to scientific outcomes, these markets theoretically provide the most accurate forecasts available by incentivizing participants to reveal their true beliefs.

Yet every existing prediction market faces the same fundamental challenge: the oracle problem. How do you resolve a market? Someone—or something—must determine whether an event occurred. Traditional platforms rely on centralized resolution: a company decides outcomes, creating single points of failure, censorship vectors, and trust requirements that undermine the decentralized promise.

Blockchain-based prediction markets attempted to solve this by distributing oracle duties, but they introduced new problems: slow finality, high transaction costs, and—critically—still require external data sources that can be manipulated or censored at the network edge.

We propose a different approach: agentic AI resolution through mesh-federated consensus, built on L3 abstractions that eliminate attack surfaces entirely.

The L3 Abstraction: IP for Modern P2P

Our thesis at Subzero Research centers on a key insight: the modern internet's architecture was designed for client-server communication, not peer-to-peer collaboration. Every abstraction—from TCP/IP to HTTP— assumes asymmetric relationships with centralized endpoints. This architectural bias creates the attack surfaces that undermine decentralized systems.

We're building Layer 3 abstractions over IP specifically designed for modern P2P networks. These abstractions enable what we call L0 application stacks—foundational layers for distributed consensus that operate above all existing blockchain and networking infrastructure.

The Subfrost Stack Architecture

L0 ApplicationPrediction Market Consensus / Agentic Resolution
L3 — subtunUser Space IP Stack (TUN, DNS, ACLs)
L2 — subp2pP2P Networking (Kademlia, GossipSub, Relay)
L1 — libp2p-webtransport-sysHTTP/3 + QUIC + Noise Encryption

The key innovation is subtun—our Layer 3 abstraction that provides a complete user-space IP stack. Unlike traditional VPNs or overlay networks, subtun creates a new networking paradigm where:

  • Every connection is cryptographically authenticated: Ed25519 identity keypairs are the network addresses, not IP addresses
  • DNS resolution maps to peer identities: Names like oracle-node.relay resolve to PeerIds, not IP addresses
  • Port-based ACLs enforce access at the network layer: Only explicitly whitelisted services are reachable—no port scanning, no service enumeration
  • All traffic is end-to-end encrypted: Noise protocol with forward secrecy; relay nodes cannot read traffic content

Zero Attack Surface Architecture

Traditional networked systems expose attack surfaces at every layer: open ports for service discovery, unencrypted metadata revealing network topology, centralized DNS enabling traffic analysis, and IP addresses that can be targeted for DDoS or censorship.

Our L3 abstraction eliminates these surfaces by design:

# Traditional Architecture Attack Surfaces:
# ❌ Open ports (22, 80, 443, 8545...) → Port scanning
# ❌ Public IP addresses → DDoS, geolocation, blocking
# ❌ DNS queries → Traffic analysis, censorship
# ❌ TLS certificates → CA compromise, MITM
# ❌ Service enumeration → Vulnerability discovery

# Subtun L3 Architecture:
# ✅ No listening ports → Nothing to scan
# ✅ Bogon IP addresses → Not routable on public internet
# ✅ P2P name resolution → No DNS leakage
# ✅ Self-certified Ed25519 → No CA dependencies
# ✅ Whitelist-only ACLs → No service enumeration

When an agentic AI node joins the prediction market network, it connects through our L3 stack:

# Start an agentic oracle node with local GPU inference
sudo subtun \
  --gateway \
  --circuit relay.subfrost.io \
  --register oracle-agent-7f3a \
  -p 8080:8080  # Only expose the consensus API

# The node is now:
# - Reachable only by peers who know its registered name
# - Protected by Noise encryption on all connections
# - Invisible to port scanners (no public listening sockets)
# - Running inference entirely on local GPU (no API calls out)

Agentic AI for Market Resolution

The second innovation is using agentic AI systems with local GPU inference as the oracle mechanism. Rather than relying on human reporters or centralized data feeds, each node in the consensus network runs its own AI agent that:

  1. Gathers evidence autonomously: Crawls relevant sources, processes documents, analyzes multimedia—all locally
  2. Forms independent judgments: Uses local LLM inference (Llama, Mistral, or similar) running on consumer GPUs
  3. Participates in distributed consensus: Submits resolution votes through the P2P network with cryptographic attestations
  4. Stakes reputation on accuracy: Agents that consistently resolve correctly gain influence; those that err lose standing
use subfrost_consensus::{Agent, Market, Resolution, Evidence};
use ollama_rs::Ollama;

pub struct OracleAgent {
    llm: Ollama,
    identity: Ed25519Keypair,
    network: SubP2PProvider,
    reputation_stake: u64,
}

impl Agent for OracleAgent {
    async fn resolve_market(&self, market: &Market) -> Resolution {
        // 1. Gather evidence from multiple sources
        let evidence = self.gather_evidence(&market.query).await;

        // 2. Local LLM inference - no external API calls
        let analysis = self.llm.generate(
            "llama3.1:70b",
            &self.format_resolution_prompt(market, &evidence)
        ).await?;

        // 3. Parse structured resolution
        let resolution = self.parse_resolution(&analysis)?;

        // 4. Create cryptographic attestation
        let attestation = Attestation {
            market_id: market.id,
            resolution: resolution.clone(),
            evidence_hashes: evidence.iter().map(|e| e.hash()).collect(),
            timestamp: SystemTime::now(),
            signature: self.identity.sign(&resolution.to_bytes()),
        };

        // 5. Submit to consensus network
        self.network.broadcast_resolution(attestation).await?;

        resolution
    }

    async fn gather_evidence(&self, query: &str) -> Vec<Evidence> {
        // Autonomous evidence gathering:
        // - Web crawling with local processing
        // - Document analysis (PDFs, filings, etc.)
        // - Social media sentiment (without API dependencies)
        // - Historical data from local indexes

        let mut evidence = Vec::new();

        // Each evidence source runs locally
        evidence.extend(self.crawl_web_sources(query).await);
        evidence.extend(self.analyze_documents(query).await);
        evidence.extend(self.process_historical_data(query).await);

        evidence
    }
}

Mesh Federated Consensus

Individual agent judgments are aggregated through mesh federated consensus—a protocol we've developed that achieves Byzantine fault tolerance without requiring a global blockchain or proof-of-work/stake mechanisms.

The key insight is that prediction market resolution is fundamentally different from financial transaction ordering. We don't need total ordering of all events—we need eventual agreement on discrete outcomes with strong guarantees against manipulation.

Consensus Properties

Sybil Resistance

Reputation staking prevents spawn attacks. New agents must build track record before gaining significant voting weight.

Collusion Resistance

Evidence attestations are committed before resolution votes are revealed, preventing coordination on false outcomes.

Censorship Resistance

No centralized relay. Mesh topology means any subset of nodes can continue operating as long as they maintain connectivity.

Verifiable Computation

Each agent commits evidence hashes before resolution, enabling post-hoc verification of reasoning chains.

use subfrost_consensus::{ConsensusRound, Vote, Threshold};

pub struct MeshConsensus {
    local_agent: OracleAgent,
    peer_votes: HashMap<PeerId, Vote>,
    evidence_commitments: HashMap<PeerId, Hash>,
    reputation_weights: HashMap<PeerId, f64>,
}

impl MeshConsensus {
    /// Two-phase commit for market resolution
    pub async fn resolve(&mut self, market: &Market) -> Result<Resolution> {
        // Phase 1: Evidence Commitment
        // All agents commit to their evidence hashes before seeing others
        let my_evidence = self.local_agent.gather_evidence(&market.query).await;
        let commitment = self.commit_evidence(&my_evidence);
        self.broadcast_commitment(commitment).await?;

        // Wait for commitment threshold (2/3 of reputation-weighted agents)
        self.wait_for_commitments(Threshold::TwoThirds).await?;

        // Phase 2: Resolution Voting
        // Now agents reveal their resolutions with evidence
        let my_resolution = self.local_agent.resolve_market(market).await;
        self.broadcast_resolution(my_resolution, my_evidence).await?;

        // Aggregate votes weighted by reputation
        self.wait_for_resolutions(Threshold::TwoThirds).await?;

        let final_resolution = self.aggregate_resolutions()?;

        // Update reputations based on agreement with final outcome
        self.update_reputations(&final_resolution);

        Ok(final_resolution)
    }

    fn aggregate_resolutions(&self) -> Result<Resolution> {
        let mut weighted_votes: HashMap<Resolution, f64> = HashMap::new();

        for (peer_id, vote) in &self.peer_votes {
            let weight = self.reputation_weights.get(peer_id).unwrap_or(&0.0);
            *weighted_votes.entry(vote.resolution.clone()).or_default() += weight;
        }

        // Resolution with >50% of reputation-weighted votes wins
        weighted_votes
            .into_iter()
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
            .map(|(resolution, _)| resolution)
            .ok_or(ConsensusError::NoMajority)
    }
}

HTTP/3 Transport: Why It Matters

The choice of HTTP/3 (QUIC) as our transport layer is deliberate. Unlike TCP-based protocols, QUIC provides properties essential for mesh consensus:

  • 0-RTT connection establishment: Agents can rapidly reconnect after network disruptions without handshake delays
  • Multiplexed streams without head-of-line blocking: Evidence gathering, vote broadcasting, and peer discovery can happen simultaneously without interference
  • Built-in encryption: TLS 1.3 is mandatory, eliminating protocol downgrade attacks
  • Connection migration: Agents can move between networks (WiFi to cellular) without dropping consensus participation
  • UDP-based: Harder to block at the protocol level than TCP; better NAT traversal

Our libp2p-webtransport-sys implementation extends these capabilities with libp2p's peer discovery and relay protocols, creating a transport layer that's both performant and censorship-resistant.

use libp2p_webtransport_sys::WebTransport;
use subp2p::{NetworkProvider, SwarmBuilder};

/// Configure the HTTP/3 transport stack for oracle agents
pub fn create_oracle_transport(
    identity: Keypair,
    relay_addr: Multiaddr,
) -> Result<impl NetworkProvider> {
    let transport = WebTransport::new(identity.clone())
        .with_certificate_verification(CertVerification::SelfSigned)
        .with_noise_encryption(NoiseConfig::XX);

    let swarm = SwarmBuilder::new(identity)
        .with_transport(transport)
        .with_relay_client(relay_addr)
        .with_kademlia()      // Peer discovery
        .with_gossipsub()     // Vote broadcasting
        .with_dcutr()         // NAT hole punching
        .build()?;

    Ok(swarm)
}

Local GPU Inference: Eliminating External Dependencies

A critical design decision is requiring local GPU inference for all AI reasoning. This eliminates several attack vectors:

  • No API rate limiting: Agents can process evidence as fast as local hardware allows
  • No API manipulation: Centralized LLM providers cannot be coerced to bias resolutions
  • No network dependency for reasoning: Inference continues even if external internet access is disrupted
  • Model diversity: Different agents can run different models, preventing monoculture vulnerabilities
  • Verifiable reproducibility: Given the same model weights and evidence, any party can reproduce the reasoning
use ollama_rs::{Ollama, GenerationRequest};

pub struct LocalInferenceEngine {
    ollama: Ollama,
    model: String,
    gpu_layers: u32,
}

impl LocalInferenceEngine {
    pub fn new(model: &str) -> Self {
        // Connect to local Ollama instance (no external network)
        let ollama = Ollama::new("http://127.0.0.1:11434".into());

        Self {
            ollama,
            model: model.to_string(),
            gpu_layers: 35, // Offload to GPU for performance
        }
    }

    pub async fn analyze_evidence(
        &self,
        market_query: &str,
        evidence: &[Evidence],
    ) -> Result<Analysis> {
        let prompt = format!(
            r#"You are an oracle agent resolving a prediction market.

MARKET QUERY: {market_query}

EVIDENCE:
{evidence_text}

Analyze the evidence and determine:
1. Whether the market condition has been met (YES/NO/UNCERTAIN)
2. Confidence level (0.0 to 1.0)
3. Key evidence supporting your conclusion
4. Any conflicting evidence or uncertainties

Respond in JSON format."#,
            market_query = market_query,
            evidence_text = self.format_evidence(evidence),
        );

        let response = self.ollama
            .generate(GenerationRequest::new(self.model.clone(), prompt))
            .await?;

        self.parse_analysis(&response.response)
    }
}

Distributed and Unbiased Global State Resolution

The combination of these technologies creates a system for distributed and unbiased resolution of global state. No single entity—not Subzero Research, not any government, not any corporation—can unilaterally determine market outcomes.

Properties of Unbiased Resolution

  • Epistemic diversity: Agents run different models, gather evidence differently, and weight factors independently
  • Geographic distribution: Agents in different jurisdictions have access to different information sources
  • Temporal independence: Evidence commitment before vote revelation prevents herding behavior
  • Economic incentives: Reputation staking aligns agent interests with accurate resolution
  • Verifiable reasoning: Evidence hashes enable post-hoc auditing of agent decision processes

Implementation: Conditional Markets on Subfrost

Putting it all together, here's how a conditional market operates on our infrastructure:

use subfrost_markets::{ConditionalMarket, Outcome, Position};

/// A conditional market with agentic AI resolution
pub struct AgenticMarket {
    pub id: MarketId,
    pub query: String,
    pub resolution_criteria: ResolutionCriteria,
    pub resolution_deadline: SystemTime,
    pub oracle_network: MeshConsensus,
    pub positions: HashMap<PeerId, Position>,
}

impl AgenticMarket {
    /// Create a new conditional market
    pub async fn create(
        query: &str,
        criteria: ResolutionCriteria,
        deadline: SystemTime,
        network: &SubP2PProvider,
    ) -> Result<Self> {
        let market = Self {
            id: MarketId::generate(),
            query: query.to_string(),
            resolution_criteria: criteria,
            resolution_deadline: deadline,
            oracle_network: MeshConsensus::new(network.clone()),
            positions: HashMap::new(),
        };

        // Broadcast market creation to the network
        network.broadcast_message(
            P2pMessage::MarketCreated(market.to_announcement()),
            "markets"
        ).await?;

        Ok(market)
    }

    /// Take a position in the market
    pub async fn take_position(
        &mut self,
        trader: PeerId,
        outcome: Outcome,
        amount: u64,
    ) -> Result<Position> {
        // Verify trader has sufficient collateral
        // Create position record
        // Update market state
        // Broadcast position to network

        let position = Position {
            trader,
            outcome,
            amount,
            timestamp: SystemTime::now(),
        };

        self.positions.insert(trader, position.clone());
        Ok(position)
    }

    /// Resolve the market using agentic consensus
    pub async fn resolve(&mut self) -> Result<Resolution> {
        // Ensure deadline has passed
        if SystemTime::now() < self.resolution_deadline {
            return Err(MarketError::DeadlineNotReached);
        }

        // Initiate mesh consensus resolution
        let resolution = self.oracle_network.resolve(&self.into()).await?;

        // Distribute payouts based on resolution
        self.distribute_payouts(&resolution).await?;

        Ok(resolution)
    }
}

// Example: Create a conditional market
async fn example_market(network: &SubP2PProvider) -> Result<()> {
    let market = AgenticMarket::create(
        "Will the Federal Reserve cut interest rates by 50bps at the December 2024 meeting?",
        ResolutionCriteria {
            evidence_sources: vec![
                "Federal Reserve press releases",
                "FOMC meeting minutes",
                "Official Fed announcements",
            ],
            resolution_type: ResolutionType::Binary,
        },
        SystemTime::now() + Duration::from_days(30),
        network,
    ).await?;

    println!("Created market: {}", market.id);
    Ok(())
}

Security Analysis

Let's examine the attack surfaces that don't exist in this architecture:

Attack VectorTraditional SystemL3 Agentic Architecture
Port ScanningExposed services discoverableNo listening ports
DDoSPublic IP can be floodedBogon IPs; relay absorbs
DNS HijackingCentral DNS can be poisonedP2P name resolution
TLS MITMCA compromise possibleSelf-certified Ed25519
Oracle ManipulationCentralized source can lieDistributed consensus
API CoercionLLM provider can be pressuredLocal GPU inference
Sybil AttackEasy to create fake nodesReputation staking

Future Directions

This architecture opens several research directions we're actively pursuing:

  • Quantum-safe cryptographic transitions: Integrating CRYSTALS-Kyber and CRYSTALS-Dilithium into the transport layer for post-quantum security
  • Specialized resolution agents: Domain-specific AI models fine-tuned for particular market categories (sports, politics, science, etc.)
  • Cross-chain settlement: Using FROST threshold signatures to settle market outcomes on multiple blockchains simultaneously
  • Reputation portability: Enabling agents to carry reputation across different market networks
  • Formal verification: Proving consensus properties hold under adversarial conditions

Conclusion

Prediction markets have always promised to be "the ultimate information aggregation mechanism," but have been held back by the oracle problem—the fundamental challenge of determining truth in a decentralized system.

By building L3 abstractions over IP specifically designed for P2P networking, connecting agentic AI systems via local GPU inference to HTTP/3 transport, and implementing mesh federated consensus, we've created an architecture that:

  • Eliminates external attack surfaces
  • Distributes resolution authority across independent AI agents
  • Provides cryptographic guarantees of reasoning verifiability
  • Operates without trusted third parties or centralized infrastructure

This is what we mean by L0 application stacks for distributed consensus—foundational infrastructure that enables a new generation of decentralized applications built on unbiased, verifiable resolution of global state.

The era of synthetic research has arrived. We're not just studying these systems—we're building them, using AI-augmented methodologies to compress years of traditional R&D into months, and deploying the results as open infrastructure for a free internet.

Build With Us

Explore our L3 networking stack and join the first generation of synthetic researchers building the infrastructure for decentralized intelligence.