Files
skills/public/hip-0095.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
hanzoskills.com/llms.txt now opens with the install line, the API
reference index and the company index, so an agent that lands on any
one of the three can find the rest.

robots.txt claimed 537 documents while llms.txt counts 920. The number
is gone from robots.txt; llms.txt derives it.

public/ is regenerated from scripts/site.py, which it had fallen
behind: the copy-prompt menu and agent bar were in the generator and
not in the committed pages. tests/site.mjs passes against the result.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-11 00:27:59 -07:00

1571 lines
65 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>hip-0095</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/hip-0095.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/hip-0095">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/hip-0095.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>hip-0095</h1><p class="lede">HIP-95: QoS Challenge System. Status Draft. Hanzo architectural specification.</p><h1>HIP-0095: QoS Challenge System</h1>
<h2>Abstract</h2>
<p>This document specifies the Quality of Service (QoS) Challenge System for Hanzo Network&#x27;s decentralized compute marketplace. The system ensures compute providers maintain advertised service levels through cryptographic challenges, verifiable proofs, and economic incentives.</p>
<h2>Table of Contents</h2>
<ol><li><a href="#problem-statement">Problem Statement</a></li><li><a href="#design-goals">Design Goals</a></li><li><a href="#architecture-overview">Architecture Overview</a></li><li><a href="#qos-challenge-protocol">QoS Challenge Protocol</a></li><li><a href="#verification-and-scoring-system">Verification and Scoring System</a></li><li><a href="#penaltyreward-mechanisms">Penalty/Reward Mechanisms</a></li><li><a href="#security-analysis">Security Analysis</a></li><li><a href="#implementation-plan">Implementation Plan</a></li></ol>
<hr>
<h2>Problem Statement</h2>
<p>In a decentralized compute marketplace, providers may:</p>
<ul><li>Claim capabilities they do not possess (GPU TFLOPS, VRAM, etc.)</li><li>Provide inconsistent service quality over time</li><li>Game the reputation system through selective performance</li><li>Fail to maintain advertised SLAs during peak demand</li></ul>
<p>The QoS Challenge System addresses these issues by continuously verifying provider capabilities and performance through cryptographic proofs.</p>
<hr>
<h2>Design Goals</h2>
<h3>Primary Goals</h3>
<ol><li><strong>Verifiable Performance</strong>: Prove providers can deliver claimed compute capabilities</li><li><strong>Continuous Monitoring</strong>: Ongoing verification, not just registration-time</li><li><strong>Sybil Resistance</strong>: Prevent gaming through multiple identities</li><li><strong>Economic Alignment</strong>: Honest behavior more profitable than cheating</li><li><strong>Low Overhead</strong>: Minimal impact on actual compute workloads</li></ol>
<h2>Architecture Overview</h2>
<pre><code> QoS Challenge System Architecture
+================================================================================+
| |
| +------------------+ +-------------------+ +--------------------+ |
| | Challenge | | Verification | | Scoring | |
| | Generator |----&gt;| Engine |----&gt;| System | |
| +------------------+ +-------------------+ +--------------------+ |
| | | | |
| v v v |
| +------------------+ +-------------------+ +--------------------+ |
| | Challenge Types | | Proof Types | | Score Factors | |
| | - Compute | | - Hash Proof | | - Latency | |
| | - Latency | | - TEE Attest | | - Throughput | |
| | - Bandwidth | | - Merkle Proof | | - Availability | |
| | - Availability | | - ZK Proof | | - Consistency | |
| +------------------+ +-------------------+ +--------------------+ |
| | |
| v |
| +------------------------------------------------------------------+ |
| | On-Chain Settlement | |
| | +-------------------+ +-------------------+ +-----------------+ | |
| | | Stake Management | | Reward/Slash | | Reputation | | |
| | | (hanzo-mining) | | Distribution | | Registry | | |
| | +-------------------+ +-------------------+ +-----------------+ | |
| +------------------------------------------------------------------+ |
| |
+================================================================================+</code></pre>
<h3>Integration with Existing Components</h3>
<p>The QoS Challenge System integrates with:</p>
<p>| Component | Integration Point | Purpose | | --------------- | ---------------------------- | ------------------------------------- | | <code>hanzo-compute</code> | <code>ComputeSwarm</code>, <code>Peer</code> | Challenge issuance, result collection | | <code>hanzo-mining</code> | <code>MiningManager</code>, <code>Consensus</code> | On-chain settlement, stake management | | <code>hanzo-libp2p</code> | P2P messaging | Challenge delivery, proof collection | | <code>hanzo-pqc</code> | Cryptographic primitives | Quantum-safe signatures for proofs |</p>
<hr>
<h2>Specification</h2>
<h3>QoS Challenge Protocol</h3>
<h4>Challenge Types</h4>
<h5>1. Compute Challenge (CC)</h5>
<p>Verifies actual compute capability (TFLOPS/GFLOPS)</p>
<pre><code class="lang-rust">pub struct ComputeChallenge {
/// Unique challenge identifier
pub id: ChallengeId,
/// Challenge type marker
pub challenge_type: ChallengeType,
/// Random seed for deterministic computation
pub seed: [u8; 32],
/// Difficulty level (determines workload size)
pub difficulty: u8,
/// Expected compute metric being tested
pub metric: ComputeMetric,
/// Maximum time allowed (milliseconds)
pub deadline_ms: u64,
/// Challenger&#x27;s signature
pub signature: Vec&lt;u8&gt;,
/// Timestamp of challenge issuance
pub issued_at: u64,
}
#[derive(Clone, Copy)]
pub enum ComputeMetric {
/// GPU FP32 TFLOPS
GpuFp32,
/// GPU FP16 TFLOPS
GpuFp16,
/// GPU INT8 TOPS
GpuInt8,
/// CPU GFLOPS
CpuGflops,
/// Memory bandwidth GB/s
MemoryBandwidth,
}
#[derive(Clone, Copy)]
pub enum ChallengeType {
Compute(ComputeMetric),
Latency,
Bandwidth,
Availability,
Model(ModelCapability),
}</code></pre>
<p><strong>Verification Method</strong>: Provider executes a deterministic computation kernel (e.g., matrix multiplication with specific seed). Result hash and execution time are submitted.</p>
<p><strong>Difficulty Scaling</strong>:</p>
<pre><code class="lang-python"># Difficulty determines problem size
def compute_problem_size(difficulty: int, metric: str) -&gt; int:
&quot;&quot;&quot;
Returns dimensions for matrix operations
difficulty 1-10 maps to increasingly large workloads
&quot;&quot;&quot;
base_sizes = {
&#x27;gpu_fp32&#x27;: 1024, # Starting matrix size
&#x27;gpu_fp16&#x27;: 2048,
&#x27;cpu_gflops&#x27;: 512,
&#x27;memory_bandwidth&#x27;: 1073741824, # 1GB base
}
return base_sizes[metric] * (2 ** (difficulty - 1))</code></pre>
<h5>2. Latency Challenge (LC)</h5>
<p>Verifies network latency and response time</p>
<pre><code class="lang-rust">pub struct LatencyChallenge {
pub id: ChallengeId,
/// Nonce to prevent replay
pub nonce: [u8; 16],
/// Target percentile (p50, p95, p99)
pub target_percentile: u8,
/// Expected max latency in milliseconds
pub max_latency_ms: u32,
/// Number of round trips required
pub rounds: u8,
pub signature: Vec&lt;u8&gt;,
}</code></pre>
<p><strong>Verification Method</strong>: Echo-response pattern with cryptographic binding. Provider must respond within deadline with signed nonce.</p>
<h5>3. Bandwidth Challenge (BC)</h5>
<p>Verifies data transfer capabilities</p>
<pre><code class="lang-rust">pub struct BandwidthChallenge {
pub id: ChallengeId,
/// Random data to transfer (merkle root)
pub data_root: [u8; 32],
/// Size of transfer in bytes
pub transfer_size: u64,
/// Direction of test
pub direction: TransferDirection,
/// Expected minimum throughput Mbps
pub min_throughput_mbps: u32,
pub signature: Vec&lt;u8&gt;,
}
pub enum TransferDirection {
Upload,
Download,
Bidirectional,
}</code></pre>
<h5>4. Availability Challenge (AC)</h5>
<p>Verifies provider is online and ready to serve</p>
<pre><code class="lang-rust">pub struct AvailabilityChallenge {
pub id: ChallengeId,
/// Random nonce
pub nonce: [u8; 32],
/// Challenge window (must respond within)
pub window_ms: u32,
/// Current epoch
pub epoch: u64,
pub signature: Vec&lt;u8&gt;,
}</code></pre>
<p><strong>Verification Method</strong>: Heartbeat-style challenges issued at random intervals. Missing responses count against availability score.</p>
<h5>5. Model Capability Challenge (MC)</h5>
<p>Verifies provider can run specific AI models</p>
<pre><code class="lang-rust">pub struct ModelChallenge {
pub id: ChallengeId,
/// Model identifier to test
pub model: String,
/// Deterministic prompt seed
pub prompt_seed: [u8; 32],
/// Expected completion hash prefix (first N bytes)
pub expected_prefix_len: u8,
/// Max generation time
pub deadline_ms: u64,
pub signature: Vec&lt;u8&gt;,
}</code></pre>
<h4>Challenge Issuance Protocol</h4>
<pre><code>┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Challenge │ │ Provider │ │ Verifier │ │ On-Chain │
│ Committee │ │ Node │ │ Network │ │ Contract │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │ │
│ 1. SELECT RANDOM PROVIDERS │ │
├───────────────────────────────────────┤ │
│ │ │ │
│ 2. ISSUE CHALLENGE │ │
├──────────────────&gt;│ │ │
│ │ │ │
│ 3. EXECUTE CHALLENGE │ │
│ ├───┐ │ │
│ │ │ │ │
│ │&lt;──┘ │ │
│ │ │ │
│ 4. SUBMIT PROOF │ │
│&lt;──────────────────┤ │ │
│ │ │ │
│ 5. FORWARD FOR VERIFICATION │ │
├──────────────────────────────────────&gt;│ │
│ │ │ │
│ 6. VERIFY PROOF │ │
│ │ ├───┐ │
│ │ │ │ │
│ │ │&lt;──┘ │
│ │ │ │
│ 7. SUBMIT RESULT (if passing) │ │
│ │ ├──────────────────&gt;│
│ │ │ │
│ 8. UPDATE SCORE &amp; DISTRIBUTE REWARDS │ │
│ │&lt;─────────────────────────────────────│
│ │ │ │</code></pre>
<h4>Challenge Frequency</h4>
<p>| Provider Tier | Challenge Frequency | Challenge Mix | | -------------------- | ------------------- | ---------------------------------------------- | | New (&lt; 10 jobs) | Every 10 minutes | 40% Compute, 30% Avail, 20% Latency, 10% Model | | Established (10-100) | Every 30 minutes | 30% Compute, 30% Avail, 25% Latency, 15% Model | | Trusted (100+) | Every 60 minutes | 25% Compute, 35% Avail, 20% Latency, 20% Model | | Elite (1000+, TEE) | Every 2 hours | 20% Compute, 40% Avail, 20% Latency, 20% Model |</p>
<h4>Proof Structure</h4>
<pre><code class="lang-rust">pub struct ChallengeProof {
/// Challenge being responded to
pub challenge_id: ChallengeId,
/// Provider submitting proof
pub provider_id: PeerId,
/// Proof data (varies by challenge type)
pub proof_data: ProofData,
/// Execution timestamp
pub executed_at: u64,
/// Execution duration in milliseconds
pub duration_ms: u64,
/// ML-DSA signature over proof
pub signature: Vec&lt;u8&gt;,
/// Optional TEE attestation
pub tee_attestation: Option&lt;TeeAttestation&gt;,
}
pub enum ProofData {
/// Compute proof: result hash + intermediate hashes
Compute {
result_hash: [u8; 32],
intermediate_hashes: Vec&lt;[u8; 32]&gt;,
actual_flops: f64,
},
/// Latency proof: signed responses per round
Latency {
round_results: Vec&lt;LatencyRound&gt;,
p50_ms: u32,
p95_ms: u32,
p99_ms: u32,
},
/// Bandwidth proof: merkle proof of transferred data
Bandwidth {
merkle_proofs: Vec&lt;MerkleProof&gt;,
achieved_mbps: u32,
bytes_transferred: u64,
},
/// Availability proof: signed nonce response
Availability {
signed_nonce: Vec&lt;u8&gt;,
response_time_ms: u32,
},
/// Model proof: completion hash and token count
Model {
completion_hash: [u8; 32],
token_count: u32,
tokens_per_second: f64,
},
}</code></pre>
<hr>
<h3>Verification and Scoring System</h3>
<h4>Verification Methods</h4>
<h5>1. Hash Verification</h5>
<p>For compute challenges, verifiers execute the same deterministic computation:</p>
<pre><code class="lang-rust">impl ComputeChallengeVerifier {
pub fn verify(&amp;self, challenge: &amp;ComputeChallenge, proof: &amp;ProofData) -&gt; VerificationResult {
match proof {
ProofData::Compute { result_hash, intermediate_hashes, actual_flops } =&gt; {
// Recreate the computation with same seed
let expected = self.execute_reference(challenge.seed, challenge.difficulty);
// Compare hashes
if expected.result_hash != *result_hash {
return VerificationResult::Failed(FailureReason::HashMismatch);
}
// Verify intermediate hashes (spot check)
let sample_indices = self.select_sample_indices(challenge.seed, 5);
for idx in sample_indices {
if expected.intermediate_hashes[idx] != intermediate_hashes[idx] {
return VerificationResult::Failed(FailureReason::IntermediateHashMismatch);
}
}
// Verify performance claim
let expected_min_flops = self.difficulty_to_min_flops(challenge.difficulty);
let performance_score = actual_flops / expected_min_flops;
VerificationResult::Passed {
score: performance_score.min(1.0),
bonus: if performance_score &gt; 1.2 { 0.1 } else { 0.0 },
}
}
_ =&gt; VerificationResult::Failed(FailureReason::WrongProofType),
}
}
}</code></pre>
<h5>2. Optimistic Verification with Fraud Proofs</h5>
<p>For efficiency, most verifications are optimistic:</p>
<pre><code class="lang-rust">pub struct OptimisticVerification {
/// Challenge ID
pub challenge_id: ChallengeId,
/// Provider&#x27;s submitted proof
pub proof: ChallengeProof,
/// Submission timestamp
pub submitted_at: u64,
/// Dispute window (blocks)
pub dispute_window: u64,
/// Current status
pub status: VerificationStatus,
}
pub enum VerificationStatus {
/// Pending - within dispute window
Pending,
/// Accepted - dispute window passed
Accepted,
/// Disputed - fraud proof submitted
Disputed { challenger: PeerId, fraud_proof: FraudProof },
/// Rejected - fraud proof verified
Rejected { slash_amount: u64 },
}
pub struct FraudProof {
/// Reference computation result
pub expected_result: ProofData,
/// Evidence of mismatch
pub evidence: FraudEvidence,
/// Challenger&#x27;s stake
pub stake: u64,
/// Challenger&#x27;s signature
pub signature: Vec&lt;u8&gt;,
}</code></pre>
<h5>3. TEE Attestation Verification</h5>
<p>For TEE-enabled providers:</p>
<pre><code class="lang-rust">pub trait TeeAttestationVerifier {
/// Verify remote attestation quote
fn verify_attestation(&amp;self, quote: &amp;[u8], expected_mrenclave: &amp;[u8; 32]) -&gt; bool;
/// Verify signed report from enclave
fn verify_report(&amp;self, report: &amp;TeeReport) -&gt; bool;
/// Get supported TEE types
fn supported_types(&amp;self) -&gt; Vec&lt;TeeType&gt;;
}
pub enum TeeType {
IntelSgx,
AmdSev,
ArmTrustZone,
NvidiaConfidentialCompute,
NvidiaBlackwellTeeIo,
}</code></pre>
<h4>QoS Score Calculation</h4>
<p>The QoS score is a composite metric:</p>
<pre><code class="lang-rust">pub struct QoSScore {
/// Overall composite score (0-1000)
pub composite: u32,
/// Individual component scores
pub components: QoSComponents,
/// Score confidence (based on sample size)
pub confidence: f64,
/// Last updated timestamp
pub updated_at: u64,
/// Historical trend (positive = improving)
pub trend: f64,
}
pub struct QoSComponents {
/// Compute performance vs claimed (0-1000)
pub compute_score: u32,
/// Latency vs SLA (0-1000)
pub latency_score: u32,
/// Bandwidth vs claimed (0-1000)
pub bandwidth_score: u32,
/// Uptime percentage * 10 (0-1000)
pub availability_score: u32,
/// Consistency of performance (0-1000)
pub consistency_score: u32,
}
impl QoSScore {
pub fn calculate(components: &amp;QoSComponents, weights: &amp;ScoreWeights) -&gt; Self {
// Weighted geometric mean for composite score
let composite = (
(components.compute_score as f64).powf(weights.compute) *
(components.latency_score as f64).powf(weights.latency) *
(components.bandwidth_score as f64).powf(weights.bandwidth) *
(components.availability_score as f64).powf(weights.availability) *
(components.consistency_score as f64).powf(weights.consistency)
).powf(1.0 / (weights.total())) as u32;
Self {
composite,
components: components.clone(),
confidence: 0.0, // Set based on sample count
updated_at: now_ms(),
trend: 0.0, // Set based on historical data
}
}
}
pub struct ScoreWeights {
pub compute: f64, // Default: 0.30
pub latency: f64, // Default: 0.20
pub bandwidth: f64, // Default: 0.15
pub availability: f64, // Default: 0.25
pub consistency: f64, // Default: 0.10
}</code></pre>
<h4>Consistency Measurement</h4>
<pre><code class="lang-rust">impl ConsistencyCalculator {
/// Calculate consistency score from recent challenge results
pub fn calculate(&amp;self, results: &amp;[ChallengeResult]) -&gt; u32 {
if results.len() &lt; 5 {
return 500; // Default neutral score for insufficient data
}
// Group by challenge type
let by_type = self.group_by_type(results);
let mut consistency_scores = Vec::new();
for (challenge_type, type_results) in by_type {
// Calculate coefficient of variation (CV = std_dev / mean)
let scores: Vec&lt;f64&gt; = type_results.iter()
.map(|r| r.performance_score)
.collect();
let mean = scores.iter().sum::&lt;f64&gt;() / scores.len() as f64;
let variance = scores.iter()
.map(|s| (s - mean).powi(2))
.sum::&lt;f64&gt;() / scores.len() as f64;
let std_dev = variance.sqrt();
let cv = std_dev / mean;
// Lower CV = higher consistency
// CV of 0.05 = perfect (1000), CV of 0.5 = poor (0)
let type_score = ((1.0 - (cv / 0.5).min(1.0)) * 1000.0) as u32;
consistency_scores.push(type_score);
}
// Average across challenge types
consistency_scores.iter().sum::&lt;u32&gt;() / consistency_scores.len() as u32
}
}</code></pre>
<hr>
<h3>Penalty/Reward Mechanisms</h3>
<h4>Economic Model</h4>
<pre><code> Economic Flow Diagram
+============================================================================+
| |
| Provider Stake Pool Challenge Rewards Pool |
| ┌─────────────────┐ ┌─────────────────┐ |
| │ │ │ │ |
| │ AI Tokens │ │ AI Tokens │ |
| │ (Locked) │ │ (Available) │ |
| │ │ │ │ |
| └────────┬────────┘ └────────┬────────┘ |
| │ │ |
| │ ┌──────────────────────────────┘ |
| │ │ |
| v v |
| ┌─────────────────────────────────────────────────────────┐ |
| │ QoS Challenge Engine │ |
| │ │ |
| │ Challenge Passed? │ |
| │ │ │ |
| │ ├── YES ──&gt; Reward Distribution │ |
| │ │ │ │ |
| │ │ ├── Base Reward (from pool) │ |
| │ │ ├── Performance Bonus │ |
| │ │ └── Reputation Increase │ |
| │ │ │ |
| │ └── NO ───&gt; Penalty Application │ |
| │ │ │ |
| │ ├── Stake Slash (to pool) │ |
| │ ├── Reputation Decrease │ |
| │ └── Potential Ban │ |
| │ │ |
| └─────────────────────────────────────────────────────────┘ |
| |
+============================================================================+</code></pre>
<h4>Reward Structure</h4>
<pre><code class="lang-rust">pub struct RewardConfig {
/// Base reward per successful challenge (AI tokens)
pub base_reward: u64,
/// Performance bonus multiplier (max 2x)
pub max_performance_bonus: f64,
/// Streak bonus for consecutive passes
pub streak_bonus_per_pass: f64,
/// Maximum streak bonus
pub max_streak_bonus: f64,
/// TEE attestation bonus
pub tee_bonus: f64,
/// Elite provider bonus threshold
pub elite_threshold_score: u32,
/// Elite provider bonus
pub elite_bonus: f64,
}
impl Default for RewardConfig {
fn default() -&gt; Self {
Self {
base_reward: 100_000_000_000_000_000, // 0.1 AI tokens (18 decimals)
max_performance_bonus: 2.0,
streak_bonus_per_pass: 0.01,
max_streak_bonus: 0.5,
tee_bonus: 0.25,
elite_threshold_score: 900,
elite_bonus: 0.15,
}
}
}
pub struct RewardCalculator {
config: RewardConfig,
}
impl RewardCalculator {
pub fn calculate_reward(
&amp;self,
challenge_result: &amp;ChallengeResult,
provider_state: &amp;ProviderState,
) -&gt; u64 {
if !challenge_result.passed {
return 0;
}
let mut reward = self.config.base_reward as f64;
// Performance bonus (0-100% additional)
let performance_bonus = (challenge_result.performance_score - 1.0)
.max(0.0)
.min(1.0)
* self.config.max_performance_bonus;
reward *= 1.0 + performance_bonus;
// Streak bonus
let streak_bonus = (provider_state.challenge_streak as f64
* self.config.streak_bonus_per_pass)
.min(self.config.max_streak_bonus);
reward *= 1.0 + streak_bonus;
// TEE bonus
if challenge_result.tee_verified {
reward *= 1.0 + self.config.tee_bonus;
}
// Elite bonus
if provider_state.qos_score.composite &gt;= self.config.elite_threshold_score {
reward *= 1.0 + self.config.elite_bonus;
}
reward as u64
}
}</code></pre>
<h4>Penalty Structure</h4>
<pre><code class="lang-rust">pub struct PenaltyConfig {
/// Base slash percentage for failed challenge
pub base_slash_percent: f64,
/// Increased slash for consecutive failures
pub consecutive_failure_multiplier: f64,
/// Maximum slash percentage per challenge
pub max_slash_percent: f64,
/// Reputation penalty per failure
pub reputation_penalty: f64,
/// Failures before temporary ban
pub failures_before_temp_ban: u32,
/// Temp ban duration (seconds)
pub temp_ban_duration: u64,
/// Failures before permanent ban
pub failures_before_perm_ban: u32,
/// Grace period for new providers
pub grace_period_challenges: u32,
}
impl Default for PenaltyConfig {
fn default() -&gt; Self {
Self {
base_slash_percent: 0.01, // 1%
consecutive_failure_multiplier: 1.5,
max_slash_percent: 0.10, // 10% max per challenge
reputation_penalty: 10.0,
failures_before_temp_ban: 5,
temp_ban_duration: 86400, // 24 hours
failures_before_perm_ban: 20,
grace_period_challenges: 3,
}
}
}
pub struct PenaltyCalculator {
config: PenaltyConfig,
}
impl PenaltyCalculator {
pub fn calculate_penalty(
&amp;self,
challenge_result: &amp;ChallengeResult,
provider_state: &amp;ProviderState,
) -&gt; Penalty {
// Grace period for new providers
if provider_state.total_challenges &lt; self.config.grace_period_challenges {
return Penalty::Warning;
}
// Calculate slash amount
let consecutive_failures = provider_state.consecutive_failures;
let slash_multiplier = self.config.consecutive_failure_multiplier
.powi(consecutive_failures as i32);
let slash_percent = (self.config.base_slash_percent * slash_multiplier)
.min(self.config.max_slash_percent);
let slash_amount = (provider_state.stake as f64 * slash_percent) as u64;
// Calculate reputation penalty
let rep_penalty = self.config.reputation_penalty
* (1.0 + 0.1 * consecutive_failures as f64);
// Check for ban conditions
if consecutive_failures &gt;= self.config.failures_before_perm_ban {
return Penalty::PermanentBan {
slash_amount: provider_state.stake, // Slash all
reason: BanReason::ExcessiveFailures,
};
}
if consecutive_failures &gt;= self.config.failures_before_temp_ban {
return Penalty::TemporaryBan {
slash_amount,
reputation_penalty: rep_penalty,
duration: self.config.temp_ban_duration,
};
}
Penalty::Slash {
amount: slash_amount,
reputation_penalty: rep_penalty,
}
}
}
pub enum Penalty {
/// Warning only (grace period)
Warning,
/// Slash stake and reduce reputation
Slash {
amount: u64,
reputation_penalty: f64,
},
/// Temporary ban with slash
TemporaryBan {
slash_amount: u64,
reputation_penalty: f64,
duration: u64,
},
/// Permanent ban with full slash
PermanentBan {
slash_amount: u64,
reason: BanReason,
},
}
pub enum BanReason {
ExcessiveFailures,
FraudDetected,
TeeAttestationRevoked,
ManualReview,
}</code></pre>
<h4>Reputation System Integration</h4>
<pre><code class="lang-rust">pub struct ReputationManager {
/// Minimum reputation to participate
min_reputation: f64,
/// Starting reputation for new providers
starting_reputation: f64,
/// Maximum reputation
max_reputation: f64,
/// Decay rate per day of inactivity
decay_rate: f64,
}
impl ReputationManager {
pub fn update_reputation(
&amp;self,
provider: &amp;mut ProviderState,
result: &amp;ChallengeResult,
penalty: &amp;Penalty,
reward: u64,
) {
match penalty {
Penalty::Warning =&gt; {
// Slight decrease for warning
provider.reputation = (provider.reputation - 1.0).max(self.min_reputation);
}
Penalty::Slash { reputation_penalty, .. } |
Penalty::TemporaryBan { reputation_penalty, .. } =&gt; {
provider.reputation = (provider.reputation - reputation_penalty)
.max(self.min_reputation);
}
Penalty::PermanentBan { .. } =&gt; {
provider.reputation = 0.0;
}
}
// Reward case - increase reputation
if result.passed {
// Asymptotic increase toward max
let increase_factor = (self.max_reputation - provider.reputation) / self.max_reputation;
let increase = result.performance_score * 2.0 * increase_factor;
provider.reputation = (provider.reputation + increase).min(self.max_reputation);
}
// Track metrics
provider.total_rewards += reward;
if result.passed {
provider.challenges_passed += 1;
provider.consecutive_failures = 0;
provider.challenge_streak += 1;
} else {
provider.challenges_failed += 1;
provider.consecutive_failures += 1;
provider.challenge_streak = 0;
}
}
/// Apply daily reputation decay for inactive providers
pub fn apply_decay(&amp;self, provider: &amp;mut ProviderState, days_inactive: f64) {
if days_inactive &gt; 0.0 {
let decay = self.decay_rate.powf(days_inactive);
provider.reputation *= decay;
provider.reputation = provider.reputation.max(self.min_reputation);
}
}
}
pub struct ProviderState {
pub id: PeerId,
pub stake: u64,
pub reputation: f64,
pub qos_score: QoSScore,
pub challenges_passed: u64,
pub challenges_failed: u64,
pub consecutive_failures: u32,
pub challenge_streak: u32,
pub total_challenges: u32,
pub total_rewards: u64,
pub total_slashed: u64,
pub last_active: u64,
pub status: ProviderStatus,
}
pub enum ProviderStatus {
Active,
TemporarilyBanned { until: u64 },
PermanentlyBanned { reason: BanReason },
Suspended { reason: String },
}</code></pre>
<h4>On-Chain Settlement</h4>
<pre><code class="lang-solidity">// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import &quot;@openzeppelin/contracts/token/ERC20/IERC20.sol&quot;;
import &quot;@openzeppelin/contracts/security/ReentrancyGuard.sol&quot;;
/**
* @title QoSChallengeSettlement
* @notice On-chain settlement for QoS challenges
*/
contract QoSChallengeSettlement is ReentrancyGuard {
IERC20 public immutable aiToken;
struct Provider {
uint256 stake;
uint256 reputation;
uint256 totalRewards;
uint256 totalSlashed;
uint32 consecutiveFailures;
uint64 lastChallengeTime;
ProviderStatus status;
}
enum ProviderStatus { Active, TempBanned, PermBanned }
struct ChallengeResult {
bytes32 challengeId;
address provider;
bool passed;
uint256 performanceScore; // 18 decimals, 1e18 = 100%
bool teeVerified;
uint256 timestamp;
}
mapping(address =&gt; Provider) public providers;
mapping(bytes32 =&gt; ChallengeResult) public results;
uint256 public constant MIN_STAKE = 100 ether; // 100 AI tokens
uint256 public constant BASE_REWARD = 0.1 ether;
uint256 public constant BASE_SLASH_PERCENT = 1; // 1%
event ChallengeSettled(
bytes32 indexed challengeId,
address indexed provider,
bool passed,
uint256 reward,
uint256 slash
);
event ProviderSlashed(
address indexed provider,
uint256 amount,
string reason
);
event ProviderBanned(
address indexed provider,
bool permanent,
string reason
);
constructor(address _aiToken) {
aiToken = IERC20(_aiToken);
}
function settleChallengeResult(
bytes32 challengeId,
address providerAddr,
bool passed,
uint256 performanceScore,
bool teeVerified,
bytes calldata signature
) external nonReentrant {
// Verify signature from challenge committee
require(verifySettlementSignature(
challengeId, providerAddr, passed, performanceScore, teeVerified, signature
), &quot;Invalid signature&quot;);
Provider storage provider = providers[providerAddr];
require(provider.status == ProviderStatus.Active, &quot;Provider not active&quot;);
uint256 reward = 0;
uint256 slash = 0;
if (passed) {
reward = calculateReward(provider, performanceScore, teeVerified);
provider.consecutiveFailures = 0;
provider.reputation += performanceScore / 1e17; // Scaled increase
} else {
(slash, bool tempBan, bool permBan) = calculatePenalty(provider);
if (slash &gt; 0) {
provider.stake -= slash;
provider.totalSlashed += slash;
emit ProviderSlashed(providerAddr, slash, &quot;Challenge failed&quot;);
}
provider.consecutiveFailures++;
provider.reputation = provider.reputation &gt; 10 ?
provider.reputation - 10 : 0;
if (permBan) {
provider.status = ProviderStatus.PermBanned;
emit ProviderBanned(providerAddr, true, &quot;Excessive failures&quot;);
} else if (tempBan) {
provider.status = ProviderStatus.TempBanned;
emit ProviderBanned(providerAddr, false, &quot;Multiple failures&quot;);
}
}
provider.lastChallengeTime = uint64(block.timestamp);
// Store result
results[challengeId] = ChallengeResult({
challengeId: challengeId,
provider: providerAddr,
passed: passed,
performanceScore: performanceScore,
teeVerified: teeVerified,
timestamp: block.timestamp
});
// Transfer reward
if (reward &gt; 0) {
provider.totalRewards += reward;
require(aiToken.transfer(providerAddr, reward), &quot;Reward transfer failed&quot;);
}
emit ChallengeSettled(challengeId, providerAddr, passed, reward, slash);
}
function calculateReward(
Provider storage provider,
uint256 performanceScore,
bool teeVerified
) internal view returns (uint256) {
uint256 reward = BASE_REWARD;
// Performance bonus (up to 2x)
if (performanceScore &gt; 1e18) {
uint256 bonus = (performanceScore - 1e18) * reward / 1e18;
reward += bonus &gt; reward ? reward : bonus;
}
// TEE bonus (25%)
if (teeVerified) {
reward = reward * 125 / 100;
}
// Elite bonus (15%) for high reputation
if (provider.reputation &gt;= 900) {
reward = reward * 115 / 100;
}
return reward;
}
function calculatePenalty(
Provider storage provider
) internal view returns (uint256 slash, bool tempBan, bool permBan) {
// Slash increases with consecutive failures
uint256 slashPercent = BASE_SLASH_PERCENT *
(150 ** provider.consecutiveFailures) / (100 ** provider.consecutiveFailures);
// Cap at 10%
if (slashPercent &gt; 10) slashPercent = 10;
slash = provider.stake * slashPercent / 100;
// Ban conditions
tempBan = provider.consecutiveFailures &gt;= 4;
permBan = provider.consecutiveFailures &gt;= 19;
return (slash, tempBan, permBan);
}
function verifySettlementSignature(
bytes32 challengeId,
address provider,
bool passed,
uint256 performanceScore,
bool teeVerified,
bytes calldata signature
) internal view returns (bool) {
// Implementation: verify ECDSA/ML-DSA signature from challenge committee
// This would verify against a multisig or threshold signature
return true; // Placeholder
}
}</code></pre>
<hr>
<h3>Security Analysis</h3>
<h4>Threat Model</h4>
<p>| Threat | Impact | Mitigation | | --------------------------- | -------------------------------------------- | ----------------------------------------------------------- | | <strong>Sybil Attack</strong> | Multiple fake identities to game reputation | Minimum stake requirement, unique hardware attestation | | <strong>Computation Outsourcing</strong> | Provider outsources challenge to faster node | Strict deadlines, random challenge timing, TEE verification | | <strong>Selective Participation</strong> | Only respond to easy challenges | Random assignment, penalty for missed challenges | | <strong>Collusion</strong> | Verifiers and providers collude | Multiple independent verifiers, fraud proofs, slashing | | <strong>Replay Attacks</strong> | Reuse old challenge responses | Unique nonces, timestamp validation, challenge expiry | | <strong>Eclipse Attack</strong> | Isolate provider from network | Multiple bootstrap nodes, diverse verifier set | | <strong>TEE Compromise</strong> | Fake attestation quotes | Quote freshness checks, revocation lists, multi-vendor TEE |</p>
<h4>Security Properties</h4>
<ol><li><strong>Unpredictability</strong>: Challenges are generated using VRF (Verifiable Random Function) to prevent prediction</li><li><strong>Non-repudiation</strong>: All proofs are cryptographically signed</li><li><strong>Atomicity</strong>: On-chain settlement is atomic (reward/slash happens together)</li><li><strong>Consistency</strong>: Distributed verifier consensus prevents single points of failure</li></ol>
<h4>Challenge Randomness</h4>
<pre><code class="lang-rust">use vrf::VRF;
pub struct ChallengeSelector {
vrf: VRF,
last_beacon: [u8; 32],
}
impl ChallengeSelector {
/// Select providers for next challenge round
pub fn select_providers(
&amp;mut self,
all_providers: &amp;[PeerId],
count: usize,
block_hash: &amp;[u8; 32],
) -&gt; Vec&lt;PeerId&gt; {
// Update beacon with latest block hash for unpredictability
let mut input = Vec::new();
input.extend_from_slice(&amp;self.last_beacon);
input.extend_from_slice(block_hash);
let (output, proof) = self.vrf.prove(&amp;input);
self.last_beacon = output;
// Use VRF output to deterministically select providers
let mut selected = Vec::new();
let mut rng = ChaCha20Rng::from_seed(output);
let mut indices: Vec&lt;usize&gt; = (0..all_providers.len()).collect();
indices.shuffle(&amp;mut rng);
for idx in indices.into_iter().take(count) {
selected.push(all_providers[idx].clone());
}
selected
}
/// Select challenge type for a provider
pub fn select_challenge_type(
&amp;self,
provider: &amp;ProviderState,
beacon: &amp;[u8; 32],
) -&gt; ChallengeType {
let mut hasher = blake3::Hasher::new();
hasher.update(beacon);
hasher.update(provider.id.as_bytes());
let hash = hasher.finalize();
// Use first byte to select type based on provider tier weights
let weights = provider.challenge_weights();
let roll = hash.as_bytes()[0] as u32 * 100 / 256;
weights.select(roll)
}
}</code></pre>
<hr>
<h3>Implementation Plan</h3>
<h4>Milestones</h4>
<p>| Milestone | Deliverable | Date | | --------- | ------------------------------------------ | ------- | | M1 | Challenge protocol specification finalized | Week 2 | | M2 | Testnet deployment with basic challenges | Week 6 | | M3 | Full verification engine operational | Week 8 | | M4 | Economic settlement on testnet | Week 10 | | M5 | Security audit complete | Week 11 | | M6 | Mainnet launch | Week 12 |</p>
<h4>Success Metrics</h4>
<p>| Metric | Target | Measurement | | ------------------------- | ------------ | --------------------------------------------- | | Challenge completion rate | &gt; 98% | Successful responses / total challenges | | False positive rate | &lt; 0.1% | Incorrect failures / total failures | | Verification latency | &lt; 5 seconds | Time from proof submission to verification | | Provider churn | &lt; 5% monthly | Providers leaving due to failed challenges | | Fraud detection rate | &gt; 99% | Detected fraudulent proofs / total fraudulent |</p>
<hr>
<h3>Appendix A: API Reference</h3>
<h4>Challenge Service gRPC API</h4>
<pre><code class="lang-protobuf">syntax = &quot;proto3&quot;;
package hanzo.qos.v1;
service QoSChallengeService {
// Issue a new challenge to a provider
rpc IssueChallenge(IssueChallengeRequest) returns (Challenge);
// Submit proof for a challenge
rpc SubmitProof(SubmitProofRequest) returns (SubmitProofResponse);
// Get challenge status
rpc GetChallengeStatus(GetChallengeStatusRequest) returns (ChallengeStatus);
// Get provider QoS score
rpc GetQoSScore(GetQoSScoreRequest) returns (QoSScore);
// Stream challenge events
rpc StreamChallenges(StreamChallengesRequest) returns (stream ChallengeEvent);
}
message Challenge {
bytes id = 1;
ChallengeType type = 2;
bytes seed = 3;
uint32 difficulty = 4;
uint64 deadline_ms = 5;
uint64 issued_at = 6;
bytes signature = 7;
}
enum ChallengeType {
CHALLENGE_TYPE_UNSPECIFIED = 0;
CHALLENGE_TYPE_COMPUTE = 1;
CHALLENGE_TYPE_LATENCY = 2;
CHALLENGE_TYPE_BANDWIDTH = 3;
CHALLENGE_TYPE_AVAILABILITY = 4;
CHALLENGE_TYPE_MODEL = 5;
}
message ChallengeProof {
bytes challenge_id = 1;
string provider_id = 2;
bytes proof_data = 3;
uint64 executed_at = 4;
uint64 duration_ms = 5;
bytes signature = 6;
optional bytes tee_attestation = 7;
}
message QoSScore {
uint32 composite = 1;
uint32 compute_score = 2;
uint32 latency_score = 3;
uint32 bandwidth_score = 4;
uint32 availability_score = 5;
uint32 consistency_score = 6;
double confidence = 7;
uint64 updated_at = 8;
}</code></pre>
<h4>REST API Endpoints</h4>
<pre><code class="lang-yaml">openapi: 3.0.0
info:
title: QoS Challenge API
version: 1.0.0
paths:
/v1/challenges:
get:
summary: List active challenges for provider
parameters:
- name: provider_id
in: query
required: true
schema:
type: string
responses:
&quot;200&quot;:
description: Active challenges
content:
application/json:
schema:
type: array
items:
$ref: &quot;#/components/schemas/Challenge&quot;
/v1/challenges/{challenge_id}/proof:
post:
summary: Submit proof for challenge
parameters:
- name: challenge_id
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
application/json:
schema:
$ref: &quot;#/components/schemas/ChallengeProof&quot;
responses:
&quot;200&quot;:
description: Proof accepted
&quot;400&quot;:
description: Invalid proof
/v1/providers/{provider_id}/qos:
get:
summary: Get provider QoS score
parameters:
- name: provider_id
in: path
required: true
schema:
type: string
responses:
&quot;200&quot;:
description: QoS score
content:
application/json:
schema:
$ref: &quot;#/components/schemas/QoSScore&quot;
/v1/providers/{provider_id}/history:
get:
summary: Get challenge history
parameters:
- name: provider_id
in: path
required: true
schema:
type: string
- name: limit
in: query
schema:
type: integer
default: 100
responses:
&quot;200&quot;:
description: Challenge history
content:
application/json:
schema:
type: array
items:
$ref: &quot;#/components/schemas/ChallengeResult&quot;
components:
schemas:
Challenge:
type: object
properties:
id:
type: string
format: byte
type:
type: string
enum: [compute, latency, bandwidth, availability, model]
seed:
type: string
format: byte
difficulty:
type: integer
deadline_ms:
type: integer
format: int64
issued_at:
type: integer
format: int64
ChallengeProof:
type: object
properties:
challenge_id:
type: string
format: byte
provider_id:
type: string
proof_data:
type: object
duration_ms:
type: integer
format: int64
signature:
type: string
format: byte
tee_attestation:
type: string
format: byte
QoSScore:
type: object
properties:
composite:
type: integer
compute_score:
type: integer
latency_score:
type: integer
bandwidth_score:
type: integer
availability_score:
type: integer
consistency_score:
type: integer
confidence:
type: number
format: double
updated_at:
type: integer
format: int64
ChallengeResult:
type: object
properties:
challenge_id:
type: string
passed:
type: boolean
performance_score:
type: number
reward:
type: integer
format: int64
slash:
type: integer
format: int64
timestamp:
type: integer
format: int64</code></pre>
<hr>
<h3>Appendix B: Reference Implementations</h3>
<h4>Compute Challenge Kernel (GPU)</h4>
<pre><code class="lang-cuda">// Reference CUDA kernel for compute challenges
// Uses deterministic matrix multiplication with seed-based initialization
__global__ void compute_challenge_kernel(
float* A, float* B, float* C,
int N, uint32_t seed
) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row &lt; N &amp;&amp; col &lt; N) {
float sum = 0.0f;
for (int k = 0; k &lt; N; k++) {
sum += A[row * N + k] * B[k * N + col];
}
C[row * N + col] = sum;
}
}
// Initialize matrices deterministically from seed
void init_challenge_matrices(float* A, float* B, int N, uint32_t seed) {
// Use PCG random generator seeded with challenge seed
pcg32_random_t rng;
pcg32_srandom_r(&amp;rng, seed, seed ^ 0xDEADBEEF);
for (int i = 0; i &lt; N * N; i++) {
// Generate deterministic values in [-1, 1]
A[i] = (pcg32_random_r(&amp;rng) / (float)UINT32_MAX) * 2.0f - 1.0f;
B[i] = (pcg32_random_r(&amp;rng) / (float)UINT32_MAX) * 2.0f - 1.0f;
}
}
// Compute challenge proof
ChallengeProof execute_compute_challenge(ComputeChallenge* challenge) {
int N = difficulty_to_size(challenge-&gt;difficulty);
float *h_A, *h_B, *h_C;
float *d_A, *d_B, *d_C;
// Allocate and initialize
h_A = (float*)malloc(N * N * sizeof(float));
h_B = (float*)malloc(N * N * sizeof(float));
h_C = (float*)malloc(N * N * sizeof(float));
init_challenge_matrices(h_A, h_B, N, *(uint32_t*)challenge-&gt;seed);
cudaMalloc(&amp;d_A, N * N * sizeof(float));
cudaMalloc(&amp;d_B, N * N * sizeof(float));
cudaMalloc(&amp;d_C, N * N * sizeof(float));
cudaMemcpy(d_A, h_A, N * N * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, h_B, N * N * sizeof(float), cudaMemcpyHostToDevice);
// Execute timed kernel
dim3 threads(16, 16);
dim3 blocks((N + 15) / 16, (N + 15) / 16);
cudaEvent_t start, stop;
cudaEventCreate(&amp;start);
cudaEventCreate(&amp;stop);
cudaEventRecord(start);
compute_challenge_kernel&lt;&lt;&lt;blocks, threads&gt;&gt;&gt;(d_A, d_B, d_C, N,
*(uint32_t*)challenge-&gt;seed);
cudaEventRecord(stop);
cudaEventSynchronize(stop);
float milliseconds = 0;
cudaEventElapsedTime(&amp;milliseconds, start, stop);
// Copy result back
cudaMemcpy(h_C, d_C, N * N * sizeof(float), cudaMemcpyDeviceToHost);
// Compute result hash
uint8_t result_hash[32];
blake3_hasher hasher;
blake3_hasher_init(&amp;hasher);
blake3_hasher_update(&amp;hasher, h_C, N * N * sizeof(float));
blake3_hasher_finalize(&amp;hasher, result_hash, 32);
// Calculate TFLOPS
double flops = 2.0 * N * N * N; // 2 ops per multiply-add
double tflops = flops / (milliseconds * 1e9);
// Build proof
ChallengeProof proof = {
.challenge_id = challenge-&gt;id,
.duration_ms = (uint64_t)milliseconds,
.actual_flops = tflops,
};
memcpy(proof.result_hash, result_hash, 32);
// Cleanup
free(h_A); free(h_B); free(h_C);
cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);
return proof;
}</code></pre>
<hr>
<h3>Document History</h3>
<p>| Version | Date | Author | Changes | | ------- | ---------- | ----------------- | ----------------------- | | 1.0 | 2026-01-24 | Architecture Team | Initial design document |</p>
<hr>
<h2>References</h2>
<ol><li>Hanzo Network Architecture Documentation</li><li>AI Token Economics Specification</li><li>hanzo-compute crate documentation</li><li>hanzo-mining consensus implementation</li><li>Intel SGX Remote Attestation Guide</li><li>NVIDIA Confidential Computing Documentation</li></ol>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/hip-0095.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>