diff --git a/doc/2026-11-14T06-22-00Z_poc_currency_gateway_boundary_results/2026-11-14T06-22-00Z_poc_currency_gateway_boundary_results.md b/doc/2026-11-14T06-22-00Z_poc_currency_gateway_boundary_results/2026-11-14T06-22-00Z_poc_currency_gateway_boundary_results.md new file mode 100644 index 0000000000..4371945bbc --- /dev/null +++ b/doc/2026-11-14T06-22-00Z_poc_currency_gateway_boundary_results/2026-11-14T06-22-00Z_poc_currency_gateway_boundary_results.md @@ -0,0 +1,96 @@ +# PoC results — currency gateway boundary (#2298) + +**Status:** proof of concept, flagged for a review round. Do NOT build +the permanent currency service on top of this unreviewed (the issue's +own gate note). Code: `pkgs/id/hosted-worker/src/currency/` +(`crypto.ts`, `ledger.ts`, `gateway.ts`, `relay.ts`); proofs: +`pkgs/id/hosted-worker/test/currency.test.ts`. + +**Gate:** respected. Work started only after (a) the #2043 currencies +v1 synthesis accepted the #2066 boundary — Drew's recorded ruling +`hosted-boundary-2298` (2026-11-12): hosted tier holds signed +snapshots only, server-scoped tokens signed by the server's token +admin key, cross-server transfers are bilateral signed double-entry, +do not block on TigerBeetle — and (b) the #2062 control-plane design +fixed the gateway shape (closed; PR #2315 merged). + +## The four proofs, demonstrated + +Run in `pkgs/id/hosted-worker`: + +``` +$ npm test +✔ proof 1: gateway transfer + signed snapshot verifies and is server-scoped +✔ proof 1b: gateway rejects an unsigned or wrongly-signed transfer +✔ proof 3: client-signed transfer and hold -> post cycle through the relay +✔ proof 1c: hold -> void releases the reservation +✔ proof 2: the intent is persisted before the gateway fetch +✔ proof 4: hibernation — response lost, wake reconciles, retry stays exactly one transfer +✔ proof 4b: mutated retry under the same request ID is a hard error +✔ ruling: cross-server transfer is bilateral signed double-entry +(plus the 4 pre-existing routing tests) — 12/12 pass +$ npm run typecheck # tsc --noEmit — clean +``` + +1. **Stub gateway** (`gateway.ts`, single process, the only ledger + client) in front of the ledger stub: `POST /v1/transfers`, + `POST /v1/holds` + `POST /v1/holds/{id}/post|void`, + `GET /v1/balances/{account}` returning a gateway-signed snapshot + (balance + pending + transfer watermark, Ed25519 signature by the + server's token admin key, domain `currency-snapshot/v1`), and + `GET /v1/transfers/{request_id}` for reconciliation lookups. + Verification is server-scoped: a tampered snapshot fails, and a + well-signed snapshot from server A does not verify as server B. +2. **Hosted-edition client** (`relay.ts`, `UserDORelay`): persists + `{request ID, intent hash, state}` in its store **before** the + gateway fetch (proven by a spying gateway that reads the store + mid-fetch), caches the signed snapshot verbatim after verifying + it, and reconciles by request-ID lookup on wake. Its only balance + read is the cached signed snapshot, re-verified on every read — + the hosted tier holds signed snapshots only, never ledger truth. +3. **Client-signed transfer + hold → post cycle through the relay:** + the client signs the intent (domain `currency-intent/v1`); the + gateway holds only the client's public key and rejects a + wrong-key signature with 401. The relay/Worker/DO never holds the + signing key — it forwards the client's signature. +4. **Hibernation idempotency:** the test wraps the gateway so the + first submit lands the transfer but the response is lost; the + intent stays `submitted`. A fresh relay over the same store (the + wake) reconciles by lookup → `completed`. A retry with the same + request ID and identical fields is deduplicated — exactly one + transfer exists. A retry with a mutated amount under the same ID + surfaces the ledger's `exists_with_different_fields` as a hard + error (HTTP 409 at the gateway; `RelayError` at the relay), never + a second transfer. + +Cross-server (Drew's ruling): `executeCrossServerTransfer` records +the transfer on both servers — debit side against server A's +settlement account, credit side against server B's — each entry +signed by its own server's admin key (domain +`currency-double-entry/v1`). Neither side treats the other's ledger +as truth. + +## Simplifications (explicit, per the issue's acceptance) + +- **Ledger:** in-process stub behind the gateway interface (Drew's + ruling explicitly allows this; do not block on TigerBeetle). + Semantics mirror TigerBeetle where the proofs depend on them + (unique transfer ID, `exists_with_different_fields`, two-phase + pending/post/void, per-account watermark). Single currency, + integer minor units, no conversions/corrections, no multi-replica + cluster, no persistence. +- **UserDO:** the relay is a class over a two-method store + interface; `SqlIntentStore` targets a DO's SQLite storage with the + user-do.ts exec shape, tests use an in-memory store where + "hibernation" is a fresh relay instance over the same store. The + relay is not yet routed through `worker.ts`/`user-do.ts`, and + nothing is deployed — consistent with this package's local-only + posture (gate #2285). +- **Keys:** standalone generated Ed25519 keys (WebCrypto) instead of + keys derived from the Iroh root key; the client public-key + registry is a constructor map instead of the #2062 account + factory's output; production auth is out of scope per the issue. +- **Gateway transport:** the gateway is exercised through its + `fetch` handler in-process, not over a real socket; no registry + UI, no central token provider (the longer-term solution per + Drew's ruling). diff --git a/pkgs/id/hosted-worker/README.md b/pkgs/id/hosted-worker/README.md index 7b10389008..16997daf4c 100644 --- a/pkgs/id/hosted-worker/README.md +++ b/pkgs/id/hosted-worker/README.md @@ -51,3 +51,25 @@ blocked pending Drew authorization). internal routing context directly because workerd cannot produce a restricted stub. The harness is never an application entry point. - `npm run typecheck` — `tsc --noEmit`. + +## Currency gateway PoC (#2298) + +`src/currency/` is the gated #2298 proof of concept (gates cleared +2026-11-12/13; Drew ruling `hosted-boundary-2298`), flagged for a +review round — not the permanent currency service: + +- `ledger.ts` — in-process ledger stub behind the gateway interface + (TigerBeetle-shaped semantics: unique request IDs, + `exists_with_different_fields`, two-phase holds, watermarks). +- `gateway.ts` — single-process stub gateway, the only ledger + client: transfers, holds + post/void, gateway-signed balance + snapshots (server-scoped, token admin key), request-ID lookup, + bilateral signed double-entry for cross-server transfers. +- `relay.ts` — the hosted-edition UserDO relay: persists + {request ID, intent hash, state} before the gateway fetch, caches + signed snapshots only, reconciles by request-ID lookup on wake. +- `crypto.ts` — Ed25519 (WebCrypto) + canonical signing payloads. + +Proofs: `test/currency.test.ts` (run by `npm test`). Results + +the explicit simplification list: +`doc/2026-11-14T06-22-00Z_poc_currency_gateway_boundary_results/`. diff --git a/pkgs/id/hosted-worker/package.json b/pkgs/id/hosted-worker/package.json index a6c8a911a2..8aaa9e7a26 100644 --- a/pkgs/id/hosted-worker/package.json +++ b/pkgs/id/hosted-worker/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "wrangler dev", "typecheck": "tsc --noEmit", - "test": "node --test test/routing.test.ts test/blobs.test.ts test/usage.test.ts", + "test": "node --test test/routing.test.ts test/blobs.test.ts test/usage.test.ts test/currency.test.ts", "smoke": "node smoke/smoke.mjs" }, "devDependencies": { diff --git a/pkgs/id/hosted-worker/src/currency/crypto.ts b/pkgs/id/hosted-worker/src/currency/crypto.ts new file mode 100644 index 0000000000..1d578d32b8 --- /dev/null +++ b/pkgs/id/hosted-worker/src/currency/crypto.ts @@ -0,0 +1,93 @@ +// Currency PoC (#2298) — signing + canonicalisation helpers. +// +// Ed25519 throughout, matching the §6 signed-export format in +// pkgs/id/src/hosted_export.rs (signature = the producing key's +// Ed25519 signature over the canonical bytes of the record, +// domain-separated per record type). Implemented on WebCrypto +// (crypto.subtle) so the same code runs in workerd and in Node's +// test runner, with no node:crypto dependency. Public keys cross +// the wire as the raw 32-byte key in hex. +// Simplification (listed in the results doc): the permanent +// service derives these keys from the Iroh root key; the PoC +// generates standalone Ed25519 keys. + +const subtle = globalThis.crypto.subtle; +const encoder = new TextEncoder(); + +// Deterministic JSON: object keys sorted recursively, so a hash or +// signature over a record does not depend on construction order. +export function canonical(value: unknown): string { + if (value === null || typeof value !== "object") return JSON.stringify(value); + if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]"; + const entries = Object.entries(value as Record) + .filter(([, v]) => v !== undefined) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); + return "{" + entries.map(([k, v]) => JSON.stringify(k) + ":" + canonical(v)).join(",") + "}"; +} + +export function bytesToHex(bytes: Uint8Array): string { + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +export function hexToBytes(hex: string): Uint8Array { + const out = new Uint8Array(hex.length / 2); + for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + return out; +} + +export async function sha256Hex(text: string): Promise { + const digest = await subtle.digest("SHA-256", encoder.encode(text)); + return bytesToHex(new Uint8Array(digest)); +} + +// Hash of a record's intent fields — the value the relay persists +// before any gateway fetch and the value the ledger compares on a +// retry to detect a mutated field under a reused request ID. +export async function intentHash(intent: unknown): Promise { + return sha256Hex(canonical(intent)); +} + +export class Ed25519Key { + readonly #privateKey: CryptoKey; + readonly #publicKey: CryptoKey; + readonly publicKeyHex: string; + + private constructor(privateKey: CryptoKey, publicKey: CryptoKey, publicKeyHex: string) { + this.#privateKey = privateKey; + this.#publicKey = publicKey; + this.publicKeyHex = publicKeyHex; + } + + static async generate(): Promise { + const pair = (await subtle.generateKey("Ed25519", true, ["sign", "verify"])) as CryptoKeyPair; + const raw = new Uint8Array(await subtle.exportKey("raw", pair.publicKey)); + return new Ed25519Key(pair.privateKey, pair.publicKey, bytesToHex(raw)); + } + + async signHex(message: string): Promise { + const sig = await subtle.sign("Ed25519", this.#privateKey, encoder.encode(message)); + return bytesToHex(new Uint8Array(sig)); + } + + static async verifyHex(publicKeyHex: string, message: string, signatureHex: string): Promise { + try { + const raw = hexToBytes(publicKeyHex); + const key = await subtle.importKey("raw", raw as BufferSource, "Ed25519", false, ["verify"]); + return await subtle.verify( + "Ed25519", + key, + hexToBytes(signatureHex) as BufferSource, + encoder.encode(message), + ); + } catch { + return false; + } + } +} + +// Domain-separated signing payload: a signature made for one record +// type can never be replayed as another's (same rule as +// hosted_export.rs's manifest domain separator). +export function signingPayload(domain: string, record: unknown): string { + return domain + ":" + canonical(record); +} diff --git a/pkgs/id/hosted-worker/src/currency/gateway.ts b/pkgs/id/hosted-worker/src/currency/gateway.ts new file mode 100644 index 0000000000..a34cae1844 --- /dev/null +++ b/pkgs/id/hosted-worker/src/currency/gateway.ts @@ -0,0 +1,286 @@ +// Currency PoC (#2298) — stub gateway: the only ledger client. +// +// A single-process gateway in front of the ledger stub, shaped by +// the #2062 control-plane design (PR #2315) and Drew's ruling +// hosted-boundary-2298 (2026-11-12): +// +// - server-scoped tokens: snapshots and receipts are signed with +// THIS server's token admin key and carry this server's id; a +// snapshot verifies only against that server's admin key and +// expected server id — it is not ledger truth anywhere else; +// - the hosted tier holds signed snapshots only (see relay.ts); +// - cross-server transfers are bilateral signed double-entry: +// each server records its own side against its settlement +// account and signs its own entry; neither side treats the +// other's record as its own ledger truth. +// +// Endpoints (the issue's step 1, plus the request-ID lookup the +// relay reconciles by on wake): +// POST /v1/transfers client-signed, idempotent by request ID +// POST /v1/holds client-signed two-phase transfer +// POST /v1/holds/{id}/post finalise a hold +// POST /v1/holds/{id}/void release a hold +// GET /v1/balances/{account} gateway-signed snapshot +// GET /v1/transfers/{id} lookup by request ID (reconciliation) +// +// Client signatures: a transfer/hold body carries the client's +// Ed25519 signature over the intent (domain "currency-intent/v1"). +// The gateway holds only the client's PUBLIC key (registered per +// debit account at construction — the account factory's job in the +// real service); the signing key never reaches the gateway, the +// Worker, or the DO. + +import { Ed25519Key, intentHash, signingPayload } from "./crypto.ts"; +import { InProcessLedger, LedgerError, type Ledger, type TransferRecord } from "./ledger.ts"; + +export const INTENT_DOMAIN = "currency-intent/v1"; +export const SNAPSHOT_DOMAIN = "currency-snapshot/v1"; +export const RECEIPT_DOMAIN = "currency-receipt/v1"; +export const ENTRY_DOMAIN = "currency-double-entry/v1"; + +export interface TransferIntent { + request_id: string; + from: string; + to: string; + amount: number; +} + +export interface SignedSnapshot { + server_id: string; + account: string; + balance: number; + pending: number; + watermark: number; + issued_at: string; + signature: string; +} + +export interface GatewayConfig { + serverId: string; + adminKey: Ed25519Key; + ledger?: Ledger; + // debit account -> client public key hex (account-factory output) + clientKeys: Record; + // settlement account used for cross-server entries + settlementAccount?: string; +} + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} + +function snapshotBody(s: Omit): unknown { + return { + server_id: s.server_id, + account: s.account, + balance: s.balance, + pending: s.pending, + watermark: s.watermark, + issued_at: s.issued_at, + }; +} + +// Verify a snapshot exactly as a hosted-tier holder must: signature +// under the EXPECTED server's admin key, and the snapshot's server +// scope equal to the expected server. A snapshot from another +// server — even a well-signed one — is not valid here. +export async function verifySnapshot( + snapshot: SignedSnapshot, + expectedServerId: string, + adminPublicKeyHex: string, +): Promise { + if (snapshot.server_id !== expectedServerId) return false; + return Ed25519Key.verifyHex( + adminPublicKeyHex, + signingPayload(SNAPSHOT_DOMAIN, snapshotBody(snapshot)), + snapshot.signature, + ); +} + +// Client-side helper (runs wherever the client's key lives — never +// in the gateway/Worker/DO): sign a transfer or hold intent. +export async function signIntent(key: Ed25519Key, intent: TransferIntent): Promise { + return key.signHex(signingPayload(INTENT_DOMAIN, intent)); +} + +export class CurrencyGateway { + readonly serverId: string; + readonly adminKey: Ed25519Key; + readonly ledger: Ledger; + readonly #clientKeys: Record; + readonly #settlement: string; + + constructor(config: GatewayConfig) { + this.serverId = config.serverId; + this.adminKey = config.adminKey; + this.ledger = config.ledger ?? new InProcessLedger(); + this.#clientKeys = config.clientKeys; + this.#settlement = config.settlementAccount ?? "settlement"; + } + + adminPublicKeyHex(): string { + return this.adminKey.publicKeyHex; + } + + async snapshotFor(account: string): Promise { + const bal = this.ledger.balance(account); + const body = { + server_id: this.serverId, + account, + balance: bal.balance, + pending: bal.pending, + watermark: bal.watermark, + issued_at: new Date().toISOString(), + }; + return { + ...body, + signature: await this.adminKey.signHex(signingPayload(SNAPSHOT_DOMAIN, snapshotBody(body))), + }; + } + + async #receipt(rec: TransferRecord): Promise { + return this.adminKey.signHex( + signingPayload(RECEIPT_DOMAIN, { + server_id: this.serverId, + request_id: rec.request_id, + intent_hash: rec.intent_hash, + state: rec.state, + seq: rec.seq, + }), + ); + } + + async #transferView(rec: TransferRecord, deduplicated: boolean): Promise { + return { transfer: rec, deduplicated, receipt_signature: await this.#receipt(rec), server_id: this.serverId }; + } + + // Parse + authenticate a client-signed create body. Throws + // LedgerError with an HTTP-ish code carried in `code`. + async #signedCreate(body: unknown): Promise<{ intent: TransferIntent; hash: string }> { + const b = body as Partial & { client_signature?: string }; + if ( + typeof b?.request_id !== "string" || + typeof b?.from !== "string" || + typeof b?.to !== "string" || + typeof b?.amount !== "number" || + typeof b?.client_signature !== "string" + ) { + throw new LedgerError("invalid_request", "body must carry request_id, from, to, amount, client_signature"); + } + const intent: TransferIntent = { request_id: b.request_id, from: b.from, to: b.to, amount: b.amount }; + const pub = this.#clientKeys[intent.from]; + if (!pub || !(await Ed25519Key.verifyHex(pub, signingPayload(INTENT_DOMAIN, intent), b.client_signature))) { + throw new LedgerError("invalid_client_signature", "client signature does not verify for the debit account"); + } + return { intent, hash: await intentHash(intent) }; + } + + async fetch(req: Request): Promise { + try { + const url = new URL(req.url); + const path = url.pathname; + + if (req.method === "POST" && (path === "/v1/transfers" || path === "/v1/holds")) { + const { intent, hash } = await this.#signedCreate(await req.json()); + const input = { + request_id: intent.request_id, + debit_account: intent.from, + credit_account: intent.to, + amount: intent.amount, + intent_hash: hash, + }; + const result = path === "/v1/transfers" ? this.ledger.transfer(input) : this.ledger.hold(input); + return json(await this.#transferView(result.transfer, result.deduplicated), result.deduplicated ? 200 : 201); + } + + const holdAction = path.match(/^\/v1\/holds\/([^/]+)\/(post|void)$/); + if (req.method === "POST" && holdAction) { + const rec = + holdAction[2] === "post" + ? this.ledger.postHold(decodeURIComponent(holdAction[1])) + : this.ledger.voidHold(decodeURIComponent(holdAction[1])); + return json(await this.#transferView(rec, false)); + } + + const balanceMatch = path.match(/^\/v1\/balances\/([^/]+)$/); + if (req.method === "GET" && balanceMatch) { + return json(await this.snapshotFor(decodeURIComponent(balanceMatch[1]))); + } + + const lookupMatch = path.match(/^\/v1\/transfers\/([^/]+)$/); + if (req.method === "GET" && lookupMatch) { + const rec = this.ledger.lookupByRequestId(decodeURIComponent(lookupMatch[1])); + if (!rec) return json({ error: "transfer_not_found" }, 404); + return json(await this.#transferView(rec, false)); + } + + return json({ error: "not_found" }, 404); + } catch (e) { + if (e instanceof LedgerError) { + const status = + e.code === "invalid_client_signature" + ? 401 + : e.code === "exists_with_different_fields" + ? 409 + : e.code.endsWith("_not_found") + ? 404 + : 400; + return json({ error: e.code, message: e.message }, status); + } + throw e; + } + } + + // Bilateral signed double-entry (Drew's ruling): a cross-server + // transfer is recorded on BOTH sides, each side against its own + // settlement account, each entry signed by its own server's admin + // key. Returns both entries with both signatures; each side can + // verify the other's signature without trusting its ledger. + async executeCrossServerTransfer( + peer: CurrencyGateway, + intent: TransferIntent, + clientSignature: string, + ): Promise<{ local: TransferRecord; remote: TransferRecord; local_signature: string; remote_signature: string }> { + // The client signed the cross-server intent as stated (from -> + // final recipient); verify that signature as-is, then record + // this server's side against its settlement account. + const pub = this.#clientKeys[intent.from]; + if (!pub || !(await Ed25519Key.verifyHex(pub, signingPayload(INTENT_DOMAIN, intent), clientSignature))) { + throw new LedgerError("invalid_client_signature", "client signature does not verify for the debit account"); + } + const localIntent: TransferIntent = { ...intent, to: this.#settlement }; + const local = this.ledger.transfer({ + request_id: intent.request_id, + debit_account: intent.from, + credit_account: this.#settlement, + amount: intent.amount, + intent_hash: await intentHash(localIntent), + }).transfer; + + const remoteIntent: TransferIntent = { ...intent, from: peer.#settlement }; + const remote = peer.ledger.transfer({ + request_id: intent.request_id, + debit_account: peer.#settlement, + credit_account: intent.to, + amount: intent.amount, + intent_hash: await intentHash(remoteIntent), + }).transfer; + + const entry = (serverId: string, rec: TransferRecord) => ({ + server_id: serverId, + request_id: rec.request_id, + debit_account: rec.debit_account, + credit_account: rec.credit_account, + amount: rec.amount, + }); + return { + local, + remote, + local_signature: await this.adminKey.signHex(signingPayload(ENTRY_DOMAIN, entry(this.serverId, local))), + remote_signature: await peer.adminKey.signHex(signingPayload(ENTRY_DOMAIN, entry(peer.serverId, remote))), + }; + } +} diff --git a/pkgs/id/hosted-worker/src/currency/ledger.ts b/pkgs/id/hosted-worker/src/currency/ledger.ts new file mode 100644 index 0000000000..2789b8ef52 --- /dev/null +++ b/pkgs/id/hosted-worker/src/currency/ledger.ts @@ -0,0 +1,184 @@ +// Currency PoC (#2298) — ledger behind the gateway interface. +// +// Drew's ruling hosted-boundary-2298 (2026-11-12): do not block on +// TigerBeetle; an in-process ledger stub behind the gateway +// interface is acceptable for the PoC, and the gateway is the only +// ledger client either way. This stub mirrors the TigerBeetle +// semantics the PoC's proofs depend on: +// +// - a transfer ID (here: the client request ID) is unique; +// re-creating it with identical fields returns the existing +// transfer (idempotent retry), re-creating it with ANY field +// mutated fails with `exists_with_different_fields` — a hard +// error, never a second transfer; +// - holds are two-phase transfers: pending reserves funds, +// post finalises, void releases the reservation; +// - every account carries a transfer watermark (the sequence of +// the last transfer touching it), which the gateway signs into +// balance snapshots. +// +// Simplification: amounts are integer minor units in a single +// currency/ledger code; balances are (posted, pending) pairs. + +export class LedgerError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +export type TransferState = "posted" | "pending" | "voided"; + +export interface TransferRecord { + request_id: string; + debit_account: string; + credit_account: string; + amount: number; + state: TransferState; + seq: number; + intent_hash: string; +} + +export interface TransferInput { + request_id: string; + debit_account: string; + credit_account: string; + amount: number; + intent_hash: string; +} + +export interface AccountBalance { + balance: number; + pending: number; + watermark: number; +} + +export interface Ledger { + createAccount(id: string, openingBalance: number): void; + balance(account: string): AccountBalance; + transfer(input: TransferInput): { transfer: TransferRecord; deduplicated: boolean }; + hold(input: TransferInput): { transfer: TransferRecord; deduplicated: boolean }; + postHold(requestId: string): TransferRecord; + voidHold(requestId: string): TransferRecord; + lookupByRequestId(requestId: string): TransferRecord | null; + transferCount(): number; +} + +interface Account { + posted: number; + pending: number; + watermark: number; +} + +export class InProcessLedger implements Ledger { + #accounts = new Map(); + #transfers = new Map(); + #seq = 0; + + createAccount(id: string, openingBalance: number): void { + if (this.#accounts.has(id)) { + throw new LedgerError("account_exists", "account already exists: " + id); + } + this.#accounts.set(id, { posted: openingBalance, pending: 0, watermark: 0 }); + } + + #account(id: string): Account { + const acct = this.#accounts.get(id); + if (!acct) throw new LedgerError("account_not_found", "unknown account: " + id); + return acct; + } + + balance(account: string): AccountBalance { + const acct = this.#account(account); + return { balance: acct.posted, pending: acct.pending, watermark: acct.watermark }; + } + + // The idempotency gate every create passes through: identical + // retry returns the stored record; a mutated field under the same + // request ID is the exists_with_different_* hard error. + #existing(input: TransferInput): TransferRecord | null { + const found = this.#transfers.get(input.request_id); + if (!found) return null; + if (found.intent_hash !== input.intent_hash) { + throw new LedgerError( + "exists_with_different_fields", + "transfer " + input.request_id + " already exists with different fields", + ); + } + return found; + } + + #record(input: TransferInput, state: TransferState): TransferRecord { + const rec: TransferRecord = { ...input, state, seq: ++this.#seq }; + this.#transfers.set(input.request_id, rec); + this.#account(input.debit_account).watermark = rec.seq; + this.#account(input.credit_account).watermark = rec.seq; + return rec; + } + + transfer(input: TransferInput): { transfer: TransferRecord; deduplicated: boolean } { + const existing = this.#existing(input); + if (existing) return { transfer: existing, deduplicated: true }; + const debit = this.#account(input.debit_account); + this.#account(input.credit_account); + if (!Number.isSafeInteger(input.amount) || input.amount <= 0) { + throw new LedgerError("invalid_amount", "amount must be a positive integer"); + } + if (debit.posted - debit.pending < input.amount) { + throw new LedgerError("insufficient_funds", "debit account cannot cover the transfer"); + } + debit.posted -= input.amount; + this.#account(input.credit_account).posted += input.amount; + return { transfer: this.#record(input, "posted"), deduplicated: false }; + } + + hold(input: TransferInput): { transfer: TransferRecord; deduplicated: boolean } { + const existing = this.#existing(input); + if (existing) return { transfer: existing, deduplicated: true }; + const debit = this.#account(input.debit_account); + this.#account(input.credit_account); + if (!Number.isSafeInteger(input.amount) || input.amount <= 0) { + throw new LedgerError("invalid_amount", "amount must be a positive integer"); + } + if (debit.posted - debit.pending < input.amount) { + throw new LedgerError("insufficient_funds", "debit account cannot cover the hold"); + } + debit.pending += input.amount; + return { transfer: this.#record(input, "pending"), deduplicated: false }; + } + + #pending(requestId: string): TransferRecord { + const rec = this.#transfers.get(requestId); + if (!rec) throw new LedgerError("transfer_not_found", "unknown transfer: " + requestId); + if (rec.state !== "pending") { + throw new LedgerError("transfer_not_pending", "transfer " + requestId + " is " + rec.state); + } + return rec; + } + + postHold(requestId: string): TransferRecord { + const rec = this.#pending(requestId); + const debit = this.#account(rec.debit_account); + debit.pending -= rec.amount; + debit.posted -= rec.amount; + this.#account(rec.credit_account).posted += rec.amount; + rec.state = "posted"; + return rec; + } + + voidHold(requestId: string): TransferRecord { + const rec = this.#pending(requestId); + this.#account(rec.debit_account).pending -= rec.amount; + rec.state = "voided"; + return rec; + } + + lookupByRequestId(requestId: string): TransferRecord | null { + return this.#transfers.get(requestId) ?? null; + } + + transferCount(): number { + return this.#transfers.size; + } +} diff --git a/pkgs/id/hosted-worker/src/currency/relay.ts b/pkgs/id/hosted-worker/src/currency/relay.ts new file mode 100644 index 0000000000..1431d0a353 --- /dev/null +++ b/pkgs/id/hosted-worker/src/currency/relay.ts @@ -0,0 +1,280 @@ +// Currency PoC (#2298) — hosted-edition client: the UserDO relay. +// +// One UserDO per user is the hosted tier's only currency actor, and +// per the #2066 boundary (accepted for #2043; Drew ruling +// hosted-boundary-2298) it holds signed snapshots only, never +// ledger truth. Its write path, end to end: +// +// 1. persist {request ID, intent hash, state} in its own storage +// BEFORE the gateway fetch — a hibernation (kill/restart) +// between submit and response can never lose the intent; +// 2. forward the CLIENT-signed intent (the client signs; this +// relay, the Worker, and the DO never hold the signing key); +// 3. on a definite response, mark the intent completed with the +// gateway's signed receipt and cache the gateway-signed +// balance snapshot verbatim; +// 4. on wake with an intent still `submitted` (the response was +// lost), reconcile by request-ID lookup against the gateway +// instead of resubmitting blind: found → completed; absent → +// the submit never landed and a retry is safe. +// +// A retry with the same request ID and identical fields is answered +// by the gateway's idempotency gate (exactly one transfer exists); +// a retry with a mutated field surfaces the ledger's +// exists_with_different_fields as a hard error (RelayError), never +// as a silent second transfer. +// +// Storage is behind a two-method store interface: SqlIntentStore +// runs against a Durable Object's SQLite storage (the same exec +// shape as user-do.ts); MemoryIntentStore backs the tests, where a +// "hibernation" is a fresh relay instance over the same store. + +import { Ed25519Key, intentHash } from "./crypto.ts"; +import { verifySnapshot, type SignedSnapshot, type TransferIntent } from "./gateway.ts"; +import type { TransferRecord } from "./ledger.ts"; + +export interface IntentStore { + get(key: string): Promise; + put(key: string, value: string): Promise; +} + +export class MemoryIntentStore implements IntentStore { + readonly map = new Map(); + async get(key: string): Promise { + return this.map.get(key) ?? null; + } + async put(key: string, value: string): Promise { + this.map.set(key, value); + } +} + +interface SqlStorage { + exec(query: string, ...params: unknown[]): { toArray(): Record[] }; +} + +// DO-backed store: a dedicated intents table with the user-do.ts +// schema-bootstrap posture (created idempotently before serving). +export class SqlIntentStore implements IntentStore { + readonly #sql: SqlStorage; + constructor(sql: SqlStorage) { + this.#sql = sql; + this.#sql.exec("CREATE TABLE IF NOT EXISTS currency_intents (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); + } + async get(key: string): Promise { + const rows = this.#sql + .exec("SELECT value FROM currency_intents WHERE key = ?", key) + .toArray(); + return rows.length === 0 ? null : String(rows[0].value); + } + async put(key: string, value: string): Promise { + this.#sql.exec( + "INSERT INTO currency_intents (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + key, + value, + ); + } +} + +export type IntentState = "submitted" | "completed" | "not_submitted" | "failed"; + +export interface PersistedIntent { + request_id: string; + intent_hash: string; + state: IntentState; + intent: TransferIntent; + client_signature: string; + receipt_signature?: string; + transfer_state?: string; + error?: string; +} + +export class RelayError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +export interface GatewayLike { + fetch(req: Request): Promise; +} + +export interface RelayConfig { + store: IntentStore; + gateway: GatewayLike; + gatewayUrl?: string; + // The gateway server this relay trusts, and its admin public key: + // snapshots are cached only after verification against both. + serverId: string; + adminPublicKeyHex: string; + account: string; +} + +const intentKey = (requestId: string) => "intent:" + requestId; +const SNAPSHOT_KEY = "snapshot:latest"; + +export class UserDORelay { + readonly #store: IntentStore; + readonly #gateway: GatewayLike; + readonly #base: string; + readonly #serverId: string; + readonly #adminPub: string; + readonly account: string; + + constructor(config: RelayConfig) { + this.#store = config.store; + this.#gateway = config.gateway; + this.#base = config.gatewayUrl ?? "https://gateway.invalid"; + this.#serverId = config.serverId; + this.#adminPub = config.adminPublicKeyHex; + this.account = config.account; + } + + async #readIntent(requestId: string): Promise { + const raw = await this.#store.get(intentKey(requestId)); + return raw === null ? null : (JSON.parse(raw) as PersistedIntent); + } + + async #writeIntent(rec: PersistedIntent): Promise { + await this.#store.put(intentKey(rec.request_id), JSON.stringify(rec)); + } + + async intentState(requestId: string): Promise { + return this.#readIntent(requestId); + } + + // Submit (or re-submit) a client-signed transfer. The intent row + // is durable BEFORE the gateway fetch in every path. + async submitTransfer(intent: TransferIntent, clientSignature: string): Promise { + return this.#submit("/v1/transfers", intent, clientSignature); + } + + async submitHold(intent: TransferIntent, clientSignature: string): Promise { + return this.#submit("/v1/holds", intent, clientSignature); + } + + async #submit(path: string, intent: TransferIntent, clientSignature: string): Promise { + const hash = await intentHash(intent); + const existing = await this.#readIntent(intent.request_id); + if (existing) { + if (existing.intent_hash !== hash) { + // Local form of the same hard error: never forward a mutated + // retry under a request ID this DO already used. + throw new RelayError( + "exists_with_different_fields", + "request " + intent.request_id + " was already submitted with different fields", + ); + } + if (existing.state === "completed") return existing; + if (existing.state === "submitted") { + const reconciled = await this.reconcile(intent.request_id); + if (reconciled.state === "completed") return reconciled; + // not_submitted: fall through and resubmit the same intent. + } + } + + const rec: PersistedIntent = { + request_id: intent.request_id, + intent_hash: hash, + state: "submitted", + intent, + client_signature: clientSignature, + }; + await this.#writeIntent(rec); // durable BEFORE the gateway fetch + + let res: Response; + try { + res = await this.#gateway.fetch( + new Request(this.#base + path, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ...intent, client_signature: clientSignature }), + }), + ); + } catch (e) { + // Response lost (hibernation, transport): the intent stays + // `submitted`; reconcile() on wake settles it by lookup. + throw new RelayError("response_lost", "gateway response lost for " + intent.request_id + ": " + String(e)); + } + return this.#settle(rec, res); + } + + async #settle(rec: PersistedIntent, res: Response): Promise { + const body = (await res.json()) as { + transfer?: TransferRecord; + receipt_signature?: string; + error?: string; + message?: string; + }; + if (!res.ok || !body.transfer) { + rec.state = "failed"; + rec.error = body.error ?? "gateway_error"; + await this.#writeIntent(rec); + throw new RelayError(rec.error, body.message ?? "gateway rejected " + rec.request_id); + } + rec.state = "completed"; + rec.receipt_signature = body.receipt_signature; + rec.transfer_state = body.transfer.state; + await this.#writeIntent(rec); + await this.refreshSnapshot(); + return rec; + } + + // Wake-path reconciliation: settle a `submitted` intent by + // request-ID lookup. Never resubmits; the lookup is the proof. + async reconcile(requestId: string): Promise { + const rec = await this.#readIntent(requestId); + if (!rec) throw new RelayError("unknown_request", "no persisted intent for " + requestId); + if (rec.state === "completed") return rec; + const res = await this.#gateway.fetch(new Request(this.#base + "/v1/transfers/" + encodeURIComponent(requestId))); + if (res.status === 404) { + rec.state = "not_submitted"; + await this.#writeIntent(rec); + return rec; + } + return this.#settle(rec, res); + } + + async holdAction(requestId: string, action: "post" | "void"): Promise { + const rec = await this.#readIntent(requestId); + if (!rec) throw new RelayError("unknown_request", "no persisted intent for " + requestId); + const res = await this.#gateway.fetch( + new Request(this.#base + "/v1/holds/" + encodeURIComponent(requestId) + "/" + action, { method: "POST" }), + ); + return this.#settle(rec, res); + } + + // Fetch the gateway-signed snapshot for this relay's account and + // cache it VERBATIM (signature included) — the hosted tier holds + // signed snapshots only. An unverifiable or wrong-server snapshot + // is refused, never cached. + async refreshSnapshot(): Promise { + const res = await this.#gateway.fetch( + new Request(this.#base + "/v1/balances/" + encodeURIComponent(this.account)), + ); + if (!res.ok) throw new RelayError("snapshot_failed", "snapshot fetch failed: " + res.status); + const snapshot = (await res.json()) as SignedSnapshot; + if (!(await verifySnapshot(snapshot, this.#serverId, this.#adminPub))) { + throw new RelayError("snapshot_unverifiable", "gateway snapshot did not verify for " + this.#serverId); + } + await this.#store.put(SNAPSHOT_KEY, JSON.stringify(snapshot)); + return snapshot; + } + + // The only balance read the hosted tier serves: the cached signed + // snapshot, re-verified on every read. + async cachedBalance(): Promise { + const raw = await this.#store.get(SNAPSHOT_KEY); + if (raw === null) throw new RelayError("no_snapshot", "no signed snapshot cached yet"); + const snapshot = JSON.parse(raw) as SignedSnapshot; + if (!(await verifySnapshot(snapshot, this.#serverId, this.#adminPub))) { + throw new RelayError("snapshot_unverifiable", "cached snapshot did not verify for " + this.#serverId); + } + return snapshot; + } +} + +// Re-exported so consumers of the relay never need the gateway's +// key material: verification keys are public by construction. +export { Ed25519Key }; diff --git a/pkgs/id/hosted-worker/test/currency.test.ts b/pkgs/id/hosted-worker/test/currency.test.ts new file mode 100644 index 0000000000..bda1e37f67 --- /dev/null +++ b/pkgs/id/hosted-worker/test/currency.test.ts @@ -0,0 +1,247 @@ +// Currency PoC (#2298) end-to-end proofs. +// +// Oracle for every test: the issue body's four proofs — +// 1. stub gateway endpoints live (transfers, holds + post/void, +// gateway-signed balance snapshots); +// 2. the UserDO relay persists {request ID, intent hash, state} +// before the gateway fetch and caches the signed snapshot; +// 3. one client-signed transfer and one hold → post cycle driven +// through the relay (the relay never holds the signing key — +// it only forwards the client's signature); +// 4. hibernation idempotency: kill/restart between submit and +// response, retry with the same request ID → exactly one +// transfer; a mutated retry under the same ID surfaces +// exists_with_different_fields as a hard error. +// Plus Drew's ruling (hosted-boundary-2298): server-scoped signed +// snapshots, and cross-server transfers as bilateral signed +// double-entry. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { Ed25519Key } from "../src/currency/crypto.ts"; +import { CurrencyGateway, signIntent, verifySnapshot } from "../src/currency/gateway.ts"; +import { InProcessLedger } from "../src/currency/ledger.ts"; +import { MemoryIntentStore, RelayError, UserDORelay } from "../src/currency/relay.ts"; + +const SERVER = "server-a"; +const ALICE = "alice"; +const BOB = "bob"; + +async function setup() { + const clientKey = await Ed25519Key.generate(); + const ledger = new InProcessLedger(); + ledger.createAccount(ALICE, 1000); + ledger.createAccount(BOB, 0); + ledger.createAccount("settlement", 5000); + const gateway = new CurrencyGateway({ + serverId: SERVER, + adminKey: await Ed25519Key.generate(), + ledger, + clientKeys: { [ALICE]: clientKey.publicKeyHex }, + }); + const store = new MemoryIntentStore(); + const relay = new UserDORelay({ + store, + gateway, + serverId: SERVER, + adminPublicKeyHex: gateway.adminPublicKeyHex(), + account: ALICE, + }); + return { clientKey, ledger, gateway, store, relay }; +} + +const post = (path: string, body: unknown) => + new Request("https://gw" + path, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + +test("proof 1: gateway transfer + signed snapshot verifies and is server-scoped", async () => { + const { clientKey, gateway } = await setup(); + const intent = { request_id: "req-1", from: ALICE, to: BOB, amount: 250 }; + const res = await gateway.fetch( + post("/v1/transfers", { ...intent, client_signature: await signIntent(clientKey, intent) }), + ); + assert.equal(res.status, 201); + const body = await res.json(); + assert.equal(body.transfer.state, "posted"); + assert.equal(body.deduplicated, false); + + const snapRes = await gateway.fetch(new Request("https://gw/v1/balances/" + ALICE)); + const snap = await snapRes.json(); + assert.equal(snap.balance, 750); + assert.equal(snap.watermark, body.transfer.seq); + assert.equal(await verifySnapshot(snap, SERVER, gateway.adminPublicKeyHex()), true); + // Tampered balance no longer verifies. + assert.equal(await verifySnapshot({ ...snap, balance: 9999 }, SERVER, gateway.adminPublicKeyHex()), false); + // The same well-signed snapshot is not valid under another server's scope. + assert.equal(await verifySnapshot(snap, "server-b", gateway.adminPublicKeyHex()), false); +}); + +test("proof 1b: gateway rejects an unsigned or wrongly-signed transfer", async () => { + const { gateway } = await setup(); + const intent = { request_id: "req-x", from: ALICE, to: BOB, amount: 10 }; + const wrong = await Ed25519Key.generate(); + const res = await gateway.fetch( + post("/v1/transfers", { ...intent, client_signature: await signIntent(wrong, intent) }), + ); + assert.equal(res.status, 401); + assert.equal((await res.json()).error, "invalid_client_signature"); +}); + +test("proof 3: client-signed transfer and hold -> post cycle through the relay", async () => { + const { clientKey, relay, ledger } = await setup(); + const t = { request_id: "req-t1", from: ALICE, to: BOB, amount: 100 }; + const done = await relay.submitTransfer(t, await signIntent(clientKey, t)); + assert.equal(done.state, "completed"); + assert.equal(done.transfer_state, "posted"); + assert.ok(done.receipt_signature); + + const h = { request_id: "req-h1", from: ALICE, to: BOB, amount: 300 }; + const held = await relay.submitHold(h, await signIntent(clientKey, h)); + assert.equal(held.transfer_state, "pending"); + assert.equal(ledger.balance(ALICE).pending, 300); + assert.equal(ledger.balance(BOB).balance, 100); // hold has not landed yet + + const posted = await relay.holdAction("req-h1", "post"); + assert.equal(posted.transfer_state, "posted"); + assert.equal(ledger.balance(ALICE).pending, 0); + assert.equal(ledger.balance(ALICE).balance, 600); + assert.equal(ledger.balance(BOB).balance, 400); + + // The relay's only balance view is the cached signed snapshot. + const cached = await relay.cachedBalance(); + assert.equal(cached.balance, 600); + assert.equal(cached.server_id, SERVER); +}); + +test("proof 1c: hold -> void releases the reservation", async () => { + const { clientKey, relay, ledger } = await setup(); + const h = { request_id: "req-h2", from: ALICE, to: BOB, amount: 200 }; + await relay.submitHold(h, await signIntent(clientKey, h)); + const voided = await relay.holdAction("req-h2", "void"); + assert.equal(voided.transfer_state, "voided"); + assert.equal(ledger.balance(ALICE).pending, 0); + assert.equal(ledger.balance(ALICE).balance, 1000); + assert.equal(ledger.balance(BOB).balance, 0); +}); + +test("proof 2: the intent is persisted before the gateway fetch", async () => { + const { clientKey, store, gateway } = await setup(); + let seenAtFetch: string | null = null; + const spying = { + async fetch(req: Request): Promise { + if (req.method === "POST") seenAtFetch = await store.get("intent:req-p1"); + return gateway.fetch(req); + }, + }; + const relay = new UserDORelay({ + store, + gateway: spying, + serverId: SERVER, + adminPublicKeyHex: gateway.adminPublicKeyHex(), + account: ALICE, + }); + const t = { request_id: "req-p1", from: ALICE, to: BOB, amount: 40 }; + await relay.submitTransfer(t, await signIntent(clientKey, t)); + assert.ok(seenAtFetch, "intent row must exist before the gateway fetch runs"); + const persisted = JSON.parse(seenAtFetch as string); + assert.equal(persisted.state, "submitted"); + assert.equal(persisted.request_id, "req-p1"); + assert.ok(persisted.intent_hash); +}); + +test("proof 4: hibernation — response lost, wake reconciles, retry stays exactly one transfer", async () => { + const { clientKey, store, gateway, ledger } = await setup(); + // Wrap the gateway so the first POST lands the transfer but the + // response is lost — the DO is killed between submit and response. + let dropNext = true; + const flaky = { + async fetch(req: Request): Promise { + const res = await gateway.fetch(req); + if (dropNext && req.method === "POST") { + dropNext = false; + await res.text(); + throw new Error("simulated hibernation: response lost"); + } + return res; + }, + }; + const mkRelay = () => + new UserDORelay({ + store, + gateway: flaky, + serverId: SERVER, + adminPublicKeyHex: gateway.adminPublicKeyHex(), + account: ALICE, + }); + + const t = { request_id: "req-hib", from: ALICE, to: BOB, amount: 125 }; + const sig = await signIntent(clientKey, t); + await assert.rejects(() => mkRelay().submitTransfer(t, sig), RelayError); + assert.equal((await mkRelay().intentState("req-hib"))?.state, "submitted"); + assert.equal(ledger.transferCount(), 1); // the submit DID land + + // Wake: a fresh relay over the same store reconciles by lookup. + const woken = mkRelay(); + const settled = await woken.reconcile("req-hib"); + assert.equal(settled.state, "completed"); + + // Retry with the same request ID + identical fields: deduplicated, + // and still exactly one transfer exists. + const retry = await woken.submitTransfer(t, sig); + assert.equal(retry.state, "completed"); + assert.equal(ledger.transferCount(), 1); + assert.equal(ledger.balance(BOB).balance, 125); +}); + +test("proof 4b: mutated retry under the same request ID is a hard error", async () => { + const { clientKey, relay, gateway, ledger } = await setup(); + const t = { request_id: "req-mut", from: ALICE, to: BOB, amount: 50 }; + await relay.submitTransfer(t, await signIntent(clientKey, t)); + + // Direct gateway retry with a mutated amount (fresh signature over + // the mutated intent, same request ID) hits the ledger gate. + const mutated = { ...t, amount: 51 }; + const res = await gateway.fetch( + post("/v1/transfers", { ...mutated, client_signature: await signIntent(clientKey, mutated) }), + ); + assert.equal(res.status, 409); + assert.equal((await res.json()).error, "exists_with_different_fields"); + assert.equal(ledger.transferCount(), 1); + + // The relay refuses a mutated retry locally as well. + await assert.rejects( + async () => relay.submitTransfer(mutated, await signIntent(clientKey, mutated)), + (e: unknown) => e instanceof RelayError && e.code === "exists_with_different_fields", + ); +}); + +test("ruling: cross-server transfer is bilateral signed double-entry", async () => { + const clientKey = await Ed25519Key.generate(); + const mkGateway = async (serverId: string) => { + const ledger = new InProcessLedger(); + ledger.createAccount(ALICE, 1000); + ledger.createAccount(BOB, 0); + ledger.createAccount("settlement", 5000); + return new CurrencyGateway({ + serverId, + adminKey: await Ed25519Key.generate(), + ledger, + clientKeys: { [ALICE]: clientKey.publicKeyHex }, + }); + }; + const a = await mkGateway("server-a"); + const b = await mkGateway("server-b"); + const intent = { request_id: "req-xs", from: ALICE, to: BOB, amount: 70 }; + const out = await a.executeCrossServerTransfer(b, intent, await signIntent(clientKey, intent)); + + // Both sides recorded their own side; neither shares a ledger. + assert.equal(a.ledger.balance(ALICE).balance, 930); + assert.equal(a.ledger.balance("settlement").balance, 5070); + assert.equal(b.ledger.balance(BOB).balance, 70); + assert.equal(b.ledger.balance("settlement").balance, 4930); + assert.ok(out.local_signature && out.remote_signature); + assert.notEqual(out.local_signature, out.remote_signature); +});