diff --git a/CHANGELOG.md b/CHANGELOG.md index 51ccf6e..d642011 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/packages/core/src/guard/budget.ts b/packages/core/src/guard/budget.ts index 12adff8..2d28f0c 100644 --- a/packages/core/src/guard/budget.ts +++ b/packages/core/src/guard/budget.ts @@ -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. */ diff --git a/packages/core/src/guard/mainnet-payer.ts b/packages/core/src/guard/mainnet-payer.ts new file mode 100644 index 0000000..57a5839 --- /dev/null +++ b/packages/core/src/guard/mainnet-payer.ts @@ -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; +} + +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 { + 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); +} diff --git a/packages/core/src/guard/run-lock.ts b/packages/core/src/guard/run-lock.ts new file mode 100644 index 0000000..611e990 --- /dev/null +++ b/packages/core/src/guard/run-lock.ts @@ -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; + 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 }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 9c208db..ed930b1 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -152,6 +152,22 @@ export { } from "./guard/mainnet-optin.js"; export { MainnetJobRefusedError, assertMainnetJob, isLocalHost, mainnetJobRefusals, type MainnetJob } from "./guard/ci-mainnet.js"; export type { MainnetSwitch } from "./guard/mainnet-optin.js"; +// The mainnet payer's $10 and the lock of a mainnet run (spec B17.5): rules that only refuse; nothing calls them yet. +export { + MAINNET_PAYER_MAX_BASE_UNITS, + MAINNET_PAYER_MAX_USD, + MainnetPayerRefusedError, + assertMainnetPayerBalance, + type MainnetPayerAccount, + type MainnetPayerRefusal, +} from "./guard/mainnet-payer.js"; +export { + MAINNET_RUN_LOCK_FILE, + MainnetRunLockedError, + acquireMainnetRunLock, + type LockHolder, + type MainnetRunLock, +} from "./guard/run-lock.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/test/unit/mainnet-payer.test.ts b/packages/core/test/unit/mainnet-payer.test.ts new file mode 100644 index 0000000..9f8e98e --- /dev/null +++ b/packages/core/test/unit/mainnet-payer.test.ts @@ -0,0 +1,131 @@ +/** + * L1's rule on the mainnet payer's account (spec B3, B4, B17.5), written + * before the code (B11). The caps hold one run to $5; two runs at once on one + * account would each get their own $5. So on stellar:pubnet the payer's USDC + * balance is read before anything is signed, and a run whose payer holds more + * than $10, or whose balance cannot be read, does not start: with $10 or less + * in it, the account itself is the limit. On a test network the rule does not + * apply and nothing is read. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; + +import { ConfigurationError } from "../../src/errors.js"; +import { + MAINNET_PAYER_MAX_BASE_UNITS, + MAINNET_PAYER_MAX_USD, + MainnetPayerRefusedError, + assertMainnetPayerBalance, +} from "../../src/guard/mainnet-payer.js"; +import { NETWORK_CLASSES } from "../../src/guard/networks.js"; + +const PUBNET = "stellar:pubnet"; +const PAYER = Keypair.random().publicKey(); + +/** A reader that counts its calls and answers `value` (or throws it, with `throws`). */ +function reader(value: unknown, options: { readonly throws?: boolean } = {}) { + const calls = { count: 0 }; + const read = async (): Promise => { + calls.count += 1; + if (options.throws === true) throw value; + return value as bigint | undefined; + }; + return { calls, read }; +} + +async function refusal(promise: Promise): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof MainnetPayerRefusedError, `not a MainnetPayerRefusedError: ${String(error)}`); + assert.ok(error instanceof ConfigurationError, "a payer refusal is a ConfigurationError: it says nothing about the target"); + return error; + } + assert.fail("the payer's balance was not refused"); +} + +describe("the mainnet payer's balance (L1, B17.5)", () => { + it("is $10 at most, 100,000,000 base units of USDC at 7 decimals", () => { + assert.equal(MAINNET_PAYER_MAX_USD, 10); + assert.equal(MAINNET_PAYER_MAX_BASE_UNITS, 10n * 10n ** 7n); + }); + + it("is not read on a test network", async () => { + for (const [network, kind] of NETWORK_CLASSES) { + if (kind !== "test") continue; + const { calls, read } = reader(10n ** 30n); + assert.equal(await assertMainnetPayerBalance({ network, payer: PAYER, readBalance: read }), undefined, network); + assert.equal(calls.count, 0, `${network}: the balance was read`); + } + }); + + it("passes on stellar:pubnet at $10 or less, and returns the balance it read", async () => { + for (const balance of [0n, 1n, 99_999_999n, MAINNET_PAYER_MAX_BASE_UNITS]) { + const { calls, read } = reader(balance); + assert.equal(await assertMainnetPayerBalance({ network: PUBNET, payer: PAYER, readBalance: read }), balance); + assert.equal(calls.count, 1, "read once"); + } + }); + + it("refuses above $10, by one base unit too, naming the balance, the payer and the limit", async () => { + const error = await refusal( + assertMainnetPayerBalance({ network: PUBNET, payer: PAYER, readBalance: reader(MAINNET_PAYER_MAX_BASE_UNITS + 1n).read }), + ); + assert.equal(error.reason, "above-max"); + assert.match(error.message, /\$10\.0000001/); + assert.match(error.message, /100000001 base units/); + assert.match(error.message, /above the \$10\.00 a mainnet payer may hold/); + assert.ok(error.message.includes(PAYER), "the payer's address is named"); + assert.match(error.message, /Nothing was signed\./); + assert.match(error.message, /\$5\.00/, "the message says what the cap does not bound"); + }); + + it("refuses a balance far above $10", async () => { + const error = await refusal(assertMainnetPayerBalance({ network: PUBNET, payer: PAYER, readBalance: reader(10n ** 30n).read })); + assert.equal(error.reason, "above-max"); + }); + + it("refuses when the balance cannot be read: no answer, a negative one, or not a whole number", async () => { + for (const value of [undefined, -1n, 5, "100", null]) { + const error = await refusal(assertMainnetPayerBalance({ network: PUBNET, payer: PAYER, readBalance: reader(value).read })); + assert.equal(error.reason, "unreadable", String(value)); + assert.match(error.message, /could not be read on stellar:pubnet/); + assert.match(error.message, /\$10\.00 or less/); + assert.match(error.message, /Nothing was signed\./); + } + }); + + it("refuses when the read throws, without echoing what it threw (an RPC URL may carry a key)", async () => { + for (const thrown of [new Error("fetch failed: https://rpc.example.test/?apikey=sk-live-0123456789"), "sk-live-0123456789", undefined]) { + const error = await refusal( + assertMainnetPayerBalance({ network: PUBNET, payer: PAYER, readBalance: reader(thrown, { throws: true }).read }), + ); + assert.equal(error.reason, "unreadable"); + assert.ok(!error.message.includes("sk-live"), "the thrown text reached the message"); + assert.ok(!error.message.includes("rpc.example.test"), "the RPC URL reached the message"); + } + }); + + it("refuses a network it has no rule for, without reading anything (fail closed)", async () => { + for (const network of ["eip155:1", "stellar:futurenet", "", "STELLAR:PUBNET", undefined as unknown as string]) { + const { calls, read } = reader(0n); + const error = await refusal(assertMainnetPayerBalance({ network, payer: PAYER, readBalance: read })); + assert.equal(error.reason, "network", String(network)); + assert.equal(calls.count, 0, `${String(network)}: the balance was read`); + assert.match(error.message, /Nothing was signed\./); + } + }); + + it("does not echo a payer that is not a Stellar address", async () => { + const odd = "GXXX\u001b]0;title\u0007"; + for (const value of [MAINNET_PAYER_MAX_BASE_UNITS + 1n, undefined]) { + const error = await refusal(assertMainnetPayerBalance({ network: PUBNET, payer: odd, readBalance: reader(value).read })); + assert.ok(!error.message.includes("GXXX"), "an odd payer value reached the message"); + // eslint-disable-next-line no-control-regex + assert.ok(!/[\u0000-\u001f\u007f]/.test(error.message), "a control character reached the message"); + } + }); +}); diff --git a/packages/core/test/unit/run-lock.test.ts b/packages/core/test/unit/run-lock.test.ts new file mode 100644 index 0000000..c18c68e --- /dev/null +++ b/packages/core/test/unit/run-lock.test.ts @@ -0,0 +1,323 @@ +/** + * The lock file of a mainnet run (spec B4, B17.5), written before the code + * (B11). The caps hold one run to $5; a second mainnet run started on the same + * machine while one is open would get its own $5. So a mainnet run takes a + * lock file in its ledger's folder before it reads its payer's balance, and a + * second one that finds the file there does not start. + * + * Any lock file that is there refuses the run, whoever left it: a run that is + * still open, one that was stopped or crashed (its 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. The lock is never taken over or deleted by + * another run. It does not see another machine or runner (B4); the account's + * $10 is the limit there. + */ + +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { ConfigurationError } from "../../src/errors.js"; +import { MAINNET_RUN_LOCK_FILE, MainnetRunLockedError, acquireMainnetRunLock } from "../../src/guard/run-lock.js"; + +const CORE = fileURLToPath(new URL("../../", import.meta.url)); +const MODULE = fileURLToPath(new URL("../../src/guard/run-lock.ts", import.meta.url)); +const POSIX = process.platform !== "win32"; + +const dirs: string[] = []; +function freshDir(): string { + const dir = mkdtempSync(path.join(tmpdir(), "wasit-lock-")); + dirs.push(dir); + return dir; +} + +afterEach(() => { + for (const dir of dirs.splice(0)) { + try { + chmodSync(dir, 0o700); + } catch { + // already gone + } + rmSync(dir, { recursive: true, force: true }); + } +}); + +function refused(dir: string): MainnetRunLockedError { + try { + const lock = acquireMainnetRunLock(dir); + lock.release(); + } catch (error) { + assert.ok(error instanceof MainnetRunLockedError, `not a MainnetRunLockedError: ${String(error)}`); + assert.ok(error instanceof ConfigurationError, "a held lock is a ConfigurationError: it says nothing about the target"); + return error; + } + assert.fail("the second mainnet run was not refused"); +} + +/** A lock file as Wasit writes it, for a process `pid`. */ +function lockText(pid: number, token = "someone-else"): string { + return `${JSON.stringify({ wasit: "mainnet-run-lock", pid, startedAt: "2026-11-21T10:00:00.000Z", token })}\n`; +} + +/** The pid of a process that ran and has ended. */ +async function endedPid(): Promise { + const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); + const pid = child.pid; + await new Promise((resolve) => child.on("exit", () => resolve())); + assert.ok(pid !== undefined); + return pid; +} + +/** Runs `source` (an ES module) in a fresh Node process that has tsx, from core's folder. */ +function runScript(dir: string, source: string): { readonly done: Promise<{ code: number | null; stdout: string }>; readonly child: ReturnType } { + const script = path.join(dir, `script-${Math.random().toString(36).slice(2)}.mts`); + writeFileSync(script, source); + const child = spawn(process.execPath, ["--import", "tsx", script], { cwd: CORE, stdio: ["ignore", "pipe", "inherit"] }); + let stdout = ""; + child.stdout!.on("data", (chunk: Buffer) => { + stdout += chunk.toString(); + }); + const done = new Promise<{ code: number | null; stdout: string }>((resolve) => + child.on("exit", (code) => resolve({ code, stdout })), + ); + return { done, child }; +} + +describe("the lock file of a mainnet run (B4, B17.5)", () => { + it("is taken in the ledger's folder, created when missing, readable by its owner only, and released", () => { + const dir = path.join(freshDir(), "ledgers", "nested"); + const lock = acquireMainnetRunLock(dir); + const file = path.join(dir, MAINNET_RUN_LOCK_FILE); + assert.equal(lock.path, file); + assert.equal(MAINNET_RUN_LOCK_FILE, "wasit-mainnet.lock"); + assert.ok(existsSync(file)); + const content = JSON.parse(readFileSync(file, "utf8")) as Record; + assert.equal(content["wasit"], "mainnet-run-lock"); + assert.equal(content["pid"], process.pid); + assert.match(String(content["startedAt"]), /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/); + assert.equal(typeof content["token"], "string"); + if (POSIX) assert.equal(statSync(file).mode & 0o777, 0o600); + lock.release(); + assert.ok(!existsSync(file), "release left the lock file"); + }); + + it("refuses a second run while the first holds it, and leaves the first one's lock as it was", () => { + const dir = freshDir(); + const first = acquireMainnetRunLock(dir); + const before = readFileSync(first.path, "utf8"); + const error = refused(dir); + assert.equal(error.holder, "running"); + assert.equal(error.lockPath, first.path); + assert.ok(error.message.includes(`process ${process.pid}`), error.message); + assert.match(error.message, /One mainnet run at a time on this machine/); + assert.match(error.message, /\$5\.00/); + assert.match(error.message, /Nothing was signed\./); + assert.equal(readFileSync(first.path, "utf8"), before, "the refused run changed the lock"); + first.release(); + assert.ok(!existsSync(first.path)); + acquireMainnetRunLock(dir).release(); + }); + + it("can be released more than once, and after the file is gone", () => { + const dir = freshDir(); + const lock = acquireMainnetRunLock(dir); + lock.release(); + lock.release(); + const again = acquireMainnetRunLock(dir); + unlinkSync(again.path); + again.release(); + }); + + it("is not deleted on release when the file there is no longer this run's", () => { + const dir = freshDir(); + const lock = acquireMainnetRunLock(dir); + writeFileSync(lock.path, lockText(process.pid, "another-run")); + lock.release(); + assert.ok(existsSync(lock.path), "release deleted a lock that was not its own"); + }); + + it("refuses a lock left by a process that has ended, and leaves it for a person to read and delete", async () => { + const dir = freshDir(); + const pid = await endedPid(); + const file = path.join(dir, MAINNET_RUN_LOCK_FILE); + writeFileSync(file, lockText(pid)); + const error = refused(dir); + assert.equal(error.holder, "gone"); + assert.ok(error.message.includes(`process ${pid}`), error.message); + assert.match(error.message, /no longer running/); + assert.match(error.message, /authorizations it signed may still be open/); + assert.match(error.message, /ledger/); + assert.match(error.message, /then delete/); + assert.match(error.message, /Nothing was signed\./); + assert.equal(readFileSync(file, "utf8"), lockText(pid), "the lock was taken over"); + }); + + it("refuses a file there that is not a lock it can read, and leaves it", () => { + for (const text of ["", "not json", "{}", JSON.stringify({ wasit: "mainnet-run-lock", pid: -1 }), JSON.stringify({ wasit: "other", pid: process.pid }), JSON.stringify({ wasit: "mainnet-run-lock", pid: "12" }), "x".repeat(10_000)]) { + const dir = freshDir(); + const file = path.join(dir, MAINNET_RUN_LOCK_FILE); + writeFileSync(file, text); + const error = refused(dir); + assert.equal(error.holder, "unknown", JSON.stringify(text.slice(0, 40))); + assert.match(error.message, /not a lock Wasit can read/); + assert.match(error.message, /Nothing was signed\./); + assert.equal(readFileSync(file, "utf8"), text, "the file was changed"); + } + }); + + it("reads a lock as Wasit's only when every field is: one field off makes it unknown, and nothing odd is echoed", () => { + const valid = { wasit: "mainnet-run-lock", pid: process.pid, startedAt: "2026-11-21T10:00:00.000Z", token: "t" }; + const cases: Array<[string, string]> = [ + ["another tag", JSON.stringify({ ...valid, wasit: "other" })], + ["pid 0 (the process group)", JSON.stringify({ ...valid, pid: 0 })], + ["a negative pid", JSON.stringify({ ...valid, pid: -1 })], + ["a pid as text", JSON.stringify({ ...valid, pid: String(process.pid) })], + ["a start time in another shape", JSON.stringify({ ...valid, startedAt: "\u001b]0;x\u0007" })], + ["no token", JSON.stringify({ ...valid, token: undefined })], + ["larger than a lock", `${JSON.stringify(valid)}${" ".repeat(5000)}`], + ]; + for (const [label, text] of cases) { + const dir = freshDir(); + writeFileSync(path.join(dir, MAINNET_RUN_LOCK_FILE), text); + const error = refused(dir); + assert.equal(error.holder, "unknown", label); + // eslint-disable-next-line no-control-regex + assert.ok(!/[\u0000-\u001f\u007f]/.test(error.message), `${label}: a control character reached the message`); + } + // The control: the same lock with every field right reads as held by this process. + const dir = freshDir(); + writeFileSync(path.join(dir, MAINNET_RUN_LOCK_FILE), JSON.stringify(valid)); + assert.equal(refused(dir).holder, "running"); + }); + + it("reads a lock of a process it may not signal (EPERM) as running", { skip: !POSIX || process.getuid?.() === 0 }, () => { + const dir = freshDir(); + writeFileSync(path.join(dir, MAINNET_RUN_LOCK_FILE), lockText(1)); + assert.equal(refused(dir).holder, "running"); + }); + + it("does not read a lock through a symbolic link, even to a valid lock", { skip: !POSIX }, () => { + const dir = freshDir(); + const target = path.join(dir, "elsewhere.lock"); + writeFileSync(target, lockText(process.pid)); + symlinkSync(target, path.join(dir, MAINNET_RUN_LOCK_FILE)); + assert.equal(refused(dir).holder, "unknown"); + }); + + it("refuses a directory in the lock's place", () => { + const dir = freshDir(); + mkdirSync(path.join(dir, MAINNET_RUN_LOCK_FILE)); + assert.equal(refused(dir).holder, "unknown"); + }); + + it("refuses a symbolic link in the lock's place and never writes through it", { skip: !POSIX }, () => { + const dir = freshDir(); + const target = path.join(dir, "elsewhere.txt"); + writeFileSync(target, "untouched"); + symlinkSync(target, path.join(dir, MAINNET_RUN_LOCK_FILE)); + assert.equal(refused(dir).holder, "unknown"); + assert.equal(readFileSync(target, "utf8"), "untouched"); + assert.ok(lstatSync(path.join(dir, MAINNET_RUN_LOCK_FILE)).isSymbolicLink()); + // A dangling link is refused the same way, and nothing is created at its target. + rmSync(target); + assert.equal(refused(dir).holder, "unknown"); + assert.ok(!existsSync(target), "the lock was written through a dangling link"); + }); + + it("refuses to start when the lock cannot be created, as a setup problem, not a held lock", () => { + const parent = freshDir(); + const notADir = path.join(parent, "file"); + writeFileSync(notADir, "a file where the folder should be"); + let error: unknown; + try { + acquireMainnetRunLock(notADir); + } catch (caught) { + error = caught; + } + assert.ok(error instanceof ConfigurationError, `not a ConfigurationError: ${String(error)}`); + assert.ok(!(error instanceof MainnetRunLockedError), "a lock that could not be created read as a held one"); + assert.match(error.message, /could not be created/); + assert.match(error.message, /Nothing was signed\./); + }); + + it("refuses to start in a folder it cannot write to", { skip: !POSIX || process.getuid?.() === 0 }, () => { + const dir = freshDir(); + chmodSync(dir, 0o500); + assert.throws(() => acquireMainnetRunLock(dir), (error: unknown) => error instanceof ConfigurationError && !(error instanceof MainnetRunLockedError) && /could not be created/.test(error.message)); + chmodSync(dir, 0o700); + assert.ok(!existsSync(path.join(dir, MAINNET_RUN_LOCK_FILE))); + }); + + it("keeps control characters of the folder's name out of the message", { skip: !POSIX }, () => { + const dir = path.join(freshDir(), "a\u001b]0;x\u0007b"); + mkdirSync(dir); + const first = acquireMainnetRunLock(dir); + const error = refused(dir); + // eslint-disable-next-line no-control-regex + assert.ok(!/[\u0000-\u001f\u007f]/.test(error.message), "a control character reached the message"); + first.release(); + }); + + it("adds one exit listener while held and removes it on release", () => { + const before = process.listenerCount("exit"); + const lock = acquireMainnetRunLock(freshDir()); + assert.equal(process.listenerCount("exit"), before + 1); + lock.release(); + assert.equal(process.listenerCount("exit"), before); + // A refused run adds none. + const held = acquireMainnetRunLock(freshDir()); + const count = process.listenerCount("exit"); + refused(path.dirname(held.path)); + assert.equal(process.listenerCount("exit"), count); + held.release(); + }); + + it("is released when the process exits without calling release", async () => { + const dir = freshDir(); + const { done } = runScript( + dir, + `import { acquireMainnetRunLock } from ${JSON.stringify(MODULE)};\n` + + `acquireMainnetRunLock(${JSON.stringify(dir)});\nconsole.log("held");\nprocess.exitCode = 0;\n`, + ); + const { code, stdout } = await done; + assert.equal(code, 0); + assert.match(stdout, /held/); + assert.ok(!existsSync(path.join(dir, MAINNET_RUN_LOCK_FILE)), "the exit left the lock file"); + }); + + it("is left behind by a process that is killed, and the next run is refused with 'no longer running'", { skip: !POSIX }, async () => { + const dir = freshDir(); + const { done, child } = runScript( + dir, + `import { acquireMainnetRunLock } from ${JSON.stringify(MODULE)};\n` + + `acquireMainnetRunLock(${JSON.stringify(dir)});\nconsole.log("held");\nsetInterval(() => {}, 1000);\n`, + ); + await new Promise((resolve) => { + child.stdout!.on("data", (chunk: Buffer) => { + if (chunk.toString().includes("held")) resolve(); + }); + }); + child.kill("SIGKILL"); + await done; + assert.ok(existsSync(path.join(dir, MAINNET_RUN_LOCK_FILE)), "a killed run removed its lock"); + assert.equal(refused(dir).holder, "gone"); + }); + + it("lets exactly one of several runs started at once take it", async () => { + const dir = freshDir(); + const source = + `import { acquireMainnetRunLock, MainnetRunLockedError } from ${JSON.stringify(MODULE)};\n` + + `try { const lock = acquireMainnetRunLock(${JSON.stringify(dir)}); console.log("won"); ` + + `setTimeout(() => lock.release(), 4000); } catch (error) { ` + + `console.log(error instanceof MainnetRunLockedError ? "refused" : "other " + String(error)); }\n`; + const runs = Array.from({ length: 4 }, () => runScript(dir, source).done); + const outputs = (await Promise.all(runs)).map((run) => run.stdout.trim()); + assert.equal(outputs.filter((line) => line === "won").length, 1, outputs.join(" | ")); + assert.equal(outputs.filter((line) => line === "refused").length, 3, outputs.join(" | ")); + assert.ok(!existsSync(path.join(dir, MAINNET_RUN_LOCK_FILE)), "the winner's release left the lock"); + }); +});