Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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).
22 changes: 22 additions & 0 deletions pkgs/id/hosted-worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`.
2 changes: 1 addition & 1 deletion pkgs/id/hosted-worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
93 changes: 93 additions & 0 deletions pkgs/id/hosted-worker/src/currency/crypto.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>)
.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<string> {
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<string> {
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<Ed25519Key> {
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<string> {
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<boolean> {
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);
}
Loading