diff --git a/CHANGELOG.md b/CHANGELOG.md index d642011..edbf753 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,28 @@ All notable changes to Wasit are recorded here. Versions follow [Semantic Versio (its authorizations may still be open, so a person reads its ledger and deletes the file), or a file that is not a lock. It does not see another machine. +- `@wasit-dev/core` exports the plan rules of the mainnet opt-in, which this + version does not have; nothing calls them yet. `MAINNET_USDC` is Circle's + USDC on Stellar mainnet (`CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75`, + checked against Circle's issuer, the contract the SDK derives from it, and + the x402 SDK's constant). A mainnet run would pay only that asset, to a + pinned payee other than the payer, at a lifetime of 1 to 300 seconds, with + the token's decimals read as 7; its RPC's latest ledger must be within 12 + ledgers of public Horizon's, and the payer's USDC balance through the RPC + must equal Horizon's (`readHorizonLatestLedger`, `readHorizonAccount`). The + run budget still values no mainnet asset. +- `@wasit-dev/core` has a run ledger (`RunLedger`), taken by the x402 payment + checks as the `ledger` option. Each signature's intent (check, endpoint, + amount, payee, asset) is written and flushed after the run is charged and + before the key is asked to sign; a ledger that cannot take it stops that + payment with nothing signed. Then its outcome: signed with the ledger its + authorization expires at (read from what the key signed), not signed, or + unknown; discarded unsent, or sent with the answer's status; and X402-06's + settlement. The file (`wasit-ledger-.json`) is created new, never + overwritten, and rewritten whole on every change so it stays valid JSON; + closing it records the payer's balances and whether they moved as the + ledger says. No CLI option writes one yet: it is the record a mainnet run + will keep. **Fixed.** - On Stellar testnet the x402 client builds and simulates the payment through diff --git a/packages/core/src/guard/horizon.ts b/packages/core/src/guard/horizon.ts new file mode 100644 index 0000000..27b8f1d --- /dev/null +++ b/packages/core/src/guard/horizon.ts @@ -0,0 +1,113 @@ +/** + * The two reads a mainnet run makes on public Horizon (spec B5 point 4, + * B17.2, B17.12), each a second source beside the run's RPC: + * + * - the latest ledger, which the RPC's latest ledger (the anchor of every + * signature's expiration bound) must be near; + * - the payer's balances, which the RPC's USDC balance must equal, and which + * the run ledger records before and after the run (USDC and XLM). + * + * Both fail closed: an error status, a redirect (never followed), a body that + * is not JSON or is too large, a Horizon of another network, or an answer that + * cannot be read plainly is a {@link MainnetPlanRefusedError}. A message names + * Horizon by its origin only. + * + * Read-only: no key, nothing signed or sent but two GET requests. This version + * has no mainnet opt-in (spec B12), and nothing calls these yet. + */ + +import { Networks, StrKey } from "@stellar/stellar-sdk"; + +import { MAINNET_USDC, MainnetPlanRefusedError, horizonBalances, type HorizonBalances } from "./mainnet-plan.js"; + +const TIMEOUT_MS = 10_000; + +/** A Horizon answer larger than this is not read. The root and one account are a few KiB. */ +const MAX_BODY_BYTES = 1024 * 1024; + +function originOf(base: string): string { + try { + const url = new URL(base); + return url.protocol === "http:" || url.protocol === "https:" ? url.origin : "Horizon"; + } catch { + return "Horizon"; + } +} + +function refuse(base: string, what: string): MainnetPlanRefusedError { + return new MainnetPlanRefusedError("horizon", `${what} could not be read from public Horizon (${originOf(base)}).`); +} + +/** GET `path` on Horizon at `base`, as JSON; throws the refusal on anything but a plain 200 JSON answer. */ +async function getJson(base: string, path: string, what: string): Promise { + let response: Response; + try { + response = await fetch(`${base.replace(/\/+$/, "")}${path}`, { + headers: { accept: "application/json" }, + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + } catch { + throw refuse(base, what); + } + if (response.status !== 200 || response.body === null) { + await response.body?.cancel().catch(() => undefined); + throw refuse(base, what); + } + const chunks: Uint8Array[] = []; + let size = 0; + try { + for await (const chunk of response.body as unknown as AsyncIterable) { + size += chunk.byteLength; + if (size > MAX_BODY_BYTES) { + await response.body.cancel().catch(() => undefined); + throw refuse(base, what); + } + chunks.push(chunk); + } + return JSON.parse(Buffer.concat(chunks).toString("utf-8")) as unknown; + } catch (error) { + if (error instanceof MainnetPlanRefusedError) throw error; + throw refuse(base, what); + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * The latest ledger Horizon at `base` has ingested, from its root, when it + * says it serves Stellar mainnet. + */ +export async function readHorizonLatestLedger(base: string): Promise { + const what = "The latest ledger"; + const root = await getJson(base, "/", what); + if (!isRecord(root) || root["network_passphrase"] !== Networks.PUBLIC) { + throw new MainnetPlanRefusedError( + "horizon", + `Public Horizon (${originOf(base)}) does not say it serves Stellar mainnet, so its latest ledger is not used.`, + ); + } + const ledger = root["history_latest_ledger"]; + if (typeof ledger !== "number" || !Number.isSafeInteger(ledger) || ledger <= 0) throw refuse(base, what); + return ledger; +} + +/** + * The USDC (mainnet USDC's trustline; 0 without one) and XLM balances of the + * account `payer` on Horizon at `base`, in base units. An address that is not + * a Stellar account is refused before any request; so is an account Horizon + * does not have. + */ +export async function readHorizonAccount(base: string, payer: string): Promise { + const what = "The payer's balances"; + if (typeof payer !== "string" || !StrKey.isValidEd25519PublicKey(payer)) { + throw new MainnetPlanRefusedError("horizon", "The payer is not a Stellar account address, so Horizon was not asked for its balances."); + } + const account = await getJson(base, `/accounts/${payer}`, what); + if (!isRecord(account) || account["account_id"] !== payer) throw refuse(base, what); + const balances = horizonBalances(account, MAINNET_USDC); + if (balances === undefined) throw refuse(base, what); + return balances; +} diff --git a/packages/core/src/guard/mainnet-plan.ts b/packages/core/src/guard/mainnet-plan.ts new file mode 100644 index 0000000..5ef8308 --- /dev/null +++ b/packages/core/src/guard/mainnet-plan.ts @@ -0,0 +1,279 @@ +/** + * L1's rules for a mainnet run (spec B3, B4, B5, B17.2), as pure checks. + * + * A mainnet run pays in one asset, Circle's USDC on Stellar mainnet, to the + * one payee its config pins, with a lifetime short enough to wait out, and + * only when the token, the RPC's latest ledger and the payer's balance read + * as expected. Each rule here throws {@link MainnetPlanRefusedError} when it + * does not hold; nothing was signed at that point. + * + * This version has no mainnet opt-in (spec B12): `stellar:pubnet` is refused + * by L0 before any of this is reached, and nothing here says "allowed". The + * opt-in calls these in L1, before anything is signed. The run budget does not + * value {@link MAINNET_USDC} in this version, so no charge on mainnet passes. + * + * Pure: no network, no key. The reads they judge are `horizon.ts` and the + * chain adapter's. + */ + +import { StrKey } from "@stellar/stellar-sdk"; + +import { ConfigurationError } from "../errors.js"; +import { shown, type PinTerms } from "./budget.js"; + +/** The one network these rules are for. */ +const STELLAR_PUBNET = "stellar:pubnet"; + +/** + * Circle's USDC on Stellar mainnet, as a Stellar Asset Contract. Checked three + * ways on 2026-11-21: the issuer as Circle's page lists it + * (https://developers.circle.com/stablecoins/usdc-contract-addresses, + * "USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN"); the + * contract derived from that issuer with the SDK + * (`new Asset("USDC", issuer).contractId(Networks.PUBLIC)`); and + * `USDC_PUBNET_ADDRESS` of `@x402/stellar` 2.28.0. A test asserts all three. + */ +export const MAINNET_USDC = { + network: STELLAR_PUBNET, + asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", + code: "USDC", + issuer: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", + decimals: 7, + symbol: "USDC", +} as const; + +/** The classic asset a Stellar Asset Contract wraps, as Horizon names it. */ +export interface ClassicAsset { + readonly code: string; + readonly issuer: string; +} + +/** The longest lifetime a mainnet payment is signed for, in seconds (B3): the run waits it out. */ +export const MAINNET_MAX_TIMEOUT_SECONDS = 300; + +/** At most this many ledgers between the RPC's latest ledger and public Horizon's (B17.2). */ +export const MAINNET_ANCHOR_MAX_GAP_LEDGERS = 12; + +/** Public Horizon of Stellar mainnet (B5 point 4): the SDK reads the ledger close time there too. */ +export const PUBNET_HORIZON_URL = "https://horizon.stellar.org"; + +/** Which rule stopped the run. */ +export type MainnetPlanRefusal = + /** The config's pin is missing, or its payee is not a valid address other than the payer. */ + | "pin" + /** An asset other than mainnet USDC. */ + | "asset" + /** An option on another scheme or network. */ + | "network" + /** A lifetime above 300 s, or not a positive whole number of seconds. */ + | "lifetime" + /** The token's decimals are not 7. */ + | "decimals" + /** The RPC's latest ledger is too far from Horizon's, or not a ledger number. */ + | "anchor" + /** The RPC's USDC balance of the payer differs from Horizon's, or has no reading. */ + | "balance" + /** Horizon could not be read, or its answer cannot be trusted. */ + | "horizon"; + +/** + * A mainnet run does not start, or stops, because of one of L1's rules. A + * `ConfigurationError`: it says nothing about the target. Nothing was signed. + */ +export class MainnetPlanRefusedError extends ConfigurationError { + public readonly reason: MainnetPlanRefusal; + + public constructor(reason: MainnetPlanRefusal, message: string) { + super(`${message} Nothing was signed.`); + this.name = "MainnetPlanRefusedError"; + this.reason = reason; + } +} + +function isStellarAddress(value: unknown): value is string { + return typeof value === "string" && (StrKey.isValidEd25519PublicKey(value) || StrKey.isValidContract(value)); +} + +/** + * The pin a mainnet environment must have (B5 point 2): a payee that is a + * valid Stellar address and not the payer itself, and mainnet USDC as the + * asset. A transfer to the payer would leave its balance as it was and hide + * what the run paid. + */ +export function assertMainnetPin(pin: PinTerms | undefined, payer: string): void { + if (pin === undefined) { + throw new MainnetPlanRefusedError( + "pin", + "A mainnet environment needs pinned.payTo and pinned.asset in the config: Wasit pays only the payee and the " + + "asset written there.", + ); + } + if (pin.asset !== MAINNET_USDC.asset) { + throw new MainnetPlanRefusedError( + "asset", + `pinned.asset of a mainnet environment must be ${MAINNET_USDC.asset}, Circle's USDC on Stellar mainnet; ` + + `the config has ${isStellarAddress(pin.asset) ? pin.asset : "another value"}.`, + ); + } + if (!isStellarAddress(pin.payTo)) { + throw new MainnetPlanRefusedError("pin", "pinned.payTo of a mainnet environment is not a valid Stellar address."); + } + if (pin.payTo === payer) { + throw new MainnetPlanRefusedError( + "pin", + "pinned.payTo is the payer's own address: on mainnet the payee must be another account, so the payer's " + + "balance shows what the run paid.", + ); + } +} + +/** The fields of a challenge's option these rules judge. */ +export interface MainnetOption { + readonly scheme: string; + readonly network: string; + readonly asset: string; + readonly maxTimeoutSeconds: number; +} + +/** + * The option a mainnet endpoint may be paid by (L1, B3): `exact` on + * `stellar:pubnet`, in mainnet USDC, valid for at most 300 s. The pin (payee + * and asset over every option) is `assertPinned`'s; the price is the budget's. + */ +export function assertMainnetOption(option: MainnetOption): void { + if (option.scheme !== "exact" || option.network !== STELLAR_PUBNET) { + throw new MainnetPlanRefusedError( + "network", + `The option to pay is ${shown(option.scheme)} on ${shown(option.network)}; a mainnet run pays exact on ` + + `${STELLAR_PUBNET} only.`, + ); + } + if (option.asset !== MAINNET_USDC.asset) { + throw new MainnetPlanRefusedError( + "asset", + `The option to pay asks for ${shown(option.asset)}; a mainnet run pays in ${MAINNET_USDC.asset} ` + + `(USDC) only.`, + ); + } + const lifetime: unknown = option.maxTimeoutSeconds; + if ( + typeof lifetime !== "number" || + !Number.isSafeInteger(lifetime) || + lifetime < 1 || + lifetime > MAINNET_MAX_TIMEOUT_SECONDS + ) { + throw new MainnetPlanRefusedError( + "lifetime", + `The option to pay stays valid for ${shown(lifetime)} s; a mainnet payment is signed for a whole number of ` + + `seconds from 1 to ${MAINNET_MAX_TIMEOUT_SECONDS}, so the run can wait until every signature it made has ` + + `expired.`, + ); + } +} + +/** The token's decimals, as read on chain (B4): the caps count USDC at 7. */ +export function assertMainnetDecimals(decimals: unknown): void { + if (decimals !== MAINNET_USDC.decimals) { + throw new MainnetPlanRefusedError( + "decimals", + `The asset contract reports ${shown(decimals)} decimals; mainnet USDC has ${MAINNET_USDC.decimals}, and the ` + + `caps are counted at ${MAINNET_USDC.decimals}.`, + ); + } +} + +function isLedger(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value > 0; +} + +/** + * The RPC's latest ledger must be within {@link MAINNET_ANCHOR_MAX_GAP_LEDGERS} + * of public Horizon's (B17.2): the expiration bound of every signature counts + * from it, so an RPC that reports a later ledger cannot stretch a signature's + * life on mainnet. + */ +export function assertAnchorNearHorizon(rpcLatest: number, horizonLatest: number): void { + if (!isLedger(rpcLatest) || !isLedger(horizonLatest)) { + throw new MainnetPlanRefusedError("anchor", "The latest ledger could not be read as a ledger number from the RPC and Horizon."); + } + const gap = Math.abs(rpcLatest - horizonLatest); + if (gap > MAINNET_ANCHOR_MAX_GAP_LEDGERS) { + throw new MainnetPlanRefusedError( + "anchor", + `The RPC's latest ledger (${rpcLatest}) is ${gap} ledgers from public Horizon's (${horizonLatest}), more than ` + + `the ${MAINNET_ANCHOR_MAX_GAP_LEDGERS} a mainnet run allows: the RPC may not serve the current chain.`, + ); + } +} + +/** Horizon's amounts: whole units, a point, exactly seven decimals. */ +const HORIZON_AMOUNT = /^(0|[1-9][0-9]{0,18})\.([0-9]{7})$/; + +/** An amount as Horizon writes it ("10.0000000"), in base units at 7 decimals; undefined for anything else. */ +export function parseHorizonAmount(text: unknown): bigint | undefined { + if (typeof text !== "string") return undefined; + const match = HORIZON_AMOUNT.exec(text); + if (match === null) return undefined; + return BigInt(match[1]!) * 10_000_000n + BigInt(match[2]!); +} + +/** An account's balances as Horizon lists them, in base units. */ +export interface HorizonBalances { + /** The trustline of the asset; 0 when the account has none. */ + readonly usdc: bigint; + /** Lumens (XLM). */ + readonly native: bigint; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * The USDC and XLM balances of a Horizon account answer, in base units. The + * trustline is matched by type, code and issuer; a token with the same code + * from another issuer is not it. Undefined for an answer that cannot be read + * plainly: no `balances`, no native balance, an amount that does not parse, + * or the same asset listed twice. + */ +export function horizonBalances(account: unknown, asset: ClassicAsset): HorizonBalances | undefined { + if (!isRecord(account) || !Array.isArray(account["balances"])) return undefined; + const type = asset.code.length <= 4 ? "credit_alphanum4" : "credit_alphanum12"; + let usdc: bigint | undefined; + let native: bigint | undefined; + for (const entry of account["balances"] as unknown[]) { + if (!isRecord(entry)) return undefined; + if (entry["asset_type"] === "native") { + if (native !== undefined) return undefined; + native = parseHorizonAmount(entry["balance"]); + if (native === undefined) return undefined; + } else if (entry["asset_type"] === type && entry["asset_code"] === asset.code && entry["asset_issuer"] === asset.issuer) { + if (usdc !== undefined) return undefined; + usdc = parseHorizonAmount(entry["balance"]); + if (usdc === undefined) return undefined; + } + } + if (native === undefined) return undefined; + return { usdc: usdc ?? 0n, native }; +} + +/** + * The payer's USDC balance as the RPC reads it must be what Horizon lists + * (B17.12): the $10 rule reads the RPC's, and an RPC that under-reports it + * would let a fuller account pay. + */ +export function assertBalancesAgree(rpcBalance: bigint | undefined, horizonBalance: bigint | undefined): void { + if (horizonBalance === undefined) { + throw new MainnetPlanRefusedError("horizon", "The payer's USDC balance could not be read from public Horizon."); + } + if (rpcBalance === undefined) { + throw new MainnetPlanRefusedError("balance", "The payer's USDC balance could not be read through the RPC."); + } + if (rpcBalance !== horizonBalance) { + throw new MainnetPlanRefusedError( + "balance", + `The RPC reads the payer's USDC balance as ${rpcBalance} base units and public Horizon as ${horizonBalance}: ` + + `the two must agree before a mainnet run signs anything.`, + ); + } +} diff --git a/packages/core/src/guard/run-ledger.ts b/packages/core/src/guard/run-ledger.ts new file mode 100644 index 0000000..0b320e1 --- /dev/null +++ b/packages/core/src/guard/run-ledger.ts @@ -0,0 +1,489 @@ +/** + * The run ledger (spec B5, safety rule 6): a file a paying run keeps beside + * it, so that a person can compare what Wasit signed with what the chain + * shows, also after a crash (B10 T13). + * + * One file per run, `wasit-ledger-.json`, created new and never + * overwritten. Every change rewrites it whole: to a temporary file, flushed to + * disk, then renamed over the ledger, so the file is valid JSON at every + * moment a process can be killed. + * + * One entry per signature (B-A03). Its intent (check, endpoint, amount, + * payee, asset) is written and flushed after the run is charged and BEFORE + * the key is asked to sign: a ledger that cannot take it stops the payment, + * with nothing signed. Then what became of it: signed, with the ledger its + * authorization expires at (decoded from what the key signed); not signed; + * or unknown (the client failed after it may have signed). Then discarded + * unsent, or sent with the answer's status, and the settlement if any. An + * entry with no outcome reads as "assume signed and sent". + * + * Balances before and after the run (USDC and XLM) and whether they are + * consistent with what the ledger says settled close it. + * + * No secret: the payer is named by its public address, the RPC by its origin, + * and free text is cut, with anything shaped like a Stellar secret or a 64-hex + * value in it masked. Works on every network; on mainnet it is not optional + * (B5). + */ + +import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; + +import { CheckSetupError } from "../errors.js"; +import { sanitizeText } from "../sanitize.js"; +import type { PinTerms } from "./budget.js"; + +/** The `format` field of every run ledger. */ +export const RUN_LEDGER_FORMAT = "wasit-run-ledger"; + +const LEDGER_VERSION = 1; + +/** The longest free text an entry keeps. */ +const MAX_NOTE = 300; + +/** `wasit-ledger-.json`, colons replaced: some file systems refuse them. */ +export function runLedgerFileName(at: Date): string { + return `wasit-ledger-${at.toISOString().replace(/:/g, "-")}.json`; +} + +/** The run ledger cannot be written, or was asked something out of order. A setup error: no verdict. */ +export class RunLedgerError extends CheckSetupError { + public constructor(message: string) { + super(message); + this.name = "RunLedgerError"; + } +} + +/** What a run states about itself when it opens its ledger. */ +export interface RunLedgerHeader { + readonly versions: Readonly>; + readonly environment: string; + readonly network: string; + /** The payer's public address. */ + readonly payer: string; + readonly pin?: PinTerms; + readonly caps: { readonly perPaymentUsd: string; readonly runUsd: string }; + /** The run's plan; bigints are written as strings. */ + readonly plan: unknown; + /** The RPC's origin, never its path or query (they may hold a key). */ + readonly rpc: string; +} + +/** A reading of the payer's balances, in base units. */ +export interface LedgerBalances { + readonly usdc: bigint; + readonly native: bigint; +} + +export type LedgerEntryState = + /** Written before the signature; no outcome yet. Read as signed. */ + | "intent" + | "signed" + /** The key was not asked, or refused: nothing was signed. */ + | "not-signed" + /** The client failed when it may already have signed. Read as signed. */ + | "unknown"; + +/** One signature of the run, as the file holds it. */ +export interface LedgerEntry { + readonly id: number; + readonly endpoint: string; + readonly check: string; + readonly network: string; + readonly asset: string; + readonly payTo: string; + /** Base units. */ + readonly amount: string; + readonly intentAt: string; + readonly state: LedgerEntryState; + readonly signedAt?: string; + /** The ledger (the chain's unit) the authorization expires at; null when it could not be read. */ + readonly expiresAtLedger?: number | null; + /** Why it was not signed, or is unknown. */ + readonly note?: string; + /** Why a signed payment was discarded, unsent. */ + readonly discarded?: string; + readonly sent?: { readonly at: string; readonly status?: number; readonly error?: string }; + readonly settlement?: { readonly reference: string; readonly verified: boolean }; +} + +/** What a payment check records about one signature. */ +export interface LedgerEntryHandle { + /** The key signed; `expiresAtLedger` undefined when it could not be read. */ + signed(expiresAtLedger: number | undefined): void; + notSigned(reason: string): void; + unknown(reason: string): void; + /** A signed payment was discarded, unsent. */ + discarded(reason: string): void; + sent(outcome: { readonly status: number } | { readonly error: string }): void; + settled(reference: string, verified: boolean): void; +} + +/** The ledger as the payment checks of one endpoint see it. */ +export interface PaymentLedger { + /** + * Writes, and flushes, the intent of a signature about to be made. Throws + * when it cannot: the caller then signs nothing. + */ + intent(entry: { + readonly check: string; + readonly network: string; + readonly asset: string; + readonly payTo: string; + readonly amount: string; + }): LedgerEntryHandle; +} + +/** Whether the payer's balances moved as the ledger says they should have. */ +export interface LedgerConsistency { + readonly consistent: boolean; + readonly reasons: readonly string[]; + /** USDC that left the payer, in base units, when both readings exist. */ + readonly spentUsdc?: bigint; + /** USDC of the settlements the run verified on chain, in base units. */ + readonly settledUsdc: bigint; +} + +/** + * Free text for the file: one line, no control characters, nothing shaped like + * a key (the sanitiser masks a Stellar secret's shape; a 64-hex value is masked + * here), at most 300 characters. + */ +function note(text: unknown): string { + return sanitizeText(String(text)) + .replace(/(? (typeof item === "bigint" ? item.toString() : item), 2)}\n`; +} + +function errorCode(error: unknown): string { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return typeof code === "string" && /^[A-Z0-9_]{1,32}$/.test(code) ? ` (${code})` : ""; +} + +type MutableEntry = { -readonly [K in keyof LedgerEntry]: LedgerEntry[K] }; + +interface Readings { + usdc: string; + native: string; + source: string; + at: string; +} + +/** + * The ledger of one paying run. Create it before the first signature; hand + * {@link RunLedger.forEndpoint} to each endpoint's payment checks; close it + * once every authorization has expired and the balances after are read. + */ +export class RunLedger { + public readonly path: string; + readonly #header: RunLedgerHeader; + readonly #now: () => Date; + readonly #openedAt: string; + readonly #entries: MutableEntry[] = []; + #before: Readings | undefined; + #after: Readings | undefined; + #result: { consistent: boolean; reasons: readonly string[] } | undefined; + #closedAt: string | undefined; + + private constructor(path: string, header: RunLedgerHeader, now: () => Date) { + this.path = path; + this.#header = header; + this.#now = now; + this.#openedAt = now().toISOString(); + } + + /** + * Creates the ledger in `dir` (made if missing), named after now, holding the + * header. Refuses a name that exists: a ledger is never overwritten. + */ + public static create(dir: string, header: RunLedgerHeader, options: { readonly now?: () => Date } = {}): RunLedger { + let origin: string | undefined; + try { + origin = new URL(header.rpc).origin; + } catch { + origin = undefined; + } + if (origin !== header.rpc) { + throw new RunLedgerError("The run ledger names the RPC by its origin only, and was given more than an origin. Nothing was signed."); + } + const now = options.now ?? (() => new Date()); + const at = now(); + const path = join(dir, runLedgerFileName(at)); + const ledger = new RunLedger(path, header, () => now()); + let fd: number | undefined; + try { + mkdirSync(dir, { recursive: true }); + fd = openSync(path, "wx", 0o644); + writeSync(fd, json(ledger.#document())); + fsyncSync(fd); + } catch (error) { + throw new RunLedgerError(`The run ledger ${basename(path)} could not be created${errorCode(error)}. Nothing was signed.`); + } finally { + if (fd !== undefined) closeSync(fd); + } + syncDirectory(dir); + return ledger; + } + + /** The entries so far, as the file holds them. */ + public get entries(): readonly LedgerEntry[] { + return this.#entries.map((entry) => structuredClone(entry)); + } + + /** The payment ledger of one endpoint's checks. */ + public forEndpoint(endpoint: string): PaymentLedger { + return { intent: (entry) => this.#intent(endpoint, entry) }; + } + + /** The payer's balances before the first signature, and where they were read. */ + public recordBalancesBefore(balances: LedgerBalances, source: string): void { + this.#assertOpen(); + this.#before = this.#readings(balances, source); + this.#flush(); + } + + /** + * Closes the ledger with the balances after the run (undefined when they + * could not be read): writes whether they are consistent with what the + * ledger says settled, and returns it. + */ + public close(input: { readonly after?: LedgerBalances; readonly source?: string } = {}): LedgerConsistency { + this.#assertOpen(); + if (input.after !== undefined) this.#after = this.#readings(input.after, input.source ?? ""); + const before = this.#before === undefined ? undefined : { usdc: BigInt(this.#before.usdc), native: BigInt(this.#before.native) }; + const result = ledgerConsistency(before, input.after, this.entries); + this.#result = { consistent: result.consistent, reasons: result.reasons }; + this.#closedAt = this.#now().toISOString(); + this.#flush(); + return result; + } + + #readings(balances: LedgerBalances, source: string): Readings { + return { usdc: balances.usdc.toString(), native: balances.native.toString(), source: note(source), at: this.#now().toISOString() }; + } + + #assertOpen(): void { + if (this.#closedAt !== undefined) throw new RunLedgerError("The run ledger is closed and takes nothing more."); + } + + #intent(endpoint: string, input: Parameters[0]): LedgerEntryHandle { + this.#assertOpen(); + if (typeof input.amount !== "string" || !/^[0-9]{1,78}$/.test(input.amount)) { + throw new RunLedgerError("The run ledger takes a whole number of base units only. Nothing was signed."); + } + const entry: MutableEntry = { + id: this.#entries.length + 1, + endpoint: note(endpoint), + check: note(input.check), + network: note(input.network), + asset: note(input.asset), + payTo: note(input.payTo), + amount: input.amount, + intentAt: this.#now().toISOString(), + state: "intent", + }; + this.#entries.push(entry); + try { + this.#flush(); + } catch (error) { + this.#entries.pop(); + throw new RunLedgerError(`${(error as Error).message} Nothing was signed.`); + } + return this.#handle(entry); + } + + #handle(entry: MutableEntry): LedgerEntryHandle { + const outcome = (state: LedgerEntryState, fields: Partial): void => { + if (entry.state !== "intent") { + throw new RunLedgerError(`The run ledger already has an outcome for ${entry.check} (entry ${entry.id}).`); + } + Object.assign(entry, { state, ...fields }); + this.#flush(); + }; + const afterSigning = (what: string): void => { + if (entry.state !== "signed") throw new RunLedgerError(`The run ledger has no signature to record ${what} for (entry ${entry.id}).`); + }; + return { + signed: (expiresAtLedger) => + outcome("signed", { + signedAt: this.#now().toISOString(), + expiresAtLedger: typeof expiresAtLedger === "number" && Number.isSafeInteger(expiresAtLedger) ? expiresAtLedger : null, + }), + notSigned: (reason) => outcome("not-signed", { note: note(reason) }), + unknown: (reason) => outcome("unknown", { note: note(reason) }), + discarded: (reason) => { + afterSigning("a discard"); + if (entry.discarded !== undefined || entry.sent !== undefined) { + throw new RunLedgerError(`The run ledger already has ${entry.check} (entry ${entry.id}) discarded or sent.`); + } + entry.discarded = note(reason); + this.#flush(); + }, + sent: (result) => { + afterSigning("a send"); + if (entry.discarded !== undefined || entry.sent !== undefined) { + throw new RunLedgerError(`The run ledger already has ${entry.check} (entry ${entry.id}) discarded or sent.`); + } + entry.sent = + "status" in result + ? { at: this.#now().toISOString(), status: result.status } + : { at: this.#now().toISOString(), error: note(result.error) }; + this.#flush(); + }, + settled: (reference, verified) => { + if (entry.sent === undefined || entry.settlement !== undefined) { + throw new RunLedgerError(`The run ledger has no send to record a settlement for (entry ${entry.id}), or has one already.`); + } + // A settlement reference is a public transaction hash (64 hex on Stellar): kept as it is, never masked, + // so a person can look it up; still one bounded line. + entry.settlement = { reference: sanitizeText(String(reference)).replace(/\s+/g, "").slice(0, 128), verified: verified === true }; + this.#flush(); + }, + }; + } + + #document(): Record { + const header = this.#header; + return { + format: RUN_LEDGER_FORMAT, + version: LEDGER_VERSION, + openedAt: this.#openedAt, + versions: header.versions, + environment: note(header.environment), + network: note(header.network), + payer: note(header.payer), + ...(header.pin === undefined ? {} : { pin: { payTo: note(header.pin.payTo), asset: note(header.pin.asset) } }), + caps: header.caps, + rpc: header.rpc, + plan: header.plan, + ...(this.#before === undefined ? {} : { balancesBefore: this.#before }), + entries: this.#entries, + ...(this.#after === undefined ? {} : { balancesAfter: this.#after }), + result: this.#result === undefined ? "open" : this.#result.consistent ? "consistent" : "inconsistent", + ...(this.#result === undefined ? {} : { reasons: this.#result.reasons }), + ...(this.#closedAt === undefined ? {} : { closedAt: this.#closedAt }), + }; + } + + /** The whole file, rewritten: temporary file, flushed, renamed over the ledger. */ + #flush(): void { + const tmp = `${this.path}.tmp`; + let fd: number | undefined; + try { + rmSync(tmp, { force: true }); + fd = openSync(tmp, "wx", 0o644); + writeSync(fd, json(this.#document())); + fsyncSync(fd); + closeSync(fd); + fd = undefined; + renameSync(tmp, this.path); + } catch (error) { + if (fd !== undefined) { + try { + closeSync(fd); + } catch { + // closed either way + } + } + try { + rmSync(tmp, { force: true }); + } catch { + // nothing more to clean + } + throw new RunLedgerError(`The run ledger ${basename(this.path)} could not be written${errorCode(error)}.`); + } + syncDirectory(dirname(this.path)); + } +} + +/** Flushes a folder's entry list, where the platform allows it (not on Windows). */ +function syncDirectory(dir: string): void { + let fd: number | undefined; + try { + fd = openSync(dir, "r"); + fsyncSync(fd); + } catch { + // Best effort: the file itself was flushed. + } finally { + if (fd !== undefined) { + try { + closeSync(fd); + } catch { + // closed either way + } + } + } +} + +/** An entry that holds a signature, or may: everything but "not-signed". */ +function maySign(entry: LedgerEntry): boolean { + return entry.state !== "not-signed"; +} + +/** + * Whether the payer's balances moved as the ledger says: its USDC went down by + * exactly the amounts of the settlements the run verified on chain, and its + * XLM did not move (on Stellar the facilitator pays the fees; Wasit sends no + * transaction from the payer). The reasons also name every entry with no + * recorded outcome, which is read as signed and sent. + */ +export function ledgerConsistency( + before: LedgerBalances | undefined, + after: LedgerBalances | undefined, + entries: readonly LedgerEntry[], +): LedgerConsistency { + const reasons: string[] = []; + for (const entry of entries) { + if (entry.state === "intent" || entry.state === "unknown") { + reasons.push(`${entry.check} of ${entry.endpoint} (entry ${entry.id}) has no recorded signature outcome: assume it was signed and sent.`); + } else if (entry.state === "signed" && entry.sent === undefined && entry.discarded === undefined) { + reasons.push(`${entry.check} of ${entry.endpoint} (entry ${entry.id}) was signed and has no recorded send: assume it was sent.`); + } + } + const settledUsdc = entries + .filter((entry) => entry.settlement?.verified === true) + .reduce((sum, entry) => sum + BigInt(entry.amount), 0n); + if (before === undefined || after === undefined) { + return { + consistent: false, + reasons: ["The payer's balances before and after the run were not both read.", ...reasons], + settledUsdc, + }; + } + const spentUsdc = before.usdc - after.usdc; + let consistent = true; + if (spentUsdc !== settledUsdc) { + consistent = false; + reasons.unshift( + `The payer's USDC went down by ${spentUsdc} base units, and the settlements this run verified add up to ${settledUsdc}.`, + ); + } + if (before.native !== after.native) { + consistent = false; + reasons.unshift( + `The payer's XLM changed by ${after.native - before.native} stroops; Wasit sends no transaction from the payer.`, + ); + } + return { consistent, reasons, spentUsdc, settledUsdc }; +} + +/** + * Until when the run's authorizations may be open (L4): the latest expiry of + * every entry that holds a signature or may, and how many of those have no + * known expiry (the caller then waits the longest a signature may live). + */ +export function openAuthorizationsUntil(entries: readonly LedgerEntry[]): { latest: number | undefined; unknown: number } { + let latest: number | undefined; + let unknown = 0; + for (const entry of entries) { + if (!maySign(entry)) continue; + if (typeof entry.expiresAtLedger === "number") latest = latest === undefined ? entry.expiresAtLedger : Math.max(latest, entry.expiresAtLedger); + else unknown += 1; + } + return { latest, unknown }; +} diff --git a/packages/core/src/guard/signed-terms.ts b/packages/core/src/guard/signed-terms.ts index bc05187..06b0955 100644 --- a/packages/core/src/guard/signed-terms.ts +++ b/packages/core/src/guard/signed-terms.ts @@ -100,6 +100,21 @@ export class SigningGate { } } +/** + * The ledger a signature the gate let through expires at, decoded from the + * preimage the key signed (spec B5: the expiry is read, never computed); + * undefined when it does not decode as the address credential's preimage. + */ +export function expirationOfSigned(record: SignedRecord): number | undefined { + try { + const decoded = xdr.HashIdPreimage.fromXDR(record.preimage, "base64"); + if (decoded.switch().name !== "envelopeTypeSorobanAuthorization") return undefined; + return decoded.sorobanAuthorization().signatureExpirationLedger(); + } catch { + return undefined; + } +} + /** * The run's first reading of the chain's latest unit (a ledger on Stellar), * and when it was read on a monotonic clock. A signature made later may stay diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index ed930b1..78f1934 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -168,6 +168,42 @@ export { type LockHolder, type MainnetRunLock, } from "./guard/run-lock.js"; +// L1's mainnet rules and the two reads on public Horizon (spec B3, B4, B17.2): rules that only refuse; nothing calls them yet. +export { + MAINNET_ANCHOR_MAX_GAP_LEDGERS, + MAINNET_MAX_TIMEOUT_SECONDS, + MAINNET_USDC, + MainnetPlanRefusedError, + PUBNET_HORIZON_URL, + assertAnchorNearHorizon, + assertBalancesAgree, + assertMainnetDecimals, + assertMainnetOption, + assertMainnetPin, + horizonBalances, + parseHorizonAmount, + type ClassicAsset, + type HorizonBalances, + type MainnetOption, + type MainnetPlanRefusal, +} from "./guard/mainnet-plan.js"; +export { readHorizonAccount, readHorizonLatestLedger } from "./guard/horizon.js"; +// The run ledger (spec B5): every signature's intent written before the key signs, then its outcome. +export { + RUN_LEDGER_FORMAT, + RunLedger, + RunLedgerError, + ledgerConsistency, + openAuthorizationsUntil, + runLedgerFileName, + type LedgerBalances, + type LedgerConsistency, + type LedgerEntry, + type LedgerEntryHandle, + type LedgerEntryState, + type PaymentLedger, + type RunLedgerHeader, +} from "./guard/run-ledger.js"; // Which RPC a result read the chain through, and the MCP server's start-up RPC lock (D-023c). export { RPC_LOCK_VARIABLE, describeRpcInUse, readRpcLock, rpcInUse } from "./guard/rpc-in-use.js"; diff --git a/packages/core/src/x402/simulator.ts b/packages/core/src/x402/simulator.ts index 3893e11..5e48838 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -16,7 +16,8 @@ import { type PinTerms, } from "../guard/budget.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; -import { SigningAnchor, SigningGate, type SigningTerms } from "../guard/signed-terms.js"; +import { SigningAnchor, SigningGate, expirationOfSigned, type SigningTerms } from "../guard/signed-terms.js"; +import type { LedgerEntryHandle, PaymentLedger } from "../guard/run-ledger.js"; import { RpcIdentityError, assertRpcServesNetwork } from "../guard/rpc-identity.js"; import type { EndpointPlan } from "./plan.js"; import { @@ -436,6 +437,13 @@ export interface X402PaymentCheckOptions extends RequestShape { readonly plan?: EndpointPlan; /** The request the service must refuse (`endpoints[].reject`), for X402-11. Absent: X402-11 is skipped. */ readonly reject?: RejectCase; + /** + * The run ledger of this endpoint (spec B5): each signature's intent is + * written before the key is asked to sign, then what became of it. A ledger + * that cannot take an intent stops that payment, with nothing signed. + * Required on mainnet; optional on a test network. + */ + readonly ledger?: PaymentLedger; /** * Called with one line when a check starts a long wait on the chain (X402-11 * waits up to six minutes), so a log does not look stuck. The line holds no @@ -822,32 +830,115 @@ async function preparePayment( amount: signing.amount, ...(planned === undefined ? {} : { planned }), }); + // The run ledger (spec B5): the intent is on disk before the key can be asked + // to sign. A ledger that cannot take it throws here, and nothing is signed. + const entry = options.ledger?.intent({ + check, + network: options.network, + asset: signing.asset, + payTo: signing.payTo, + amount: signing.amount, + }); - await beforeSigning?.(selected); - // The signed-terms gate (spec B17.2): the key signs only what was checked and - // charged above, once, within this payment's lifetime. - if (chain.signedTerms !== undefined) { - gate.arm( - await signingTerms(chain.signedTerms, options.network, rpcUrl, anchorOf(budget), chain.payerAddress(options.payerSecretKey), signing), + let asked = false; + let signed; + try { + await beforeSigning?.(selected); + // The signed-terms gate (spec B17.2): the key signs only what was checked and + // charged above, once, within this payment's lifetime. + if (chain.signedTerms !== undefined) { + gate.arm( + await signingTerms(chain.signedTerms, options.network, rpcUrl, anchorOf(budget), chain.payerAddress(options.payerSecretKey), signing), + ); + } + asked = true; + signed = await withinSpendControls(options.network, selected, () => + client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }), ); + } catch (error) { + recordUnsigned(entry, chain, gate, asked, error); + throw error; } - const signed = await withinSpendControls(options.network, selected, () => - client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }), - ); - // What the SDK says it signed must be the option checked, field by field; - // otherwise the payload is discarded here, unsent. It stays charged. - if (canonical(signed.accepted) !== canonical(signing)) { - throw new PaymentGuardRefusedError( - "accepted", - `The payment the x402 client built for ${check} names other terms in its accepted field than the ` + - `option Wasit checked.`, - { signed: true }, - ); + // Recorded before the payload can be used: a signature the ledger cannot + // take is never sent. + entry?.signed(gate.signed === undefined ? undefined : expirationOfSigned(gate.signed)); + try { + // What the SDK says it signed must be the option checked, field by field; + // otherwise the payload is discarded here, unsent. It stays charged. + if (canonical(signed.accepted) !== canonical(signing)) { + throw new PaymentGuardRefusedError( + "accepted", + `The payment the x402 client built for ${check} names other terms in its accepted field than the ` + + `option Wasit checked.`, + { signed: true }, + ); + } + // And what it carries must be the one authorization the gate let the key sign. + chain.signedTerms?.bind(signed.payload, gate); + } catch (error) { + recordDiscarded(entry, error); + throw error; } - // And what it carries must be the one authorization the gate let the key sign. - chain.signedTerms?.bind(signed.payload, gate); const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected }; - return { httpClient, paymentPayload, selected, idempotent, payUrl }; + return { httpClient, paymentPayload, selected, idempotent, payUrl, entry }; +} + +function reasonOf(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * What became of a payment that failed before its payload was built. With + * the gate armed, only a signature the gate recorded was made: the gate is the + * only way to the key. Without a gate (EVM and Solana, test networks only), + * a client that failed once it was asked may have signed. A ledger that cannot + * take the outcome leaves the intent, which reads as signed. + */ +function recordUnsigned( + entry: LedgerEntryHandle | undefined, + chain: PaymentChain, + gate: SigningGate, + asked: boolean, + error: unknown, +): void { + if (entry === undefined) return; + try { + if (gate.signed !== undefined) entry.signed(expirationOfSigned(gate.signed)); + else if (!asked || chain.signedTerms !== undefined) entry.notSigned(reasonOf(error)); + else entry.unknown(reasonOf(error)); + } catch { + // The payment's own error is what the check reports; the intent stays. + } +} + +/** A signed payload discarded unsent. A ledger that cannot take it leaves "signed", which reads as sent. */ +function recordDiscarded(entry: LedgerEntryHandle | undefined, error: unknown): void { + try { + entry?.discarded(reasonOf(error)); + } catch { + // The payment's own error is what the check reports. + } +} + +/** + * Sends a signed payment and records it in the run ledger: the answer's + * status, or that no answer came (the payment may still have reached the + * service). The ledger's own text, never the service's. + */ +async function sendPayment(entry: LedgerEntryHandle | undefined, url: string, init: RequestInit): Promise { + let response: Response; + try { + response = await fetchTarget(url, init); + } catch (error) { + try { + entry?.sent({ error: "no answer: the payment may have reached the service" }); + } catch { + // The send's own error is what the check reports. + } + throw error; + } + entry?.sent({ status: response.status }); + return response; } /** @@ -974,11 +1065,11 @@ async function checkSignatureAccepted(options: X402PaymentCheckOptions): Promise const name = "Signature Resubmit Accepted"; const fail = (detail: string, hint: string): CheckResult => ({ id, name, pass: false, detail, hint }); - const { httpClient, paymentPayload, idempotent, payUrl } = await preparePayment(options, "X402-06", undefined, (selected) => + const { httpClient, paymentPayload, idempotent, payUrl, entry } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected), ); const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload); - const paid = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders)); + const paid = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders)); const honest = (result: CheckResult, accepted: boolean): HonestPayment => ({ result, accepted, @@ -1040,6 +1131,7 @@ async function checkSignatureAccepted(options: X402PaymentCheckOptions): Promise recipient: accepted.payTo, payer: chain.payerAddress(options.payerSecretKey), }); + entry?.settled(reference, verdict.pass); return honest( verdict.pass @@ -1077,7 +1169,7 @@ async function checkSignatureAccepted(options: X402PaymentCheckOptions): Promise async function checkInvalidSignatureRejected( options: X402PaymentCheckOptions, ): Promise { - const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-07"); + const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-07"); const corrupted = { ...paymentPayload, @@ -1085,7 +1177,7 @@ async function checkInvalidSignatureRejected( }; const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted); - const response = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders)); + const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders)); return signatureRejectionVerdict(response.status, await refusalReason(response)); } @@ -1269,8 +1361,9 @@ async function checkUnderpaymentRejected(options: X402PaymentCheckOptions): Prom } throw error; } - const { httpClient, paymentPayload, payUrl } = prepared; - const response = await fetchTarget( + const { httpClient, paymentPayload, payUrl, entry } = prepared; + const response = await sendPayment( + entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)), ); @@ -1321,13 +1414,14 @@ async function checkExpiredRejected(options: X402PaymentCheckOptions): Promise { + const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-10", async (selected) => { const expired = await chain.expiredSigning(selected, rpcUrl); holdMs = expired.holdMs; return expired.terms; }); await new Promise((done) => setTimeout(done, holdMs)); - const response = await fetchTarget( + const response = await sendPayment( + entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)), ); @@ -1522,28 +1616,33 @@ async function checkRejectedRequestNotSettled( if (error instanceof RejectLifetimeOutside) return outside(error.lifetime, true); throw error; } - const { httpClient, paymentPayload, selected, payUrl } = prepared; + const { httpClient, paymentPayload, selected, payUrl, entry } = prepared; + // A signed payment this check does not send: recorded as discarded, then the check stops. + const discard = (message: string): never => { + recordDiscarded(entry, new Error(message)); + throw new CheckSetupError(message); + }; const amount = BigInt(selected.amount); const ours = authorizationOf(chain, paymentPayload.payload, payer, "this payment"); if (ours.nonce === control.nonce) { - throw new CheckSetupError("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent."); + discard("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent."); } // Right before sending: ours unused, the control found. This read's ledger // starts the range the transfers are read over. const before = await watch.read(network, rpcUrl, [ours, control]); if (before.used[1] === undefined) { - throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, so this payment was not sent."); + discard("The chain's answer leaves out X402-06's authorization, so this payment was not sent."); } if (before.used[0] !== undefined) { - throw new CheckSetupError("The chain records this payment's authorization as used before it was sent, so it was not sent."); + discard("The chain records this payment's authorization as used before it was sent, so it was not sent."); } // What the client signed, not what it was asked: an authorization that stays // valid longer than the 300 s this check waits is not sent (2 units of slack // for the ledgers that close while it is built). const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / watch.unitSeconds) + 2; if (ours.expiresAt - before.latest > longest) { - throw new CheckSetupError( + discard( `This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` + `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}), longer than the ` + `${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds this check waits. It was signed and discarded; it was not sent.`, @@ -1551,7 +1650,7 @@ async function checkRejectedRequestNotSettled( } // And long enough that a service which settles it could still get it on chain. if (ours.expiresAt - before.latest < REJECTED_REQUEST_MIN_UNITS_LEFT) { - throw new CheckSetupError( + discard( `This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` + `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}): too soon for an unused ` + `authorization to show anything. It was signed and discarded; it was not sent.`, @@ -1559,7 +1658,7 @@ async function checkRejectedRequestNotSettled( } const sentAt = Date.now(); - const response = await fetchTarget(payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload))); + const response = await sendPayment(entry, payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload))); const status = response.status; const reason = await refusalReason(response); options.onProgress?.( diff --git a/packages/core/test/unit/horizon.test.ts b/packages/core/test/unit/horizon.test.ts new file mode 100644 index 0000000..b1b2871 --- /dev/null +++ b/packages/core/test/unit/horizon.test.ts @@ -0,0 +1,148 @@ +/** + * The two reads a mainnet run makes on public Horizon (spec B5 point 4, + * B17.2, B17.12), written before the code (B11): the latest ledger, which the + * RPC's anchor is held to, and the payer's balances, which the RPC's USDC + * balance is held to. Both fail closed: anything but a plain, readable answer + * from Stellar mainnet's Horizon is a refusal, and a redirect is not followed. + * Offline: a loopback stand-in answers. + */ + +import assert from "node:assert/strict"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import { after, before, describe, it } from "node:test"; + +import { Keypair, Networks } from "@stellar/stellar-sdk"; + +import { ConfigurationError } from "../../src/errors.js"; +import { readHorizonAccount, readHorizonLatestLedger } from "../../src/guard/horizon.js"; +import { MAINNET_USDC, MainnetPlanRefusedError } from "../../src/guard/mainnet-plan.js"; + +const PAYER = Keypair.random().publicKey(); + +interface Answer { + readonly status?: number; + readonly body?: string; + readonly headers?: Record; +} + +const seen: string[] = []; +let answer: (path: string) => Answer = () => ({ status: 500 }); +let base = ""; + +const server = http.createServer((request, response) => { + seen.push(request.url ?? ""); + const { status = 200, body = "", headers = {} } = answer(request.url ?? ""); + response.writeHead(status, { "content-type": "application/json", ...headers }); + response.end(body); +}); + +before(async () => { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); +after(async () => { + await new Promise((resolve) => server.close(() => resolve())); +}); + +function root(fields: Record): Answer { + return { body: JSON.stringify({ history_latest_ledger: 65_594_567, network_passphrase: Networks.PUBLIC, ...fields }) }; +} + +async function refused(promise: Promise): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof MainnetPlanRefusedError, `not a MainnetPlanRefusedError: ${String(error)}`); + assert.ok(error instanceof ConfigurationError); + assert.equal(error.reason, "horizon", error.message); + assert.match(error.message, /Nothing was signed\.$/); + return error; + } + assert.fail("Horizon's answer was not refused"); +} + +describe("Horizon's latest ledger", () => { + it("is read from the root of a Horizon that serves Stellar mainnet", async () => { + seen.length = 0; + answer = () => root({}); + assert.equal(await readHorizonLatestLedger(base), 65_594_567); + assert.deepEqual(seen, ["/"]); + }); + + it("is refused from a Horizon of another network", async () => { + answer = () => root({ network_passphrase: Networks.TESTNET }); + await refused(readHorizonLatestLedger(base)); + answer = () => root({ network_passphrase: undefined }); + await refused(readHorizonLatestLedger(base)); + }); + + it("is refused when it is not a positive whole number", async () => { + for (const history_latest_ledger of [0, -1, 1.5, "65594567", null, undefined]) { + answer = () => root({ history_latest_ledger }); + await refused(readHorizonLatestLedger(base)); + } + }); + + it("is refused on an error status, a redirect (not followed), a body that is not JSON, or one that is too large", async () => { + for (const bad of [ + { status: 500, body: "{}" }, + { status: 404, body: "{}" }, + { status: 301, body: "", headers: { location: `${base}/elsewhere` } }, + { status: 200, body: "not json" }, + { status: 200, body: JSON.stringify({ pad: "x".repeat(2 * 1024 * 1024), history_latest_ledger: 1, network_passphrase: Networks.PUBLIC }) }, + ] satisfies Answer[]) { + seen.length = 0; + answer = () => bad; + await refused(readHorizonLatestLedger(base)); + assert.ok(!seen.includes("/elsewhere"), "a redirect is never followed"); + } + }); + + it("is refused on any status but 200, even with a body that would read", async () => { + for (const status of [201, 203, 206, 404, 410, 429]) { + answer = () => ({ ...root({}), status }); + await refused(readHorizonLatestLedger(base)); + } + }); + + it("is refused when Horizon cannot be reached, and the message does not quote the URL's path", async () => { + const error = await refused(readHorizonLatestLedger("http://127.0.0.1:1/secret-path")); + assert.doesNotMatch(error.message, /secret-path/); + }); +}); + +describe("the payer's balances on Horizon", () => { + const account = (balances: unknown[]): Answer => ({ body: JSON.stringify({ account_id: PAYER, balances }) }); + + it("are read from /accounts/, USDC and XLM in base units", async () => { + seen.length = 0; + answer = () => + account([ + { balance: "9.5000000", asset_type: "credit_alphanum4", asset_code: "USDC", asset_issuer: MAINNET_USDC.issuer }, + { balance: "3.0000000", asset_type: "native" }, + ]); + assert.deepEqual(await readHorizonAccount(base, PAYER), { usdc: 95_000_000n, native: 30_000_000n }); + assert.deepEqual(seen, [`/accounts/${PAYER}`]); + }); + + it("are not asked for an address that is not a Stellar account", async () => { + seen.length = 0; + for (const payer of ["", "../ledgers", `${PAYER}?x=1`, PAYER.toLowerCase(), MAINNET_USDC.asset]) { + await refused(readHorizonAccount(base, payer)); + } + assert.deepEqual(seen, []); + }); + + it("are refused for an account Horizon does not have, or an answer that cannot be read", async () => { + for (const bad of [ + { status: 404, body: JSON.stringify({ status: 404 }) }, + account([]), + account([{ balance: "x", asset_type: "native" }]), + { status: 200, body: JSON.stringify({ account_id: Keypair.random().publicKey(), balances: [{ balance: "1.0000000", asset_type: "native" }] }) }, + ] satisfies Answer[]) { + answer = () => bad; + await refused(readHorizonAccount(base, PAYER)); + } + }); +}); diff --git a/packages/core/test/unit/mainnet-plan.test.ts b/packages/core/test/unit/mainnet-plan.test.ts new file mode 100644 index 0000000..e4aa21d --- /dev/null +++ b/packages/core/test/unit/mainnet-plan.test.ts @@ -0,0 +1,234 @@ +/** + * L1's rules for a mainnet run (spec B3, B4, B5, B17.2), written before the + * code (B11): the mainnet USDC constant, the pin a mainnet environment must + * have, the option a mainnet endpoint may be paid by, the token's decimals, + * and the two cross-checks against public Horizon (the anchor ledger and the + * payer's USDC balance). Pure: nothing here reads a network. + * + * This version has no mainnet opt-in (B12): these rules refuse, and nothing + * calls them yet. The budget still cannot value mainnet USDC, so no charge on + * stellar:pubnet can pass on this branch. + */ + +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { describe, it } from "node:test"; + +import { Asset, Keypair, Networks, StrKey } from "@stellar/stellar-sdk"; +import { USDC_PUBNET_ADDRESS, USDC_TESTNET_ADDRESS } from "@x402/stellar"; + +import { ConfigurationError } from "../../src/errors.js"; +import { usdAsset } from "../../src/guard/budget.js"; +import { + MAINNET_ANCHOR_MAX_GAP_LEDGERS, + MAINNET_MAX_TIMEOUT_SECONDS, + MAINNET_USDC, + MainnetPlanRefusedError, + PUBNET_HORIZON_URL, + assertAnchorNearHorizon, + assertBalancesAgree, + assertMainnetDecimals, + assertMainnetOption, + assertMainnetPin, + horizonBalances, + parseHorizonAmount, + type MainnetPlanRefusal, +} from "../../src/guard/mainnet-plan.js"; + +const PUBNET = "stellar:pubnet"; +/** Circle's USDC issuer on Stellar mainnet, as its page lists it (read 2026-11-21). */ +const CIRCLE_ISSUER = "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN"; +const PAYER = Keypair.random().publicKey(); +const PAY_TO = Keypair.random().publicKey(); + +function refused(run: () => unknown, reason: MainnetPlanRefusal): MainnetPlanRefusedError { + try { + run(); + } catch (error) { + assert.ok(error instanceof MainnetPlanRefusedError, `not a MainnetPlanRefusedError: ${String(error)}`); + assert.ok(error instanceof ConfigurationError, "a plan refusal is a ConfigurationError: it says nothing about the target"); + assert.equal(error.reason, reason, error.message); + assert.match(error.message, /Nothing was signed\.$/); + return error; + } + assert.fail(`not refused (expected ${reason})`); +} + +describe("the mainnet USDC constant (B4), checked three ways", () => { + it("is the Stellar Asset Contract of Circle's USDC on mainnet, as derived and as the x402 SDK has it", () => { + assert.equal(MAINNET_USDC.network, PUBNET); + assert.equal(MAINNET_USDC.code, "USDC"); + assert.equal(MAINNET_USDC.issuer, CIRCLE_ISSUER); + assert.equal(MAINNET_USDC.decimals, 7); + assert.equal(MAINNET_USDC.symbol, "USDC"); + assert.equal(MAINNET_USDC.asset, new Asset("USDC", CIRCLE_ISSUER).contractId(Networks.PUBLIC)); + assert.equal(MAINNET_USDC.asset, USDC_PUBNET_ADDRESS); + assert.ok(StrKey.isValidContract(MAINNET_USDC.asset)); + }); + + it("is not the testnet USDC", () => { + assert.notEqual(MAINNET_USDC.asset, USDC_TESTNET_ADDRESS); + }); + + it("is not valued by the run budget in this version (B12): no charge on stellar:pubnet can pass", () => { + assert.equal(usdAsset(PUBNET, MAINNET_USDC.asset), undefined); + }); + + it("goes with fixed limits: 300 s of lifetime, 12 ledgers between the RPC and Horizon, Horizon at its public address", () => { + assert.equal(MAINNET_MAX_TIMEOUT_SECONDS, 300); + assert.equal(MAINNET_ANCHOR_MAX_GAP_LEDGERS, 12); + assert.equal(PUBNET_HORIZON_URL, "https://horizon.stellar.org"); + }); +}); + +describe("the pin of a mainnet environment (B5 point 2)", () => { + it("passes a G or C payee other than the payer, in mainnet USDC", () => { + assertMainnetPin({ payTo: PAY_TO, asset: MAINNET_USDC.asset }, PAYER); + assertMainnetPin({ payTo: StrKey.encodeContract(randomBytes(32)), asset: MAINNET_USDC.asset }, PAYER); + }); + + it("is required", () => { + refused(() => assertMainnetPin(undefined, PAYER), "pin"); + }); + + it("must name mainnet USDC as the asset", () => { + refused(() => assertMainnetPin({ payTo: PAY_TO, asset: USDC_TESTNET_ADDRESS }, PAYER), "asset"); + refused(() => assertMainnetPin({ payTo: PAY_TO, asset: MAINNET_USDC.asset.toLowerCase() }, PAYER), "asset"); + refused(() => assertMainnetPin({ payTo: PAY_TO, asset: ` ${MAINNET_USDC.asset}` }, PAYER), "asset"); + }); + + it("must name a valid Stellar address as the payee", () => { + for (const payTo of ["", "not an address", PAY_TO.toLowerCase(), `${PAY_TO} `, PAY_TO.slice(0, -1), Keypair.random().secret()]) { + const error = refused(() => assertMainnetPin({ payTo, asset: MAINNET_USDC.asset }, PAYER), "pin"); + assert.doesNotMatch(error.message, /S[A-Z2-7]{55}/, "never echoes a key"); + } + }); + + it("must not pay the payer itself: a transfer to oneself would hide what left the account", () => { + refused(() => assertMainnetPin({ payTo: PAYER, asset: MAINNET_USDC.asset }, PAYER), "pin"); + }); +}); + +describe("the option a mainnet endpoint may be paid by (L1, B3)", () => { + const option = { scheme: "exact", network: PUBNET, payTo: PAY_TO, asset: MAINNET_USDC.asset, maxTimeoutSeconds: 60 }; + + it("passes exact, stellar:pubnet, mainnet USDC, a lifetime from 1 to 300 s", () => { + assertMainnetOption(option); + assertMainnetOption({ ...option, maxTimeoutSeconds: 1 }); + assertMainnetOption({ ...option, maxTimeoutSeconds: 300 }); + }); + + it("refuses another scheme or network", () => { + refused(() => assertMainnetOption({ ...option, scheme: "upto" }), "network"); + refused(() => assertMainnetOption({ ...option, network: "stellar:testnet" }), "network"); + }); + + it("refuses another asset", () => { + refused(() => assertMainnetOption({ ...option, asset: USDC_TESTNET_ADDRESS }), "asset"); + }); + + it("refuses a lifetime above 300 s, or one that is not a positive whole number of seconds", () => { + for (const maxTimeoutSeconds of [301, 3600, 0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, "300", undefined, null]) { + refused(() => assertMainnetOption({ ...option, maxTimeoutSeconds: maxTimeoutSeconds as number }), "lifetime"); + } + }); +}); + +describe("the token's decimals, read on chain (B4)", () => { + it("must be 7", () => { + assertMainnetDecimals(7); + for (const decimals of [6, 8, 0, "7", 7.5, undefined, null, Number.NaN, 7n]) { + refused(() => assertMainnetDecimals(decimals), "decimals"); + } + }); +}); + +describe("the anchor ledger against Horizon (B17.2)", () => { + it("passes when the RPC's latest ledger is within 12 of Horizon's, either way", () => { + for (const gap of [0, 1, 12, -1, -12]) assertAnchorNearHorizon(65_594_567 + gap, 65_594_567); + }); + + it("refuses a gap of 13 or more", () => { + refused(() => assertAnchorNearHorizon(65_594_567 + 13, 65_594_567), "anchor"); + refused(() => assertAnchorNearHorizon(65_594_567 - 13, 65_594_567), "anchor"); + refused(() => assertAnchorNearHorizon(65_594_567 + 10_000_000, 65_594_567), "anchor"); + }); + + it("refuses a reading that is not a positive whole ledger number", () => { + for (const bad of [0, -1, 1.5, Number.NaN, undefined, "65594567"]) { + refused(() => assertAnchorNearHorizon(bad as number, 65_594_567), "anchor"); + refused(() => assertAnchorNearHorizon(65_594_567, bad as number), "anchor"); + } + }); +}); + +describe("Horizon's amounts and balances", () => { + it("reads an amount with exactly 7 decimals into base units", () => { + assert.equal(parseHorizonAmount("10.0000000"), 100_000_000n); + assert.equal(parseHorizonAmount("0.0000001"), 1n); + assert.equal(parseHorizonAmount("0.0000000"), 0n); + assert.equal(parseHorizonAmount("21871636256.6342925"), 218_716_362_566_342_925n); + }); + + it("reads nothing else", () => { + for (const bad of ["10", "10.000000", "10.00000000", "-1.0000000", "+1.0000000", "1e3", " 1.0000000", "1.0000000 ", "", "0x1.0000000", 10, null, undefined]) { + assert.equal(parseHorizonAmount(bad), undefined, String(bad)); + } + }); + + const usdc = (balance: string, issuer = CIRCLE_ISSUER, code = "USDC", type = "credit_alphanum4") => ({ + balance, + asset_type: type, + asset_code: code, + asset_issuer: issuer, + }); + const native = (balance: string) => ({ balance, asset_type: "native" }); + + it("finds the USDC trustline by code, issuer and type, and the native balance", () => { + const account = { balances: [usdc("9.5000000"), native("3.0000000")] }; + assert.deepEqual(horizonBalances(account, MAINNET_USDC), { usdc: 95_000_000n, native: 30_000_000n }); + }); + + it("ignores a token with the same code from another issuer, or a longer code", () => { + const other = Keypair.random().publicKey(); + const account = { balances: [usdc("1000.0000000", other), usdc("1000.0000000", CIRCLE_ISSUER, "USDCAllow", "credit_alphanum12"), native("3.0000000")] }; + assert.deepEqual(horizonBalances(account, MAINNET_USDC), { usdc: 0n, native: 30_000_000n }); + }); + + it("reads no USDC trustline as zero", () => { + assert.deepEqual(horizonBalances({ balances: [native("1.0000000")] }, MAINNET_USDC), { usdc: 0n, native: 10_000_000n }); + }); + + it("gives no reading for an answer it cannot trust", () => { + const cases: unknown[] = [ + undefined, + null, + {}, + { balances: "x" }, + { balances: [] }, + { balances: [usdc("1.0000000")] }, + { balances: [usdc("1.0"), native("1.0000000")] }, + { balances: [usdc("1.0000000"), native("x")] }, + { balances: [usdc("1.0000000"), usdc("2.0000000"), native("1.0000000")] }, + { balances: [native("1.0000000"), native("2.0000000")] }, + ]; + for (const account of cases) assert.equal(horizonBalances(account, MAINNET_USDC), undefined, JSON.stringify(account)); + }); +}); + +describe("the payer's USDC balance, RPC against Horizon (B17.12)", () => { + it("passes when both say the same", () => { + assertBalancesAgree(95_000_000n, 95_000_000n); + assertBalancesAgree(0n, 0n); + }); + + it("refuses when they differ, by one base unit too", () => { + refused(() => assertBalancesAgree(95_000_000n, 95_000_001n), "balance"); + refused(() => assertBalancesAgree(1n, 0n), "balance"); + }); + + it("refuses when either has no reading", () => { + refused(() => assertBalancesAgree(undefined, 1n), "balance"); + refused(() => assertBalancesAgree(1n, undefined), "horizon"); + }); +}); diff --git a/packages/core/test/unit/run-ledger-wiring.test.ts b/packages/core/test/unit/run-ledger-wiring.test.ts new file mode 100644 index 0000000..6c0cfa6 --- /dev/null +++ b/packages/core/test/unit/run-ledger-wiring.test.ts @@ -0,0 +1,306 @@ +/** + * How the payment checks keep the run ledger (spec B5, B-A03), written before + * the code (B11): `preparePayment` writes the intent of each signature after + * the run is charged and before the key is asked to sign, then what became of + * it; each check records what it sent and the answer's status; X402-06 records + * the settlement. A ledger that cannot take the intent stops the payment with + * nothing signed. It works on every network; here, a test network. + * + * Offline: the recording chain of `../support/recording-chain.ts`, and a gated + * variant that signs through the signed-terms gate as the Stellar signer does. + */ + +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { Address, Keypair, Networks, hash, nativeToScVal, xdr } from "@stellar/stellar-sdk"; + +import type { CheckResult } from "../../src/check.js"; +import { CheckSetupError } from "../../src/errors.js"; +import { PaymentGuardRefusedError, RunBudget } from "../../src/guard/budget.js"; +import { setRpcIdentityTransportForTesting } from "../../src/guard/rpc-identity.js"; +import { RunLedger, type LedgerEntry, type PaymentLedger } from "../../src/guard/run-ledger.js"; +import { setPaymentChainsForTesting } from "../../src/x402/chains/index.js"; +import type { PaymentChain } from "../../src/x402/chains/types.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; +import { NETWORK, PAYER, PAY_TO, USDC, option, paywall, recordingChain, type Paywall, type Recorder } from "../support/recording-chain.js"; + +const dirs: string[] = []; +const walls: Paywall[] = []; +let recorder: Recorder; + +beforeEach(() => { + recorder = { signed: [] }; +}); + +afterEach(async () => { + setPaymentChainsForTesting(undefined); + setRpcIdentityTransportForTesting(undefined); + await Promise.all(walls.splice(0).map((wall) => wall.close())); + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function install(chain: PaymentChain): void { + setPaymentChainsForTesting([chain]); + setRpcIdentityTransportForTesting(async (_url, method) => (method === "eth_chainId" ? "0x14a34" : undefined)); +} + +function newLedger(): RunLedger { + const dir = mkdtempSync(join(tmpdir(), "wasit-ledger-wiring-")); + dirs.push(dir); + return RunLedger.create(dir, { + versions: { core: "test" }, + environment: "test", + network: NETWORK, + payer: PAYER, + caps: { perPaymentUsd: "$1.00", runUsd: "$5.00" }, + plan: {}, + rpc: "http://127.0.0.1:9", + }); +} + +function entriesOf(ledger: RunLedger): LedgerEntry[] { + return (JSON.parse(readFileSync(ledger.path, "utf-8")) as { entries: LedgerEntry[] }).entries; +} + +async function wall(amount: string): Promise { + const created = await paywall([option({ amount })]); + walls.push(created); + return created; +} + +function byId(results: readonly CheckResult[], id: string): CheckResult { + const found = results.find((result) => result.id === id); + assert.ok(found, `no ${id}`); + return found; +} + +const run = (target: string, ledger: PaymentLedger) => + runX402PaymentChecks({ target, network: NETWORK, payerSecretKey: "test-payer-key", budget: new RunBudget(), ledger }); + +/** A Stellar authorization preimage expiring at `expiration`, as the gate records what it let the key sign. */ +function preimage(expiration: number): string { + const invocation = new xdr.SorobanAuthorizedInvocation({ + function: xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn( + new xdr.InvokeContractArgs({ + contractAddress: new Address("CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75").toScAddress(), + functionName: "transfer", + args: [ + new Address(Keypair.random().publicKey()).toScVal(), + new Address(Keypair.random().publicKey()).toScVal(), + nativeToScVal(1n, { type: "i128" }), + ], + }), + ), + subInvocations: [], + }); + return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization( + new xdr.HashIdPreimageSorobanAuthorization({ + networkId: hash(Buffer.from(Networks.TESTNET)), + nonce: xdr.Int64.fromString("7"), + invocation, + signatureExpirationLedger: expiration, + }), + ).toXDR("base64"); +} + +interface GatedOptions { + /** Asks the gate for a second signature: refused, nothing recorded. */ + readonly twice?: boolean; + readonly bind?: () => void; + /** Called when the key is asked to sign, before it signs. */ + readonly onSign?: (requirements: { amount: string }) => void; +} + +/** The recording chain, signing through the gate and recording a preimage that expires at the gate's bound. */ +function gatedChain(options: GatedOptions = {}): PaymentChain { + const base = recordingChain(recorder); + return { + ...base, + registerPayer(client, _network, _key, _rpc, gate) { + client.register(NETWORK, { + scheme: "exact", + findDefaultAsset: (asset, network) => + network === NETWORK && asset.toLowerCase() === USDC.toLowerCase() ? { asset: USDC, decimals: 6, symbol: "USDC" } : undefined, + async createPaymentPayload(version, requirements) { + options.onSign?.(requirements); + const terms = gate.take(); + if (options.twice === true) gate.take(); + gate.record({ preimage: preimage(terms.maxExpiration), signature: Buffer.alloc(64, 1) }); + recorder.signed.push(requirements); + return { x402Version: version, payload: { signature: `sig-${recorder.signed.length}` } }; + }, + }); + }, + signedTerms: { + unitSeconds: 5, + latestUnit: async () => 1000, + bind: () => options.bind?.(), + }, + }; +} + +describe("the run ledger in the payment checks", () => { + it("has each signature's intent on disk before the key is asked to sign it", async () => { + const ledger = newLedger(); + const seenBeforeSigning: LedgerEntry[] = []; + install( + gatedChain({ + onSign: () => { + const last = entriesOf(ledger).at(-1); + assert.ok(last !== undefined, "an intent is on disk"); + seenBeforeSigning.push(last); + }, + }), + ); + const target = await wall("10000"); + const results = await run(target.url, ledger.forEndpoint("paid")); + assert.equal(byId(results, "X402-06").pass, true, byId(results, "X402-06").detail); + assert.deepEqual( + seenBeforeSigning.map((entry) => [entry.check, entry.state, entry.amount]), + [ + ["X402-06", "intent", "10000"], + ["X402-07", "intent", "10000"], + ["X402-09", "intent", "5000"], + ["X402-10", "intent", "10000"], + ], + ); + }); + + it("records each signature with its expiry, what was sent, and X402-06's settlement", async () => { + const ledger = newLedger(); + install(gatedChain()); + const target = await wall("10000"); + await run(target.url, ledger.forEndpoint("paid")); + const entries = entriesOf(ledger); + assert.deepEqual(entries.map((entry) => entry.check), ["X402-06", "X402-07", "X402-09", "X402-10"]); + for (const entry of entries) { + assert.equal(entry.state, "signed", entry.check); + assert.equal(entry.endpoint, "paid"); + assert.equal(entry.payTo, PAY_TO); + assert.equal(entry.asset, USDC); + assert.equal(typeof entry.expiresAtLedger, "number", `${entry.check} expiry`); + assert.equal(typeof entry.sent?.status, "number", `${entry.check} sent`); + } + // 60 s of lifetime from ledger 1000: at most 1000 + 12 + 2 (+ the time since the anchor). + assert.ok(entries[0]!.expiresAtLedger! >= 1014 && entries[0]!.expiresAtLedger! <= 1016); + assert.equal(entries[0]!.settlement?.verified, true); + assert.match(entries[0]!.settlement?.reference ?? "", /^tx-/); + assert.equal(entries[1]!.settlement, undefined); + }); + + it("records not signed when the run stops before the key is asked (the payer cannot pay)", async () => { + const ledger = newLedger(); + install({ ...gatedChain(), payerBalance: async () => 0n }); + const target = await wall("10000"); + const results = await run(target.url, ledger.forEndpoint("paid")); + assert.equal(byId(results, "X402-06").error?.kind, "setup"); + const [entry, ...rest] = entriesOf(ledger); + assert.equal(entry!.state, "not-signed"); + assert.equal(rest.length, 0); + assert.equal(recorder.signed.length, 0); + }); + + it("records not signed when the gate refuses, since the gate is the only way to the key", async () => { + const ledger = newLedger(); + install(gatedChain({ twice: true })); + const target = await wall("10000"); + await run(target.url, ledger.forEndpoint("paid")); + const [entry] = entriesOf(ledger); + assert.equal(entry!.state, "not-signed"); + assert.match(entry!.note ?? "", /second signature/); + }); + + it("records a payload it cannot bind as signed and discarded, never sent", async () => { + const ledger = newLedger(); + install( + gatedChain({ + bind: () => { + throw new PaymentGuardRefusedError("signed-terms", "The payment names another invocation.", { signed: true }); + }, + }), + ); + const target = await wall("10000"); + await run(target.url, ledger.forEndpoint("paid")); + const [entry] = entriesOf(ledger); + assert.equal(entry!.state, "signed"); + assert.match(entry!.discarded ?? "", /another invocation/); + assert.equal(entry!.sent, undefined); + assert.equal(target.paid, 0); + }); + + it("records unknown when a client without a gate fails while building: it may have signed", async () => { + const ledger = newLedger(); + const base = recordingChain(recorder); + install({ + ...base, + registerPayer(client) { + client.register(NETWORK, { + scheme: "exact", + findDefaultAsset: () => ({ asset: USDC, decimals: 6, symbol: "USDC" }), + async createPaymentPayload() { + throw new Error("the client failed after the key was used"); + }, + }); + }, + }); + const target = await wall("10000"); + await run(target.url, ledger.forEndpoint("paid")); + const [entry] = entriesOf(ledger); + assert.equal(entry!.state, "unknown"); + }); + + it("records signed when the client fails after the gate let the key sign: the signature exists", async () => { + const ledger = newLedger(); + const base = gatedChain(); + install({ + ...base, + registerPayer(client, _network, _key, _rpc, gate) { + client.register(NETWORK, { + scheme: "exact", + findDefaultAsset: () => ({ asset: USDC, decimals: 6, symbol: "USDC" }), + async createPaymentPayload() { + const terms = gate.take(); + gate.record({ preimage: preimage(terms.maxExpiration), signature: Buffer.alloc(64, 1) }); + throw new Error("the second simulation failed"); + }, + }); + }, + }); + const target = await wall("10000"); + await run(target.url, ledger.forEndpoint("paid")); + const [entry] = entriesOf(ledger); + assert.equal(entry!.state, "signed"); + assert.equal(typeof entry!.expiresAtLedger, "number"); + assert.equal(entry!.sent, undefined, "no send recorded: read as sent"); + }); + + it("records not signed on a chain without a gate when the run stops before the client is asked", async () => { + const ledger = newLedger(); + install({ ...recordingChain(recorder), payerBalance: async () => 0n }); + const target = await wall("10000"); + await run(target.url, ledger.forEndpoint("paid")); + const [entry] = entriesOf(ledger); + assert.equal(entry!.state, "not-signed"); + assert.equal(recorder.signed.length, 0); + }); + + it("signs nothing when the intent cannot be written", async () => { + install(gatedChain()); + const target = await wall("10000"); + const broken: PaymentLedger = { + intent() { + throw new CheckSetupError("The run ledger could not be written. Nothing was signed."); + }, + }; + const results = await run(target.url, broken); + const first = byId(results, "X402-06"); + assert.equal(first.error?.kind, "setup", first.detail); + assert.match(first.detail, /Nothing was signed\./); + assert.equal(recorder.signed.length, 0); + assert.equal(target.paid, 0); + }); +}); diff --git a/packages/core/test/unit/run-ledger.test.ts b/packages/core/test/unit/run-ledger.test.ts new file mode 100644 index 0000000..de4f91c --- /dev/null +++ b/packages/core/test/unit/run-ledger.test.ts @@ -0,0 +1,373 @@ +/** + * The run ledger (spec B5, safety rule 6), written before the code (B11): a + * file a paying run keeps beside it, so that a person can compare what Wasit + * signed with what the chain shows, even after a crash. + * + * - One file per run, `wasit-ledger-.json`, created new (never + * overwritten), valid JSON after every write (written whole to a temporary + * file, flushed, then renamed over the ledger). + * - One entry per signature: "intent" first, written before the signature; + * then signed (with the ledger it expires at), not signed, or unknown; then + * discarded, or sent with the answer's status; the settlement if any. + * - Balances before and after, and whether they are consistent with what the + * ledger says settled. + * - No secret: free text is cut, and anything shaped like a Stellar secret or + * a 64-hex value in it is masked. + */ + +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, it } from "node:test"; + +import { Address, Keypair, Networks, hash, nativeToScVal, xdr } from "@stellar/stellar-sdk"; + +import { CheckSetupError } from "../../src/errors.js"; +import { + RUN_LEDGER_FORMAT, + RunLedger, + RunLedgerError, + ledgerConsistency, + openAuthorizationsUntil, + runLedgerFileName, + type LedgerEntry, + type RunLedgerHeader, +} from "../../src/guard/run-ledger.js"; +import { expirationOfSigned } from "../../src/guard/signed-terms.js"; + +const PAYER = Keypair.random().publicKey(); +const PAY_TO = Keypair.random().publicKey(); +const USDC = "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75"; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function folder(): string { + const dir = mkdtempSync(join(tmpdir(), "wasit-ledger-test-")); + dirs.push(dir); + return dir; +} + +const header: RunLedgerHeader = { + versions: { core: "0.8.0-test", cli: "0.8.0-test" }, + environment: "mainnet", + network: "stellar:pubnet", + payer: PAYER, + pin: { payTo: PAY_TO, asset: USDC }, + caps: { perPaymentUsd: "$1.00", runUsd: "$5.00" }, + plan: { worstCaseUsd: "$0.045", endpoints: [{ name: "weather", signatures: [{ check: "X402-06", amount: 100_000n }] }] }, + rpc: "https://rpc.example", +}; + +let clock = Date.parse("2026-11-21T11:01:29.123Z"); +const now = (): Date => new Date((clock += 1000)); + +function onDisk(ledger: RunLedger): Record { + return JSON.parse(readFileSync(ledger.path, "utf-8")) as Record; +} + +function entriesOnDisk(ledger: RunLedger): LedgerEntry[] { + return onDisk(ledger)["entries"] as LedgerEntry[]; +} + +const intent = { check: "X402-06", network: "stellar:pubnet", asset: USDC, payTo: PAY_TO, amount: "100000" }; + +describe("the run ledger's file", () => { + it("is named after the run's start in UTC, with no character a file system refuses", () => { + assert.equal(runLedgerFileName(new Date("2026-11-21T11:01:29.123Z")), "wasit-ledger-2026-11-21T11-01-29.123Z.json"); + }); + + it("is created in its folder, made if missing, and holds the header from the start", () => { + const dir = join(folder(), "ledgers", "run"); + const ledger = RunLedger.create(dir, header, { now }); + assert.ok(ledger.path.startsWith(dir)); + const doc = onDisk(ledger); + assert.equal(doc["format"], RUN_LEDGER_FORMAT); + assert.equal(doc["version"], 1); + assert.equal(doc["payer"], PAYER); + assert.equal(doc["network"], "stellar:pubnet"); + assert.deepEqual(doc["pin"], { payTo: PAY_TO, asset: USDC }); + assert.equal(doc["rpc"], "https://rpc.example"); + assert.deepEqual(doc["entries"], []); + assert.equal(doc["result"], "open"); + // bigints of the plan are written as strings. + assert.match(JSON.stringify(doc["plan"]), /"amount":"100000"/); + }); + + it("is never overwritten: a second ledger with the same name is refused", () => { + const dir = folder(); + const fixed = (): Date => new Date("2026-11-21T11:01:29.123Z"); + const first = RunLedger.create(dir, header, { now: fixed }); + first.forEndpoint("weather").intent(intent); + assert.throws(() => RunLedger.create(dir, header, { now: fixed }), RunLedgerError); + assert.equal(entriesOnDisk(first).length, 1, "the first ledger is untouched"); + }); + + it("refuses an RPC that is not given as an origin, so no path or key of it is written", () => { + assert.throws(() => RunLedger.create(folder(), { ...header, rpc: "https://rpc.example/v1/SECRETKEY" }, { now }), RunLedgerError); + }); + + it("is valid JSON after every write, and leaves no temporary file", () => { + const dir = folder(); + const ledger = RunLedger.create(dir, header, { now }); + const entry = ledger.forEndpoint("weather").intent(intent); + JSON.parse(readFileSync(ledger.path, "utf-8")); + entry.signed(65_594_600); + JSON.parse(readFileSync(ledger.path, "utf-8")); + entry.sent({ status: 200 }); + entry.settled("a".repeat(64), true); + ledger.close({ after: { usdc: 0n, native: 0n }, source: "test" }); + JSON.parse(readFileSync(ledger.path, "utf-8")); + assert.deepEqual(readdirSync(dir), [ledger.path.slice(dir.length + 1)]); + }); + + it("refuses to record an intent it cannot write, so the caller signs nothing", () => { + const dir = folder(); + const ledger = RunLedger.create(dir, header, { now }); + rmSync(dir, { recursive: true, force: true }); + assert.throws(() => ledger.forEndpoint("weather").intent(intent), (error: unknown) => { + assert.ok(error instanceof RunLedgerError); + assert.ok(error instanceof CheckSetupError, "a ledger that cannot be written is a setup error: no verdict"); + assert.match(error.message, /Nothing was signed\./); + return true; + }); + }); +}); + +describe("one entry per signature", () => { + it("starts as an intent, on disk before the call returns", () => { + const ledger = RunLedger.create(folder(), header, { now }); + ledger.forEndpoint("weather").intent(intent); + const [entry] = entriesOnDisk(ledger); + assert.equal(entry!.state, "intent"); + assert.equal(entry!.id, 1); + assert.equal(entry!.endpoint, "weather"); + assert.equal(entry!.check, "X402-06"); + assert.equal(entry!.amount, "100000"); + assert.equal(entry!.payTo, PAY_TO); + assert.equal(entry!.asset, USDC); + assert.equal(typeof entry!.intentAt, "string"); + }); + + it("records the signature with the ledger it expires at, then what was sent and what settled", () => { + const ledger = RunLedger.create(folder(), header, { now }); + const handle = ledger.forEndpoint("weather").intent(intent); + handle.signed(65_594_600); + handle.sent({ status: 200 }); + handle.settled("b".repeat(64), true); + const [entry] = entriesOnDisk(ledger); + assert.equal(entry!.state, "signed"); + assert.equal(entry!.expiresAtLedger, 65_594_600); + assert.equal(entry!.sent?.status, 200); + assert.deepEqual(entry!.settlement, { reference: "b".repeat(64), verified: true }); + }); + + it("records a signature whose expiry could not be read as such", () => { + const ledger = RunLedger.create(folder(), header, { now }); + ledger.forEndpoint("weather").intent(intent).signed(undefined); + assert.equal(entriesOnDisk(ledger)[0]!.expiresAtLedger, null); + }); + + it("records not signed, unknown, discarded and an error on sending", () => { + const ledger = RunLedger.create(folder(), header, { now }); + const endpoint = ledger.forEndpoint("weather"); + endpoint.intent({ ...intent, check: "X402-07" }).notSigned("The signed-terms gate refused it."); + endpoint.intent({ ...intent, check: "X402-09" }).unknown("The client failed while building the payment."); + const discarded = endpoint.intent({ ...intent, check: "X402-10" }); + discarded.signed(65_594_570); + discarded.discarded("The payload names other terms."); + const failed = endpoint.intent({ ...intent, check: "X402-11" }); + failed.signed(65_594_660); + failed.sent({ error: "no answer" }); + const [a, b, c, d] = entriesOnDisk(ledger); + assert.equal(a!.state, "not-signed"); + assert.match(a!.note ?? "", /gate refused/); + assert.equal(b!.state, "unknown"); + assert.equal(c!.state, "signed"); + assert.match(c!.discarded ?? "", /other terms/); + assert.equal(c!.sent, undefined); + assert.equal(d!.sent?.error, "no answer"); + assert.deepEqual(entriesOnDisk(ledger).map((entry) => entry.id), [1, 2, 3, 4]); + }); + + it("refuses an entry that is not a whole positive amount, or a second outcome", () => { + const ledger = RunLedger.create(folder(), header, { now }); + const endpoint = ledger.forEndpoint("weather"); + assert.throws(() => endpoint.intent({ ...intent, amount: "-1" }), RunLedgerError); + assert.throws(() => endpoint.intent({ ...intent, amount: "1.5" }), RunLedgerError); + const handle = endpoint.intent(intent); + handle.notSigned("refused"); + assert.throws(() => handle.signed(1), RunLedgerError); + }); + + it("refuses a send or a discard without a signature, and a second one", () => { + const ledger = RunLedger.create(folder(), header, { now }); + const endpoint = ledger.forEndpoint("weather"); + const refused = endpoint.intent(intent); + refused.notSigned("refused"); + assert.throws(() => refused.sent({ status: 200 }), RunLedgerError); + assert.throws(() => refused.discarded("x"), RunLedgerError); + const sent = endpoint.intent(intent); + sent.signed(1); + sent.sent({ status: 402 }); + assert.throws(() => sent.sent({ status: 200 }), RunLedgerError); + assert.throws(() => sent.discarded("x"), RunLedgerError); + const discarded = endpoint.intent(intent); + discarded.signed(1); + discarded.discarded("x"); + assert.throws(() => discarded.discarded("y"), RunLedgerError); + assert.throws(() => discarded.sent({ status: 200 }), RunLedgerError); + }); + + it("keeps no trace of an intent it could not write: the next one is entry 1", () => { + const dir = folder(); + const ledger = RunLedger.create(dir, header, { now }); + rmSync(dir, { recursive: true, force: true }); + assert.throws(() => ledger.forEndpoint("weather").intent(intent), RunLedgerError); + mkdirSync(dir, { recursive: true }); + ledger.forEndpoint("weather").intent({ ...intent, check: "X402-07" }); + assert.deepEqual(entriesOnDisk(ledger).map((entry) => [entry.id, entry.check]), [[1, "X402-07"]]); + }); + + it("masks anything shaped like a secret in free text, and cuts it", () => { + const ledger = RunLedger.create(folder(), header, { now }); + const secret = Keypair.random().secret(); + const hex = "c".repeat(64); + ledger.forEndpoint("weather").intent(intent).notSigned(`an error naming ${secret} and ${hex} ${"x".repeat(1000)}`); + const raw = readFileSync(ledger.path, "utf-8"); + assert.ok(!raw.includes(secret)); + assert.ok(!raw.includes(hex)); + assert.ok((entriesOnDisk(ledger)[0]!.note ?? "").length <= 300); + }); +}); + +describe("balances and the ledger's result", () => { + const entry = (overrides: Partial): LedgerEntry => ({ + id: 1, + endpoint: "weather", + check: "X402-06", + network: "stellar:pubnet", + asset: USDC, + payTo: PAY_TO, + amount: "100000", + intentAt: "2026-11-21T11:01:30.123Z", + state: "signed", + expiresAtLedger: 65_594_600, + ...overrides, + }); + + it("is consistent when the payer's USDC went down by exactly the verified settlements, and its XLM did not move", () => { + const result = ledgerConsistency( + { usdc: 1_000_000n, native: 50_000_000n }, + { usdc: 900_000n, native: 50_000_000n }, + [entry({ settlement: { reference: "d".repeat(64), verified: true } }), entry({ id: 2, check: "X402-07" })], + ); + assert.equal(result.consistent, true, result.reasons.join("; ")); + assert.equal(result.spentUsdc, 100_000n); + assert.equal(result.settledUsdc, 100_000n); + }); + + it("is inconsistent when more left the account than the ledger shows settled, or less", () => { + const more = ledgerConsistency({ usdc: 1_000_000n, native: 1n }, { usdc: 850_000n, native: 1n }, [ + entry({ settlement: { reference: "d".repeat(64), verified: true } }), + ]); + assert.equal(more.consistent, false); + assert.match(more.reasons.join(" "), /150000/); + const less = ledgerConsistency({ usdc: 1_000_000n, native: 1n }, { usdc: 1_000_000n, native: 1n }, [ + entry({ settlement: { reference: "d".repeat(64), verified: true } }), + ]); + assert.equal(less.consistent, false); + // A settlement the run could not verify on chain is not counted as settled. + const unverified = ledgerConsistency({ usdc: 1_000_000n, native: 1n }, { usdc: 900_000n, native: 1n }, [ + entry({ settlement: { reference: "d".repeat(64), verified: false } }), + ]); + assert.equal(unverified.consistent, false); + assert.equal(unverified.settledUsdc, 0n); + }); + + it("is inconsistent when the payer's XLM moved: Wasit sends no transaction from the payer", () => { + const result = ledgerConsistency({ usdc: 1n, native: 50_000_000n }, { usdc: 1n, native: 49_999_900n }, []); + assert.equal(result.consistent, false); + assert.match(result.reasons.join(" "), /XLM/); + }); + + it("is inconsistent when either reading is missing", () => { + assert.equal(ledgerConsistency(undefined, { usdc: 1n, native: 1n }, []).consistent, false); + assert.equal(ledgerConsistency({ usdc: 1n, native: 1n }, undefined, []).consistent, false); + }); + + it("names entries with no outcome, read as signed", () => { + const result = ledgerConsistency({ usdc: 1n, native: 1n }, { usdc: 1n, native: 1n }, [entry({ state: "intent", expiresAtLedger: undefined })]); + assert.match(result.reasons.join(" "), /X402-06.*assume/); + }); + + it("is written with the balances on close", () => { + const ledger = RunLedger.create(folder(), header, { now }); + ledger.recordBalancesBefore({ usdc: 1_000_000n, native: 50_000_000n }, "rpc and horizon"); + const handle = ledger.forEndpoint("weather").intent(intent); + handle.signed(65_594_600); + handle.sent({ status: 200 }); + handle.settled("e".repeat(64), true); + const result = ledger.close({ after: { usdc: 900_000n, native: 50_000_000n }, source: "horizon" }); + assert.equal(result.consistent, true); + const doc = onDisk(ledger); + assert.deepEqual(doc["balancesBefore"], { usdc: "1000000", native: "50000000", source: "rpc and horizon", at: (doc["balancesBefore"] as { at: string }).at }); + assert.equal((doc["balancesAfter"] as { usdc: string }).usdc, "900000"); + assert.equal(doc["result"], "consistent"); + assert.equal(typeof doc["closedAt"], "string"); + assert.throws(() => ledger.forEndpoint("weather").intent(intent), RunLedgerError, "a closed ledger takes no entry"); + assert.throws(() => ledger.close({ after: { usdc: 0n, native: 0n } }), RunLedgerError, "a ledger is closed once"); + assert.equal(onDisk(ledger)["result"], "consistent", "a second close changes nothing"); + }); +}); + +describe("when every authorization of the run has expired (L4)", () => { + const base = { endpoint: "w", network: "stellar:pubnet", asset: USDC, payTo: PAY_TO, amount: "1", intentAt: "t" }; + it("is after the latest expiry of every entry that may be signed", () => { + const entries: LedgerEntry[] = [ + { ...base, id: 1, check: "X402-06", state: "signed", expiresAtLedger: 100 }, + { ...base, id: 2, check: "X402-07", state: "signed", expiresAtLedger: 140 }, + { ...base, id: 3, check: "X402-09", state: "not-signed" }, + ]; + assert.deepEqual(openAuthorizationsUntil(entries), { latest: 140, unknown: 0 }); + }); + + it("counts the entries whose expiry is not known, so the caller waits its longest bound", () => { + const entries: LedgerEntry[] = [ + { ...base, id: 1, check: "X402-06", state: "intent" }, + { ...base, id: 2, check: "X402-07", state: "unknown" }, + { ...base, id: 3, check: "X402-09", state: "signed", expiresAtLedger: null }, + { ...base, id: 4, check: "X402-10", state: "signed", expiresAtLedger: 90 }, + ]; + assert.deepEqual(openAuthorizationsUntil(entries), { latest: 90, unknown: 3 }); + }); +}); + +describe("the expiry of a signature, from what the key signed", () => { + it("is the preimage's signature expiration ledger", () => { + const invocation = new xdr.SorobanAuthorizedInvocation({ + function: xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn( + new xdr.InvokeContractArgs({ + contractAddress: new Address(USDC).toScAddress(), + functionName: "transfer", + args: [new Address(PAYER).toScVal(), new Address(PAY_TO).toScVal(), nativeToScVal(100_000n, { type: "i128" })], + }), + ), + subInvocations: [], + }); + const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization( + new xdr.HashIdPreimageSorobanAuthorization({ + networkId: hash(Buffer.from(Networks.PUBLIC)), + nonce: xdr.Int64.fromString("7"), + invocation, + signatureExpirationLedger: 65_594_600, + }), + ).toXDR("base64"); + assert.equal(expirationOfSigned({ preimage, signature: Buffer.alloc(64) }), 65_594_600); + assert.equal(expirationOfSigned({ preimage: "not xdr", signature: Buffer.alloc(64) }), undefined); + }); +}); +