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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add vanity proof-of-grind certificate store, API, and split-key; refine text-to-image
nirholas8fe8effa6372
diff --git a/api/_lib/vanity-cert-store.js b/api/_lib/vanity-cert-store.jsnew file mode 100644index 000000000..8a6eb41e2--- /dev/null+++ b/api/_lib/vanity-cert-store.js@@ -0,0 +1,159 @@+/**+ * Freshness/uniqueness registry for proof-of-grind certificates.+ *+ * A proof-of-grind certificate (src/solana/vanity/proof-of-grind.js) is fully+ * verifiable OFFLINE — signature, pattern, difficulty, and split-key non-custody+ * all recompute from public values. This registry adds the one guarantee a lone+ * signature cannot: that exactly ONE "freshly ground" certificate exists per+ * address. It records the FIRST certificate issued for an address and refuses to+ * overwrite it, so a seller cannot mint a second "fresh" proof to re-sell a+ * wallet that already changed hands. A buyer (or a resale marketplace) queries+ * the registry to confirm the certificate they hold is the canonical original.+ *+ * Stores ONLY public, secret-free provenance metadata — never a key, seed,+ * sealed envelope, or pattern beyond prefix/suffix. The allowlist below is the+ * privacy boundary: a secret cannot be persisted even if a caller passes a full+ * grind response, because `toCanonicalRecord()` structurally drops everything+ * not on the list.+ *+ * Backing store mirrors the rest of the codebase: Upstash Redis when configured,+ * an in-process Map fallback otherwise (local/CI works; a Redis outage degrades+ * to "no registry" rather than throwing). Layout:+ *+ * HASH vanity:cert:by-address field=address → JSON(record) [first-write-wins]+ * HASH vanity:cert:by-id field=certId → address [secondary index]+ */++import { getRedis } from './redis.js';++const NS = 'vanity:cert';+const K = {+ byAddress: `${NS}:by-address`,+ byId: `${NS}:by-id`,+};++const memByAddress = new Map(); // address → record+const memById = new Map(); // certId → address++// The EXACT fields a registry record may carry. Anything else is dropped — no+// secret/seed/sealed/signature-material field is on this list.+const RECORD_FIELDS = Object.freeze([+ 'certId',+ 'address',+ 'pattern',+ 'format',+ 'nonce',+ 'issuedAt',+ 'servicePublicKey',+ 'keyId',+ 'rarityScore',+ 'rarityTier',+]);++/**+ * Project a certificate (or compatible object) down to the public canonical+ * record. Returns null when the minimum identifying fields are absent.+ * @param {object} cert+ * @returns {object|null}+ */+export function toCanonicalRecord(cert) {+ if (!cert || typeof cert !== 'object') return null;+ const rec = {+ certId: cert.certId,+ address: cert.address,+ pattern: sanitizePattern(cert.pattern),+ format: cert.format,+ nonce: cert.freshness?.nonce ?? cert.nonce,+ issuedAt: cert.freshness?.issuedAt ?? cert.issuedAt,+ servicePublicKey: cert.servicePublicKey,+ keyId: cert.keyId ?? null,+ rarityScore: typeof cert.rarity?.score === 'number' ? cert.rarity.score : null,+ rarityTier: cert.rarity?.tier ?? null,+ };+ if (!rec.certId || !rec.address || !rec.nonce) return null;+ const out = {};+ for (const k of RECORD_FIELDS) if (rec[k] !== undefined) out[k] = rec[k];+ return out;+}++function sanitizePattern(p) {+ if (!p || typeof p !== 'object') return { prefix: null, suffix: null, ignoreCase: false };+ return {+ prefix: p.prefix ? String(p.prefix).slice(0, 16) : null,+ suffix: p.suffix ? String(p.suffix).slice(0, 16) : null,+ ignoreCase: !!p.ignoreCase,+ };+}++function parse(raw) {+ if (!raw) return null;+ if (typeof raw === 'object') return raw;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++/**+ * Register a certificate as the canonical proof for its address (first-write-wins).+ *+ * @param {object} cert - a signed proof-of-grind certificate.+ * @returns {Promise<{ record: object, isNew: boolean, conflict: boolean }>}+ * isNew — this address had no prior cert; the record was stored.+ * conflict — a DIFFERENT cert already owns this address (duplicate/re-sale);+ * `record` is the existing canonical one, not the submitted cert.+ */+export async function registerCert(cert) {+ const rec = toCanonicalRecord(cert);+ if (!rec) throw Object.assign(new Error('invalid certificate for registry'), { status: 400 });+ const addr = rec.address;+ const redis = getRedis();++ if (redis) {+ // Atomic first-write-wins: HSETNX returns 1 only if the field was absent.+ const wrote = await redis.hsetnx(K.byAddress, addr, JSON.stringify(rec));+ if (wrote === 1 || wrote === true) {+ await redis.hset(K.byId, { [rec.certId]: addr });+ return { record: rec, isNew: true, conflict: false };+ }+ const existing = parse(await redis.hget(K.byAddress, addr)) || rec;+ return { record: existing, isNew: false, conflict: existing.certId !== rec.certId };+ }++ if (memByAddress.has(addr)) {+ const existing = memByAddress.get(addr);+ return { record: existing, isNew: false, conflict: existing.certId !== rec.certId };+ }+ memByAddress.set(addr, rec);+ memById.set(rec.certId, addr);+ return { record: rec, isNew: true, conflict: false };+}++/** Fetch the canonical record for an address, or null. */+export async function getCanonicalByAddress(address) {+ const addr = String(address || '');+ if (!addr) return null;+ const redis = getRedis();+ if (redis) return parse(await redis.hget(K.byAddress, addr));+ return memByAddress.get(addr) || null;+}++/** Fetch the canonical record for a certId, or null. */+export async function getByCertId(certId) {+ const id = String(certId || '');+ if (!id) return null;+ const redis = getRedis();+ if (redis) {+ const addr = await redis.hget(K.byId, id);+ return addr ? parse(await redis.hget(K.byAddress, addr)) : null;+ }+ const addr = memById.get(id);+ return addr ? memByAddress.get(addr) || null : null;+}++/** Test-only: clear the in-memory fallback between cases. */+export function _resetMemory() {+ memByAddress.clear();+ memById.clear();+}diff --git a/api/_lib/vanity-service-key.js b/api/_lib/vanity-service-key.jsindex 0f9001e4a..04a464cec 100644--- a/api/_lib/vanity-service-key.js+++ b/api/_lib/vanity-service-key.js@@ -61,19 +61,32 @@ async function loadSeed() {return hkdf(sha256, ikm, sha256(DEV_INFO), DEV_INFO, SEED_BYTES);}+/**+ * Stable, rotation-aware key id derived from the public key itself, so the+ * issuer, the published well-known keyring, and any verifier always agree on the+ * id without separate configuration — rotating the seed rotates the id for free.+ * @param {string} publicKeyHex+ * @returns {string}+ */+export function keyIdForPublicKey(publicKeyHex) {+ return `pog-${String(publicKeyHex).slice(0, 16)}`;+}+/*** Resolve the service signing identity. Cached after first load.- * @returns {Promise<{ seed: Uint8Array, publicKey: Uint8Array, publicKeyBase58: string, publicKeyHex: string }>}+ * @returns {Promise<{ seed: Uint8Array, publicKey: Uint8Array, publicKeyBase58: string, publicKeyHex: string, keyId: string }>}*/export async function getServiceIdentity() {if (_cached) return _cached;const seed = await loadSeed();const publicKey = ed25519.getPublicKey(seed);+ const publicKeyHex = bytesToHex(publicKey);_cached = {seed,publicKey,publicKeyBase58: bs58.encode(publicKey),- publicKeyHex: bytesToHex(publicKey),+ publicKeyHex,+ keyId: keyIdForPublicKey(publicKeyHex),};return _cached;}diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex 2ffe27ac3..dcb4908ce 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -23,6 +23,48 @@ import { markProviderCooldown, providersInCooldown } from '../_lib/provider-healconst REPLICATE_BASE = 'https://api.replicate.com/v1';const DEFAULT_TXT2IMG_MODEL = 'black-forest-labs/flux-schnell';+// `Prefer: wait` asks Replicate to hold the create request open until the+// prediction finishes, but it only waits ~60s and, under load or with a cold+// model, returns the prediction still `starting`/`processing` and output-less.+// flux-schnell finishes in a few seconds, so we poll the prediction's status+// URL to a terminal state rather than dead-ending the FREE, never-fail text→3D+// lane on a transient "did not complete (status: starting)". Bounded so a truly+// stuck prediction still fails over instead of stalling the serverless budget.+const REPLICATE_POLL_TIMEOUT_MS = 45_000;+const REPLICATE_POLL_INTERVAL_MS = 1_500;+const REPLICATE_TERMINAL_STATUSES = new Set(['succeeded', 'failed', 'canceled']);++// Poll a Replicate prediction's `get` URL until it reaches a terminal state.+// Returns the final prediction object on success; throws on a failed/canceled+// prediction; returns the last seen object (caller surfaces a clear error) when+// the poll budget is exhausted. A transient poll blip is retried within budget,+// never fatal — the prediction keeps running upstream regardless.+async function pollReplicatePrediction(getUrl, token) {+ const deadline = Date.now() + REPLICATE_POLL_TIMEOUT_MS;+ let last = null;+ while (Date.now() < deadline) {+ await sleep(REPLICATE_POLL_INTERVAL_MS);+ let res;+ try {+ res = await fetch(getUrl, {+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },+ signal: AbortSignal.timeout(15_000),+ });+ } catch {+ continue;+ }+ const data = await res.json().catch(() => ({}));+ if (!res.ok) continue;+ last = data;+ if (data.status === 'succeeded') return data;+ if (data.status === 'failed' || data.status === 'canceled') {+ const reason = data.error ? `: ${String(data.error).slice(0, 160)}` : '';+ throw new Error(`text-to-image ${data.status}${reason}`);+ }+ }+ return last;+}+// Circuit-breaker key + window for the free NIM FLUX synthesis lane. When NVCF// times out / errors, one slow window otherwise makes every text→image caller// (forge text→3D, avatar generation, studio) re-pay the full NIM timeout before@@ -382,11 +424,25 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false});}- // With `Prefer: wait` the prediction usually completes inline. If Replicate- // returned before completion (slow model, timeout), surface the partial- // state so the handler can decide — but for flux-schnell this is rare.- const url = extractImageUrl(data.output);+ // With `Prefer: wait` the prediction usually completes inline. When Replicate+ // returns before completion (slow model, cold start, wait window elapsed) it+ // hands back a non-terminal status and no output — poll the prediction to a+ // terminal state so the free text→3D lane never dead-ends on a transient+ // "starting", instead of surfacing the partial state as a hard failure.+ let url = extractImageUrl(data.output);if (!url) {+ const getUrl = data?.urls?.get;+ const nonTerminal = data.status && !REPLICATE_TERMINAL_STATUSES.has(data.status);+ if (getUrl && nonTerminal) {+ const finished = await pollReplicatePrediction(getUrl, token);+ url = extractImageUrl(finished?.output);+ if (url) {+ return { imageUrl: url, predictionId: finished?.id || data.id, model: modelRef };+ }+ throw new Error(+ `text-to-image did not complete (status: ${finished?.status || data.status})`,+ );+ }if (data.status && data.status !== 'succeeded') {throw new Error(`text-to-image did not complete (status: ${data.status})`);}diff --git a/api/vanity/cert.js b/api/vanity/cert.jsnew file mode 100644index 000000000..81f155f44--- /dev/null+++ b/api/vanity/cert.js@@ -0,0 +1,68 @@+// /api/vanity/cert — proof-of-grind certificate registry lookup (public, read-only).+//+// GET /api/vanity/cert?address=<base58> → canonical cert record for an address+// GET /api/vanity/cert?id=<certId> → canonical cert record by certId+//+// A proof-of-grind certificate verifies entirely offline (signature, pattern,+// difficulty, split-key non-custody). This endpoint adds the freshness/uniqueness+// guarantee: it returns the FIRST certificate registered for an address so a+// buyer or resale marketplace can confirm the cert they hold is the canonical+// original — not a second "freshly ground" proof minted to re-sell the same+// wallet. Returns ONLY public, secret-free metadata (the store allowlists fields;+// secrets are structurally un-persistable). Readable cross-origin so the+// /vanity/verify page and third-party verifiers can call it.++import { wrap, cors, error, json } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getCanonicalByAddress, getByCertId } from '../_lib/vanity-cert-store.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const CERTID_RE = /^[0-9a-f]{64}$/i;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (req.method !== 'GET') {+ res.setHeader('allow', 'GET');+ return error(res, 405, 'method_not_allowed', 'use GET');+ }++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) {+ res.setHeader('retry-after', '1');+ return error(res, 429, 'rate_limited', 'too many requests');+ }++ const url = new URL(req.url, 'http://x');+ const address = (url.searchParams.get('address') || '').trim();+ const id = (url.searchParams.get('id') || '').trim();++ if (!address && !id) {+ return error(res, 400, 'missing_param', 'supply ?address=<base58> or ?id=<certId>');+ }++ let record = null;+ try {+ if (id) {+ if (!CERTID_RE.test(id)) return error(res, 400, 'invalid_id', 'certId must be 64 hex chars');+ record = await getByCertId(id);+ } else {+ if (!BASE58_RE.test(address)) return error(res, 400, 'invalid_address', 'address must be a Base58 Solana public key');+ record = await getCanonicalByAddress(address);+ }+ } catch (err) {+ return error(res, 502, 'registry_error', err.message);+ }++ return json(+ res,+ 200,+ {+ found: !!record,+ canonical: record || null,+ note: record+ ? 'This is the canonical (first-issued) proof-of-grind certificate for this address. A certificate with a different certId for the same address is a duplicate/re-sale and is not fresh.'+ : 'No certificate is registered for this address. The certificate may still verify offline, but its single-issuance freshness cannot be confirmed by the registry.',+ },+ { 'cache-control': 'public, max-age=30' },+ );+});diff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex c9f48ca17..1b6a9b5ec 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -66,6 +66,9 @@ import {parseX25519Key,SEALED_ENVELOPE_SCHEME,} from '../../src/solana/vanity/sealed-envelope.js';+import { buildCertificateCore, signCertificate } from '../../src/solana/vanity/proof-of-grind.js';+import { getServiceIdentity } from '../_lib/vanity-service-key.js';+import { registerCert } from '../_lib/vanity-cert-store.js';import bs58 from 'bs58';const ROUTE = '/api/x402/vanity';diff --git a/src/solana/vanity/split-key.js b/src/solana/vanity/split-key.jsnew file mode 100644index 000000000..a73c9c9e8--- /dev/null+++ b/src/solana/vanity/split-key.js@@ -0,0 +1,402 @@+/**+ * Trustless split-key vanity grinding — `three-split-key/v1`.+ *+ * The single biggest reason nobody buys vanity wallets for value: every paid+ * grinder *sees the private key it sells you*. Split-key grinding removes that+ * objection mathematically. It splits the wallet's secret across two parties so+ * that NEITHER the grinder (a pool worker) NOR the operator ever holds — or can+ * reconstruct — the final private key.+ *+ * ── The math (Ed25519 group, basepoint B, scalar order L) ────────────────────+ * 1. The requester picks a secret scalar a1 ∈ [1, L) locally and publishes+ * only P1 = a1·B (a public Ed25519 point). a1 NEVER leaves their machine.+ * 2. A worker grinds an *offset* scalar a2, computing candidate addresses+ * A = P1 + a2·B+ * and checking each against the requested Base58 pattern. The worker knows+ * a2 and P1 but NOT a1, so it cannot compute the final secret.+ * 3. On a hit the worker submits (a2, A). The server verifies, with no secret,+ * P1 + a2·B == A+ * and that A matches the pattern, then pays the worker. The server learns+ * a2 but not a1 — it also cannot reconstruct the key.+ * 4. The requester combines a_final = (a1 + a2) mod L on their own machine.+ * Because a_final·B = a1·B + a2·B = P1 + a2·B = A, the secret scalar+ * a_final controls exactly the vanity address A, and it only ever exists on+ * the requester's device. Trustless by construction.+ *+ * Crucially the offset a2 is NOT itself a secret — it is useless without a1 — so+ * unlike the seal-based bounty protocol (which encrypts a full key the worker+ * generated and therefore *saw*), split-key needs no envelope to be safe: the+ * worker simply never possesses the key. This is what makes a pool safe to use+ * for valuable addresses.+ *+ * ── Honest wallet-import tradeoff (surfaced, never hidden) ────────────────────+ * a_final is a *raw Ed25519 scalar*, not a 32-byte seed (you cannot invert SHA-512+ * to find a seed that expands to a chosen scalar — that's preimage-hard). So a+ * split-key wallet is an "expanded" key: it signs perfectly via {@link signWithScalar}+ * / {@link SplitKeySigner} and is a valid Solana account, but it cannot be imported+ * into seed-only wallets (Phantom's "import private key" expects a 64-byte+ * seed||pubkey). Tools that accept an expanded/extended secret key (libsodium+ * `crypto_sign_*` with an external scalar, our SDK signer, server-side signing for+ * an agent's custodial wallet) use it directly. We expose {@link expandedSecretKey}+ * for those and document the limitation rather than papering over it.+ *+ * Pure + isomorphic: @noble/curves + @noble/hashes only, no Node-only APIs, so the+ * identical code runs in the browser grind worker, the serverless verifier, the+ * agent/CLI worker, and the tests. Behaviour is pinned by fixed vectors in+ * tests/vanity-split-key.test.js.+ */++import { ed25519 } from '@noble/curves/ed25519.js';+import { sha512 } from '@noble/hashes/sha512.js';+import { sha256 } from '@noble/hashes/sha256.js';+import { bytesToHex, hexToBytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';+import bs58 from 'bs58';++import { addressMatchesPattern } from './bounty-protocol.js';+import { validatePattern } from './validation.js';++export const SPLIT_KEY_PROTOCOL = 'three-split-key/v1';++const Point = ed25519.Point;+const B = Point.BASE;+/** Ed25519 prime-order subgroup order L. */+export const L = Point.Fn.ORDER;++// Domain separation for the deterministic signing-nonce prefix derived from the+// combined scalar (a split-key wallet has no RFC-8032 seed to take a prefix from).+const TAG_SIGN_PREFIX = utf8ToBytes('three-split-key/sign-prefix/v1');++// ── scalar <-> bytes (Ed25519 scalars are little-endian, RFC 8032) ────────────++/** 32-byte little-endian encoding of a scalar already reduced mod L. */+export function scalarToBytes(n) {+ let v = ((n % L) + L) % L;+ const out = new Uint8Array(32);+ for (let i = 0; i < 32; i++) {+ out[i] = Number(v & 0xffn);+ v >>= 8n;+ }+ return out;+}++/** Little-endian 32-byte → bigint, reduced mod L. */+export function bytesToScalar(b) {+ const bytes = typeof b === 'string' ? hexToBytes(b) : b;+ let n = 0n;+ for (let i = bytes.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(bytes[i]);+ return ((n % L) + L) % L;+}++/** A uniformly random nonzero scalar in [1, L). */+export function randomScalar() {+ // Rejection-free: 512 bits reduced mod L has negligible bias; matches how+ // Ed25519 derives its own scalars. Guarantee nonzero (probability of 0 is ~2^-512).+ const wide = new Uint8Array(64);+ cryptoRandom(wide);+ let n = 0n;+ for (let i = wide.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(wide[i]);+ const s = n % L;+ return s === 0n ? 1n : s;+}++function cryptoRandom(buf) {+ const g = globalThis.crypto || (globalThis.require && globalThis.require('crypto').webcrypto);+ if (!g || !g.getRandomValues) throw new Error('split-key: no secure RNG available');+ g.getRandomValues(buf);+ return buf;+}++// ── point (de)serialization ──────────────────────────────────────────────────++/** Parse a public point P1 from Base58 (Solana address form) or hex / bytes. */+export function parsePoint(p1) {+ if (p1 instanceof Point) return p1;+ let bytes;+ if (p1 instanceof Uint8Array) bytes = p1;+ else if (typeof p1 === 'string') {+ const s = p1.trim();+ bytes = /^[0-9a-fA-F]{64}$/.test(s) ? hexToBytes(s) : bs58.decode(s);+ } else {+ throw new Error('parsePoint: expected Base58 string, hex string, or bytes');+ }+ if (bytes.length !== 32) throw new Error('parsePoint: expected a 32-byte Ed25519 point');+ return Point.fromBytes(bytes);+}++/** Base58 address of a point (the Solana public-key form). */+export function pointToAddress(point) {+ return bs58.encode(point.toBytes());+}++// ── requester side: keypair share ────────────────────────────────────────────++/**+ * Generate a requester key share locally. Returns the SECRET scalar a1 (hex, LE)+ * which must never leave the requester, and the PUBLIC point P1 = a1·B (Base58 ++ * hex) which is safe to publish in a bounty so workers can grind offsets against+ * it. This must be called client-side; the server only ever sees `p1`.+ * @returns {{ a1:string, p1:string, p1Hex:string, protocol:string }}+ */+export function generateRequesterShare() {+ const a1 = randomScalar();+ const P1 = B.multiply(a1);+ return {+ a1: bytesToHex(scalarToBytes(a1)),+ p1: pointToAddress(P1),+ p1Hex: bytesToHex(P1.toBytes()),+ protocol: SPLIT_KEY_PROTOCOL,+ };+}++/** Validate a P1 string is a well-formed, non-identity, prime-order Ed25519 point. */+export function isValidP1(p1) {+ try {+ const P = parsePoint(p1);+ if (P.is0()) return false;+ // Reject small-order / torsion points: a malicious P1 could otherwise leak+ // info about offsets. Prime-order check is cheap and decisive.+ return P.isTorsionFree();+ } catch {+ return false;+ }+}++// ── worker side: incremental offset grind ────────────────────────────────────++/**+ * Grind an offset scalar a2 such that `P1 + a2·B` matches the pattern. Uses the+ * standard fast-vanity incrementing trick: seed once with a full scalar mult at a+ * random base offset, then advance by a single point addition (Q += B, a2 += 1)+ * per candidate instead of a fresh multiply — ~12× the field-op throughput.+ *+ * A worker only ever sees a2 and P1, never the requester's a1, so it cannot+ * reconstruct the final key it just helped grind. A distinct random `startOffset`+ * per worker shards the keyspace: two random 256-bit starts cannot collide within+ * any feasible attempt budget, so workers never duplicate effort.+ *+ * @param {object} opts+ * @param {string} opts.p1 requester public point (Base58/hex)+ * @param {string} [opts.prefix] Base58 prefix to match+ * @param {string} [opts.suffix] Base58 suffix to match+ * @param {boolean} [opts.ignoreCase] case-insensitive match+ * @param {Uint8Array|string} [opts.startOffset] base offset scalar (LE bytes/hex); random if omitted+ * @param {number} [opts.maxAttempts] stop after this many candidates (default Infinity)+ * @param {number} [opts.timeBudgetMs] stop after this many ms (default Infinity)+ * @param {(p:{attempts:number,rate:number})=>void} [opts.onProgress] progress callback+ * @param {number} [opts.progressEvery] candidates between progress callbacks (default 4096)+ * @param {{aborted:boolean}|AbortSignal} [opts.signal] cooperative cancellation+ * @returns {{ found:boolean, offset?:string, address?:string, attempts:number, durationMs:number }}+ */+export function grindSplitKeyOffset(opts = {}) {+ const {+ p1,+ prefix = '',+ suffix = '',+ ignoreCase = false,+ startOffset,+ maxAttempts = Infinity,+ timeBudgetMs = Infinity,+ onProgress,+ progressEvery = 4096,+ signal,+ } = opts;++ const pattern = { prefix, suffix, ignoreCase };+ const P1 = parsePoint(p1);+ let a2 = startOffset != null ? bytesToScalar(startOffset) : randomScalar();+ let Q = P1.add(B.multiply(a2));++ const started = now();+ let attempts = 0;+ let sincePb = 0;++ const aborted = () => (signal instanceof Object && 'aborted' in signal ? signal.aborted : false);++ for (;;) {+ const address = bs58.encode(Q.toBytes());+ attempts++;+ sincePb++;+ if (addressMatchesPattern(address, pattern)) {+ return {+ found: true,+ offset: bytesToHex(scalarToBytes(a2)),+ address,+ attempts,+ durationMs: Math.round(now() - started),+ };+ }+ if (sincePb >= progressEvery) {+ sincePb = 0;+ if (onProgress) {+ const dt = (now() - started) / 1000;+ onProgress({ attempts, rate: dt > 0 ? Math.round(attempts / dt) : 0 });+ }+ if (aborted()) break;+ if (attempts >= maxAttempts) break;+ if (now() - started >= timeBudgetMs) break;+ }+ // Advance one step: next candidate corresponds to offset a2 + 1.+ Q = Q.add(B);+ a2 = (a2 + 1n) % L;+ }+ return { found: false, attempts, durationMs: Math.round(now() - started) };+}++// ── server side: secret-free verification ─────────────────────────────────────++/**+ * Verify a worker's claim WITHOUT any secret: confirm `P1 + offset·B == address`+ * and (optionally) that the address satisfies the pattern. This is the pool's+ * anti-cheat gate — a worker cannot claim a bogus result, and the verifier never+ * holds a private key. Pure point arithmetic, reproducible by anyone.+ *+ * @param {object} p+ * @param {string} p.p1+ * @param {Uint8Array|string} p.offset offset scalar (LE bytes/hex)+ * @param {string} p.address claimed Base58 address+ * @param {{prefix?:string,suffix?:string,ignoreCase?:boolean}} [p.pattern]+ * @returns {{ ok:boolean, derivationOk:boolean, patternOk:boolean, derivedAddress:string, reason:string }}+ */+export function verifySplitKeyClaim({ p1, offset, address, pattern }) {+ let derivedAddress = '';+ let derivationOk = false;+ try {+ const P1 = parsePoint(p1);+ const a2 = bytesToScalar(offset);+ if (a2 === 0n) {+ return { ok: false, derivationOk: false, patternOk: false, derivedAddress: '', reason: 'offset scalar is zero' };+ }+ const Q = P1.add(B.multiply(a2));+ derivedAddress = bs58.encode(Q.toBytes());+ derivationOk = derivedAddress === String(address || '');+ } catch (e) {+ return { ok: false, derivationOk: false, patternOk: false, derivedAddress, reason: `derivation error: ${e.message}` };+ }+ const patternOk = pattern ? addressMatchesPattern(derivedAddress, pattern) : true;+ const ok = derivationOk && patternOk;+ let reason = '';+ if (!derivationOk) reason = `P1 + offset·B = ${derivedAddress} ≠ claimed ${address}`;+ else if (!patternOk) reason = `${derivedAddress} does not match the requested pattern`;+ return { ok, derivationOk, patternOk, derivedAddress, reason };+}++// ── requester side: combine + sign ────────────────────────────────────────────++/**+ * Combine the requester's secret a1 with a worker's offset into the final secret+ * scalar a_final = (a1 + offset) mod L. Returns the scalar (LE hex) and the+ * resulting Base58 address (which must equal the ground vanity address). Runs only+ * on the requester's machine.+ * @param {Uint8Array|string} a1+ * @param {Uint8Array|string} offset+ * @returns {{ scalar:string, address:string }}+ */+export function combineScalars(a1, offset) {+ const s1 = bytesToScalar(a1);+ const s2 = bytesToScalar(offset);+ const aFinal = (s1 + s2) % L;+ if (aFinal === 0n) throw new Error('combineScalars: degenerate combined scalar');+ return { scalar: bytesToHex(scalarToBytes(aFinal)), address: pointToAddress(B.multiply(aFinal)) };+}++/**+ * Deterministic 32-byte signing-nonce prefix for a split-key (expanded) wallet.+ * A split-key wallet has no RFC-8032 seed to take the standard prefix from, so we+ * derive one from the secret scalar under a domain tag. It is secret (depends on+ * a_final) and deterministic, giving RFC-8032-style per-message nonces.+ */+function signPrefix(aFinalBytes) {+ return sha512(concatBytes(TAG_SIGN_PREFIX, aFinalBytes)).slice(0, 32);+}++/**+ * The 64-byte "expanded" secret key (scalar ‖ prefix), the format external signers+ * (libsodium external-scalar signing, our SDK) accept. NOT a seed-based Solana+ * keypair — see the module header's wallet-import note.+ * @param {Uint8Array|string} aFinal LE scalar bytes/hex+ * @returns {Uint8Array} 64 bytes+ */+export function expandedSecretKey(aFinal) {+ const bytes = scalarToBytes(bytesToScalar(aFinal));+ return concatBytes(bytes, signPrefix(bytes));+}++/**+ * Produce a valid Ed25519 signature for `message` using the combined scalar+ * directly (RFC 8032 with an external scalar + derived nonce). The signature+ * verifies against the vanity public key, so a split-key wallet is fully usable+ * for signing even though it has no seed.+ * @param {Uint8Array} message+ * @param {Uint8Array|string} aFinal LE scalar bytes/hex+ * @returns {Uint8Array} 64-byte signature (R ‖ S)+ */+export function signWithScalar(message, aFinal) {+ const msg = message instanceof Uint8Array ? message : utf8ToBytes(String(message));+ const sBytes = scalarToBytes(bytesToScalar(aFinal));+ const s = bytesToScalar(sBytes);+ const prefix = signPrefix(sBytes);+ const A = B.multiply(s).toBytes();+ const r = mod512(sha512(concatBytes(prefix, msg)));+ const R = B.multiply(r === 0n ? 1n : r).toBytes();+ const k = mod512(sha512(concatBytes(R, A, msg)));+ const S = (r + ((k * s) % L)) % L;+ return concatBytes(R, scalarToBytes(S));+}++/** Verify a signature against a vanity public key (Base58/hex/bytes). */+export function verifySignature(message, signature, publicKey) {+ const msg = message instanceof Uint8Array ? message : utf8ToBytes(String(message));+ const pub = parsePoint(publicKey).toBytes();+ return ed25519.verify(signature, msg, pub);+}++function mod512(hash64) {+ let n = 0n;+ for (let i = hash64.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(hash64[i]);+ return n % L;+}++/**+ * A minimal signer object a requester (or an agent's custodial backend) can use to+ * sign with a split-key wallet without re-deriving anything. `secretKey` is the+ * expanded key from {@link expandedSecretKey}; `publicKey` is the Base58 address.+ */+export class SplitKeySigner {+ constructor(aFinal) {+ this.scalarBytes = scalarToBytes(bytesToScalar(aFinal));+ this.publicKey = pointToAddress(B.multiply(bytesToScalar(this.scalarBytes)));+ this.secretKey = expandedSecretKey(this.scalarBytes);+ }+ sign(message) {+ return signWithScalar(message, this.scalarBytes);+ }+}++// ── validation reused by API/worker ────────────────────────────────────────────++/** Validate a requested split-key pattern; throws a 400-tagged error if malformed. */+export function validateSplitKeyPattern({ prefix = '', suffix = '', ignoreCase = false } = {}) {+ const pre = typeof prefix === 'string' ? prefix.trim() : '';+ const suf = typeof suffix === 'string' ? suffix.trim() : '';+ if (!pre && !suf) throw bad('a prefix or suffix is required');+ for (const [label, p] of [['prefix', pre], ['suffix', suf]]) {+ if (!p) continue;+ const v = validatePattern(p);+ if (!v.valid) throw bad(`invalid ${label}: ${v.errors.join('; ')}`);+ }+ return { prefix: pre, suffix: suf, ignoreCase: !!ignoreCase };+}++function bad(message) {+ return Object.assign(new Error(message), { status: 400, code: 'validation_error' });+}++/** Short, stable fingerprint of a P1 — used as a public bounty/share key. */+export function p1Fingerprint(p1) {+ const P = parsePoint(p1);+ return bytesToHex(sha256(P.toBytes())).slice(0, 16);+}++function now() {+ return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();+}diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.jsindex b83c96063..1128f3733 100644--- a/tests/api/text-to-image.test.js+++ b/tests/api/text-to-image.test.js@@ -419,6 +419,101 @@ describe('textToImage — Vertex → Replicate fallback', () => {expect(caught.message).not.toMatch(/credit|purchase|payment/i);});+ it('polls a Replicate prediction that returns non-terminal, then resolves', async () => {+ // Regression: under load / cold start Replicate returns the prediction still+ // `starting` (Prefer: wait elapsed) with no output. The free text→3D lane+ // must poll the prediction to completion, never dead-end on a transient+ // "text-to-image did not complete (status: starting)".+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';+ let pollHits = 0;+ stubFetch([+ [+ '/predictions/pred_poll',+ () => {+ pollHits += 1;+ const done = pollHits >= 2;+ return new Response(+ JSON.stringify({+ id: 'pred_poll',+ status: done ? 'succeeded' : 'processing',+ output: done ? ['https://replicate.delivery/polled.png'] : null,+ }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ );+ },+ ],+ [+ 'flux-schnell',+ () =>+ new Response(+ JSON.stringify({+ id: 'pred_poll',+ status: 'starting',+ output: null,+ urls: { get: 'https://api.replicate.com/v1/predictions/pred_poll' },+ }),+ { status: 201, headers: { 'content-type': 'application/json' } },+ ),+ ],+ ]);++ vi.useFakeTimers();+ try {+ const textToImage = await freshTextToImage();+ const p = textToImage('a red teapot');+ await vi.advanceTimersByTimeAsync(5_000); // let two poll intervals elapse+ const result = await p;+ expect(result.imageUrl).toBe('https://replicate.delivery/polled.png');+ expect(result.predictionId).toBe('pred_poll');+ expect(pollHits).toBeGreaterThanOrEqual(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('surfaces a clean error when a polled Replicate prediction fails', async () => {+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';+ stubFetch([+ [+ '/predictions/pred_fail',+ () =>+ new Response(+ JSON.stringify({ id: 'pred_fail', status: 'failed', error: 'NSFW content detected' }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ ),+ ],+ [+ 'flux-schnell',+ () =>+ new Response(+ JSON.stringify({+ id: 'pred_fail',+ status: 'starting',+ output: null,+ urls: { get: 'https://api.replicate.com/v1/predictions/pred_fail' },+ }),+ { status: 201, headers: { 'content-type': 'application/json' } },+ ),+ ],+ ]);++ vi.useFakeTimers();+ try {+ const textToImage = await freshTextToImage();+ const p = textToImage('a red teapot');+ const settled = p.then(+ () => null,+ (e) => e,+ );+ await vi.advanceTimersByTimeAsync(3_000);+ const caught = await settled;+ expect(caught).toBeTruthy();+ expect(caught.message).toMatch(/text-to-image failed/);+ } finally {+ vi.useRealTimers();+ }+ });+it('persists a Vertex data: URI to object storage and returns the https URL', async () => {process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';vertexState.configured = true;