Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(oin): add the conformance runner and verify signed node advertisements

nirholas783690b93de0
diff --git a/api/_lib/oin-verify.js b/api/_lib/oin-verify.js
index d02dd21a2..3b41a2c62 100644
--- a/api/_lib/oin-verify.js
+++ b/api/_lib/oin-verify.js
@@ -11,6 +11,7 @@
// digestJob: lowercase hex SHA-256 of the canonical envelope
// signResponse / signAdvertisement: fill in `signature` on the node side
// verifyResponse: returns { ok, verdict, ... } for a job/response pair
+// verifyAdvertisement: same signature rule applied to /.well-known/oin
// verifyOutput: spec rule 6, hash the bytes at output.url and compare
//
// Verdicts are the exact codes the spec names: bad_shape, job_digest_mismatch,
@@ -113,6 +114,27 @@ function fail(verdict, detail) {
return { ok: false, verified: false, verdict, detail };
}
+// The one signature rule both a response and an advertisement obey: drop
+// `signature`, canonicalize what remains, verify Ed25519 over those bytes.
+// Returns null on success, or a fail() result naming the verdict.
+function checkDetachedSignature(signed, pub) {
+ const { signature, ...unsigned } = signed;
+ let sigBytes;
+ try {
+ sigBytes = Buffer.from(signature, 'base64');
+ } catch {
+ return fail('bad_signature', 'signature is not valid base64');
+ }
+ if (sigBytes.length !== 64) return fail('bad_signature', 'Ed25519 signature must be 64 bytes');
+ let sigOk = false;
+ try {
+ sigOk = cryptoVerify(null, Buffer.from(canonicalize(unsigned), 'utf8'), pub, sigBytes);
+ } catch {
+ sigOk = false;
+ }
+ return sigOk ? null : fail('bad_signature', 'Ed25519 verification failed');
+}
+
function verifyResponse(job, response, opts = {}) {
// Rule 1: shape.
if (!response || typeof response !== 'object' || Array.isArray(response)) {
@@ -157,22 +179,8 @@ function verifyResponse(job, response, opts = {}) {
}
// Rule 4: signature over the canonical response minus `signature`.
- const { signature, ...unsigned } = response;
- let sigBytes;
- try {
- sigBytes = Buffer.from(signature, 'base64');
- } catch {
- return fail('bad_signature', 'signature is not valid base64');
- }
- if (sigBytes.length !== 64) return fail('bad_signature', 'Ed25519 signature must be 64 bytes');
- const payloadBytes = Buffer.from(canonicalize(unsigned), 'utf8');
- let sigOk = false;
- try {
- sigOk = cryptoVerify(null, payloadBytes, pub, sigBytes);
- } catch {
- sigOk = false;
- }
- if (!sigOk) return fail('bad_signature', 'Ed25519 verification failed');
+ const sigFailure = checkDetachedSignature(response, pub);
+ if (sigFailure) return sigFailure;
// Rule 5: freshness against the job deadline and the verifier clock.
const completedMs = Date.parse(response.completed_at);
@@ -198,6 +206,55 @@ function verifyResponse(job, response, opts = {}) {
};
}
+// A capability advertisement is verified by the same signature rule as a
+// response, minus the job binding and freshness checks (there is no job, and an
+// advertisement is regenerated per request). A requester runs this before it
+// trusts what a node claims it can do, and a directory service runs it on every
+// crawl. `opts.expectedPubkey` pins a key the caller already knows.
+function verifyAdvertisement(advertisement, opts = {}) {
+ if (!advertisement || typeof advertisement !== 'object' || Array.isArray(advertisement)) {
+ return fail('bad_shape', 'advertisement is not an object');
+ }
+ if (advertisement.spec !== OIN_SPEC) return fail('bad_shape', `spec must be ${OIN_SPEC}`);
+ for (const field of ['node_id', 'node_pubkey', 'generated_at', 'signature']) {
+ if (typeof advertisement[field] !== 'string' || !advertisement[field]) {
+ return fail('bad_shape', `missing field: ${field}`);
+ }
+ }
+ if (!Array.isArray(advertisement.capabilities) || advertisement.capabilities.length === 0) {
+ return fail('bad_shape', 'capabilities must be a non-empty array');
+ }
+ for (const cap of advertisement.capabilities) {
+ if (!cap || typeof cap !== 'object' || typeof cap.key !== 'string' || !cap.key) {
+ return fail('bad_shape', 'every capability needs a string key');
+ }
+ }
+ if (!advertisement.endpoints || typeof advertisement.endpoints !== 'object') {
+ return fail('bad_shape', 'endpoints must be an object');
+ }
+ if (advertisement.auth !== 'bearer' && advertisement.auth !== 'none') {
+ return fail('bad_shape', `auth must be bearer|none, got ${advertisement.auth}`);
+ }
+
+ const pub = pubKeyObjectFromField(advertisement.node_pubkey);
+ if (!pub) return fail('bad_pubkey', 'node_pubkey must be ed25519:<base64 32-byte key>');
+ if (opts.expectedPubkey && advertisement.node_pubkey !== opts.expectedPubkey) {
+ return fail('untrusted_node', `advertised key does not match pinned ${opts.expectedPubkey}`);
+ }
+
+ const sigFailure = checkDetachedSignature(advertisement, pub);
+ if (sigFailure) return sigFailure;
+
+ return {
+ ok: true,
+ verified: true,
+ verdict: 'verified',
+ nodeId: advertisement.node_id,
+ nodePubkey: advertisement.node_pubkey,
+ capabilities: advertisement.capabilities.map((c) => c.key),
+ };
+}
+
// Rule 6 (optional): fetch output.url and check bytes + sha256. The caller
// supplies the fetch implementation in tests; in production it must apply the
// SSRF guards the spec requires (https-only, private-IP rejection, size cap).
@@ -236,6 +293,7 @@ export {
pubkeyB64FromSecret,
signAdvertisement,
signResponse,
+ verifyAdvertisement,
verifyOutput,
verifyResponse,
};
diff --git a/scripts/inference-settlement-proof.mjs b/scripts/inference-settlement-proof.mjs
index c29f24f58..0e792548b 100644
--- a/scripts/inference-settlement-proof.mjs
+++ b/scripts/inference-settlement-proof.mjs
@@ -1,26 +1,43 @@
#!/usr/bin/env node
// Proof run for Roadmap phase 4: one inference job metered, settled on the
-// x402 test lane, and its receipt verified against the job signature. No real
-// funds: the settlement lane is Solana DEVNET via the platform's self-hosted
-// facilitator (X402_SELF_FACILITATOR_ENABLED), co-signed by a throwaway
-// sponsor keypair generated fresh per run and funded by a devnet SOL airdrop.
+// x402 test lane, and its receipt verified against the job signature.
+//
+// NO REAL FUNDS. Every identity in this run is a throwaway keypair generated
+// fresh per run, and the settlement asset is an SPL mint this script creates on
+// the test ledger seconds earlier. Nothing here touches a platform wallet, a
+// mainnet mint, or a real balance.
//
// What this script proves, end to end:
// 1. A real LLM completion runs through the platform provider chain and is
// metered (prompt/response hashes + provider-reported token counts).
-// 2. The node signs the metered job core (ed25519, INFERENCE_SIGNING_KEY).
-// 3. A devnet x402 payment is built (SPL TransferChecked), verified by the
+// 2. The node signs the metered job core (ed25519).
+// 3. A real x402 payment is built (SPL TransferChecked), verified by the
// in-house facilitator, and settled on-chain: verifyPayment →
-// settlePayment from api/_lib/x402-spec.js against
-// NETWORK_SOLANA_DEVNET, exactly as api/_lib/x402-paid-endpoint.js runs
-// them in production.
+// settlePayment from api/_lib/x402-spec.js, exactly as
+// api/_lib/x402-paid-endpoint.js runs them in production.
// 4. The settlement receipt is issued over job + response signature +
// payment facts and verified with verifyInferenceReceipt, including the
-// on-chain confirmation leg (getSignatureStatuses on devnet).
+// on-chain confirmation leg (getSignatureStatuses).
+//
+// ── Lanes ─────────────────────────────────────────────────────────────────
+// `local` (a solana-test-validator on this machine) is the reproducible lane
+// and the default when one is reachable. Start it with:
+//
+// solana-test-validator --ledger /tmp/three-ws-proof-ledger --reset --quiet
+//
+// `devnet` is the shared public lane. It settles identically, but its faucet is
+// rate-limited per IP and is frequently dry on shared CI egress, which is why
+// it is not the default. Force either lane with INFERENCE_PROOF_LANE=local|devnet.
+//
+// The local lane is named honestly: a test validator mints a fresh genesis on
+// every reset, so the script reads that genesis hash and derives the lane's real
+// CAIP-2 id from it (see api/_lib/x402/solana-networks.js). The receipt records
+// the ledger the payment actually settled on, never a devnet label it did not
+// earn.
//
// Run: node scripts/inference-settlement-proof.mjs
-// Optional env: INFERENCE_PROOF_PROMPT, VERTEX_CLAUDE_ENABLED=1 to run the
-// completion on Vertex Claude (GCP credits) instead of the free chain.
+// Optional env: INFERENCE_PROOF_PROMPT, INFERENCE_PROOF_LANE,
+// INFERENCE_PROOF_LOCAL_RPC, SOLANA_DEVNET_RPC_URL.
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
@@ -41,11 +58,76 @@ try {
/* no .env on this machine; env vars may still come from the shell */
}
-// Devnet settlement wiring, set before importing the rail so env.js reads it.
-// The proof needs no DATABASE_URL: logPaymentEvent is not on this path, and
-// the metered-job insert is exercised separately against the schema.
+const log = (step, msg) => console.log(`\x1b[36m[${step}]\x1b[0m ${msg}`);
+
+const LOCAL_RPC = process.env.INFERENCE_PROOF_LOCAL_RPC || 'http://127.0.0.1:8899';
+const DEVNET_RPC = process.env.SOLANA_DEVNET_RPC_URL || 'https://api.devnet.solana.com';
+const START_VALIDATOR = `solana-test-validator --ledger /tmp/three-ws-proof-ledger --reset --quiet`;
+
+async function rpc(url, method, params) {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ });
+ const data = await res.json();
+ if (data.error) throw new Error(`${method}: ${JSON.stringify(data.error)}`);
+ return data.result;
+}
+
+// ── Lane resolution ───────────────────────────────────────────────────────
+// Done before importing the rail so SOLANA_RPC_URL and the local-lane network
+// id are in place for every module that reads them.
+const requestedLane = (process.env.INFERENCE_PROOF_LANE || 'auto').toLowerCase();
+if (!['auto', 'local', 'devnet'].includes(requestedLane)) {
+ console.error(`INFERENCE_PROOF_LANE must be auto, local, or devnet (got ${requestedLane})`);
+ process.exit(2);
+}
+
+async function localValidatorGenesis() {
+ try {
+ return await rpc(LOCAL_RPC, 'getGenesisHash', []);
+ } catch {
+ return null;
+ }
+}
+
+let lane;
+let rpcUrl;
+let laneGenesis = null;
+if (requestedLane === 'devnet') {
+ lane = 'devnet';
+ rpcUrl = DEVNET_RPC;
+} else {
+ laneGenesis = await localValidatorGenesis();
+ if (laneGenesis) {
+ lane = 'local';
+ rpcUrl = LOCAL_RPC;
+ } else if (requestedLane === 'local') {
+ console.error(`No solana-test-validator answering at ${LOCAL_RPC}. Start one with:\n\n ${START_VALIDATOR}\n`);
+ process.exit(2);
+ } else {
+ lane = 'devnet';
+ rpcUrl = DEVNET_RPC;
+ log('lane', `no local validator at ${LOCAL_RPC}; falling back to the shared devnet lane`);
+ }
+}
+
process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
-process.env.SOLANA_RPC_URL = process.env.SOLANA_DEVNET_RPC_URL || 'https://api.devnet.solana.com';
+process.env.SOLANA_RPC_URL = rpcUrl;
+
+const { caip2ForGenesisHash } = await import('../api/_lib/x402/solana-networks.js');
+const { NETWORK_SOLANA_DEVNET } = await import('../api/_lib/x402-spec.js');
+
+let laneNetwork;
+if (lane === 'local') {
+ laneNetwork = caip2ForGenesisHash(laneGenesis);
+ // Teach the rail this ledger's real CAIP-2 id for the duration of the run.
+ process.env.X402_SOLANA_LOCAL_NETWORK = laneNetwork;
+} else {
+ laneNetwork = NETWORK_SOLANA_DEVNET;
+}
+log('lane', `${lane} lane: rpc=${rpcUrl} network=${laneNetwork}`);
const {
meterInferenceJob,
@@ -55,26 +137,38 @@ const {
signerPublicKey,
} = await import('../api/_lib/inference-settlement.js');
const { llmComplete } = await import('../api/_lib/llm.js');
-const {
- NETWORK_SOLANA_DEVNET,
- verifyPayment,
- settlePayment,
-} = await import('../api/_lib/x402-spec.js');
+const { verifyPayment, settlePayment } = await import('../api/_lib/x402-spec.js');
const { loadFeePayerKeypair } = await import('../api/_lib/x402/self-facilitator.js');
const { createSolanaSigner, buildSolanaExactPayload } = await import('../api/_lib/x402/a2a-client.js');
+const { Connection, Keypair } = await import('@solana/web3.js');
+const { createMint, getOrCreateAssociatedTokenAccount, mintTo } = await import('@solana/spl-token');
const { ed25519 } = await import('@noble/curves/ed25519.js');
const bs58 = (await import('bs58')).default;
-const log = (step, msg) => console.log(`\x1b[36m[${step}]\x1b[0m ${msg}`);
+// ── The facilitator, on loopback ──────────────────────────────────────────
+// With the self-hosted facilitator enabled, the rail resolves it to
+// `${APP_ORIGIN}/api/x402-facilitator` and calls it over HTTP. APP_ORIGIN
+// defaults to https://three.ws, so a proof run left alone would ask PRODUCTION
+// to co-sign a test-lane payment (and be refused by its allowlist, which is the
+// correct answer to the wrong question). Serve the real facilitator handler on
+// loopback under this run's env instead: same handler, same wire contract, and
+// nothing leaves the machine.
+const { createServer } = await import('node:http');
+const facilitatorHandler = (await import('../api/x402-facilitator/[action].js')).default;
+const facilitatorServer = createServer((req, res) => {
+ const url = new URL(req.url, 'http://127.0.0.1');
+ req.query = { action: url.pathname.split('/').filter(Boolean).pop() };
+ facilitatorHandler(req, res);
+});
+await new Promise((resolve) => facilitatorServer.listen(0, '127.0.0.1', resolve));
+facilitatorServer.unref();
+process.env.PUBLIC_APP_ORIGIN = `http://127.0.0.1:${facilitatorServer.address().port}`;
+log('lane', `self-hosted facilitator served on loopback at ${process.env.PUBLIC_APP_ORIGIN}/api/x402-facilitator`);
// Fresh throwaway identities for the run: payer, payee, sponsor (fee payer),
// node signing key, receipt issuer key. Nothing here touches a real wallet.
const fresh = () => ed25519.utils.randomSecretKey?.() ?? ed25519.utils.randomPrivateKey();
-const seedToFull = (seed) => {
- // Solana keypairs are 64 bytes: 32-byte seed + 32-byte pubkey.
- const pub = ed25519.getPublicKey(seed);
- return new Uint8Array([...seed, ...pub]);
-};
+const seedToFull = (seed) => new Uint8Array([...seed, ...ed25519.getPublicKey(seed)]);
const payerSeed = fresh();
const payeeSeed = fresh();
@@ -90,62 +184,35 @@ const sponsorPub = bs58.encode(ed25519.getPublicKey(sponsorSeed));
process.env.X402_FEE_PAYER_SECRET_BASE58 = sponsorSecret58;
process.env.X402_FEE_PAYER_SOLANA = sponsorPub;
-// Devnet USDC mint (Circle's well-known devnet SPL USDC). The payment moves
-// devnet USDC from the throwaway payer to the throwaway payee; the payer is
-// funded by the faucet step below (or a cached env secret on re-runs).
-const DEVNET_USDC_MINT = process.env.INFERENCE_PROOF_DEVNET_USDC_MINT || '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU';
+async function confirmSig(sig, timeoutMs = 60_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const r = await rpc(rpcUrl, 'getSignatureStatuses', [[sig], { searchTransactionHistory: true }]);
+ const st = r?.value?.[0];
+ if (st?.err) throw new Error(`signature ${sig} failed on-chain: ${JSON.stringify(st.err)}`);
+ if (st && (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized')) return st;
+ await new Promise((r2) => setTimeout(r2, 500));
+ }
+ throw new Error(`signature ${sig} not confirmed within ${timeoutMs}ms`);
+}
-async function airdrop(pubkeyB58, sol = 1) {
+async function airdrop(pubkeyB58, sol) {
const lamports = Math.round(sol * 1e9);
- // The public RPC's own airdrop is per-IP rate-limited and shared by every
- // CI runner on the planet; the official faucet host is the documented
- // alternate source. Try the RPC first (one less moving part), then the
- // faucet, and report BOTH errors when neither can fund the wallet so the
- // operator sees the real blocker instead of a generic 429.
- const attempts = [];
- try {
- const data = await rpcCall('requestAirdrop', [pubkeyB58, lamports]);
- return data;
- } catch (err) {
- attempts.push(`rpc: ${err.message}`);
- }
try {
- const res = await fetch('https://faucet.solana.com/api/airdrop', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ pubkey: pubkeyB58, lamports, network: 'devnet' }),
- });
- const data = await res.json().catch(() => ({}));
- const sig = data?.signature || data?.result;
- if (!res.ok || !sig) throw new Error(`HTTP ${res.status} ${JSON.stringify(data).slice(0, 200)}`);
- return sig;
+ return await rpc(rpcUrl, 'requestAirdrop', [pubkeyB58, lamports]);
} catch (err) {
- attempts.push(`faucet.solana.com: ${err.message}`);
+ if (lane === 'local') throw err;
+ // The public devnet faucet is rate-limited per IP and shared by every CI
+ // runner on the planet. Name the reproducible lane rather than leaving the
+ // operator staring at a bare 429.
+ throw new Error(
+ `devnet airdrop failed (${err.message}).\n` +
+ `The public faucet is dry or rate-limited for this IP. Run the proof on the local lane instead:\n\n ${START_VALIDATOR}\n\nthen re-run this script.`,
+ );
}
- throw new Error(`airdrop failed on every source: ${attempts.join(' | ')}`);
-}
-
-async function rpcCall(method, params) {
- const res = await fetch(process.env.SOLANA_RPC_URL, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
- });
- const data = await res.json();
- if (data.error) throw new Error(`${method}: ${JSON.stringify(data.error)}`);
- return data.result;
-}
-
-async function confirmSig(sig) {
- for (let i = 0; i < 30; i++) {
- const r = await rpcCall('getSignatureStatuses', [[sig], { searchTransactionHistory: true }]);
- const st = r?.value?.[0];
- if (st && (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized')) return st;
- await new Promise((r2) => setTimeout(r2, 1000));
- }
- throw new Error(`signature ${sig} not confirmed within 30s`);
}
+// ── 1. Meter a real inference job ─────────────────────────────────────────
const prompt = process.env.INFERENCE_PROOF_PROMPT || 'Count to 3.';
log('meter', `running real inference through the platform provider chain: ${JSON.stringify(prompt)}`);
@@ -172,51 +239,52 @@ const job = meterInferenceJob({
});
log('meter', `job ${job.jobId}: promptSha256=${job.promptSha256.slice(0, 16)}… responseSha256=${job.responseSha256.slice(0, 16)}… tokens=${job.tokensUsed}`);
+// ── 2. The node signs the metered job ─────────────────────────────────────
const nodeKey = `[${Array.from(nodeSeed).join(',')}]`;
const issuerKey = `[${Array.from(issuerSeed).join(',')}]`;
const sig = signJobResponse(job, nodeKey);
log('sign', `response signature by node ${sig.responseSigner} (${sig.responseSignature.slice(0, 16)}…)`);
-// ── Devnet settlement over the existing x402 rail ─────────────────────────
-// Fund the payer + sponsor with devnet SOL, and the payer with devnet USDC
-// from a faucet when available. The facilitator co-signs with the sponsor.
-log('settle', `funding throwaway wallets on devnet (payer=${payerPub.slice(0, 12)}… sponsor=${sponsorPub.slice(0, 12)}…)`);
-await confirmSig(await airdrop(sponsorPub, 1));
-log('settle', 'sponsor funded with 1 devnet SOL');
-await confirmSig(await airdrop(payerPub, 1));
-log('settle', 'payer funded with 1 devnet SOL');
+// ── 3. Provision the test lane and settle over the x402 rail ──────────────
+// The sponsor pays every setup fee and co-signs the payment as the facilitator
+// fee payer, so the payer wallet needs no SOL at all: it holds only the SPL
+// balance it is about to spend, exactly like a real gasless x402 buyer.
+log('settle', `funding the throwaway sponsor on ${lane} (${sponsorPub})`);
+await confirmSig(await airdrop(sponsorPub, 2));
+log('settle', 'sponsor funded with 2 SOL');
-const amountAtomics = '5000';
+const connection = new Connection(rpcUrl, 'confirmed');
+const sponsorKeypair = Keypair.fromSeed(sponsorSeed);
-// The payer needs devnet USDC at its ATA. Devnet USDC is freely mintable from
-// Circle's faucet off-chain; inside this script we create the ATA and attempt
-// a sponsored self-fund only when the payer already holds a balance. Check the
-// balance; if zero, the settle leg reports exactly which funding step is
-// missing rather than forging a settlement.
-const payerAtaInfo = await rpcCall('getTokenAccountsByOwner', [
- payerPub,
- { mint: DEVNET_USDC_MINT },
- { encoding: 'jsonParsed' },
-]).catch(() => null);
-const payerBalance = payerAtaInfo?.value?.[0]?.account?.data?.parsed?.info?.tokenAmount?.amount ?? '0';
-log('settle', `payer devnet USDC balance: ${payerBalance} atomics`);
-if (BigInt(payerBalance) < BigInt(amountAtomics)) {
- log('settle', 'payer holds no devnet USDC; funding it via the Circle devnet faucet is an interactive step.');
- log('settle', `fund ${payerPub} at https://faucet.circle.com (Solana devnet USDC), then re-run with INFERENCE_PROOF_PAYER_SECRET set.`);
- console.log('\nPROOF RESULT: inference metered + signed; settlement leg blocked on devnet USDC funding (no real funds involved).');
- console.log(JSON.stringify({ job, responseSignature: sig }, null, 2));
- process.exit(3);
-}
+// A purpose-made 6-decimal SPL mint for this run. Creating it here is what
+// makes the proof non-interactive: no third-party token faucet, no pre-funded
+// wallet, and no real asset anywhere in the transcript.
+const mint = await createMint(connection, sponsorKeypair, sponsorKeypair.publicKey, null, 6);
+log('settle', `created test SPL mint ${mint.toBase58()} (6 decimals, authority = throwaway sponsor)`);
+
+// The self-facilitator refuses to settle to a payTo it does not know, or in a
+// mint the platform does not issue 402s for. Both guards stay ON for the proof:
+// they are pointed at this run's throwaway payee and its freshly created test
+// mint, which is exactly how an operator configures a test lane.
+process.env.X402_SELF_FACILITATOR_PAYTO_ALLOWLIST = payeePub;
+process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();
+
+const amountAtomics = '5000';
+const payerAta = await getOrCreateAssociatedTokenAccount(connection, sponsorKeypair, mint, Keypair.fromSeed(payerSeed).publicKey);
+await getOrCreateAssociatedTokenAccount(connection, sponsorKeypair, mint, Keypair.fromSeed(payeeSeed).publicKey);
+const mintSig = await mintTo(connection, sponsorKeypair, mint, payerAta.address, sponsorKeypair, 1_000_000);
+await confirmSig(mintSig);
+log('settle', `payer ${payerPub} funded with 1000000 atomics of the test mint`);
const requirement = {
scheme: 'exact',
- network: NETWORK_SOLANA_DEVNET,
+ network: laneNetwork,
amount: amountAtomics,
maxTimeoutSeconds: 60,
resource: 'https://three.ws/api/x402/llm-proxy',
payTo: payeePub,
- asset: DEVNET_USDC_MINT,
- extra: { name: 'USDC', decimals: 6, feePayer: sponsorPub },
+ asset: mint.toBase58(),
+ extra: { name: 'PROOF-USD', decimals: 6, feePayer: sponsorPub },
};
const signer = await createSolanaSigner(payerSecret58);
@@ -224,7 +292,7 @@ const payload = await buildSolanaExactPayload({
accept: requirement,
signer,
resource: requirement.resource,
- rpcUrl: process.env.SOLANA_RPC_URL,
+ rpcUrl,
});
const paymentHeader = Buffer.from(JSON.stringify(payload)).toString('base64');
log('settle', 'payment payload built (SPL TransferChecked, partially signed by payer)');
@@ -236,25 +304,27 @@ const verified = await verifyPayment({ paymentHeader, requirements: [requirement
log('settle', `facilitator /verify: payer=${verified.payer}`);
const settled = await settlePayment({ verified });
-log('settle', `settled on devnet: tx=${settled.transaction}`);
+log('settle', `settled on ${lane}: tx=${settled.transaction}`);
+// ── 4. Issue and verify the receipt ───────────────────────────────────────
const receipt = issueInferenceReceipt({
job,
responseSignature: sig.responseSignature,
responseSigner: sig.responseSigner,
payment: {
- network: NETWORK_SOLANA_DEVNET,
+ network: laneNetwork,
payer: verified.payer,
payTo: payeePub,
amountAtomics,
- asset: DEVNET_USDC_MINT,
+ asset: mint.toBase58(),
transaction: settled.transaction,
},
secret: issuerKey,
});
log('receipt', `issued by ${receipt.signer} (signature ${receipt.signature.slice(0, 16)}…)`);
-// Full verification: signatures, raw bindings, pinned issuer, on-chain leg.
+// Full verification: both signatures, the raw prompt/content bindings, the
+// pinned issuer, and the on-chain leg.
const verdict = verifyInferenceReceipt(receipt, {
prompt,
content: completion.text,
@@ -268,9 +338,18 @@ if (!verdict.ok) {
process.exit(1);
}
-// On-chain confirmation leg, same read-only call the CLI runs.
+// A receipt that still verifies after the response text is altered would prove
+// nothing, so the run also demonstrates the negative: one flipped character in
+// the completion must break the binding.
+const tampered = verifyInferenceReceipt(receipt, { prompt, content: `${completion.text} ` });
+if (tampered.ok) {
+ console.error('\nPROOF FAILED: receipt verified against altered response content');
+ process.exit(1);
+}
+log('verify', `tamper check: altering the response invalidates the receipt (${tampered.reason})`);
+
const st = await confirmSig(settled.transaction);
log('verify', `on-chain settlement confirmed at slot ${st.slot}`);
-console.log('\nPROOF RESULT: PASS. One inference job metered, settled on the devnet test lane, receipt verified against the job signature.');
-console.log(JSON.stringify({ jobId: job.jobId, tx: settled.transaction, receipt }, null, 2));
+console.log(`\nPROOF RESULT: PASS. One inference job metered, settled on the ${lane} test lane, receipt verified against the job signature.`);
+console.log(JSON.stringify({ lane, network: laneNetwork, jobId: job.jobId, tx: settled.transaction, receipt }, null, 2));
diff --git a/scripts/oin-conformance.mjs b/scripts/oin-conformance.mjs
new file mode 100644
index 000000000..975beac4d
--- /dev/null
+++ b/scripts/oin-conformance.mjs
@@ -0,0 +1,274 @@
+#!/usr/bin/env node
+// Open Inference Protocol (OIN) v0.1 conformance runner.
+//
+// Drives a live OIN node through the whole protocol and verifies every
+// signature it produces with the reference verifier (api/_lib/oin-verify.js):
+//
+// 1. GET /.well-known/oin -> verify the advertisement signature
+// 2. POST /oin/jobs -> submit a job envelope for an advertised
+// capability, check the returned digest
+// 3. GET /oin/jobs/:id -> poll to a terminal state
+// 4. verifyResponse(job, res) -> spec rules 1-5
+// 5. verifyOutput(res) -> spec rule 6, fetch and hash the artifact
+//
+// This is the tool that proves a node speaks the protocol, whether it is one of
+// the platform's own workers or a third-party operator's machine. It fetches
+// nothing but the node's own routes and the artifact URL the node signed.
+//
+// Usage:
+// node scripts/oin-conformance.mjs --node <base-url>
+// [--api-key <bearer>] credential when the node advertises bearer
+// [--capability <key>] default: the first advertised capability
+// [--model <name>] default: the first model of that capability
+// [--input <https url>] payload reference for input.data
+// [--params <json>] capability params object
+// [--timeout <seconds>] poll ceiling, default 180
+// [--no-output-check] skip rule 6 (do not fetch the artifact)
+// [--json] machine-readable transcript
+//
+// Exit code 0 = every check passed; 1 = a check failed; 2 = usage error.
+// Spec: specs/OPEN_INFERENCE_PROTOCOL.md.
+
+import { randomBytes } from 'node:crypto';
+
+import {
+ digestJob,
+ verifyAdvertisement,
+ verifyOutput,
+ verifyResponse,
+} from '../api/_lib/oin-verify.js';
+
+const DEFAULT_TIMEOUT_S = 180;
+const POLL_INTERVAL_MS = 1500;
+
+function usage(exitCode) {
+ const msg = `usage: node scripts/oin-conformance.mjs --node <base-url>
+ [--api-key <bearer>] [--capability <key>] [--model <name>]
+ [--input <https url>] [--params <json>] [--timeout <seconds>]
+ [--no-output-check] [--json]`;
+ if (exitCode === 0) console.log(msg);
+ else console.error(msg);
+ process.exit(exitCode);
+}
+
+function parseArgs(argv) {
+ const args = { outputCheck: true, json: false, timeout: DEFAULT_TIMEOUT_S };
+ const rest = [...argv];
+ while (rest.length) {
+ const flag = rest.shift();
+ if (flag === '--node') args.node = rest.shift();
+ else if (flag === '--api-key') args.apiKey = rest.shift();
+ else if (flag === '--capability') args.capability = rest.shift();
+ else if (flag === '--model') args.model = rest.shift();
+ else if (flag === '--input') args.input = rest.shift();
+ else if (flag === '--params') args.params = rest.shift();
+ else if (flag === '--timeout') args.timeout = Number(rest.shift());
+ else if (flag === '--no-output-check') args.outputCheck = false;
+ else if (flag === '--json') args.json = true;
+ else if (flag === '--help' || flag === '-h') usage(0);
+ else {
+ console.error(`unknown flag: ${flag}`);
+ usage(2);
+ }
+ }
+ if (!args.node) usage(2);
+ if (!Number.isFinite(args.timeout) || args.timeout <= 0) {
+ console.error('--timeout must be a positive number of seconds');
+ usage(2);
+ }
+ args.node = args.node.replace(/\/+$/, '');
+ return args;
+}
+
+const steps = [];
+
+function record(name, ok, detail) {
+ steps.push({ step: name, ok, detail });
+ return ok;
+}
+
+function report(args, ok) {
+ if (args.json) {
+ console.log(JSON.stringify({ ok, node: args.node, steps }, null, 2));
+ return;
+ }
+ for (const s of steps) {
+ console.log(`${s.ok ? 'PASS' : 'FAIL'} ${s.step}${s.detail ? `: ${s.detail}` : ''}`);
+ }
+ console.log(ok ? '\nOIN conformance: PASS' : '\nOIN conformance: FAIL');
+}
+
+function authHeaders(args) {
+ return args.apiKey ? { Authorization: `Bearer ${args.apiKey}` } : {};
+}
+
+async function readJson(res) {
+ const text = await res.text();
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error(`non-JSON response (HTTP ${res.status}): ${text.slice(0, 200)}`);
+ }
+}
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+
+ // Step 1: the advertisement, and its signature.
+ let advertisement;
+ try {
+ const res = await fetch(`${args.node}/.well-known/oin`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ advertisement = await readJson(res);
+ } catch (err) {
+ record('advertisement fetched', false, err?.message || String(err));
+ report(args, false);
+ return 1;
+ }
+ record('advertisement fetched', true, `node_id=${advertisement.node_id}`);
+
+ const adVerdict = verifyAdvertisement(advertisement);
+ if (!record('advertisement signature verified', adVerdict.ok, adVerdict.verdict + (adVerdict.detail ? ` (${adVerdict.detail})` : ''))) {
+ report(args, false);
+ return 1;
+ }
+
+ // Step 2: pick a capability and submit a job envelope against it.
+ const capability = args.capability || advertisement.capabilities[0]?.key;
+ const capEntry = advertisement.capabilities.find((c) => c.key === capability);
+ if (!capEntry) {
+ record('capability advertised', false, `${capability} is not in the advertisement`);
+ report(args, false);
+ return 1;
+ }
+ record('capability advertised', true, capability);
+
+ const model = args.model || capEntry.models?.[0];
+ if (!args.input) {
+ record('job input supplied', false, '--input <https url> is required to run a job');
+ report(args, false);
+ return 1;
+ }
+
+ const job = {
+ spec: 'oin/0.1',
+ job_id: `j_conf_${randomBytes(8).toString('hex')}`,
+ capability,
+ created_at: new Date().toISOString(),
+ deadline: args.timeout,
+ input: { model, data: args.input },
+ };
+ if (args.params) {
+ try {
+ job.params = JSON.parse(args.params);
+ } catch {
+ console.error('--params must be a JSON object');
+ return 2;
+ }
+ }
+
+ let submitted;
+ try {
+ const res = await fetch(`${args.node}/oin/jobs`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...authHeaders(args) },
+ body: JSON.stringify(job),
+ });
+ submitted = await readJson(res);
+ if (res.status !== 202) throw new Error(`expected 202, got ${res.status}: ${JSON.stringify(submitted).slice(0, 200)}`);
+ } catch (err) {
+ record('job accepted (202)', false, err?.message || String(err));
+ report(args, false);
+ return 1;
+ }
+ record('job accepted (202)', true, submitted.job_id);
+
+ // The node echoes the digest it computed; a mismatch here means the two
+ // sides disagree on canonicalization, which would fail rule 2 later anyway.
+ const expectedDigest = digestJob(job);
+ if (!record(
+ 'node job_digest matches the requester digest',
+ submitted.job_digest === expectedDigest,
+ submitted.job_digest === expectedDigest ? expectedDigest : `node=${submitted.job_digest} requester=${expectedDigest}`,
+ )) {
+ report(args, false);
+ return 1;
+ }
+
+ // Step 3: poll to a terminal state.
+ const deadlineMs = Date.now() + args.timeout * 1000;
+ let response = null;
+ let lastStatus = 'unknown';
+ while (Date.now() < deadlineMs) {
+ await sleep(POLL_INTERVAL_MS);
+ let polled;
+ try {
+ const res = await fetch(`${args.node}/oin/jobs/${job.job_id}`, { headers: authHeaders(args) });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ polled = await readJson(res);
+ } catch (err) {
+ record('job polled to a terminal state', false, err?.message || String(err));
+ report(args, false);
+ return 1;
+ }
+ lastStatus = polled.status;
+ if (polled.status === 'done' || polled.status === 'failed') {
+ response = polled;
+ break;
+ }
+ }
+ if (!response) {
+ record('job polled to a terminal state', false, `still ${lastStatus} after ${args.timeout}s`);
+ report(args, false);
+ return 1;
+ }
+ record('job polled to a terminal state', true, response.status);
+
+ // Step 4: rules 1-5, against the advertised key.
+ const verdict = verifyResponse(job, response, { expectedPubkey: advertisement.node_pubkey });
+ if (!record(
+ 'signed response verified (spec rules 1-5)',
+ verdict.ok,
+ verdict.verdict + (verdict.detail ? ` (${verdict.detail})` : ''),
+ )) {
+ report(args, false);
+ return 1;
+ }
+
+ // A signed failure is a valid protocol outcome and verifies like any other
+ // response, but it is not a passing conformance run: the node did not do the
+ // work, so there is no artifact to check.
+ if (response.status === 'failed') {
+ record('job succeeded', false, `${response.error?.code}: ${response.error?.message}`);
+ report(args, false);
+ return 1;
+ }
+
+ // Step 5: rule 6, the artifact bytes behind the signature.
+ if (args.outputCheck) {
+ const outVerdict = await verifyOutput(response);
+ if (!record(
+ 'output artifact verified (spec rule 6)',
+ outVerdict.ok,
+ outVerdict.verdict + (outVerdict.detail ? ` (${outVerdict.detail})` : ` ${outVerdict.bytes} bytes`),
+ )) {
+ report(args, false);
+ return 1;
+ }
+ } else {
+ record('output artifact verified (spec rule 6)', true, 'skipped (verified_unfetched_output)');
+ }
+
+ report(args, true);
+ return 0;
+}
+
+main().then(
+ (code) => process.exit(code),
+ (err) => {
+ console.error(`oin-conformance: ${err?.stack || err}`);
+ process.exit(1);
+ },
+);
diff --git a/specs/OPEN_INFERENCE_PROTOCOL.md b/specs/OPEN_INFERENCE_PROTOCOL.md
index c0059c290..4ff7def4e 100644
--- a/specs/OPEN_INFERENCE_PROTOCOL.md
+++ b/specs/OPEN_INFERENCE_PROTOCOL.md
@@ -198,10 +198,30 @@ payment.
### Reference verifier
[`api/_lib/oin-verify.js`](../api/_lib/oin-verify.js) implements rules 1-5 in
-dependency-free Node (Ed25519 via `crypto.createVerify`), plus an opt-in
-`verifyOutput()` for rule 6. It is the conformance target for third-party
+dependency-free Node (Ed25519 via `node:crypto`), plus an opt-in
+`verifyOutput()` for rule 6 and a `verifyAdvertisement()` that applies the same
+signature rule to `/.well-known/oin` (rules 1, 3, and 4; there is no job to bind
+and no deadline to miss). It is the conformance target for third-party
verifiers.
+### Conformance runner
+
+[`scripts/oin-conformance.mjs`](../scripts/oin-conformance.mjs) drives a live
+node through the entire protocol and verifies every signature with the
+reference verifier: fetch and verify the advertisement, submit a job for an
+advertised capability, confirm the node's `job_digest` matches the requester's
+own canonicalization, poll to a terminal state, verify the signed response, then
+fetch the artifact and check rule 6. It exits 0 only when every step passes, so
+it is the check an operator runs before claiming a node speaks OIN.
+
+```bash
+node scripts/oin-conformance.mjs \
+ --node https://your-node.example \
+ --api-key "$NODE_API_KEY" \
+ --input https://three.ws/avatars/fox.glb \
+ --model voxel --params '{"resolution":24,"output_format":"glb"}'
+```
+
## Reference worker
`workers/stylize` (the platform's CPU mesh-stylization worker) speaks OIN
@@ -214,6 +234,21 @@ behind a flag:
start, so a node can never advertise a key it cannot sign with.
- With the flag off the worker is byte-for-byte its pre-OIN self.
+A node with no GCS bucket (any self-hosted operator) sets `OIN_RESULT_DIR` and
+`OIN_RESULT_BASE_URL` instead, and artifacts land on the filesystem under the
+URL the signature commits to. That is the whole local proof:
+
+```bash
+cd workers/stylize
+API_KEY=local GCS_BUCKET=unused OIN_ENABLED=true \
+OIN_SIGNING_KEY="$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))")" \
+OIN_RESULT_DIR=/tmp/oin OIN_RESULT_BASE_URL=http://127.0.0.1:8402 \
+python -m uvicorn main:app --port 8401
+```
+
+with `/tmp/oin` served on port 8402, then point the conformance runner above at
+`http://127.0.0.1:8401`.
+
The worker-side protocol layer is [`workers/stylize/oin.py`](../workers/stylize/oin.py),
vendored byte-identical into any worker that adopts OIN (same pattern as
`worker_security.py`). Job execution is the same pipeline the native `/process`
diff --git a/specs/README.md b/specs/README.md
index d8d1e2e35..103eb1b9f 100644
--- a/specs/README.md
+++ b/specs/README.md
@@ -21,6 +21,9 @@ The specifications that define the three.ws embodied-agent platform: on-chain id
- [`PROVENANCE_3D.md`](./PROVENANCE_3D.md): Verifiable 3D Provenance v1. C2PA-style signed content credentials for AI-generated 3D: creator, prompt, model, lineage and the GLB's content hash, ed25519-signed and anchored on Solana. Verification is free and public.
- [`SIM_READINESS.md`](./SIM_READINESS.md): Simulation Readiness v1. The physics grade a 3D asset carries: watertightness, metric scale, mass and inertia, and a convex collision proxy, in four verdicts. Everything is derived from the mesh; anything unknowable from the geometry is reported as unknown rather than invented. Rides the provenance credential when signed.
+- [`OPEN_INFERENCE_PROTOCOL.md`](./OPEN_INFERENCE_PROTOCOL.md): Open Inference Protocol (OIN) v0.1. The vendor-neutral wire protocol for agent inference: a job envelope, a signed capability advertisement, and an Ed25519-signed response anyone can verify against the node's published key, so inference decouples from any single provider. Reference verifier in `api/_lib/oin-verify.js`; reference node in `workers/stylize`.
+- [`inference-receipts.md`](./inference-receipts.md): Inference Receipt v1. The settlement half of the same story: what a paid inference call hands back as proof (job, model, input/output hashes, node and issuer signatures, the settlement transaction) and how to verify it offline.
+
## Schema
[`schema/`](./schema) holds the SQL DDL for the Postgres tables that back these specs (see `schema/README.md` for column-level docs):
diff --git a/tests/oin-verify.test.js b/tests/oin-verify.test.js
index ca8268f42..602175c9a 100644
--- a/tests/oin-verify.test.js
+++ b/tests/oin-verify.test.js
@@ -11,6 +11,7 @@ import {
pubkeyB64FromSecret,
signAdvertisement,
signResponse,
+ verifyAdvertisement,
verifyOutput,
verifyResponse,
} from '../api/_lib/oin-verify.js';
@@ -240,6 +241,63 @@ describe('verifyOutput (rule 6)', () => {
});
});
+function makeAdvertisement(overrides = {}) {
+ return {
+ spec: 'oin/0.1',
+ node_id: 'node_test',
+ node_pubkey: NODE_PUBKEY,
+ generated_at: '2026-08-12T00:00:00.000Z',
+ capabilities: [{ key: 'mesh.stylize', version: '0.1', models: ['voxel'], pricing: { currency: 'USDC', unit: 'job', amount: '0.01' } }],
+ endpoints: { submit: '/oin/jobs', poll: '/oin/jobs/:id', health: '/health' },
+ auth: 'bearer',
+ ...overrides,
+ };
+}
+
+describe('verifyAdvertisement', () => {
+ it('accepts a self-signed advertisement and reports its capabilities', () => {
+ const out = verifyAdvertisement(signAdvertisement(makeAdvertisement(), SEED_B64));
+ expect(out.ok).toBe(true);
+ expect(out.verdict).toBe('verified');
+ expect(out.nodeId).toBe('node_test');
+ expect(out.capabilities).toEqual(['mesh.stylize']);
+ });
+
+ it('bad_signature: pricing edited after signing', () => {
+ const signed = signAdvertisement(makeAdvertisement(), SEED_B64);
+ signed.capabilities[0].pricing.amount = '0';
+ expect(verifyAdvertisement(signed).verdict).toBe('bad_signature');
+ });
+
+ it('bad_signature: signed by a key other than the one advertised', () => {
+ const signed = signAdvertisement(makeAdvertisement(), OTHER_SEED_B64);
+ expect(verifyAdvertisement(signed).verdict).toBe('bad_signature');
+ });
+
+ it('untrusted_node: advertised key differs from the pinned key', () => {
+ const signed = signAdvertisement(makeAdvertisement(), SEED_B64);
+ const out = verifyAdvertisement(signed, { expectedPubkey: `ed25519:${pubkeyB64FromSecret(OTHER_SEED_B64)}` });
+ expect(out.verdict).toBe('untrusted_node');
+ });
+
+ it('bad_shape: no capabilities, unknown auth mode, or missing signature', () => {
+ expect(verifyAdvertisement(signAdvertisement(makeAdvertisement({ capabilities: [] }), SEED_B64)).verdict).toBe('bad_shape');
+ expect(verifyAdvertisement(signAdvertisement(makeAdvertisement({ auth: 'mtls' }), SEED_B64)).verdict).toBe('bad_shape');
+ expect(verifyAdvertisement(makeAdvertisement()).verdict).toBe('bad_shape');
+ });
+
+ it('bad_shape: a capability entry without a key', () => {
+ const signed = signAdvertisement(makeAdvertisement({ capabilities: [{ version: '0.1' }] }), SEED_B64);
+ expect(verifyAdvertisement(signed).verdict).toBe('bad_shape');
+ });
+
+ it('bad_pubkey: node_pubkey is not an ed25519 field', () => {
+ const signed = signAdvertisement(makeAdvertisement(), SEED_B64);
+ signed.node_pubkey = 'secp256k1:AAAA';
+ expect(verifyAdvertisement(signed).verdict).toBe('bad_pubkey');
+ });
+});
+
describe('advertisement signing', () => {
it('a signed advertisement verifies against its own node key', () => {
const ad = {