@wasit-dev/core 0.8.0-beta.1 → 0.8.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.js +3 -1
  3. package/dist/check.d.ts +1 -1
  4. package/dist/ci-report.js +15 -7
  5. package/dist/config-writer.d.ts +96 -0
  6. package/dist/config-writer.js +281 -0
  7. package/dist/guard/budget.d.ts +6 -3
  8. package/dist/guard/budget.js +10 -3
  9. package/dist/guard/ci-event.d.ts +6 -0
  10. package/dist/guard/ci-event.js +7 -3
  11. package/dist/guard/ci-mainnet.d.ts +59 -0
  12. package/dist/guard/ci-mainnet.js +149 -0
  13. package/dist/guard/horizon.d.ts +30 -0
  14. package/dist/guard/horizon.js +107 -0
  15. package/dist/guard/mainnet-payer.d.ts +66 -0
  16. package/dist/guard/mainnet-payer.js +92 -0
  17. package/dist/guard/mainnet-plan.d.ts +133 -0
  18. package/dist/guard/mainnet-plan.js +208 -0
  19. package/dist/guard/mainnet-run.d.ts +87 -0
  20. package/dist/guard/mainnet-run.js +225 -0
  21. package/dist/guard/networks.d.ts +9 -8
  22. package/dist/guard/networks.js +21 -10
  23. package/dist/guard/optin.d.ts +106 -0
  24. package/dist/guard/optin.js +202 -0
  25. package/dist/guard/run-ledger.d.ts +212 -0
  26. package/dist/guard/run-ledger.js +426 -0
  27. package/dist/guard/run-lock.d.ts +62 -0
  28. package/dist/guard/run-lock.js +172 -0
  29. package/dist/guard/signed-terms.d.ts +96 -0
  30. package/dist/guard/signed-terms.js +207 -0
  31. package/dist/index.d.ts +18 -7
  32. package/dist/index.js +19 -5
  33. package/dist/mpp/channel-credential.d.ts +13 -1
  34. package/dist/mpp/channel-credential.js +18 -2
  35. package/dist/mpp/channel.d.ts +6 -0
  36. package/dist/mpp/channel.js +7 -3
  37. package/dist/mpp/charge.d.ts +31 -1
  38. package/dist/mpp/charge.js +74 -20
  39. package/dist/mpp/plan.d.ts +77 -0
  40. package/dist/mpp/plan.js +188 -0
  41. package/dist/mpp/suite.d.ts +6 -0
  42. package/dist/mpp/suite.js +2 -1
  43. package/dist/route-reader.d.ts +124 -0
  44. package/dist/route-reader.js +349 -0
  45. package/dist/wallet.d.ts +58 -1
  46. package/dist/wallet.js +128 -0
  47. package/dist/x402/chains/stellar.js +134 -3
  48. package/dist/x402/chains/types.d.ts +36 -2
  49. package/dist/x402/plan.d.ts +102 -0
  50. package/dist/x402/plan.js +380 -6
  51. package/dist/x402/rejected-request.d.ts +10 -0
  52. package/dist/x402/rejected-request.js +18 -0
  53. package/dist/x402/simulator.d.ts +34 -0
  54. package/dist/x402/simulator.js +452 -46
  55. package/package.json +1 -1
  56. package/dist/guard/mainnet-optin.d.ts +0 -58
  57. package/dist/guard/mainnet-optin.js +0 -95
@@ -0,0 +1,426 @@
1
+ /**
2
+ * The run ledger (spec B5, safety rule 6): a file a paying run keeps beside
3
+ * it, so that a person can compare what Wasit signed with what the chain
4
+ * shows, also after a crash (B10 T13).
5
+ *
6
+ * One file per run, `wasit-ledger-<UTC time>.json`, created new and never
7
+ * overwritten. Every change rewrites it whole: to a temporary file, flushed to
8
+ * disk, then renamed over the ledger, so the file is valid JSON at every
9
+ * moment a process can be killed.
10
+ *
11
+ * One entry per signature (B-A03). Its intent (check, endpoint, amount,
12
+ * payee, asset) is written and flushed after the run is charged and BEFORE
13
+ * the key is asked to sign: a ledger that cannot take it stops the payment,
14
+ * with nothing signed. Then what became of it: signed, with the ledger its
15
+ * authorization expires at (decoded from what the key signed); not signed;
16
+ * or unknown (the client failed after it may have signed). Then discarded
17
+ * unsent, or sent with the answer's status, and the settlement if any. An
18
+ * entry with no outcome reads as "assume signed and sent".
19
+ *
20
+ * Each entry also takes the verdict of the check it belongs to, once that
21
+ * check has one. Balances before and after the run (USDC and XLM) close it,
22
+ * with whether they are consistent with what the ledger says settled:
23
+ * consistent, explained (the payer paid more than the settlements the run
24
+ * verified, but no more than the payments of checks that FAILed, which a
25
+ * service that takes what it should refuse may have settled), or
26
+ * inconsistent.
27
+ *
28
+ * No secret: the payer is named by its public address, the RPC by its origin,
29
+ * and free text is cut, with anything shaped like a Stellar secret or a 64-hex
30
+ * value in it masked. Works on every network; on mainnet it is not optional
31
+ * (B5).
32
+ */
33
+ import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
34
+ import { basename, dirname, join } from "node:path";
35
+ import { CheckSetupError } from "../errors.js";
36
+ import { sanitizeText } from "../sanitize.js";
37
+ /** The `format` field of every run ledger. */
38
+ export const RUN_LEDGER_FORMAT = "wasit-run-ledger";
39
+ const LEDGER_VERSION = 1;
40
+ /** The longest free text an entry keeps. */
41
+ const MAX_NOTE = 300;
42
+ /** `wasit-ledger-<UTC time>.json`, colons replaced: some file systems refuse them. */
43
+ export function runLedgerFileName(at) {
44
+ return `wasit-ledger-${at.toISOString().replace(/:/g, "-")}.json`;
45
+ }
46
+ /** The run ledger cannot be written, or was asked something out of order. A setup error: no verdict. */
47
+ export class RunLedgerError extends CheckSetupError {
48
+ constructor(message) {
49
+ super(message);
50
+ this.name = "RunLedgerError";
51
+ }
52
+ }
53
+ /**
54
+ * Free text for the file: one line, no control characters, nothing shaped like
55
+ * a key (the sanitiser masks a Stellar secret's shape; a 64-hex value is masked
56
+ * here), at most 300 characters.
57
+ */
58
+ function note(text) {
59
+ return sanitizeText(String(text))
60
+ .replace(/(?<![0-9a-fA-F])[0-9a-fA-F]{64}(?![0-9a-fA-F])/g, "[64-hex value masked]")
61
+ .replace(/\s+/g, " ")
62
+ .slice(0, MAX_NOTE);
63
+ }
64
+ function json(value) {
65
+ return `${JSON.stringify(value, (_key, item) => (typeof item === "bigint" ? item.toString() : item), 2)}\n`;
66
+ }
67
+ function errorCode(error) {
68
+ const code = error?.code;
69
+ return typeof code === "string" && /^[A-Z0-9_]{1,32}$/.test(code) ? ` (${code})` : "";
70
+ }
71
+ /**
72
+ * The ledger of one paying run. Create it before the first signature; hand
73
+ * {@link RunLedger.forEndpoint} to each endpoint's payment checks; close it
74
+ * once every authorization has expired and the balances after are read.
75
+ */
76
+ export class RunLedger {
77
+ path;
78
+ #header;
79
+ #now;
80
+ #openedAt;
81
+ #entries = [];
82
+ #before;
83
+ #after;
84
+ #result;
85
+ #closedAt;
86
+ constructor(path, header, now) {
87
+ this.path = path;
88
+ this.#header = header;
89
+ this.#now = now;
90
+ this.#openedAt = now().toISOString();
91
+ }
92
+ /**
93
+ * Creates the ledger in `dir` (made if missing), named after now, holding the
94
+ * header. Refuses a name that exists: a ledger is never overwritten.
95
+ */
96
+ static create(dir, header, options = {}) {
97
+ let origin;
98
+ try {
99
+ origin = new URL(header.rpc).origin;
100
+ }
101
+ catch {
102
+ origin = undefined;
103
+ }
104
+ if (origin !== header.rpc) {
105
+ throw new RunLedgerError("The run ledger names the RPC by its origin only, and was given more than an origin. Nothing was signed.");
106
+ }
107
+ const now = options.now ?? (() => new Date());
108
+ const at = now();
109
+ const path = join(dir, runLedgerFileName(at));
110
+ const ledger = new RunLedger(path, header, () => now());
111
+ let fd;
112
+ try {
113
+ mkdirSync(dir, { recursive: true });
114
+ fd = openSync(path, "wx", 0o644);
115
+ writeSync(fd, json(ledger.#document()));
116
+ fsyncSync(fd);
117
+ }
118
+ catch (error) {
119
+ throw new RunLedgerError(`The run ledger ${basename(path)} could not be created${errorCode(error)}. Nothing was signed.`);
120
+ }
121
+ finally {
122
+ if (fd !== undefined)
123
+ closeSync(fd);
124
+ }
125
+ syncDirectory(dir);
126
+ return ledger;
127
+ }
128
+ /** The entries so far, as the file holds them. */
129
+ get entries() {
130
+ return this.#entries.map((entry) => structuredClone(entry));
131
+ }
132
+ /** The payment ledger of one endpoint's checks. */
133
+ forEndpoint(endpoint) {
134
+ const name = note(endpoint);
135
+ return {
136
+ intent: (entry) => this.#intent(endpoint, entry),
137
+ verdict: (check, verdict) => this.#verdict(name, check, verdict),
138
+ };
139
+ }
140
+ /** The payer's balances before the first signature, and where they were read. */
141
+ recordBalancesBefore(balances, source) {
142
+ this.#assertOpen();
143
+ this.#before = this.#readings(balances, source);
144
+ this.#flush();
145
+ }
146
+ /**
147
+ * Closes the ledger with the balances after the run (undefined when they
148
+ * could not be read): writes whether they are consistent with what the
149
+ * ledger says settled, and returns it.
150
+ */
151
+ close(input = {}) {
152
+ this.#assertOpen();
153
+ if (input.after !== undefined)
154
+ this.#after = this.#readings(input.after, input.source ?? "");
155
+ const before = this.#before === undefined ? undefined : { usdc: BigInt(this.#before.usdc), native: BigInt(this.#before.native) };
156
+ const result = ledgerConsistency(before, input.after, this.entries);
157
+ this.#result = { result: result.result, reasons: result.reasons };
158
+ this.#closedAt = this.#now().toISOString();
159
+ this.#flush();
160
+ return result;
161
+ }
162
+ #readings(balances, source) {
163
+ return { usdc: balances.usdc.toString(), native: balances.native.toString(), source: note(source), at: this.#now().toISOString() };
164
+ }
165
+ #assertOpen() {
166
+ if (this.#closedAt !== undefined)
167
+ throw new RunLedgerError("The run ledger is closed and takes nothing more.");
168
+ }
169
+ #intent(endpoint, input) {
170
+ this.#assertOpen();
171
+ if (typeof input.amount !== "string" || !/^[0-9]{1,78}$/.test(input.amount)) {
172
+ throw new RunLedgerError("The run ledger takes a whole number of base units only. Nothing was signed.");
173
+ }
174
+ const entry = {
175
+ id: this.#entries.length + 1,
176
+ endpoint: note(endpoint),
177
+ check: note(input.check),
178
+ network: note(input.network),
179
+ asset: note(input.asset),
180
+ payTo: note(input.payTo),
181
+ amount: input.amount,
182
+ intentAt: this.#now().toISOString(),
183
+ state: "intent",
184
+ };
185
+ this.#entries.push(entry);
186
+ try {
187
+ this.#flush();
188
+ }
189
+ catch (error) {
190
+ this.#entries.pop();
191
+ throw new RunLedgerError(`${error.message} Nothing was signed.`);
192
+ }
193
+ return this.#handle(entry);
194
+ }
195
+ #verdict(endpoint, check, verdict) {
196
+ this.#assertOpen();
197
+ if (!LEDGER_VERDICTS.has(verdict))
198
+ throw new RunLedgerError("The run ledger takes a check's verdict as pass, fail, no-verdict or skipped.");
199
+ const id = note(check);
200
+ let changed = false;
201
+ for (const entry of this.#entries) {
202
+ if (entry.endpoint === endpoint && entry.check === id && entry.verdict === undefined) {
203
+ entry.verdict = verdict;
204
+ changed = true;
205
+ }
206
+ }
207
+ if (changed)
208
+ this.#flush();
209
+ }
210
+ #handle(entry) {
211
+ const outcome = (state, fields) => {
212
+ if (entry.state !== "intent") {
213
+ throw new RunLedgerError(`The run ledger already has an outcome for ${entry.check} (entry ${entry.id}).`);
214
+ }
215
+ Object.assign(entry, { state, ...fields });
216
+ this.#flush();
217
+ };
218
+ const afterSigning = (what) => {
219
+ if (entry.state !== "signed")
220
+ throw new RunLedgerError(`The run ledger has no signature to record ${what} for (entry ${entry.id}).`);
221
+ };
222
+ return {
223
+ signed: (expiresAtLedger) => outcome("signed", {
224
+ signedAt: this.#now().toISOString(),
225
+ expiresAtLedger: typeof expiresAtLedger === "number" && Number.isSafeInteger(expiresAtLedger) ? expiresAtLedger : null,
226
+ }),
227
+ notSigned: (reason) => outcome("not-signed", { note: note(reason) }),
228
+ unknown: (reason) => outcome("unknown", { note: note(reason) }),
229
+ discarded: (reason) => {
230
+ afterSigning("a discard");
231
+ if (entry.discarded !== undefined || entry.sent !== undefined) {
232
+ throw new RunLedgerError(`The run ledger already has ${entry.check} (entry ${entry.id}) discarded or sent.`);
233
+ }
234
+ entry.discarded = note(reason);
235
+ this.#flush();
236
+ },
237
+ sent: (result) => {
238
+ afterSigning("a send");
239
+ if (entry.discarded !== undefined || entry.sent !== undefined) {
240
+ throw new RunLedgerError(`The run ledger already has ${entry.check} (entry ${entry.id}) discarded or sent.`);
241
+ }
242
+ entry.sent =
243
+ "status" in result
244
+ ? { at: this.#now().toISOString(), status: result.status }
245
+ : { at: this.#now().toISOString(), error: note(result.error) };
246
+ this.#flush();
247
+ },
248
+ settled: (reference, verified) => {
249
+ if (entry.sent === undefined || entry.settlement !== undefined) {
250
+ throw new RunLedgerError(`The run ledger has no send to record a settlement for (entry ${entry.id}), or has one already.`);
251
+ }
252
+ // A settlement reference is a public transaction hash (64 hex on Stellar): kept as it is, never masked,
253
+ // so a person can look it up; still one bounded line.
254
+ entry.settlement = { reference: sanitizeText(String(reference)).replace(/\s+/g, "").slice(0, 128), verified: verified === true };
255
+ this.#flush();
256
+ },
257
+ };
258
+ }
259
+ #document() {
260
+ const header = this.#header;
261
+ return {
262
+ format: RUN_LEDGER_FORMAT,
263
+ version: LEDGER_VERSION,
264
+ openedAt: this.#openedAt,
265
+ versions: header.versions,
266
+ environment: note(header.environment),
267
+ network: note(header.network),
268
+ payer: note(header.payer),
269
+ ...(header.pin === undefined ? {} : { pin: { payTo: note(header.pin.payTo), asset: note(header.pin.asset) } }),
270
+ caps: header.caps,
271
+ rpc: header.rpc,
272
+ plan: header.plan,
273
+ ...(this.#before === undefined ? {} : { balancesBefore: this.#before }),
274
+ entries: this.#entries,
275
+ ...(this.#after === undefined ? {} : { balancesAfter: this.#after }),
276
+ result: this.#result === undefined ? "open" : this.#result.result,
277
+ ...(this.#result === undefined ? {} : { reasons: this.#result.reasons }),
278
+ ...(this.#closedAt === undefined ? {} : { closedAt: this.#closedAt }),
279
+ };
280
+ }
281
+ /** The whole file, rewritten: temporary file, flushed, renamed over the ledger. */
282
+ #flush() {
283
+ const tmp = `${this.path}.tmp`;
284
+ let fd;
285
+ try {
286
+ rmSync(tmp, { force: true });
287
+ fd = openSync(tmp, "wx", 0o644);
288
+ writeSync(fd, json(this.#document()));
289
+ fsyncSync(fd);
290
+ closeSync(fd);
291
+ fd = undefined;
292
+ renameSync(tmp, this.path);
293
+ }
294
+ catch (error) {
295
+ if (fd !== undefined) {
296
+ try {
297
+ closeSync(fd);
298
+ }
299
+ catch {
300
+ // closed either way
301
+ }
302
+ }
303
+ try {
304
+ rmSync(tmp, { force: true });
305
+ }
306
+ catch {
307
+ // nothing more to clean
308
+ }
309
+ throw new RunLedgerError(`The run ledger ${basename(this.path)} could not be written${errorCode(error)}.`);
310
+ }
311
+ syncDirectory(dirname(this.path));
312
+ }
313
+ }
314
+ /** Flushes a folder's entry list, where the platform allows it (not on Windows). */
315
+ function syncDirectory(dir) {
316
+ let fd;
317
+ try {
318
+ fd = openSync(dir, "r");
319
+ fsyncSync(fd);
320
+ }
321
+ catch {
322
+ // Best effort: the file itself was flushed.
323
+ }
324
+ finally {
325
+ if (fd !== undefined) {
326
+ try {
327
+ closeSync(fd);
328
+ }
329
+ catch {
330
+ // closed either way
331
+ }
332
+ }
333
+ }
334
+ }
335
+ const LEDGER_VERDICTS = new Set(["pass", "fail", "no-verdict", "skipped"]);
336
+ /** An entry that holds a signature, or may: everything but "not-signed". */
337
+ function maySign(entry) {
338
+ return entry.state !== "not-signed";
339
+ }
340
+ /** An entry whose payment may have reached the service: it may be signed, and was not discarded unsent. */
341
+ function maySend(entry) {
342
+ return maySign(entry) && entry.discarded === undefined;
343
+ }
344
+ /**
345
+ * Whether the payer's balances moved as the ledger says (see
346
+ * {@link LedgerResult}). On Stellar the facilitator pays the fees and Wasit
347
+ * sends no transaction from the payer, so its XLM must not move. The USDC
348
+ * the run verified settled is the sum of the entries whose settlement it read
349
+ * back from the chain. More than that is explained only by the entries, sent
350
+ * and not verified, of checks that FAILed: a check with no verdict, a SKIP or
351
+ * a PASS explains nothing, and neither does a payment discarded unsent. The
352
+ * reasons also name every entry with no recorded outcome, which is read as
353
+ * signed and sent.
354
+ */
355
+ export function ledgerConsistency(before, after, entries) {
356
+ const reasons = [];
357
+ for (const entry of entries) {
358
+ if (entry.state === "intent" || entry.state === "unknown") {
359
+ reasons.push(`${entry.check} of ${entry.endpoint} (entry ${entry.id}) has no recorded signature outcome: assume it was signed and sent.`);
360
+ }
361
+ else if (entry.state === "signed" && entry.sent === undefined && entry.discarded === undefined) {
362
+ reasons.push(`${entry.check} of ${entry.endpoint} (entry ${entry.id}) was signed and has no recorded send: assume it was sent.`);
363
+ }
364
+ }
365
+ const settledUsdc = entries
366
+ .filter((entry) => entry.settlement?.verified === true)
367
+ .reduce((sum, entry) => sum + BigInt(entry.amount), 0n);
368
+ const inconsistent = (lines, spentUsdc) => ({
369
+ result: "inconsistent",
370
+ consistent: false,
371
+ reasons: [...lines, ...reasons],
372
+ ...(spentUsdc === undefined ? {} : { spentUsdc }),
373
+ settledUsdc,
374
+ });
375
+ if (before === undefined || after === undefined) {
376
+ return inconsistent(["The payer's balances before and after the run were not both read."]);
377
+ }
378
+ const spentUsdc = before.usdc - after.usdc;
379
+ const problems = [];
380
+ if (before.native !== after.native) {
381
+ problems.push(`The payer's XLM changed by ${after.native - before.native} stroops; Wasit sends no transaction from the payer.`);
382
+ }
383
+ const gap = spentUsdc - settledUsdc;
384
+ const failed = entries.filter((entry) => maySend(entry) && entry.settlement?.verified !== true && entry.verdict === "fail");
385
+ const failedUsdc = failed.reduce((sum, entry) => sum + BigInt(entry.amount), 0n);
386
+ const explained = gap > 0n && gap <= failedUsdc;
387
+ if (gap !== 0n && !explained) {
388
+ problems.push(`The payer's USDC went down by ${spentUsdc} base units, and the settlements this run verified add up to ${settledUsdc}` +
389
+ (gap > 0n && failedUsdc > 0n ? `; the payments of the checks that FAILed add up to only ${failedUsdc} more.` : "."));
390
+ }
391
+ if (problems.length > 0)
392
+ return inconsistent(problems, spentUsdc);
393
+ if (!explained)
394
+ return { result: "consistent", consistent: true, reasons, spentUsdc, settledUsdc };
395
+ return {
396
+ result: "explained",
397
+ consistent: false,
398
+ reasons: [
399
+ `The payer's USDC went down by ${spentUsdc} base units: ${settledUsdc} in the settlements this run verified, and ` +
400
+ `${gap} more, within the ${failedUsdc} of payments sent for checks that FAILed (` +
401
+ failed.map((entry) => `${entry.check} of ${entry.endpoint}, entry ${entry.id}, ${entry.amount}`).join("; ") +
402
+ `): the service settled payments it should have refused. Its XLM did not move.`,
403
+ ...reasons,
404
+ ],
405
+ spentUsdc,
406
+ settledUsdc,
407
+ };
408
+ }
409
+ /**
410
+ * Until when the run's authorizations may be open (L4): the latest expiry of
411
+ * every entry that holds a signature or may, and how many of those have no
412
+ * known expiry (the caller then waits the longest a signature may live).
413
+ */
414
+ export function openAuthorizationsUntil(entries) {
415
+ let latest;
416
+ let unknown = 0;
417
+ for (const entry of entries) {
418
+ if (!maySign(entry))
419
+ continue;
420
+ if (typeof entry.expiresAtLedger === "number")
421
+ latest = latest === undefined ? entry.expiresAtLedger : Math.max(latest, entry.expiresAtLedger);
422
+ else
423
+ unknown += 1;
424
+ }
425
+ return { latest, unknown };
426
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The lock file of a mainnet run (spec B4, B17.5).
3
+ *
4
+ * The caps hold one run to $5 (`budget.ts`). A second mainnet run started on
5
+ * the same machine while one is open would get its own $5. So a mainnet run
6
+ * takes this lock in its ledger's folder before it reads its payer's balance,
7
+ * and a run that finds a lock there does not start.
8
+ *
9
+ * Any file in the lock's place refuses the run, whoever left it: a run that is
10
+ * still open; a run that was stopped or crashed, whose authorizations may still
11
+ * be open, so a person reads its ledger before deleting the file; or a file
12
+ * that is not a lock Wasit can read. No run takes over or deletes another's
13
+ * lock. The file is created exclusively (it fails when anything is at its path,
14
+ * a symbolic link included), so two runs started at once cannot both take it.
15
+ *
16
+ * What it does not see: a run on another machine or runner, and a run whose
17
+ * ledger is in another folder (spec B4). The payer account's $10
18
+ * (`mainnet-payer.ts`) is the limit there.
19
+ *
20
+ * The opt-in (`openMainnetOptIn`) takes the lock before L1, and its close
21
+ * (`closeMainnetRun`) releases it when the run has ended.
22
+ */
23
+ import { ConfigurationError } from "../errors.js";
24
+ /** The lock's name in the ledger's folder. */
25
+ export declare const MAINNET_RUN_LOCK_FILE = "wasit-mainnet.lock";
26
+ /** Who holds the lock a run found. */
27
+ export type LockHolder =
28
+ /** A process that is still running. */
29
+ "running"
30
+ /** A process that has ended without releasing it. */
31
+ | "gone"
32
+ /** The file is not a lock Wasit can read. */
33
+ | "unknown";
34
+ /**
35
+ * A mainnet run does not start: a lock is already in its ledger's folder. A
36
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
37
+ */
38
+ export declare class MainnetRunLockedError extends ConfigurationError {
39
+ readonly lockPath: string;
40
+ readonly holder: LockHolder;
41
+ constructor(lockPath: string, holder: LockHolder, message: string);
42
+ }
43
+ /** A lock this run holds. */
44
+ export interface MainnetRunLock {
45
+ /** The lock file. */
46
+ readonly path: string;
47
+ /**
48
+ * Deletes the lock file when it is still this run's. Safe to call more than
49
+ * once, and after the file is gone. It is also called when the process exits
50
+ * (`exit`), but not when the process is killed: then the file stays, and the
51
+ * next run is refused until a person deletes it.
52
+ */
53
+ release(): void;
54
+ }
55
+ /**
56
+ * Takes the lock of a mainnet run in `dir`, the folder of the run's ledger,
57
+ * creating the folder when it is missing.
58
+ *
59
+ * @throws {MainnetRunLockedError} When anything is already at the lock's path.
60
+ * @throws {ConfigurationError} When the lock cannot be created.
61
+ */
62
+ export declare function acquireMainnetRunLock(dir: string): MainnetRunLock;
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The lock file of a mainnet run (spec B4, B17.5).
3
+ *
4
+ * The caps hold one run to $5 (`budget.ts`). A second mainnet run started on
5
+ * the same machine while one is open would get its own $5. So a mainnet run
6
+ * takes this lock in its ledger's folder before it reads its payer's balance,
7
+ * and a run that finds a lock there does not start.
8
+ *
9
+ * Any file in the lock's place refuses the run, whoever left it: a run that is
10
+ * still open; a run that was stopped or crashed, whose authorizations may still
11
+ * be open, so a person reads its ledger before deleting the file; or a file
12
+ * that is not a lock Wasit can read. No run takes over or deletes another's
13
+ * lock. The file is created exclusively (it fails when anything is at its path,
14
+ * a symbolic link included), so two runs started at once cannot both take it.
15
+ *
16
+ * What it does not see: a run on another machine or runner, and a run whose
17
+ * ledger is in another folder (spec B4). The payer account's $10
18
+ * (`mainnet-payer.ts`) is the limit there.
19
+ *
20
+ * The opt-in (`openMainnetOptIn`) takes the lock before L1, and its close
21
+ * (`closeMainnetRun`) releases it when the run has ended.
22
+ */
23
+ import { randomUUID } from "node:crypto";
24
+ import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
25
+ import path from "node:path";
26
+ import { ConfigurationError } from "../errors.js";
27
+ import { sanitizeText } from "../sanitize.js";
28
+ import { PER_RUN_CAP_USD, formatUsd, usdFromDollars } from "./budget.js";
29
+ /** The lock's name in the ledger's folder. */
30
+ export const MAINNET_RUN_LOCK_FILE = "wasit-mainnet.lock";
31
+ /** What the lock file says it is. */
32
+ const TAG = "mainnet-run-lock";
33
+ /** A lock Wasit writes is far smaller; a larger file is not read. */
34
+ const MAX_LOCK_BYTES = 4096;
35
+ /** A start time as `Date.toISOString` writes it; anything else is never echoed. */
36
+ const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
37
+ /** An error code as Node writes them; anything else is never echoed. */
38
+ const ERROR_CODE = /^E[A-Z]{2,20}$/;
39
+ /**
40
+ * A mainnet run does not start: a lock is already in its ledger's folder. A
41
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
42
+ */
43
+ export class MainnetRunLockedError extends ConfigurationError {
44
+ lockPath;
45
+ holder;
46
+ constructor(lockPath, holder, message) {
47
+ super(`${message} Nothing was signed.`);
48
+ this.name = "MainnetRunLockedError";
49
+ this.lockPath = lockPath;
50
+ this.holder = holder;
51
+ }
52
+ }
53
+ /** The lock at `file`, when it is a regular file Wasit wrote; undefined otherwise. */
54
+ function readLock(file) {
55
+ try {
56
+ const stat = lstatSync(file);
57
+ if (!stat.isFile() || stat.size > MAX_LOCK_BYTES)
58
+ return undefined;
59
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
60
+ if (typeof parsed !== "object" || parsed === null)
61
+ return undefined;
62
+ const { wasit, pid, startedAt, token } = parsed;
63
+ if (wasit !== TAG || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
64
+ return undefined;
65
+ if (typeof startedAt !== "string" || !ISO_TIME.test(startedAt) || typeof token !== "string")
66
+ return undefined;
67
+ return { pid, startedAt, token };
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ }
73
+ /** Whether process `pid` runs on this machine; undefined when that cannot be told. */
74
+ function isRunning(pid) {
75
+ try {
76
+ process.kill(pid, 0);
77
+ return true;
78
+ }
79
+ catch (error) {
80
+ const code = error.code;
81
+ if (code === "EPERM")
82
+ return true;
83
+ if (code === "ESRCH")
84
+ return false;
85
+ return undefined;
86
+ }
87
+ }
88
+ function lockedError(file) {
89
+ const shownFile = sanitizeText(file);
90
+ const lock = readLock(file);
91
+ const running = lock === undefined ? undefined : isRunning(lock.pid);
92
+ if (lock === undefined || running === undefined) {
93
+ 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 ` +
94
+ `is open, read the latest ledger in that folder, wait until the last authorization in it has expired, then ` +
95
+ `delete ${shownFile}.`);
96
+ }
97
+ const holder = `process ${lock.pid}, started ${lock.startedAt}`;
98
+ if (running) {
99
+ return new MainnetRunLockedError(file, "running", `Another mainnet run (${holder}) holds ${shownFile}. One mainnet run at a time on this machine: the ` +
100
+ `${formatUsd(usdFromDollars(PER_RUN_CAP_USD))} cap holds each run, not two at once on one account. Wait until ` +
101
+ `it has ended.`);
102
+ }
103
+ return new MainnetRunLockedError(file, "gone", `${shownFile} was left by a mainnet run (${holder}) that is no longer running: it ended without releasing the ` +
104
+ `lock, and authorizations it signed may still be open. Read that run's ledger, wait until the last ` +
105
+ `authorization in it has expired, then delete ${shownFile}.`);
106
+ }
107
+ function notCreated(dir, error) {
108
+ const code = error?.code;
109
+ return new ConfigurationError(`The lock file of a mainnet run could not be created in ${sanitizeText(dir)}` +
110
+ `${typeof code === "string" && ERROR_CODE.test(code) ? ` (${code})` : ""}, so the run does not start. ` +
111
+ `Nothing was signed.`);
112
+ }
113
+ /**
114
+ * Takes the lock of a mainnet run in `dir`, the folder of the run's ledger,
115
+ * creating the folder when it is missing.
116
+ *
117
+ * @throws {MainnetRunLockedError} When anything is already at the lock's path.
118
+ * @throws {ConfigurationError} When the lock cannot be created.
119
+ */
120
+ export function acquireMainnetRunLock(dir) {
121
+ const file = path.join(dir, MAINNET_RUN_LOCK_FILE);
122
+ const token = randomUUID();
123
+ const content = `${JSON.stringify({ wasit: TAG, pid: process.pid, startedAt: new Date().toISOString(), token })}\n`;
124
+ try {
125
+ // Apart from the open: mkdir also says EEXIST, for a file where the folder should be.
126
+ mkdirSync(dir, { recursive: true });
127
+ }
128
+ catch (error) {
129
+ throw notCreated(dir, error);
130
+ }
131
+ let fd;
132
+ try {
133
+ fd = openSync(file, "wx", 0o600);
134
+ }
135
+ catch (error) {
136
+ if (error.code === "EEXIST")
137
+ throw lockedError(file);
138
+ throw notCreated(dir, error);
139
+ }
140
+ try {
141
+ writeSync(fd, content);
142
+ fsyncSync(fd);
143
+ }
144
+ catch (error) {
145
+ closeSync(fd);
146
+ try {
147
+ unlinkSync(file);
148
+ }
149
+ catch {
150
+ // nothing more to do: the run does not start either way
151
+ }
152
+ throw notCreated(dir, error);
153
+ }
154
+ closeSync(fd);
155
+ let released = false;
156
+ const release = () => {
157
+ if (released)
158
+ return;
159
+ released = true;
160
+ process.removeListener("exit", release);
161
+ if (readLock(file)?.token !== token)
162
+ return;
163
+ try {
164
+ unlinkSync(file);
165
+ }
166
+ catch {
167
+ // gone already
168
+ }
169
+ };
170
+ process.once("exit", release);
171
+ return { path: file, release };
172
+ }