@wasit-dev/core 0.7.0 → 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.
- package/README.md +13 -2
- package/dist/baseline.d.ts +109 -0
- package/dist/baseline.js +353 -0
- package/dist/catalogue.js +10 -0
- package/dist/check.d.ts +57 -2
- package/dist/check.js +46 -6
- package/dist/ci-report.d.ts +74 -0
- package/dist/ci-report.js +399 -0
- package/dist/config-writer.d.ts +96 -0
- package/dist/config-writer.js +281 -0
- package/dist/config.d.ts +205 -0
- package/dist/config.js +1011 -0
- package/dist/denied-env.d.ts +33 -0
- package/dist/denied-env.js +86 -0
- package/dist/errors.d.ts +44 -1
- package/dist/errors.js +151 -2
- package/dist/guard/budget.d.ts +138 -0
- package/dist/guard/budget.js +206 -0
- package/dist/guard/ci-event.d.ts +56 -0
- package/dist/guard/ci-event.js +129 -0
- package/dist/guard/ci-mainnet.d.ts +59 -0
- package/dist/guard/ci-mainnet.js +149 -0
- package/dist/guard/horizon.d.ts +30 -0
- package/dist/guard/horizon.js +107 -0
- package/dist/guard/mainnet-payer.d.ts +66 -0
- package/dist/guard/mainnet-payer.js +92 -0
- package/dist/guard/mainnet-plan.d.ts +133 -0
- package/dist/guard/mainnet-plan.js +208 -0
- package/dist/guard/mainnet-run.d.ts +87 -0
- package/dist/guard/mainnet-run.js +225 -0
- package/dist/guard/networks.d.ts +51 -0
- package/dist/guard/networks.js +91 -0
- package/dist/guard/optin.d.ts +106 -0
- package/dist/guard/optin.js +202 -0
- package/dist/guard/rpc-identity.d.ts +45 -0
- package/dist/guard/rpc-identity.js +156 -0
- package/dist/guard/rpc-in-use.d.ts +48 -0
- package/dist/guard/rpc-in-use.js +84 -0
- package/dist/guard/run-ledger.d.ts +212 -0
- package/dist/guard/run-ledger.js +426 -0
- package/dist/guard/run-lock.d.ts +62 -0
- package/dist/guard/run-lock.js +172 -0
- package/dist/guard/signed-terms.d.ts +96 -0
- package/dist/guard/signed-terms.js +207 -0
- package/dist/index.d.ts +44 -4
- package/dist/index.js +42 -2
- package/dist/mpp/channel-commitment.d.ts +48 -2
- package/dist/mpp/channel-commitment.js +80 -4
- package/dist/mpp/channel-credential.d.ts +13 -1
- package/dist/mpp/channel-credential.js +21 -2
- package/dist/mpp/channel.d.ts +6 -0
- package/dist/mpp/channel.js +36 -3
- package/dist/mpp/charge.d.ts +33 -1
- package/dist/mpp/charge.js +90 -20
- package/dist/mpp/network.js +4 -1
- package/dist/mpp/plan.d.ts +77 -0
- package/dist/mpp/plan.js +188 -0
- package/dist/mpp/suite.d.ts +6 -0
- package/dist/mpp/suite.js +12 -3
- package/dist/report.d.ts +163 -0
- package/dist/report.js +282 -0
- package/dist/route-reader.d.ts +124 -0
- package/dist/route-reader.js +349 -0
- package/dist/sanitize.d.ts +52 -0
- package/dist/sanitize.js +106 -0
- package/dist/settlement.d.ts +14 -0
- package/dist/settlement.js +1 -1
- package/dist/verdict.d.ts +24 -0
- package/dist/verdict.js +46 -0
- package/dist/versions.d.ts +50 -0
- package/dist/versions.js +123 -0
- package/dist/wallet.d.ts +58 -1
- package/dist/wallet.js +128 -0
- package/dist/x402/chains/evm.js +3 -0
- package/dist/x402/chains/index.d.ts +8 -0
- package/dist/x402/chains/index.js +13 -2
- package/dist/x402/chains/stellar.d.ts +8 -1
- package/dist/x402/chains/stellar.js +259 -4
- package/dist/x402/chains/types.d.ts +104 -2
- package/dist/x402/plan.d.ts +184 -0
- package/dist/x402/plan.js +520 -0
- package/dist/x402/rejected-request.d.ts +156 -0
- package/dist/x402/rejected-request.js +287 -0
- package/dist/x402/requirements.d.ts +1 -0
- package/dist/x402/requirements.js +37 -4
- package/dist/x402/simulator.d.ts +86 -1
- package/dist/x402/simulator.js +863 -87
- package/package.json +1 -1
|
@@ -0,0 +1,212 @@
|
|
|
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 { CheckSetupError } from "../errors.js";
|
|
34
|
+
import type { PinTerms } from "./budget.js";
|
|
35
|
+
/** The `format` field of every run ledger. */
|
|
36
|
+
export declare const RUN_LEDGER_FORMAT = "wasit-run-ledger";
|
|
37
|
+
/** `wasit-ledger-<UTC time>.json`, colons replaced: some file systems refuse them. */
|
|
38
|
+
export declare function runLedgerFileName(at: Date): string;
|
|
39
|
+
/** The run ledger cannot be written, or was asked something out of order. A setup error: no verdict. */
|
|
40
|
+
export declare class RunLedgerError extends CheckSetupError {
|
|
41
|
+
constructor(message: string);
|
|
42
|
+
}
|
|
43
|
+
/** What a run states about itself when it opens its ledger. */
|
|
44
|
+
export interface RunLedgerHeader {
|
|
45
|
+
readonly versions: Readonly<Record<string, string>>;
|
|
46
|
+
readonly environment: string;
|
|
47
|
+
readonly network: string;
|
|
48
|
+
/** The payer's public address. */
|
|
49
|
+
readonly payer: string;
|
|
50
|
+
readonly pin?: PinTerms;
|
|
51
|
+
readonly caps: {
|
|
52
|
+
readonly perPaymentUsd: string;
|
|
53
|
+
readonly runUsd: string;
|
|
54
|
+
};
|
|
55
|
+
/** The run's plan; bigints are written as strings. */
|
|
56
|
+
readonly plan: unknown;
|
|
57
|
+
/** The RPC's origin, never its path or query (they may hold a key). */
|
|
58
|
+
readonly rpc: string;
|
|
59
|
+
}
|
|
60
|
+
/** A reading of the payer's balances, in base units. */
|
|
61
|
+
export interface LedgerBalances {
|
|
62
|
+
readonly usdc: bigint;
|
|
63
|
+
readonly native: bigint;
|
|
64
|
+
}
|
|
65
|
+
export type LedgerEntryState =
|
|
66
|
+
/** Written before the signature; no outcome yet. Read as signed. */
|
|
67
|
+
"intent" | "signed"
|
|
68
|
+
/** The key was not asked, or refused: nothing was signed. */
|
|
69
|
+
| "not-signed"
|
|
70
|
+
/** The client failed when it may already have signed. Read as signed. */
|
|
71
|
+
| "unknown";
|
|
72
|
+
/** What the check a signature belongs to found, as the ledger records it. */
|
|
73
|
+
export type LedgerVerdict = "pass" | "fail" | "no-verdict" | "skipped";
|
|
74
|
+
/** One signature of the run, as the file holds it. */
|
|
75
|
+
export interface LedgerEntry {
|
|
76
|
+
readonly id: number;
|
|
77
|
+
readonly endpoint: string;
|
|
78
|
+
readonly check: string;
|
|
79
|
+
readonly network: string;
|
|
80
|
+
readonly asset: string;
|
|
81
|
+
readonly payTo: string;
|
|
82
|
+
/** Base units. */
|
|
83
|
+
readonly amount: string;
|
|
84
|
+
readonly intentAt: string;
|
|
85
|
+
readonly state: LedgerEntryState;
|
|
86
|
+
readonly signedAt?: string;
|
|
87
|
+
/** The ledger (the chain's unit) the authorization expires at; null when it could not be read. */
|
|
88
|
+
readonly expiresAtLedger?: number | null;
|
|
89
|
+
/** Why it was not signed, or is unknown. */
|
|
90
|
+
readonly note?: string;
|
|
91
|
+
/** Why a signed payment was discarded, unsent. */
|
|
92
|
+
readonly discarded?: string;
|
|
93
|
+
readonly sent?: {
|
|
94
|
+
readonly at: string;
|
|
95
|
+
readonly status?: number;
|
|
96
|
+
readonly error?: string;
|
|
97
|
+
};
|
|
98
|
+
readonly settlement?: {
|
|
99
|
+
readonly reference: string;
|
|
100
|
+
readonly verified: boolean;
|
|
101
|
+
};
|
|
102
|
+
/** The verdict of the check this signature belongs to; absent until that check has one. */
|
|
103
|
+
readonly verdict?: LedgerVerdict;
|
|
104
|
+
}
|
|
105
|
+
/** What a payment check records about one signature. */
|
|
106
|
+
export interface LedgerEntryHandle {
|
|
107
|
+
/** The key signed; `expiresAtLedger` undefined when it could not be read. */
|
|
108
|
+
signed(expiresAtLedger: number | undefined): void;
|
|
109
|
+
notSigned(reason: string): void;
|
|
110
|
+
unknown(reason: string): void;
|
|
111
|
+
/** A signed payment was discarded, unsent. */
|
|
112
|
+
discarded(reason: string): void;
|
|
113
|
+
sent(outcome: {
|
|
114
|
+
readonly status: number;
|
|
115
|
+
} | {
|
|
116
|
+
readonly error: string;
|
|
117
|
+
}): void;
|
|
118
|
+
settled(reference: string, verified: boolean): void;
|
|
119
|
+
}
|
|
120
|
+
/** The ledger as the payment checks of one endpoint see it. */
|
|
121
|
+
export interface PaymentLedger {
|
|
122
|
+
/**
|
|
123
|
+
* Writes, and flushes, the intent of a signature about to be made. Throws
|
|
124
|
+
* when it cannot: the caller then signs nothing.
|
|
125
|
+
*/
|
|
126
|
+
intent(entry: {
|
|
127
|
+
readonly check: string;
|
|
128
|
+
readonly network: string;
|
|
129
|
+
readonly asset: string;
|
|
130
|
+
readonly payTo: string;
|
|
131
|
+
readonly amount: string;
|
|
132
|
+
}): LedgerEntryHandle;
|
|
133
|
+
/**
|
|
134
|
+
* Records `check`'s verdict on every entry of it that has none yet. Only a
|
|
135
|
+
* FAIL recorded here can explain USDC the run did not verify settled; a
|
|
136
|
+
* ledger without this method, or one that cannot write it, explains none.
|
|
137
|
+
*/
|
|
138
|
+
verdict?(check: string, verdict: LedgerVerdict): void;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* How the payer's balances compare with the ledger. `consistent`: its USDC
|
|
142
|
+
* went down by exactly the settlements the run verified, and its XLM did not
|
|
143
|
+
* move. `explained`: its XLM did not move, and its USDC went down by more
|
|
144
|
+
* than the verified settlements, but by no more than the payments, signed and
|
|
145
|
+
* sent, of checks that FAILed (each counted once): a service that settles
|
|
146
|
+
* what it should refuse. Anything else is `inconsistent`.
|
|
147
|
+
*/
|
|
148
|
+
export type LedgerResult = "consistent" | "explained" | "inconsistent";
|
|
149
|
+
/** Whether the payer's balances moved as the ledger says they should have. */
|
|
150
|
+
export interface LedgerConsistency {
|
|
151
|
+
readonly result: LedgerResult;
|
|
152
|
+
/** True only when `result` is "consistent". */
|
|
153
|
+
readonly consistent: boolean;
|
|
154
|
+
readonly reasons: readonly string[];
|
|
155
|
+
/** USDC that left the payer, in base units, when both readings exist. */
|
|
156
|
+
readonly spentUsdc?: bigint;
|
|
157
|
+
/** USDC of the settlements the run verified on chain, in base units. */
|
|
158
|
+
readonly settledUsdc: bigint;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The ledger of one paying run. Create it before the first signature; hand
|
|
162
|
+
* {@link RunLedger.forEndpoint} to each endpoint's payment checks; close it
|
|
163
|
+
* once every authorization has expired and the balances after are read.
|
|
164
|
+
*/
|
|
165
|
+
export declare class RunLedger {
|
|
166
|
+
#private;
|
|
167
|
+
readonly path: string;
|
|
168
|
+
private constructor();
|
|
169
|
+
/**
|
|
170
|
+
* Creates the ledger in `dir` (made if missing), named after now, holding the
|
|
171
|
+
* header. Refuses a name that exists: a ledger is never overwritten.
|
|
172
|
+
*/
|
|
173
|
+
static create(dir: string, header: RunLedgerHeader, options?: {
|
|
174
|
+
readonly now?: () => Date;
|
|
175
|
+
}): RunLedger;
|
|
176
|
+
/** The entries so far, as the file holds them. */
|
|
177
|
+
get entries(): readonly LedgerEntry[];
|
|
178
|
+
/** The payment ledger of one endpoint's checks. */
|
|
179
|
+
forEndpoint(endpoint: string): PaymentLedger;
|
|
180
|
+
/** The payer's balances before the first signature, and where they were read. */
|
|
181
|
+
recordBalancesBefore(balances: LedgerBalances, source: string): void;
|
|
182
|
+
/**
|
|
183
|
+
* Closes the ledger with the balances after the run (undefined when they
|
|
184
|
+
* could not be read): writes whether they are consistent with what the
|
|
185
|
+
* ledger says settled, and returns it.
|
|
186
|
+
*/
|
|
187
|
+
close(input?: {
|
|
188
|
+
readonly after?: LedgerBalances;
|
|
189
|
+
readonly source?: string;
|
|
190
|
+
}): LedgerConsistency;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Whether the payer's balances moved as the ledger says (see
|
|
194
|
+
* {@link LedgerResult}). On Stellar the facilitator pays the fees and Wasit
|
|
195
|
+
* sends no transaction from the payer, so its XLM must not move. The USDC
|
|
196
|
+
* the run verified settled is the sum of the entries whose settlement it read
|
|
197
|
+
* back from the chain. More than that is explained only by the entries, sent
|
|
198
|
+
* and not verified, of checks that FAILed: a check with no verdict, a SKIP or
|
|
199
|
+
* a PASS explains nothing, and neither does a payment discarded unsent. The
|
|
200
|
+
* reasons also name every entry with no recorded outcome, which is read as
|
|
201
|
+
* signed and sent.
|
|
202
|
+
*/
|
|
203
|
+
export declare function ledgerConsistency(before: LedgerBalances | undefined, after: LedgerBalances | undefined, entries: readonly LedgerEntry[]): LedgerConsistency;
|
|
204
|
+
/**
|
|
205
|
+
* Until when the run's authorizations may be open (L4): the latest expiry of
|
|
206
|
+
* every entry that holds a signature or may, and how many of those have no
|
|
207
|
+
* known expiry (the caller then waits the longest a signature may live).
|
|
208
|
+
*/
|
|
209
|
+
export declare function openAuthorizationsUntil(entries: readonly LedgerEntry[]): {
|
|
210
|
+
latest: number | undefined;
|
|
211
|
+
unknown: number;
|
|
212
|
+
};
|
|
@@ -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
|
+
}
|