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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ All notable changes to Wasit are recorded here. Versions follow [Semantic Versio
Actions none of them applies. `--mainnet` and the Action's `mainnet: true`
still refuse in this version, and now also name the runner rule on a runner
that is not GitHub-hosted.
- `@wasit-dev/core` exports two more rules of the mainnet opt-in, which this
version does not have; nothing calls them yet. `assertMainnetPayerBalance`
reads the payer's USDC balance on `stellar:pubnet` and refuses the run when
the account holds more than $10 or the balance cannot be read: the $5 cap
holds one run, not two at once on one account, so the account is the limit.
On a test network it reads nothing. `acquireMainnetRunLock` takes a lock file
(`wasit-mainnet.lock`) in the run's ledger folder, and a run that finds
anything there does not start: a run still open, one that was stopped
(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.

**Fixed.**
- On Stellar testnet the x402 client builds and simulates the payment through
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/guard/budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,14 @@ export function usdAsset(network: string, asset: string): UsdAsset | undefined {
return USD_ASSETS.find((entry) => entry.network === network && sameAddress(network, entry.asset, asset));
}

/** `amount` base units of a dollar token with `decimals` decimals, in this module's dollar units. */
export function usdFromBaseUnits(amount: bigint, decimals: number): bigint {
return (amount * DOLLAR) / 10n ** BigInt(decimals);
}

/** `amount` base units of `asset`, in this module's dollar units. */
function toUsd(asset: UsdAsset, amount: bigint): bigint {
return (amount * DOLLAR) / 10n ** BigInt(asset.decimals);
return usdFromBaseUnits(amount, asset.decimals);
}

/** Whole and fractional dollars, rounded down to a millionth: a cap is never rounded up. */
Expand Down
132 changes: 132 additions & 0 deletions packages/core/src/guard/mainnet-payer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/**
* L1's rule on the mainnet payer's account (spec B3, B4, B17.5).
*
* The caps hold one run to $5 (`budget.ts`). They do not hold two runs at once
* on the same account, nor a server that is restarted: each gets its own $5.
* What bounds those is the account. So before a mainnet run signs anything, it
* reads its payer's USDC balance and does not start when the account holds
* more than $10, or when the balance cannot be read. With $10 or less in it,
* runs at once on that account can together sign no more than it holds.
*
* The balance is the RPC's answer. It is read through the run's RPC, the one
* whose network was checked; a reader the caller hands in, so the rule itself
* is pure.
*
* This version has no mainnet opt-in (spec B12): `stellar:pubnet` is refused
* before any of this is read, and nothing here says "allowed" for it. The
* opt-in calls {@link assertMainnetPayerBalance} in L1, after it takes the
* run's lock (`run-lock.ts`) and before anything is signed.
*/

import { ConfigurationError } from "../errors.js";
import { PER_RUN_CAP_USD, formatUsd, usdFromBaseUnits, usdFromDollars } from "./budget.js";
import { networkClass } from "./networks.js";

/** At most this many dollars of USDC in the account a mainnet run pays from. */
export const MAINNET_PAYER_MAX_USD = 10;

/** USDC on Stellar has 7 decimals, as every Stellar Asset Contract has. */
const STELLAR_USDC_DECIMALS = 7;

/** {@link MAINNET_PAYER_MAX_USD} in base units of USDC on Stellar. */
export const MAINNET_PAYER_MAX_BASE_UNITS = BigInt(MAINNET_PAYER_MAX_USD) * 10n ** BigInt(STELLAR_USDC_DECIMALS);

/** The one mainnet a payer's balance is held to the rule on. */
const STELLAR_PUBNET = "stellar:pubnet";

/** A Stellar account address; anything else is never echoed. */
const STELLAR_ADDRESS = /^G[A-Z2-7]{55}$/;

/** Why the payer's account stops the run. */
export type MainnetPayerRefusal =
/** It holds more than $10 of USDC. */
| "above-max"
/** Its balance could not be read. */
| "unreadable"
/** The run's network has no rule here (fail closed). */
| "network";

/**
* A mainnet run does not start because of its payer's account. A
* `ConfigurationError`: it says nothing about the target. Nothing was signed.
*/
export class MainnetPayerRefusedError extends ConfigurationError {
public readonly reason: MainnetPayerRefusal;

public constructor(reason: MainnetPayerRefusal, message: string) {
super(`${message} Nothing was signed.`);
this.name = "MainnetPayerRefusedError";
this.reason = reason;
}
}

export interface MainnetPayerAccount {
/** The run's network. */
readonly network: string;
/** The payer's public address. */
readonly payer: string;
/**
* Reads the payer's balance of the run's USDC in base units, through the
* run's RPC; undefined when it cannot.
*/
readonly readBalance: () => Promise<bigint | undefined>;
}

function payerShown(payer: unknown): string {
return typeof payer === "string" && STELLAR_ADDRESS.test(payer) ? `the mainnet payer ${payer}` : "the mainnet payer";
}

/**
* Holds the payer's account to {@link MAINNET_PAYER_MAX_USD}.
*
* On a test network nothing is read and undefined is returned: the rule is for
* real funds. On `stellar:pubnet` the balance is read once and returned when
* it is $10 or less, for the plan to print. Any other network has no rule here
* and is refused without a read.
*
* @throws {MainnetPayerRefusedError} On `stellar:pubnet` when the balance is
* above $10 or cannot be read (no answer, an answer that is not a whole
* number of base units, or a read that threw: what it threw is not echoed,
* since an RPC URL may carry a key); and on any network that is neither a
* test network nor `stellar:pubnet`.
*/
export async function assertMainnetPayerBalance(account: MainnetPayerAccount): Promise<bigint | undefined> {
const { network } = account;
if (networkClass(network) === "test") return undefined;
if (network !== STELLAR_PUBNET) {
throw new MainnetPayerRefusedError(
"network",
"The run's network is not one whose payer's balance Wasit can hold to a limit, so no payment is made on it.",
);
}

const max = usdFromDollars(MAINNET_PAYER_MAX_USD);
let balance: unknown;
try {
balance = await account.readBalance();
} catch {
balance = undefined;
}
if (typeof balance !== "bigint" || balance < 0n) {
throw new MainnetPayerRefusedError(
"unreadable",
`The USDC balance of ${payerShown(account.payer)} could not be read on ${STELLAR_PUBNET}, so this run cannot ` +
`show that the account holds ${formatUsd(max)} or less.`,
);
}
if (balance > MAINNET_PAYER_MAX_BASE_UNITS) {
throw new MainnetPayerRefusedError(
"above-max",
`${capitalised(payerShown(account.payer))} holds ${formatUsd(usdFromBaseUnits(balance, STELLAR_USDC_DECIMALS))} ` +
`in USDC (${balance} base units), above the ${formatUsd(max)} a mainnet payer may hold. The ` +
`${formatUsd(usdFromDollars(PER_RUN_CAP_USD))} cap holds one run, not two at once on one account: with ` +
`${formatUsd(max)} or less in it, the account is the limit. Move the rest out of this account, or pay from ` +
`a dedicated account that holds ${formatUsd(max)} or less.`,
);
}
return balance;
}

function capitalised(text: string): string {
return text.charAt(0).toUpperCase() + text.slice(1);
}
214 changes: 214 additions & 0 deletions packages/core/src/guard/run-lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/**
* The lock file of a mainnet run (spec B4, B17.5).
*
* The caps hold one run to $5 (`budget.ts`). A second mainnet run started on
* the same machine while one is open would get its own $5. So a mainnet run
* takes this lock in its ledger's folder before it reads its payer's balance,
* and a run that finds a lock there does not start.
*
* Any file in the lock's place refuses the run, whoever left it: a run that is
* still open; a run that was stopped or crashed, whose authorizations may still
* be open, so a person reads its ledger before deleting the file; or a file
* that is not a lock Wasit can read. No run takes over or deletes another's
* lock. The file is created exclusively (it fails when anything is at its path,
* a symbolic link included), so two runs started at once cannot both take it.
*
* What it does not see: a run on another machine or runner, and a run whose
* ledger is in another folder (spec B4). The payer account's $10
* (`mainnet-payer.ts`) is the limit there.
*
* This version has no mainnet opt-in (spec B12): nothing calls this yet. The
* opt-in takes the lock before L1 and releases it when the run has ended.
*/

import { randomUUID } from "node:crypto";
import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
import path from "node:path";

import { ConfigurationError } from "../errors.js";
import { sanitizeText } from "../sanitize.js";
import { PER_RUN_CAP_USD, formatUsd, usdFromDollars } from "./budget.js";

/** The lock's name in the ledger's folder. */
export const MAINNET_RUN_LOCK_FILE = "wasit-mainnet.lock";

/** What the lock file says it is. */
const TAG = "mainnet-run-lock";

/** A lock Wasit writes is far smaller; a larger file is not read. */
const MAX_LOCK_BYTES = 4096;

/** A start time as `Date.toISOString` writes it; anything else is never echoed. */
const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;

/** An error code as Node writes them; anything else is never echoed. */
const ERROR_CODE = /^E[A-Z]{2,20}$/;

/** Who holds the lock a run found. */
export type LockHolder =
/** A process that is still running. */
| "running"
/** A process that has ended without releasing it. */
| "gone"
/** The file is not a lock Wasit can read. */
| "unknown";

/**
* A mainnet run does not start: a lock is already in its ledger's folder. A
* `ConfigurationError`: it says nothing about the target. Nothing was signed.
*/
export class MainnetRunLockedError extends ConfigurationError {
public readonly lockPath: string;
public readonly holder: LockHolder;

public constructor(lockPath: string, holder: LockHolder, message: string) {
super(`${message} Nothing was signed.`);
this.name = "MainnetRunLockedError";
this.lockPath = lockPath;
this.holder = holder;
}
}

/** A lock this run holds. */
export interface MainnetRunLock {
/** The lock file. */
readonly path: string;
/**
* Deletes the lock file when it is still this run's. Safe to call more than
* once, and after the file is gone. It is also called when the process exits
* (`exit`), but not when the process is killed: then the file stays, and the
* next run is refused until a person deletes it.
*/
release(): void;
}

interface LockContent {
readonly pid: number;
readonly startedAt: string;
readonly token: string;
}

/** The lock at `file`, when it is a regular file Wasit wrote; undefined otherwise. */
function readLock(file: string): LockContent | undefined {
try {
const stat = lstatSync(file);
if (!stat.isFile() || stat.size > MAX_LOCK_BYTES) return undefined;
const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
if (typeof parsed !== "object" || parsed === null) return undefined;
const { wasit, pid, startedAt, token } = parsed as Record<string, unknown>;
if (wasit !== TAG || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) return undefined;
if (typeof startedAt !== "string" || !ISO_TIME.test(startedAt) || typeof token !== "string") return undefined;
return { pid, startedAt, token };
} catch {
return undefined;
}
}

/** Whether process `pid` runs on this machine; undefined when that cannot be told. */
function isRunning(pid: number): boolean | undefined {
try {
process.kill(pid, 0);
return true;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "EPERM") return true;
if (code === "ESRCH") return false;
return undefined;
}
}

function lockedError(file: string): MainnetRunLockedError {
const shownFile = sanitizeText(file);
const lock = readLock(file);
const running = lock === undefined ? undefined : isRunning(lock.pid);
if (lock === undefined || running === undefined) {
return new MainnetRunLockedError(
file,
"unknown",
`${shownFile} is there and is not a lock Wasit can read, so this mainnet run does not start. If no mainnet run ` +
`is open, read the latest ledger in that folder, wait until the last authorization in it has expired, then ` +
`delete ${shownFile}.`,
);
}
const holder = `process ${lock.pid}, started ${lock.startedAt}`;
if (running) {
return new MainnetRunLockedError(
file,
"running",
`Another mainnet run (${holder}) holds ${shownFile}. One mainnet run at a time on this machine: the ` +
`${formatUsd(usdFromDollars(PER_RUN_CAP_USD))} cap holds each run, not two at once on one account. Wait until ` +
`it has ended.`,
);
}
return new MainnetRunLockedError(
file,
"gone",
`${shownFile} was left by a mainnet run (${holder}) that is no longer running: it ended without releasing the ` +
`lock, and authorizations it signed may still be open. Read that run's ledger, wait until the last ` +
`authorization in it has expired, then delete ${shownFile}.`,
);
}

function notCreated(dir: string, error: unknown): ConfigurationError {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return new ConfigurationError(
`The lock file of a mainnet run could not be created in ${sanitizeText(dir)}` +
`${typeof code === "string" && ERROR_CODE.test(code) ? ` (${code})` : ""}, so the run does not start. ` +
`Nothing was signed.`,
);
}

/**
* Takes the lock of a mainnet run in `dir`, the folder of the run's ledger,
* creating the folder when it is missing.
*
* @throws {MainnetRunLockedError} When anything is already at the lock's path.
* @throws {ConfigurationError} When the lock cannot be created.
*/
export function acquireMainnetRunLock(dir: string): MainnetRunLock {
const file = path.join(dir, MAINNET_RUN_LOCK_FILE);
const token = randomUUID();
const content = `${JSON.stringify({ wasit: TAG, pid: process.pid, startedAt: new Date().toISOString(), token })}\n`;

try {
// Apart from the open: mkdir also says EEXIST, for a file where the folder should be.
mkdirSync(dir, { recursive: true });
} catch (error) {
throw notCreated(dir, error);
}
let fd: number;
try {
fd = openSync(file, "wx", 0o600);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "EEXIST") throw lockedError(file);
throw notCreated(dir, error);
}
try {
writeSync(fd, content);
fsyncSync(fd);
} catch (error) {
closeSync(fd);
try {
unlinkSync(file);
} catch {
// nothing more to do: the run does not start either way
}
throw notCreated(dir, error);
}
closeSync(fd);

let released = false;
const release = (): void => {
if (released) return;
released = true;
process.removeListener("exit", release);
if (readLock(file)?.token !== token) return;
try {
unlinkSync(file);
} catch {
// gone already
}
};
process.once("exit", release);
return { path: file, release };
}
Loading
Loading