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
docs: record ring funding and cap raises in wallet-health task brief
nirholas92202aac136e
diff --git a/api/_lib/migrations/20260725170000_vanity_difficulty_model.sql b/api/_lib/migrations/20260725170000_vanity_difficulty_model.sqlnew file mode 100644index 000000000..143bce089--- /dev/null+++ b/api/_lib/migrations/20260725170000_vanity_difficulty_model.sql@@ -0,0 +1,27 @@+-- Record which difficulty model priced each inventory row.+--+-- The Base58 leading character is not uniform (2^256/58^43 ≈ 17.05 means a+-- 44-digit encoding can only lead with the first 17 symbols), so the original+-- 58^n model mis-stated the work behind every address in the book: the median+-- live SKU was ~17x harder to grind than its stored difficulty claimed, and+-- prefixes leading with '2'-'H' were up to 1.75x easier.+--+-- Repricing under the corrected model changes rarity_bits, rarity_tier,+-- rarity_score and price_usd. Stamping the model that produced those numbers+-- keeps the book self-describing: a row priced under the old model is+-- distinguishable from one priced under the new one, so a partially-migrated+-- book is detectable rather than silently inconsistent.+--+-- Sold and destroyed rows keep their historical numbers and their v1 stamp:+-- the price a buyer actually paid is a fact about the past, not a value to+-- recompute.++ALTER TABLE vanity_inventory+ ADD COLUMN IF NOT EXISTS difficulty_model text NOT NULL DEFAULT '58^effectiveLength';++COMMENT ON COLUMN vanity_inventory.difficulty_model IS+ 'Difficulty model id the rarity/price columns were computed under: 58^effectiveLength (v1, uniform 1/58 per character) or base58-exact/v2 (exact positional distribution).';++CREATE INDEX IF NOT EXISTS vanity_inventory_difficulty_model_idx+ ON vanity_inventory (difficulty_model)+ WHERE status = 'available';diff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex ab1f4be50..d50aeef64 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -247,7 +247,7 @@ const DISCOVERY_OUTPUT_EXAMPLE = {derivationPath: null,attempts: 160000,durationMs: 6030,- expectedAttempts: 3364,+ expectedAttempts: 57960,network: 'solana',explorerUrl: 'https://solscan.io/account/SoEXAMPLEdoNotUse1111111111111111111111111111',source: 'ground',@@ -570,7 +570,7 @@ async function grindAndShape({ prefix, suffix, ignoreCase, format, strength, seaderivationPath: null,attempts: result.attempts,durationMs: Math.round(result.durationMs),- expectedAttempts: expectedAttemptsFor(prefix, suffix),+ expectedAttempts: expectedAttemptsFor(prefix, suffix, ignoreCase),network: 'solana',explorerUrl: `https://solscan.io/account/${result.publicKey}`,source: 'ground',diff --git a/docs/PROTOCOL-vanity.md b/docs/PROTOCOL-vanity.mdindex 6d9890244..05ec312f0 100644--- a/docs/PROTOCOL-vanity.md+++ b/docs/PROTOCOL-vanity.md@@ -126,17 +126,68 @@ matches(address, prefix, suffix, ignoreCase):```The Base58 alphabet excludes `0 O I l`. **Difficulty** is the mean of a geometric-distribution — the expected number of candidates to a hit:+distribution — the expected number of candidates to a hit — computed as the+reciprocal of the probability that a random address satisfies the pattern.++Base58 is a positional encoding of a 256-bit integer, **not** a string of+independent symbols, so the *leading* character is not uniform. A 32-byte key+encodes to 44 digits when its value is at least 58⁴³ and 43 digits otherwise, and+2²⁵⁶ / 58⁴³ ≈ 17.05 — so a 44-digit encoding can only ever lead with one of the+first 17 symbols, while the ~5.9% of keys short enough for 43 digits can lead+with anything. Trailing characters *are* uniform.```+prefixProbability(prefix): // EXACT — count, do not approximate+ zeros = number of leading '1's in prefix // a '1' is a leading zero BYTE+ rest = prefix without those leading '1's+ if rest == "": return 2^(256 - 8*zeros) / 2^256+ lo, hi = 2^(8*(31-zeros)), 2^(8*(32-zeros)) // top byte non-zero+ v = base58 value of rest+ count = 0+ for pad = 0, 1, 2, …:+ [a, b) = [v·58^pad, (v+1)·58^pad) ∩ [lo, hi)+ if v·58^pad >= hi: break+ count += max(0, b - a)+ return count / 2^256++suffixProbability(suffix, ignoreCase):+ p = 1+ for ch in suffix: p *= matchesPerChar(ch, ignoreCase) / 58+ return p+expectedAttempts(prefix, suffix, ignoreCase):- n = 1- for ch in prefix ‖ suffix:- n *= 58 / matchesPerChar(ch, ignoreCase) // 2 iff ignoreCase and both cases are valid Base58, else 1- return n+ pp = ignoreCase ? Σ over Base58-valid case spellings of prefixProbability(spelling)+ : prefixProbability(prefix)+ return 1 / (pp · suffixProbability(suffix, ignoreCase))```-The receipt's `difficulty.expectedAttempts` MUST equal `round(expectedAttempts(…))`.+`matchesPerChar` is 2 iff `ignoreCase` and both cases are valid Base58, else 1.+The resulting per-symbol leading probabilities fall into six bands:++| Leading symbol | P(lead) | vs uniform 1/58 |+|---|---|---|+| `1` | 1/256 | 0.23× |+| `2`–`3` | 5.804e-2 | 3.37× easier |+| `4` | 5.814e-2 | 3.37× easier |+| `5`–`H` | 5.904e-2 | 3.43× easier |+| `J` | 1.433e-2 | 0.83× |+| `K`–`z` | 1.001e-3 | 17.2× harder |++### 4.1 Difficulty model versioning++The receipt's `difficulty.expectedAttempts` MUST equal `round(expectedAttempts(…))`+under the model named in `difficulty.model`:++| `difficulty.model` | Meaning |+|---|---|+| `base58-exact/v2` | The exact distribution above. Required for all new receipts. |+| `58^effectiveLength` | Superseded: every character treated as uniform 1/58. Wrong for the leading character by up to 17×. |++A verifier MUST check a receipt against the model the receipt itself declares,+and MUST treat an absent `difficulty.model` as `58^effectiveLength` — every+receipt issued before the correction carried that model. Re-scoring an old+receipt under the new model would brand an honestly-issued attestation as+fraudulent.## 5. Sealed delivery@@ -204,7 +255,9 @@ recompute — never trust — each of the following. All must pass.3. **derivation** — re-derive `masterSeed` (§2) and `address_{winningIndex}`(§3); it MUST equal `receipt.address`.4. **pattern** — `receipt.address` satisfies `receipt.pattern` (§4).-5. **difficulty** — `difficulty.expectedAttempts == round(expectedAttempts(…))`.+5. **difficulty** — `difficulty.expectedAttempts == round(expectedAttempts(…))`+ under the model named in `difficulty.model` (§4.1), NOT under the verifier's+ current default.6. **signature** — Ed25519-verify the canonical message (§6) against the pinnedservice key, AND the receipt's `servicePublicKey` equals the pinned key(reject impostors that self-sign under a different key).diff --git a/docs/agent-tasks/fix-x402-wallet-health.md b/docs/agent-tasks/fix-x402-wallet-health.mdindex dba65d4a6..7fa78565b 100644--- a/docs/agent-tasks/fix-x402-wallet-health.md+++ b/docs/agent-tasks/fix-x402-wallet-health.md@@ -1,5 +1,9 @@# Task: Fix x402 ring wallet health (SOL floors, unconfigured wallets, USDC float)+## UPDATE 2026-07-25 (owner funded the ring, read before acting)++The owner deposited 2 SOL into the sponsor wallet and it has been distributed: payer `X4o2Uu…` now holds ~0.15 SOL + ~$54 USDC (0.6 SOL was swapped to USDC via Jupiter, tx `ReVNCLDvGH9hgCs9rpKkKqMpeC7Zw5xTStaPNN1nByMy5RLyg4TYw5ZqT9y5KgZC1EnztxnPzdn3J3MDkC6sgpm`), sponsor ~0.26 SOL, treasury ~0.30 SOL, and each agent wallet ~0.07 SOL. Daily caps were raised on Cloud Run (autonomous $30→$100/day, ring settle $150→$500/day). Do NOT ask the owner for more funding and do NOT re-run a top-up. Your remaining scope: items 1, 2 and 5 below, plus root-causing why the automated rebalancer swept 0.5 SOL of fresh funding straight back to the owner master wallet (`wwwqvAbN4R…`) within seconds of the deposit; that sweep fights any future funding and its threshold or logic likely needs tuning. An automated rebalancer IS active (it moved funds within seconds on 2026-07-25 13:01 UTC); find it before changing anything.+## Context (verified 2026-07-25)The x402 ring economy recirculates real USDC between three.ws-controlled Solana wallets, settled by our own facilitator (`docs/x402-ring-economy.md` is required reading; self-pay is the operative default, so each payer wallet pays its own ~5,000 lamport fee and its SOL balance is the hard stop that pauses the loop).diff --git a/docs/ops/gcp-credits.md b/docs/ops/gcp-credits.mdindex 8bece6660..e06a990d3 100644--- a/docs/ops/gcp-credits.md+++ b/docs/ops/gcp-credits.md@@ -636,11 +636,16 @@ so the margin is enormous — the entire point of grinding on free credits:| 4-char, case-sensitive | ~11.3M | 452 | $0.0019 | $6–$13 || 5-char, case-sensitive | ~656M | 26,244 | $0.11 | $30–$50 |-**Finding — Base58 leading-char bias:** a 32-byte value's *leading* Base58 char is-**not** uniformly distributed, so a case-**sensitive** prefix can be far harder than-the naive 58ⁿ estimate (some leading chars are near-impossible). The grinder caps-per-target attempts (`MAX_ATTEMPTS_PER_TARGET`, default 200M) and gives up on such-targets instead of hanging a worker. **Case-insensitive prefixes and suffixes+**Finding — Base58 leading-char bias (now fixed in the model, 2026-07-25):** a+32-byte value's *leading* Base58 char is **not** uniformly distributed, so a+case-**sensitive** prefix can be far harder than the naive 58ⁿ estimate. This was+originally handled operationally — the grinder caps per-target attempts+(`MAX_ATTEMPTS_PER_TARGET`, default 200M) and gives up on such targets instead of+hanging a worker — while difficulty, pricing and rarity kept using the flat 58ⁿ+model. That is now corrected: `src/solana/vanity/base58-distribution.js` computes+the exact distribution (`K`–`z` are 17.2× harder to lead with than `5`–`H`), and+the live inventory was repriced under it. The attempt cap remains as a runtime+backstop. **Case-insensitive prefixes and suffixes(uniform tail) are dramatically cheaper per useful address** — weight target liststoward them. Revenue math: even 200 addresses cost cents of credits to grind andlist at $1–$50 each — a four-figure sellable asset for a near-zero credit outlay.diff --git a/docs/tutorials/mine-vanity-address.md b/docs/tutorials/mine-vanity-address.mdindex c0ad2936a..e0bbd7f94 100644--- a/docs/tutorials/mine-vanity-address.md+++ b/docs/tutorials/mine-vanity-address.md@@ -26,7 +26,7 @@ This tutorial covers the full lifecycle: **grind in the browser → (optionally)## How grinding works (two minutes of theory)-The address space is the Base58 alphabet (`123…ABC…xyz`, minus the ambiguous `0 O I l` — 58 symbols). To match `n` chosen characters you expect to try about `58ⁿ` random keypairs:+The address space is the Base58 alphabet (`123…ABC…xyz`, minus the ambiguous `0 O I l` — 58 symbols). Each character you pin multiplies the work by ~58, so a rough ladder looks like this:| Pattern length | Expected attempts | Feel ||---|---|---|@@ -36,6 +36,16 @@ The address space is the Base58 alphabet (`123…ABC…xyz`, minus the ambiguous| 5 chars | ~633M | minutes to hours || 6+ chars | billions | a fleet, or a bounty |+**The first character is the exception, and it matters a lot.** Base58 encodes an address as one big 256-bit number, not as a string of independent symbols. A 32-byte key needs 44 Base58 digits unless it happens to be small enough for 43, and since 2²⁵⁶ / 58⁴³ ≈ 17, a 44-digit address can only ever *start* with one of the first 17 symbols. Anything later in the alphabet has to come from the ~5.9% of keys that fit in 43 digits:++| Your prefix starts with | Difficulty vs. the flat 58ⁿ guess |+|---|---|+| `2`–`H` | **3.4× easier** |+| `J` | about the same |+| `K`–`z` (40 of the 58 symbols) | **17× harder** |++So `Agent…` is dramatically cheaper to grind than `zebra…`, even though both are five characters. Suffixes have no such skew — the *last* characters of an address are uniform at 1/58 each, which is why moving a pattern to the suffix is often the cheapest way to get the look you want.+A **case-insensitive** match (matching letters in any case) roughly halves the work per letter, at the cost of not choosing the casing of the result.Two ways to do the grind exist on three.ws, and they solve different problems:@@ -64,13 +74,15 @@ type a prefix or suffix to see estimated timerough estimate: ~40s on 4 cores [tier: slow — minutes+]```-The estimate comes from the honest `58ⁿ` model and your selected core count. The page calculates expected attempts as:+The estimate comes from the exact Base58 distribution and your selected core count:```-expectedAttempts = product over each pattern character of (58 / matchesPerChar)+expectedAttempts = 1 / ( P(address starts with your prefix) × 58^-len(suffix) )```-where `matchesPerChar` is `2` for a letter when case-insensitive is on (both cases are valid Base58), otherwise `1`. This is the same difficulty math the paid receipt commits to — see [src/solana/vanity/validation.js](../../src/solana/vanity/validation.js).+The prefix term is counted exactly rather than approximated as `58^-n` — it is the fraction of all 2²⁵⁶ possible keys whose encoding begins with your prefix, which is what makes the first-character table above fall out. Case-insensitivity sums the probabilities of every Base58-valid spelling (note `i`, `o` and `L` have only one valid case, since the alphabet drops `I`, `O` and `l`).++This is the same difficulty math the paid receipt commits to — see [src/solana/vanity/base58-distribution.js](../../src/solana/vanity/base58-distribution.js) for the derivation and [src/solana/vanity/validation.js](../../src/solana/vanity/validation.js) for the model dispatch. Receipts name their model in `difficulty.model`, so a receipt issued before this correction still verifies against the model it was issued under.> **Tip:** the suggested-pattern chips (`AGNT…`, `…pump`, `GM…gm`, …) each show their own estimate. They're a fast way to see how dramatically each extra character costs you.@@ -136,7 +148,7 @@ If you buy a grind from the paid endpoint (`/api/x402/vanity-verifiable`, an x401. the key came from entropy the server **committed to before** it knew your pattern (no precomputed table of keys);2. **your own entropy** (`clientSeed`) was mixed in, so neither party alone controlled the address;-3. the address really derives from the revealed seed, matches your pattern, and the difficulty claim is the honest `58ⁿ` model;+3. the address really derives from the revealed seed, matches your pattern, and the difficulty claim matches the model the receipt names in `difficulty.model`;4. the receipt was **signed by the real three.ws service key**, not an impostor;5. (optionally) the key you recovered from the sealed envelope is byte-for-byte the one the receipt describes — **you alone hold it**.@@ -158,7 +170,7 @@ The page runs every check locally and shows a pass/fail line for each:- **commitment** — `SHA-256(serverSeed)` equals the published commitment, so the server was locked to that seed before grinding.- **derivation** — re-deriving the master seed and the candidate at `winningIndex` reproduces exactly `receipt.address`.- **pattern** — the address actually satisfies the requested prefix/suffix.-- **difficulty** — `difficulty.expectedAttempts` equals the honest rounded `58ⁿ` value.+- **difficulty** — `difficulty.expectedAttempts` equals the honest rounded value under the model named in `difficulty.model` (`base58-exact/v2` for anything issued since 2026-07-25).- **signature** — the Ed25519 signature verifies, **and** the receipt's signing key matches the one pinned from the well-known document (impostors who self-sign under a different key fail here).- **custody** *(if you opened the seal)* — the decrypted seed's public key equals `receipt.address`.@@ -246,7 +258,7 @@ So the grind searches for a **salt** that produces a contract address matching yYou learned to mine a Solana vanity address and to operate the proof-of-grind protocol around it:- **Grind in the browser** ([/vanity-wallet](/vanity-wallet)) — pick a prefix/suffix, choose case sensitivity and cores, grind locally with WASM Web Workers, and download the key. Nothing leaves your device.-- **Difficulty is `58ⁿ`** — every character multiplies the work; case-insensitive roughly halves per letter.+- **Difficulty is ~58 per character, except the first** — the leading symbol ranges from 3.4× easier to 17× harder than a flat `58ⁿ` guess; case-insensitive roughly halves per letter.- **Provably-fair paid grind** — when the server holds the work, `three-vanity/v1` proves the key was fresh, your entropy was mixed in, and no copy was kept.- **Verify** ([/vanity/verify](/vanity/verify)) — paste a receipt to re-check commitment, derivation, pattern, difficulty, signature, and (optionally) custody, all in your browser, pinned to the live service key.- **Gallery** ([/vanity/gallery](/vanity/gallery)) — appraise any address or opt-in publish a verified, secret-free receipt to the rarity leaderboard.diff --git a/docs/vanity.md b/docs/vanity.mdindex a58613b0f..f60535c3f 100644--- a/docs/vanity.md+++ b/docs/vanity.md@@ -35,11 +35,16 @@ the currency an agent on Base or Solana already holds — and the key is deliveronce, over TLS, and never stored.> **What can you actually match?** Base58 excludes `0`, `O`, `I`, `l`. An address-> is 32 random bytes Base58-encoded, so its **leading** characters are not-> uniformly distributed — a given prefix can be markedly harder than the naive-> 58ⁿ estimate, while suffix characters are uniform. Each extra character-> multiplies expected work by ~58, which is why the char caps and price ladder-> climb steeply.+> is 32 random bytes Base58-encoded, so its **leading** character is not+> uniformly distributed: the 40 symbols from `K` to `z` are **~17× harder** to+> lead with than `2`–`H`, a 58× spread across the alphabet. Suffix characters+> *are* uniform at 1/58. Quotes, prices and rarity all use the exact+> distribution rather than a flat 58ⁿ estimate, so a `zebra…` prefix is priced+> as the genuinely harder grind it is, and an `Agent…` prefix is not overcharged.+> Each *additional* character still multiplies expected work by ~58, which is why+> the char caps and price ladder climb steeply. If a pattern cannot be found+> inside the request's time budget, the endpoint declines it up front with the+> real attempt count instead of grinding to a timeout.---@@ -98,7 +103,7 @@ tier for the requested pattern.| `ignoreCase` | `1`/`true` matches the pattern case-insensitively (faster, less specific). || `format` | `keypair` (default) or `mnemonic`. || `strength` | Mnemonic only: `128` (12 words, default) or `256` (24 words). |-| `sealTo` | Optional X25519 public key (Base58/Base64url/hex) — see [Security model](#security-model). |+| `sealTo` | Optional X25519 public key (Base58/Base64url/hex) — see [Security model](#security-model). Prefix with `base58:`, `base64url:` or `hex:` to be explicit; a bare 43-character string is a valid encoding under two of them and is rejected rather than guessed. Keys from our SDK's `generateRecipientKeypair()` are always unambiguous. |### Examplediff --git a/mcp-server/src/lib/base58-distribution.js b/mcp-server/src/lib/base58-distribution.jsnew file mode 100644index 000000000..cfc93e0fb--- /dev/null+++ b/mcp-server/src/lib/base58-distribution.js@@ -0,0 +1,116 @@+// The true probability distribution of Base58-encoded Solana addresses.+//+// Base58 is a positional encoding of a 256-bit integer, not a string of+// independent symbols, so the LEADING character is not uniform. 2²⁵⁶/58⁴³ ≈+// 17.05 means a 44-digit encoding can only lead with one of the first 17+// symbols, while the ~5.9% of keys small enough to encode in 43 digits can lead+// with anything. The spread across the alphabet is 58×:+//+// '2'…'H' P ≈ 5.9e-2 (~3.4× easier than a uniform 1/58 model claims)+// 'J' P ≈ 1.4e-2+// 'K'…'z' P ≈ 1.0e-3 (~17× harder)+// '1' P = 1/256 (a leading zero byte, not a digit)+//+// Trailing characters genuinely are uniform, so a suffix stays 58⁻ⁿ.+//+// This file is a deliberate standalone copy of+// src/solana/vanity/base58-distribution.js: the MCP server ships as its own+// zero-dependency npm package and cannot import from the site source. The two+// are held in agreement by tests/vanity-model-parity.test.js.++export const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';++const INDEX = new Map([...BASE58_ALPHABET].map((c, i) => [c, i]));+const KEY_BYTES = 32;+const TOTAL = 1n << BigInt(8 * KEY_BYTES);+const POW58 = [1n];+for (let i = 1; i <= 64; i++) POW58.push(POW58[i - 1] * 58n);+const SCALE = 10n ** 25n;++/** Count the 32-byte values whose Base58 encoding begins with `prefix`. */+function prefixCount(prefix) {+ if (!prefix) return TOTAL;+ for (const ch of prefix) if (!INDEX.has(ch)) return 0n;++ // Leading '1's are leading zero BYTES, not digits of the numeral.+ let zeros = 0;+ while (zeros < prefix.length && prefix[zeros] === '1') zeros++;+ if (zeros > KEY_BYTES) return 0n;+ const rest = prefix.slice(zeros);+ if (rest === '') return TOTAL >> BigInt(8 * zeros);++ const width = KEY_BYTES - zeros;+ if (width < 1) return 0n;+ const lo = 1n << BigInt(8 * (width - 1));+ const hi = 1n << BigInt(8 * width);++ let value = 0n;+ for (const ch of rest) value = value * 58n + BigInt(INDEX.get(ch));++ let count = 0n;+ for (let pad = 0; pad + rest.length <= 64; pad++) {+ const unit = POW58[pad];+ const start = value * unit;+ if (start >= hi) break;+ const end = (value + 1n) * unit;+ const a = start > lo ? start : lo;+ const b = end < hi ? end : hi;+ if (b > a) count += b - a;+ }+ return count;+}++/** Every Base58-valid case spelling of `pattern` (empty when unreachable). */+export function caseVariants(pattern) {+ let out = [''];+ for (const ch of pattern) {+ const lower = ch.toLowerCase();+ const upper = ch.toUpperCase();+ const set = new Set();+ if (INDEX.has(ch)) set.add(ch);+ if (lower !== upper) {+ if (INDEX.has(lower)) set.add(lower);+ if (INDEX.has(upper)) set.add(upper);+ }+ if (set.size === 0) return [];+ const options = [...set];+ out = out.flatMap((head) => options.map((c) => head + c));+ }+ return out;+}++/** Exact probability that a random Solana address starts with `prefix`. */+export function prefixProbability(prefix, ignoreCase = false) {+ if (!prefix) return 1;+ const variants = ignoreCase ? caseVariants(prefix) : [prefix];+ if (variants.length === 0) return 0;+ let count = 0n;+ for (const variant of variants) count += prefixCount(variant);+ if (count === 0n) return 0;+ return Number((count * SCALE) / TOTAL) / 1e25;+}++/** Probability that a random Solana address ends with `suffix` (uniform 58⁻ⁿ). */+export function suffixProbability(suffix, ignoreCase = false) {+ if (!suffix) return 1;+ let p = 1;+ for (const ch of suffix) {+ const lower = ch.toLowerCase();+ const upper = ch.toUpperCase();+ const set = new Set();+ if (INDEX.has(ch)) set.add(ch);+ if (lower !== upper && ignoreCase) {+ if (INDEX.has(lower)) set.add(lower);+ if (INDEX.has(upper)) set.add(upper);+ }+ if (set.size === 0) return 0;+ p *= set.size / 58;+ }+ return p;+}++/** Expected attempts for a vanity pattern; Infinity when unreachable. */+export function expectedAttempts({ prefix = '', suffix = '', ignoreCase = false } = {}) {+ const p = prefixProbability(prefix || '', ignoreCase) * suffixProbability(suffix || '', ignoreCase);+ return p > 0 ? 1 / p : Infinity;+}diff --git a/mcp-server/src/lib/pump-vanity.js b/mcp-server/src/lib/pump-vanity.jsindex 7a906db62..8e9ec54a3 100644--- a/mcp-server/src/lib/pump-vanity.js+++ b/mcp-server/src/lib/pump-vanity.js@@ -57,14 +57,15 @@ export function isValidVanityPrefix(prefix) {return true;}-// Estimated attempts ≈ 58^n (per pattern position). Used by callers to set+// Expected attempts under the exact Base58 distribution. Used by callers to set// a reasonable maxIterations and to surface difficulty in error messages.-export function estimateAttempts({ prefix, suffix, ignoreCase = false } = {}) {- const len = (prefix?.length || 0) + (suffix?.length || 0);- if (len === 0) return 1;- const alphabetSize = ignoreCase ? 33 : 58; // lowercase-folded alphabet ≈ 33 distinct- return Math.pow(alphabetSize, len);-}+//+// This was 58^n (or 33^n when case-folding), which treats every position as an+// independent uniform symbol. That is right for a suffix and wrong for the+// leading character by up to 17× — see base58-distribution.js. Getting it wrong+// meant a "2-character" budget that clears `A?` in a second and cannot clear+// `z?` at all.+export { expectedAttempts as estimateAttempts } from './base58-distribution.js';/*** Grind a Solana Keypair whose base58 address matches a prefix and/or suffix.diff --git a/scripts/reprice-vanity-inventory.mjs b/scripts/reprice-vanity-inventory.mjsnew file mode 100644index 000000000..3acd14409--- /dev/null+++ b/scripts/reprice-vanity-inventory.mjs@@ -0,0 +1,150 @@+#!/usr/bin/env node+/**+ * Reprice the vanity inventory under the corrected Base58 difficulty model.+ *+ * WHY+ * ---+ * Every rarity_bits / rarity_tier / rarity_score / price_usd in+ * `vanity_inventory` was computed with a model that assumed each Base58+ * character is uniform at 1/58. That is true for a suffix and false for the+ * leading character: Base58 encodes a 256-bit integer positionally, and+ * 2^256/58^43 ~= 17.05 means a 44-digit encoding can only ever lead with one of+ * the first 17 symbols. The alphabet splits into bands spanning 58x in+ * difficulty (see src/solana/vanity/base58-distribution.js).+ *+ * The consequence on the live book: the median available SKU was ~17x harder to+ * grind than its stored difficulty claimed (prefixes leading 'K'-'z', which is+ * most dictionary words), while prefixes leading '2'-'H' were up to 1.75x+ * easier. Since price is an exponential function of rarity bits, the book was+ * mispriced in both directions.+ *+ * WHAT IT TOUCHES+ * ---------------+ * Only rows with status='available' — unsold stock. A sold or destroyed row+ * keeps the numbers it was transacted at; the price a buyer actually paid is a+ * fact about the past, not a value to recompute. Every touched row is stamped+ * difficulty_model='base58-exact/v2' so a partially-migrated book is visible.+ *+ * USAGE+ * -----+ * node scripts/reprice-vanity-inventory.mjs # dry run (default)+ * node scripts/reprice-vanity-inventory.mjs --apply # write+ * node scripts/reprice-vanity-inventory.mjs --apply --backup out.json+ *+ * Requires DATABASE_URL.+ */++import { writeFileSync } from 'node:fs';+import { neon } from '@neondatabase/serverless';+import { computeRarity } from '../src/solana/vanity/rarity.js';+import { priceFromRarity } from '../api/_lib/vanity-inventory-pricing.js';+import { DIFFICULTY_MODEL } from '../src/solana/vanity/validation.js';++const apply = process.argv.includes('--apply');+const backupIdx = process.argv.indexOf('--backup');+const backupPath = backupIdx >= 0 ? process.argv[backupIdx + 1] : null;++const url = process.env.DATABASE_URL;+if (!url) {+ console.error('DATABASE_URL is required');+ process.exit(1);+}+const sql = neon(url);++const rows = await sql`+ SELECT id, address, prefix, suffix, ignore_case, status,+ difficulty_attempts, rarity_bits, rarity_tier, rarity_score, price_usd+ FROM vanity_inventory+ WHERE status = 'available'+ ORDER BY created_at+`;++const changes = [];+for (const row of rows) {+ const rarity = computeRarity({+ prefix: row.prefix || '',+ suffix: row.suffix || '',+ ignoreCase: row.ignore_case,+ });+ // An unreachable pattern would price to Infinity; such a row is data+ // corruption rather than a repricing target, so leave it for a human.+ if (!Number.isFinite(rarity.expectedAttempts)) {+ console.warn(`skipping ${row.address}: pattern is unreachable (${row.prefix}/${row.suffix})`);+ continue;+ }+ const { priceUsd } = priceFromRarity(rarity);+ const before = {+ attempts: Number(row.difficulty_attempts),+ bits: Number(row.rarity_bits),+ tier: row.rarity_tier,+ score: row.rarity_score,+ price: Number(row.price_usd),+ };+ const after = {+ attempts: rarity.expectedAttempts,+ bits: rarity.rarityBits,+ tier: rarity.tier,+ score: rarity.rarityScore,+ price: priceUsd,+ };+ if (+ before.attempts === after.attempts &&+ before.tier === after.tier &&+ before.price === after.price+ ) {+ continue;+ }+ changes.push({ id: row.id, address: row.address, pattern: row.prefix || row.suffix, before, after });+}++const priceDelta = changes.reduce((sum, c) => sum + (c.after.price - c.before.price), 0);+const tierMoves = changes.filter((c) => c.before.tier !== c.after.tier).length;++console.log(`available rows : ${rows.length}`);+console.log(`rows to reprice : ${changes.length}`);+console.log(`tier changes : ${tierMoves}`);+console.log(`book value delta : ${priceDelta >= 0 ? '+' : ''}$${priceDelta.toFixed(2)}`);++const sorted = [...changes].sort((a, b) => b.after.price - b.before.price - (a.after.price - a.before.price));+console.log('\nlargest increases (understated difficulty):');+for (const c of sorted.slice(0, 6)) {+ console.log(+ ` ${String(c.pattern).padEnd(6)} $${c.before.price} -> $${c.after.price} ` ++ `${c.before.tier} -> ${c.after.tier} (${c.before.attempts} -> ${c.after.attempts} attempts)`,+ );+}+console.log('\nlargest decreases (overstated difficulty):');+for (const c of sorted.slice(-6).reverse()) {+ console.log(+ ` ${String(c.pattern).padEnd(6)} $${c.before.price} -> $${c.after.price} ` ++ `${c.before.tier} -> ${c.after.tier} (${c.before.attempts} -> ${c.after.attempts} attempts)`,+ );+}++if (backupPath) {+ writeFileSync(backupPath, JSON.stringify(changes, null, 2));+ console.log(`\nbackup of prior values written to ${backupPath}`);+}++if (!apply) {+ console.log('\nDRY RUN — re-run with --apply to write.');+ process.exit(0);+}++let written = 0;+for (const c of changes) {+ await sql`+ UPDATE vanity_inventory+ SET difficulty_attempts = ${c.after.attempts},+ rarity_bits = ${c.after.bits},+ rarity_tier = ${c.after.tier},+ rarity_score = ${c.after.score},+ price_usd = ${c.after.price},+ difficulty_model = ${DIFFICULTY_MODEL},+ updated_at = now()+ WHERE id = ${c.id}+ AND status = 'available'+ `;+ written++;+}+console.log(`\napplied to ${written} rows, stamped ${DIFFICULTY_MODEL}`);diff --git a/solana-agent-sdk/src/vanity/sealed.ts b/solana-agent-sdk/src/vanity/sealed.tsindex 00d00df9a..8b5ee2694 100644--- a/solana-agent-sdk/src/vanity/sealed.ts+++ b/solana-agent-sdk/src/vanity/sealed.ts@@ -39,18 +39,64 @@ function fromBase64url(str: string): Uint8Array {return new Uint8Array(Buffer.from(b64, "base64"));}+const KEY_DECODERS: Record<string, (s: string) => Uint8Array> = {+ hex: (s) => {+ if (!/^[0-9a-fA-F]+$/.test(s) || s.length % 2) throw new Error("not hex");+ return Uint8Array.from(s.match(/.{2}/g)!.map((h) => parseInt(h, 16)));+ },+ base58: (s) => bs58.decode(s),+ base64url: (s) => fromBase64url(s),+};++/**+ * Parse a 32-byte X25519 key from a Uint8Array, or a Base58 / Base64url / hex+ * string, refusing to guess when the string is genuinely ambiguous.+ *+ * Base58's alphabet is a subset of Base64url's and Base64url spends exactly 43+ * characters on 32 bytes — the same length Base58 uses for the ~5.4% of keys+ * small enough to need only 43 digits. So a bare 43-character string can encode+ * two different keys. Picking one silently is how a buyer ends up unable to open+ * an envelope they paid for, so an unresolvable string throws instead. An+ * explicit `hex:`, `base58:` or `base64url:` prefix always wins.+ *+ * Mirrors src/solana/vanity/sealed-envelope.js.+ */function parseX25519Key(key: Uint8Array | string, label: string): Uint8Array {let bytes: Uint8Array;if (key instanceof Uint8Array) {bytes = key;} else {const s = key.trim();- if (/^[0-9a-fA-F]{64}$/.test(s)) {- bytes = Uint8Array.from(s.match(/.{2}/g)!.map((h) => parseInt(h, 16)));- } else if (/^[1-9A-HJ-NP-Za-km-z]+$/.test(s) && !s.includes("-") && !s.includes("_")) {- bytes = bs58.decode(s);+ const explicit = /^(hex|base58|base64url):(.*)$/s.exec(s);+ if (explicit) {+ bytes = KEY_DECODERS[explicit[1]!]!(explicit[2]!.trim());+ } else if (/^[0-9a-fA-F]{64}$/.test(s)) {+ bytes = KEY_DECODERS.hex!(s);+ } else if (/^[1-9A-HJ-NP-Za-km-z]{44}$/.test(s)) {+ bytes = KEY_DECODERS.base58!(s);} else {- bytes = fromBase64url(s);+ const found = new Map<string, { name: string; bytes: Uint8Array }>();+ for (const [name, decode] of Object.entries(KEY_DECODERS)) {+ let out: Uint8Array;+ try {+ out = decode(s);+ } catch {+ continue;+ }+ if (out?.length !== X25519_KEY_BYTES) continue;+ found.set([...out].map((b) => b.toString(16).padStart(2, "0")).join(""), { name, bytes: out });+ }+ if (found.size === 1) {+ bytes = [...found.values()][0]!.bytes;+ } else if (found.size === 0) {+ throw new Error(`${label} is not a valid Base58/Base64url/hex 32-byte key`);+ } else {+ const names = [...found.values()].map((v) => v.name).sort();+ throw new Error(+ `${label} is ambiguous: it is a valid ${names.join(" and ")} encoding of two different ` ++ `32-byte keys. Prefix it to be explicit, e.g. "base58:${s}" or "base64url:${s}".`,+ );+ }}}if (bytes.length !== X25519_KEY_BYTES) {@@ -96,9 +142,21 @@ export function openSealedJson<T = unknown>(/** Generate a throwaway X25519 recipient keypair (Base58). Pass publicKey as sealTo. */export function generateRecipientKeypair(): { publicKey: string; secretKey: string } {- const secret = x25519.utils.randomSecretKey();- return {- publicKey: bs58.encode(x25519.getPublicKey(secret)),- secretKey: bs58.encode(secret),- };+ // Keep drawing until BOTH Base58 forms are 44 characters.+ //+ // Base64url encodes 32 bytes in exactly 43 characters, and Base58's alphabet+ // is a subset of Base64url's — so a 43-character Base58 key is also a valid+ // Base64url string decoding to a *different* key, and a bare `sealTo=` value+ // cannot say which was meant. 44 characters is unambiguous, and only ~5.4% of+ // keys are short enough to need 43, so this costs ~11% of one extra keygen+ // and keeps the sealed-delivery path exact against every server version.+ // The secret is constrained too: it travels through the same parser when the+ // buyer opens the envelope.+ for (;;) {+ const secret = x25519.utils.randomSecretKey();+ const publicKey = bs58.encode(x25519.getPublicKey(secret));+ const secretKey = bs58.encode(secret);+ if (publicKey.length !== 44 || secretKey.length !== 44) continue;+ return { publicKey, secretKey };+ }}diff --git a/src/solana/vanity/grinder-node.js b/src/solana/vanity/grinder-node.jsindex 336b1c8fd..54df39019 100644--- a/src/solana/vanity/grinder-node.js+++ b/src/solana/vanity/grinder-node.js@@ -24,9 +24,9 @@ import { fileURLToPath } from 'node:url';import { join } from 'node:path';import { initSync, grind } from './wasm/vanity_grinder.js';-import { validatePattern, estimateAttempts, BASE58_ALPHABET } from './validation.js';+import { validatePattern, estimateAttempts, expectedAttempts, BASE58_ALPHABET } from './validation.js';-export { BASE58_ALPHABET, validatePattern, estimateAttempts };+export { BASE58_ALPHABET, validatePattern, estimateAttempts, expectedAttempts };// Largest combined (prefix + suffix) length the server will grind. Past this,// the expected attempt count blows past what a single WASM thread can clear@@ -42,6 +42,55 @@ const DEFAULT_TIME_BUDGET_MS = 45_000;// negligible, small enough that we re-check the time budget promptly.const BATCH_SIZE = 20_000;+/** Measured single-threaded WASM throughput. Override where the host is slower. */+export const KEYPAIR_ATTEMPTS_PER_SECOND = Number(+ globalThis.process?.env?.KEYPAIR_GRIND_RATE || 25_000,+);++/**+ * Minimum ratio of affordable to expected attempts before a job is accepted.+ * A geometric grind clears `n` attempts with probability 1 − e^(−n/E), so n/E ≥ 3+ * finishes ~95% of the time.+ */+const FEASIBILITY_MARGIN = 3;++/**+ * Reject a pattern the budget cannot realistically satisfy.+ *+ * `MAX_SERVER_PATTERN_LENGTH` alone is not a sufficient guard. Base58's leading+ * character spans a 58× difficulty range (see base58-distribution.js), so a+ * 3-character pattern is ~57k attempts when it leads with '2'–'H' and ~3.3M when+ * it leads with 'K'–'z' — the latter needs ~132s, three times the budget. Such a+ * request used to be accepted, grind for the full 45s, and fail.+ *+ * @param {string} prefix+ * @param {string} suffix+ * @param {boolean} ignoreCase+ * @param {number} timeBudgetMs+ * @throws {Error} status 400 / code `pattern_infeasible`+ */+export function assertKeypairFeasible(prefix, suffix, ignoreCase, timeBudgetMs) {+ const expected = expectedAttempts(prefix || '', suffix || '', ignoreCase);+ const affordable = (timeBudgetMs / 1000) * KEYPAIR_ATTEMPTS_PER_SECOND;+ if (expected * FEASIBILITY_MARGIN <= affordable) return;++ const seconds = Math.ceil(expected / KEYPAIR_ATTEMPTS_PER_SECOND);+ const chance = Math.round((1 - Math.exp(-affordable / expected)) * 100);+ throw Object.assign(+ new Error(+ `pattern needs ~${Math.round(expected).toLocaleString('en-US')} attempts ` ++ `(~${seconds}s at ${KEYPAIR_ATTEMPTS_PER_SECOND.toLocaleString('en-US')}/sec), but the ` ++ `${Math.round(timeBudgetMs / 1000)}s budget only affords ` ++ `~${Math.round(affordable).toLocaleString('en-US')} — about a ${chance}% chance of a hit. ` ++ `Base58's leading character is not uniform: the 40 symbols from 'K' to 'z' are ~17× ` ++ `harder to lead with than '2'–'H'. Try a prefix starting with one of 2-9 or A-H, move ` ++ `the pattern to the suffix (uniform 1/58 per character), or grind it in the browser at ` ++ `/vanity, which parallelizes across all your cores.`,+ ),+ { status: 400, code: 'pattern_infeasible', expectedAttempts: Math.round(expected) },+ );+}+let wasmReady = false;export class GrindExhaustedError extends Error {@@ -106,12 +155,19 @@ function ensureWasm() {/*** Estimate the combined difficulty (expected attempts) for a pattern.+ *+ * Uses the exact Base58 distribution rather than 58^length: the leading+ * character spans a 58× difficulty range, so a length-only estimate is wrong by+ * up to 17× in either direction. See+ * [base58-distribution.js](./base58-distribution.js).+ ** @param {string} prefix* @param {string} suffix+ * @param {boolean} [ignoreCase=false]* @returns {number}*/-export function expectedAttemptsFor(prefix, suffix) {- return estimateAttempts((prefix?.length || 0) + (suffix?.length || 0));+export function expectedAttemptsFor(prefix, suffix, ignoreCase = false) {+ return expectedAttempts(prefix || '', suffix || '', ignoreCase);}/**@@ -167,6 +223,8 @@ export function grindVanityNode(opts = {}) {);}+ assertKeypairFeasible(prefix, suffix, ignoreCase, timeBudgetMs);+ensureWasm();const startedAt = performance.now();diff --git a/src/solana/vanity/mnemonic-grinder.js b/src/solana/vanity/mnemonic-grinder.jsindex 78341fd70..998aaece5 100644--- a/src/solana/vanity/mnemonic-grinder.js+++ b/src/solana/vanity/mnemonic-grinder.js@@ -9,12 +9,19 @@* buyer can type into any wallet — at the same address.** Cost model: each attempt runs PBKDF2-HMAC-SHA512 (2048 iterations) + an- * HMAC-SHA512 chain, so throughput is ~200–250 keypairs/sec single-threaded —- * roughly 100× slower than the WASM keypair grinder. The honest server ceiling- * is therefore a 2-character combined pattern (~3.4k expected attempts, found- * inside the default 45s budget the large majority of the time). On budget- * exhaustion we throw GrindExhaustedError so the x402 endpoint declines to- * charge the buyer. Longer mnemonic patterns belong on the user's own machine.+ * HMAC-SHA512 chain, so throughput is ~350 keypairs/sec single-threaded —+ * roughly 100× slower than the WASM keypair grinder. On budget exhaustion we+ * throw GrindExhaustedError so the x402 endpoint declines to charge the buyer.+ * Longer mnemonic patterns belong on the user's own machine.+ *+ * A character-count cap alone is NOT a safe ceiling. Base58's leading character+ * spans a 58× difficulty range (see base58-distribution.js), so "2 characters"+ * covers everything from `A?` (~982 attempts, under 3 seconds) to `z?` (~57k+ * attempts, ~2.7 minutes) — the latter far past any serverless budget. Requests+ * used to be accepted on length alone, grind for the full 45 seconds, and fail;+ * the buyer got nothing and we burned the compute. `assertFeasible` now rejects+ * those up front with the real numbers, and the length cap stays only as a+ * coarse outer guard.*/import { validatePattern, expectedAttempts } from './validation.js';@@ -29,6 +36,56 @@ export const MAX_MNEMONIC_PATTERN_LENGTH = 2;const DEFAULT_TIME_BUDGET_MS = 45_000;+/**+ * Measured single-threaded throughput of the mnemonic grind loop (mnemonic →+ * PBKDF2 seed → SLIP-10 chain → Ed25519 public key). Override with+ * `MNEMONIC_GRIND_RATE` where the host is slower than the reference machine.+ */+export const MNEMONIC_ATTEMPTS_PER_SECOND = Number(+ globalThis.process?.env?.MNEMONIC_GRIND_RATE || 350,+);++/**+ * Minimum ratio of affordable attempts to expected attempts before we accept a+ * job. A geometric grind succeeds within `n` attempts with probability+ * 1 − e^(−n/E), so n/E ≥ 3 means we finish ~95% of the time. Below that the+ * buyer is more likely to get a timeout than an address, which is worse than an+ * immediate, honest rejection.+ */+const FEASIBILITY_MARGIN = 3;++/**+ * Reject a pattern the budget cannot realistically satisfy, with the real+ * numbers rather than a generic timeout 45 seconds later.+ *+ * @param {string} prefix+ * @param {string} suffix+ * @param {boolean} ignoreCase+ * @param {number} timeBudgetMs+ * @throws {Error} status 400 / code `pattern_infeasible`+ */+export function assertMnemonicFeasible(prefix, suffix, ignoreCase, timeBudgetMs) {+ const expected = expectedMnemonicAttempts(prefix, suffix, ignoreCase);+ const affordable = (timeBudgetMs / 1000) * MNEMONIC_ATTEMPTS_PER_SECOND;+ if (expected * FEASIBILITY_MARGIN <= affordable) return;++ const seconds = Math.ceil(expected / MNEMONIC_ATTEMPTS_PER_SECOND);+ const chance = Math.round((1 - Math.exp(-affordable / expected)) * 100);+ throw Object.assign(+ new Error(+ `pattern needs ~${Math.round(expected).toLocaleString('en-US')} attempts ` ++ `(~${seconds}s at ${MNEMONIC_ATTEMPTS_PER_SECOND}/sec), but the ${Math.round(+ timeBudgetMs / 1000,+ )}s budget only affords ~${Math.round(affordable).toLocaleString('en-US')} ` ++ `— about a ${chance}% chance of a hit. Base58's leading character is not uniform: ` ++ `the 40 symbols from 'K' to 'z' are ~17× harder to lead with than '2'–'H'. ` ++ `Try a prefix starting with one of 2-9 or A-H, move the pattern to the suffix ` ++ `(uniform 1/58 per character), or grind it on your own machine.`,+ ),+ { status: 400, code: 'pattern_infeasible', expectedAttempts: Math.round(expected) },+ );+}+// How often to re-check the wall-clock budget. The per-attempt cost is high// (~4–5ms), so a small batch keeps the budget check responsive without adding// measurable overhead.@@ -93,6 +150,8 @@ export function grindVanityMnemonic(opts = {}) {);}+ assertMnemonicFeasible(prefix, suffix, ignoreCase, timeBudgetMs);+const wantPrefix = prefix ? (ignoreCase ? prefix.toLowerCase() : prefix) : null;const wantSuffix = suffix ? (ignoreCase ? suffix.toLowerCase() : suffix) : null;const pLen = wantPrefix?.length || 0;diff --git a/src/solana/vanity/sealed-envelope.js b/src/solana/vanity/sealed-envelope.jsindex 961990f96..7f2991ede 100644--- a/src/solana/vanity/sealed-envelope.js+++ b/src/solana/vanity/sealed-envelope.js@@ -38,6 +38,13 @@ import { sha256 } from '@noble/hashes/sha256';export const SEALED_ENVELOPE_SCHEME = 'x25519-hkdf-sha256-aes256gcm/v1';const HKDF_INFO = new TextEncoder().encode('three.ws sealed-envelope v1');const X25519_KEY_BYTES = 32;++/**+ * Base58 length at which a 32-byte key cannot be confused with Base64url.+ * Base64url always spends exactly 43 characters on 32 bytes, so a 44-character+ * Base58 string is unambiguous while a 43-character one is not.+ */+export const X25519_UNAMBIGUOUS_B58_LENGTH = 44;const NONCE_BYTES = 12;const cryptoObj = globalThis.crypto;@@ -57,6 +64,44 @@ function randomBytes(n) {return b;}+/**+ * Run every decoder that accepts `s` and return the one 32-byte key they agree+ * on. Throws when two decoders yield two *different* 32-byte keys — that is a+ * real ambiguity in the input, and picking one is how a buyer ends up with an+ * envelope sealed to a key they do not hold.+ */+function disambiguate(s, label) {+ const found = new Map();+ for (const [name, decode] of Object.entries(KEY_DECODERS)) {+ let out;+ try {+ out = decode(s);+ } catch {+ continue;+ }+ if (out?.length !== X25519_KEY_BYTES) continue;+ found.set(bytesKey(out), { name, bytes: out });+ }+ if (found.size === 1) return [...found.values()][0].bytes;+ if (found.size === 0) throw new Error('no decoder produced a 32-byte key');+ const names = [...found.values()].map((v) => v.name).sort();+ throw Object.assign(+ new Error(+ `${label} is ambiguous: it is a valid ${names.join(' and ')} encoding of two different ` ++ `32-byte keys. Base58's alphabet is a subset of Base64url's and both encode 32 bytes ` ++ `in 43 characters, so the string alone cannot say which you meant. Prefix it to be ` ++ `explicit, e.g. "base58:${s}" or "base64url:${s}".`,+ ),+ { status: 400, code: 'ambiguous_recipient_key', candidates: names },+ );+}++function bytesKey(bytes) {+ let out = '';+ for (const b of bytes) out += b.toString(16).padStart(2, '0');+ return out;+}+function toBase64url(bytes) {let bin = '';for (const b of bytes) bin += String.fromCharCode(b);@@ -72,8 +117,46 @@ function fromBase64url(str) {}/**- * Parse a 32-byte X25519 key supplied as a Uint8Array, Base58, Base64url, or- * hex string. Throws a 400-tagged error on anything that isn't a 32-byte key.+ * Encodings `parseX25519Key` accepts, and the `name:` prefix that names each+ * one explicitly. An explicit prefix is the only way to be certain — see below.+ */+const KEY_DECODERS = {+ hex: (s) => {+ if (!/^[0-9a-fA-F]+$/.test(s) || s.length % 2) throw new Error('not hex');+ return Uint8Array.from(s.match(/.{2}/g).map((h) => parseInt(h, 16)));+ },+ base58: (s) => bs58.decode(s),+ base64url: (s) => fromBase64url(s),+};++/**+ * Parse a 32-byte X25519 key supplied as a Uint8Array, or as a Base58,+ * Base64url or hex string.+ *+ * ── The ambiguity this resolves ──────────────────────────────────────────────+ * Base58's alphabet is a strict SUBSET of Base64url's, and Base64url encodes 32+ * bytes in exactly 43 characters — the same length Base58 produces for the ~5.4%+ * of keys small enough to need only 43 digits. So a bare 43-character string can+ * be a valid encoding of two *different* 32-byte keys, with nothing in the string+ * itself to say which.+ *+ * Guessing is not harmless here. The previous implementation tried Base58 first+ * whenever the string contained no `-` or `_`, which measured at **1.5% of+ * Base64url keys mis-parsed, 95% of those silently** — the same characters+ * decoded to a valid-looking but wrong 32-byte key, the secret was sealed to it,+ * and the buyer could not open the envelope they had paid for.+ *+ * The fix is to let the caller be explicit, and to be honest when they were not:+ *+ * • `hex:`, `base58:` or `base64url:` prefix → decoded as stated, no guessing.+ * • 64 hex characters → unambiguously hex (no 32-byte Base58 or Base64url+ * encoding is 64 characters long).+ * • 44 characters → unambiguously Base58 (Base64url is always 43).+ * • anything else → every applicable decoder is run, and a single 32-byte+ * result wins. Two different 32-byte results is a genuine ambiguity and+ * throws `ambiguous_recipient_key` naming the prefixes that resolve it,+ * rather than silently picking one.+ ** @param {Uint8Array|string} key* @param {string} [label='key']* @returns {Uint8Array}@@ -84,15 +167,19 @@ export function parseX25519Key(key, label = 'key') {bytes = key;} else if (typeof key === 'string') {const s = key.trim();+ const explicit = /^(hex|base58|base64url):(.*)$/s.exec(s);try {- if (/^[0-9a-fA-F]{64}$/.test(s)) {- bytes = Uint8Array.from(s.match(/.{2}/g).map((h) => parseInt(h, 16)));- } else if (/^[1-9A-HJ-NP-Za-km-z]+$/.test(s) && !s.includes('-') && !s.includes('_')) {- bytes = bs58.decode(s);+ if (explicit) {+ bytes = KEY_DECODERS[explicit[1]](explicit[2].trim());+ } else if (/^[0-9a-fA-F]{64}$/.test(s)) {+ bytes = KEY_DECODERS.hex(s);+ } else if (/^[1-9A-HJ-NP-Za-km-z]{44}$/.test(s)) {+ bytes = KEY_DECODERS.base58(s);} else {- bytes = fromBase64url(s);+ bytes = disambiguate(s, label);}- } catch {+ } catch (err) {+ if (err?.code === 'ambiguous_recipient_key') throw err;throw Object.assign(new Error(`${label} is not valid Base58/Base64/hex`), {status: 400,code: 'invalid_recipient_key',@@ -125,8 +212,7 @@ function toBytes(plaintext) {*/export async function sealToRecipient(plaintext, recipientPublicKey) {const recipientPub = parseX25519Key(recipientPublicKey, 'recipient public key');- const ephemeralSecret = x25519.utils.randomSecretKey();- const ephemeralPublic = x25519.getPublicKey(ephemeralSecret);+ const { secret: ephemeralSecret, publicKey: ephemeralPublic } = randomUnambiguousKeypair();const shared = x25519.getSharedSecret(ephemeralSecret, recipientPub);const salt = new Uint8Array(ephemeralPublic.length + recipientPub.length);@@ -199,10 +285,40 @@ export async function openSealedText(envelope, recipientSecretKey) {* and keep `secretKey` to open the envelope.* @returns {{publicKey:string, secretKey:string}}*/+/**+ * Draw an X25519 keypair whose Base58 forms are both 44 characters.+ *+ * Every 32-byte value this module Base58-encodes is re-parsed later by+ * `parseX25519Key`, and a 43-character Base58 string is indistinguishable from+ * a Base64url one (see that function). Constraining generation keeps the wire+ * format byte-identical while making every value we emit unambiguous — which+ * matters most for the ephemeral key, since a 43-character `epk` would make+ * ~5.4% of sealed envelopes unopenable.+ *+ * Rejection sampling conditions the public key on being ≥ 58⁴³, a uniform+ * restriction that leaves ~255.9 bits of entropy. It costs ~11% of one extra+ * keygen on average.+ */+function randomUnambiguousKeypair() {+ for (;;) {+ const secret = x25519.utils.randomSecretKey();+ const publicKey = x25519.getPublicKey(secret);+ if (bs58.encode(publicKey).length !== X25519_UNAMBIGUOUS_B58_LENGTH) continue;+ if (bs58.encode(secret).length !== X25519_UNAMBIGUOUS_B58_LENGTH) continue;+ return { secret, publicKey };+ }+}+export function generateRecipientKeypair() {- const secret = x25519.utils.randomSecretKey();- return {- publicKey: bs58.encode(x25519.getPublicKey(secret)),- secretKey: bs58.encode(secret),- };+ // Keep drawing until the public key's Base58 form is 44 characters.+ //+ // Base64url encodes 32 bytes in exactly 43 characters, and Base58's alphabet+ // is a subset of Base64url's — so a 43-character Base58 key is also a valid+ // Base64url string decoding to a *different* key, and a bare `sealTo=` value+ // cannot say which was meant (see `parseX25519Key`). 44 characters is+ // unambiguous, and only ~5.4% of keys are short enough to need 43, so this+ // loop costs a few percent of one keygen. Callers of every server version+ // then work without needing an explicit `base58:` prefix on the wire.+ const { secret, publicKey } = randomUnambiguousKeypair();+ return { publicKey: bs58.encode(publicKey), secretKey: bs58.encode(secret) };}diff --git a/tests/vanity-mnemonic.test.js b/tests/vanity-mnemonic.test.jsindex fbc23b50c..94b7f086c 100644--- a/tests/vanity-mnemonic.test.js+++ b/tests/vanity-mnemonic.test.js@@ -124,8 +124,12 @@ describe('parseDerivationPath / deriveEd25519PrivateKey', () => {describe('grindVanityMnemonic', () => {it('grinds a 1-char prefix and returns an importable phrase', () => {- const r = grindVanityMnemonic({ prefix: 'z', timeBudgetMs: 20_000 });- expect(r.publicKey.startsWith('z')).toBe(true);+ // 'A' is in the easy leading band (~17 expected attempts). The original+ // version of this test ground 'z' — a hard-band symbol needing ~982+ // attempts — and flaked on slower CI hosts, which is what surfaced the+ // leading-character bug in the first place.+ const r = grindVanityMnemonic({ prefix: 'A', timeBudgetMs: 20_000 });+ expect(r.publicKey.startsWith('A')).toBe(true);expect(r.wordCount).toBe(12);expect(r.derivationPath).toBe(DEFAULT_DERIVATION_PATH);expect(r.attempts).toBeGreaterThan(0);@@ -153,9 +157,44 @@ describe('grindVanityMnemonic', () => {expect(MAX_MNEMONIC_PATTERN_LENGTH).toBe(2);});- it('throws GrindExhaustedError when the budget runs out', () => {- // A 2-char pattern with a near-zero budget cannot be found in time.- expect(() => grindVanityMnemonic({ prefix: 'zz', timeBudgetMs: 1 })).toThrow();+ it('rejects an infeasible pattern up front instead of burning the budget', () => {+ // 'zz' needs ~57k attempts (~2.7 min). Accepting it, grinding for the+ // full budget and failing leaves the buyer with nothing and costs us the+ // compute; the honest answer is an immediate 400 carrying the real cost.+ let thrown;+ const startedAt = performance.now();+ try {+ grindVanityMnemonic({ prefix: 'zz', timeBudgetMs: 45_000 });+ } catch (err) {+ thrown = err;+ }+ expect(thrown?.code).toBe('pattern_infeasible');+ expect(thrown?.status).toBe(400);+ expect(thrown.expectedAttempts).toBeGreaterThan(50_000);+ expect(thrown.message).toMatch(/leading character is not uniform/);+ // The whole point is that it does not grind first.+ expect(performance.now() - startedAt).toBeLessThan(1_000);+ });++ it('accepts the same length when the leading character is an easy one', () => {+ // Identical character count, 58× less work: a length-only cap cannot tell+ // these apart, which is why the guard is difficulty-based.+ expect(expectedMnemonicAttempts('Az', '', false)).toBeLessThan(+ expectedMnemonicAttempts('zz', '', false) / 50,+ );+ const r = grindVanityMnemonic({ prefix: 'Az', timeBudgetMs: 45_000 });+ expect(r.publicKey.startsWith('Az')).toBe(true);+ });++ it('explains a rejection with numbers a buyer can act on', () => {+ try {+ grindVanityMnemonic({ prefix: 'zz', timeBudgetMs: 45_000 });+ throw new Error('should have been rejected');+ } catch (err) {+ expect(err.message).toMatch(/attempts/);+ expect(err.message).toMatch(/budget only affords/);+ expect(err.message).toMatch(/suffix/); // an actionable alternative+ }});it('requires at least one of prefix/suffix', () => {diff --git a/tests/vanity-model-parity.test.js b/tests/vanity-model-parity.test.jsnew file mode 100644index 000000000..00c2f2926--- /dev/null+++ b/tests/vanity-model-parity.test.js@@ -0,0 +1,105 @@+// The Base58 difficulty model exists in three independently-shipped artifacts:+//+// 1. src/solana/vanity/base58-distribution.js — the site + API+// 2. solana-agent-sdk/src/vanity/verify.ts — the published TS SDK verifier+// 3. mcp-server/src/lib/base58-distribution.js — the standalone MCP npm package+//+// Each is zero-dependency by design and cannot import the others, so the code is+// deliberately duplicated. Duplication without a parity check is how the three+// drift apart, and a verifier that disagrees with the issuer about difficulty+// rejects honest receipts. These tests are the thing that keeps them honest.++import { describe, it, expect } from 'vitest';++import {+ prefixProbability as sitePrefixProbability,+ BASE58_ALPHABET,+} from '../src/solana/vanity/base58-distribution.js';+import {+ expectedAttempts as siteExpectedAttempts,+ expectedAttemptsUniform as siteUniform,+ difficultyModel as siteDifficultyModel,+ DIFFICULTY_MODEL,+ DIFFICULTY_MODEL_V1,+} from '../src/solana/vanity/validation.js';+import {+ expectedAttempts as sdkExpectedAttempts,+ expectedAttemptsUniform as sdkUniform,+ difficultyModel as sdkDifficultyModel,+ DIFFICULTY_MODEL as SDK_DIFFICULTY_MODEL,+ DIFFICULTY_MODEL_V1 as SDK_DIFFICULTY_MODEL_V1,+} from '../solana-agent-sdk/src/vanity/verify.ts';+import { expectedAttempts as mcpExpectedAttempts } from '../mcp-server/src/lib/base58-distribution.js';++/** Patterns chosen to hit every band and edge case of the encoding. */+const VECTORS = [+ { prefix: 'A', suffix: '', ignoreCase: false }, // easy band+ { prefix: '2', suffix: '', ignoreCase: false }, // 44-digit-only band+ { prefix: '4', suffix: '', ignoreCase: false }, // boundary symbol+ { prefix: 'J', suffix: '', ignoreCase: false }, // partial band+ { prefix: 'z', suffix: '', ignoreCase: false }, // hard band+ { prefix: '1', suffix: '', ignoreCase: false }, // leading zero byte+ { prefix: '11', suffix: '', ignoreCase: false }, // two zero bytes+ { prefix: '1a', suffix: '', ignoreCase: false }, // zero byte then a digit+ { prefix: 'cat', suffix: '', ignoreCase: false },+ { prefix: 'MOON', suffix: '', ignoreCase: true }, // the live-inventory shape+ { prefix: '', suffix: 'z', ignoreCase: false }, // suffix only+ { prefix: '', suffix: 'Az', ignoreCase: true },+ { prefix: 'So', suffix: 'ana', ignoreCase: false }, // both ends+ { prefix: 'I', suffix: '', ignoreCase: true }, // no valid uppercase form+];++const label = (v) => `${v.prefix || '-'}…${v.suffix || '-'}${v.ignoreCase ? ' (ci)' : ''}`;++describe('all three implementations agree on the exact model', () => {+ for (const v of VECTORS) {+ it(`agrees on ${label(v)}`, () => {+ const site = siteExpectedAttempts(v.prefix, v.suffix, v.ignoreCase);+ const sdk = sdkExpectedAttempts(v.prefix, v.suffix, v.ignoreCase);+ const mcp = mcpExpectedAttempts(v);+ // Relative comparison: these span 1e1 … 1e10, so an absolute epsilon+ // would be meaninglessly loose at the top and impossible at the bottom.+ expect(sdk / site).toBeCloseTo(1, 12);+ expect(mcp / site).toBeCloseTo(1, 12);+ });+ }++ it('agrees on the superseded v1 model too, so old receipts verify anywhere', () => {+ for (const v of VECTORS) {+ expect(sdkUniform(v.prefix, v.suffix, v.ignoreCase)).toBeCloseTo(+ siteUniform(v.prefix, v.suffix, v.ignoreCase),+ 9,+ );+ }+ });++ it('uses identical model identifiers, so dispatch cannot silently diverge', () => {+ expect(SDK_DIFFICULTY_MODEL).toBe(DIFFICULTY_MODEL);+ expect(SDK_DIFFICULTY_MODEL_V1).toBe(DIFFICULTY_MODEL_V1);+ });++ it('dispatches to the same function for a given model id', () => {+ for (const model of [DIFFICULTY_MODEL, DIFFICULTY_MODEL_V1, undefined]) {+ expect(sdkDifficultyModel(model)('cat', '', false)).toBeCloseTo(+ siteDifficultyModel(model)('cat', '', false),+ 6,+ );+ }+ });++ it('agrees across the entire alphabet, not just the sampled vectors', () => {+ for (const ch of BASE58_ALPHABET) {+ const site = 1 / sitePrefixProbability(ch);+ expect(sdkExpectedAttempts(ch, '', false) / site).toBeCloseTo(1, 12);+ expect(mcpExpectedAttempts({ prefix: ch }) / site).toBeCloseTo(1, 12);+ }+ });+});++describe('the correction is not cosmetic', () => {+ it('differs from the superseded model by more than a rounding error', () => {+ // If these ever coincide, someone has quietly reverted the model.+ expect(siteExpectedAttempts('z', '', false) / siteUniform('z', '', false)).toBeGreaterThan(15);+ expect(siteExpectedAttempts('A', '', false) / siteUniform('A', '', false)).toBeLessThan(0.35);+ });+});diff --git a/tests/x402-vanity-sealed-envelope.test.js b/tests/x402-vanity-sealed-envelope.test.jsindex dd0eac723..b55c9b444 100644--- a/tests/x402-vanity-sealed-envelope.test.js+++ b/tests/x402-vanity-sealed-envelope.test.js@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest';import bs58 from 'bs58';+import { x25519 } from '@noble/curves/ed25519.js';import {sealToRecipient,@@ -81,12 +82,60 @@ describe('sealed-envelope', () => {const raw = parseX25519Key(publicKey);const hex = Buffer.from(raw).toString('hex');const b64 = toBase64url(raw);- for (const form of [publicKey, hex, b64]) {+ // Explicit prefixes are always unambiguous; bare forms are covered below.+ for (const form of [publicKey, hex, `base58:${publicKey}`, `hex:${hex}`, `base64url:${b64}`]) {const env = await sealToRecipient('ok', form);expect(await openSealedText(env, secretKey)).toBe('ok');}});+ it('generates recipient keys that are unambiguous on the wire', () => {+ // Base64url spends exactly 43 characters on 32 bytes and Base58's alphabet+ // is a subset of Base64url's, so a 43-character Base58 key is ALSO a valid+ // Base64url string for a different key. Generating only 44-character keys+ // means a bare `sealTo=` from our own SDK can never be misread.+ for (let i = 0; i < 200; i++) {+ const kp = generateRecipientKeypair();+ // Both halves: the secret travels through the same parser on open.+ expect(kp.publicKey).toHaveLength(44);+ expect(kp.secretKey).toHaveLength(44);+ }+ });++ it('never silently seals to the wrong key when an encoding is ambiguous', async () => {+ // A hand-rolled caller can still submit a 43-character key. The old parser+ // tried Base58 first whenever the string had no '-' or '_', which measured+ // at 1.5% of Base64url keys decoding to a valid-looking but WRONG key: the+ // buyer paid, got a sealed envelope, and could not open it. Refusing to+ // guess is the only outcome that cannot do that.+ let ambiguous = 0;+ for (let i = 0; i < 400 && ambiguous < 1; i++) {+ const secret = x25519.utils.randomSecretKey();+ const raw = x25519.getPublicKey(secret);+ const b58 = bs58.encode(raw);+ if (b58.length !== 43) continue; // only 43-char keys collide+ ambiguous++;+ // Bare form is refused with an actionable error...+ let err;+ try {+ parseX25519Key(b58);+ } catch (e) {+ err = e;+ }+ expect(err?.code).toBe('ambiguous_recipient_key');+ expect(err?.status).toBe(400);+ expect(err.message).toMatch(/base58:/);+ // ...and the prefix the message suggests actually resolves it.+ expect(Buffer.from(parseX25519Key(`base58:${b58}`))).toEqual(Buffer.from(raw));+ }+ expect(ambiguous, 'expected to draw at least one 43-char key in 400 tries').toBe(1);+ });++ it('rejects an unknown encoding prefix rather than guessing', () => {+ const { publicKey } = generateRecipientKeypair();+ expect(() => parseX25519Key(`base32:${publicKey}`)).toThrow(/not valid/i);+ });+it('throws a 400-tagged error on a wrong-length recipient key', () => {try {parseX25519Key('deadbeef'); // 4 bytes, not 32