@dvmkit/dvm-cli 0.4.2 → 0.6.0
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 +18 -0
- package/dist/{chunk-JVQFBKDX.js → chunk-3YE43JJR.js} +3 -3
- package/dist/{chunk-2TKOJBBB.js → chunk-4KINCBHL.js} +53 -51
- package/dist/{chunk-CSRGRJB6.js → chunk-EE2MREOM.js} +68 -4
- package/dist/chunk-ERJFRCJO.js +150 -0
- package/dist/chunk-FL2ICZW5.js +383 -0
- package/dist/chunk-FSYEZERJ.js +1667 -0
- package/dist/{chunk-6KEZKHN7.js → chunk-ID5G54HJ.js} +211 -35
- package/dist/{chunk-4NWEJTAW.js → chunk-MJ4X4BEW.js} +7953 -8036
- package/dist/{chunk-KBFK5MM5.js → chunk-QICJRKB7.js} +6972 -1321
- package/dist/{chunk-ECEM3ZAS.js → chunk-R55XNXAR.js} +53 -185
- package/dist/{chunk-OOA6X5MI.js → chunk-SHZMNEXE.js} +58 -17
- package/dist/{chunk-PRN4FHDY.js → chunk-TZWZTS37.js} +38 -23
- package/dist/{chunk-DRO3JP42.js → chunk-VOO5IAK7.js} +582 -83
- package/dist/{chunk-2VVVWBQA.js → chunk-WTM2EICO.js} +2 -352
- package/dist/chunk-XHOFQ3OS.js +717 -0
- package/dist/{chunk-KUBOPQ3N.js → chunk-Z4CZUMUT.js} +937 -1599
- package/dist/{client-OWIOFBKS.js → client-RYDA62DU.js} +11 -8
- package/dist/{dist-2G3QBGID.js → dist-GKCEIY2A.js} +7 -4
- package/dist/dvm.js +866 -121
- package/dist/{internal-DS42OMXR.js → internal-INUTGTXQ.js} +52 -38
- package/dist/{payout-reporter-TQ3YIFLZ-64RGUGTA.js → payout-reporter-3Y2U55ZX-CMKACKA3.js} +2 -2
- package/dist/{pocket-refill-3WMWHMOT.js → pocket-refill-K5T4LZF6.js} +18 -14
- package/dist/{revenue-reporter-VN4WYN74-T7HYTIDM.js → revenue-reporter-MAERPYGK-CCPZXGFA.js} +2 -2
- package/dist/tempo-AXTE4ZEA.js +34 -0
- package/dist/{tempo-lifecycle-TJ62A7UX-OLLWSS3I.js → tempo-lifecycle-ZBBLFBMH-HWI4PLYP.js} +11 -7
- package/dist/{tempo-wallet-RCGBBAJH-TSTQAZKT.js → tempo-wallet-B5XXV3YH-SRQBMYFV.js} +2 -2
- package/dist/{x402-S47Q77UE-33J7AIH3.js → x402-R6HPBY5D-VMSW7Z32.js} +3 -3
- package/package.json +2 -2
- package/skills/dvm/calling.md +2 -0
- package/skills/dvm/credit.md +4 -0
- package/skills/dvm/wallets.md +4 -0
|
@@ -5,14 +5,67 @@ import {
|
|
|
5
5
|
BTC_RATE_FILE,
|
|
6
6
|
CREDITS_FILE,
|
|
7
7
|
DvmError,
|
|
8
|
+
bytesToHex,
|
|
8
9
|
ensureConfigDir,
|
|
9
10
|
ensureConfigSubdir,
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
hexToBytes,
|
|
12
|
+
require_proper_lockfile,
|
|
13
|
+
schnorr,
|
|
14
|
+
sha256
|
|
15
|
+
} from "./chunk-4KINCBHL.js";
|
|
12
16
|
import {
|
|
13
17
|
__toESM
|
|
14
18
|
} from "./chunk-IYHTITNZ.js";
|
|
15
19
|
|
|
20
|
+
// node_modules/@dvmkit/sdk/dist/chunk-OFVV37XC.js
|
|
21
|
+
function canonicalize(value) {
|
|
22
|
+
return JSON.stringify(sortDeep(value));
|
|
23
|
+
}
|
|
24
|
+
function canonicaliseForSigning(value) {
|
|
25
|
+
return new TextEncoder().encode(canonicalize(value));
|
|
26
|
+
}
|
|
27
|
+
function sortDeep(value) {
|
|
28
|
+
if (value === null) return null;
|
|
29
|
+
if (typeof value === "string" || typeof value === "boolean") return value;
|
|
30
|
+
if (typeof value === "number") {
|
|
31
|
+
if (!Number.isFinite(value)) {
|
|
32
|
+
throw new TypeError(`canonicalize: non-finite number is not JSON-serialisable`);
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
if (Array.isArray(value)) return value.map(sortDeep);
|
|
37
|
+
if (typeof value === "object") {
|
|
38
|
+
const sorted = {};
|
|
39
|
+
for (const key of Object.keys(value).sort()) {
|
|
40
|
+
const v = value[key];
|
|
41
|
+
if (v === void 0) continue;
|
|
42
|
+
sorted[key] = sortDeep(v);
|
|
43
|
+
}
|
|
44
|
+
return sorted;
|
|
45
|
+
}
|
|
46
|
+
throw new TypeError(`canonicalize: unsupported value of type ${typeof value}`);
|
|
47
|
+
}
|
|
48
|
+
function verifyCanonicalSignedRequest(payload, signatureHex, pubkeyHex) {
|
|
49
|
+
if (!/^[0-9a-f]{64}$/i.test(pubkeyHex) || !/^[0-9a-f]{128}$/i.test(signatureHex)) {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
const data = canonicaliseForSigning(payload);
|
|
53
|
+
const signature = hexToBytes2(signatureHex);
|
|
54
|
+
const pubkey = hexToBytes2(pubkeyHex);
|
|
55
|
+
try {
|
|
56
|
+
return schnorr.verify(signature, data, pubkey);
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function hexToBytes2(hex) {
|
|
62
|
+
const out = new Uint8Array(hex.length / 2);
|
|
63
|
+
for (let i = 0; i < out.length; i++) {
|
|
64
|
+
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
16
69
|
// node_modules/@dvmkit/sdk/dist/chunk-AT6V3SY7.js
|
|
17
70
|
var InvalidFxRateError = class extends Error {
|
|
18
71
|
code = "invalid_fx_rate";
|
|
@@ -105,7 +158,7 @@ var FIAT_SYMBOLS = {
|
|
|
105
158
|
jpy: "\xA5"
|
|
106
159
|
};
|
|
107
160
|
|
|
108
|
-
// node_modules/@dvmkit/sdk/dist/chunk-
|
|
161
|
+
// node_modules/@dvmkit/sdk/dist/chunk-PAIM66YA.js
|
|
109
162
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
110
163
|
import { dirname } from "path";
|
|
111
164
|
var IMPLICIT_CREDIT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
@@ -191,13 +244,13 @@ function formatSats(msats) {
|
|
|
191
244
|
}
|
|
192
245
|
function formatAmount(msats, rate, opts) {
|
|
193
246
|
const usd = msatsToUsd(msats, rate);
|
|
194
|
-
const
|
|
195
|
-
return opts?.anchor === false ?
|
|
247
|
+
const base2 = `~$${formatUsd2(usd)} (${formatSats(msats)})`;
|
|
248
|
+
return opts?.anchor === false ? base2 : `${base2} \u2014 ${costAnchor(usd)}`;
|
|
196
249
|
}
|
|
197
250
|
function formatPaymentAmount(msats, fiat, opts) {
|
|
198
251
|
if (!fiat || fiat.amount <= 0) return formatAmountBestEffort(msats, opts);
|
|
199
|
-
const
|
|
200
|
-
return opts?.anchor === false ?
|
|
252
|
+
const base2 = `${formatFiat(fiat.amount, fiat.currency)} (${formatSats(msats)})`;
|
|
253
|
+
return opts?.anchor === false ? base2 : `${base2} \u2014 ${costAnchor(fiat.amount, fiat.currency)}`;
|
|
201
254
|
}
|
|
202
255
|
var COST_ANCHOR_BANDS = {
|
|
203
256
|
usd: [0.01, 0.1, 1, 10],
|
|
@@ -278,9 +331,9 @@ function formatAmountBestEffort(msats, opts) {
|
|
|
278
331
|
const m = msats ?? 0;
|
|
279
332
|
const cached = getLastKnownBtcRate();
|
|
280
333
|
if (cached === null) return `${Math.round(m / 1e3)} sats`;
|
|
281
|
-
const
|
|
282
|
-
if (Date.now() - cached.cachedAt < CACHE_TTL) return
|
|
283
|
-
return `${
|
|
334
|
+
const base2 = formatAmount(m, cached.rate, opts);
|
|
335
|
+
if (Date.now() - cached.cachedAt < CACHE_TTL) return base2;
|
|
336
|
+
return `${base2} (rate cached ${formatStaleness(cached.cachedAt)})`;
|
|
284
337
|
}
|
|
285
338
|
var CACHE_TTL = 5 * 60 * 1e3;
|
|
286
339
|
var CACHE_FILE = BTC_RATE_FILE;
|
|
@@ -326,45 +379,91 @@ async function fetchFromApi() {
|
|
|
326
379
|
}
|
|
327
380
|
return rate;
|
|
328
381
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
382
|
+
function computeResultHash(summary, artifactContents) {
|
|
383
|
+
const artifactHashes = artifactContents.map(
|
|
384
|
+
(content) => bytesToHex(sha256(canonicaliseForSigning(content)))
|
|
385
|
+
);
|
|
386
|
+
return bytesToHex(
|
|
387
|
+
sha256(
|
|
388
|
+
canonicaliseForSigning({
|
|
389
|
+
summary: summary ?? null,
|
|
390
|
+
artifact_hashes: artifactHashes
|
|
391
|
+
})
|
|
392
|
+
)
|
|
393
|
+
);
|
|
338
394
|
}
|
|
339
|
-
function
|
|
340
|
-
|
|
395
|
+
function signReceipt(unsigned, secretHex) {
|
|
396
|
+
const bytes = canonicaliseForSigning(unsigned);
|
|
397
|
+
const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
|
|
398
|
+
return { ...unsigned, signature };
|
|
341
399
|
}
|
|
342
|
-
function
|
|
343
|
-
|
|
344
|
-
|
|
400
|
+
function verifyReceipt(receipt) {
|
|
401
|
+
try {
|
|
402
|
+
const { signature, ...unsigned } = receipt;
|
|
403
|
+
const bytes = canonicaliseForSigning(unsigned);
|
|
404
|
+
return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
|
|
405
|
+
} catch {
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
345
408
|
}
|
|
346
|
-
function
|
|
347
|
-
|
|
409
|
+
function isSignedJobReceipt(value) {
|
|
410
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
411
|
+
const r = value;
|
|
412
|
+
const paid = r.paid;
|
|
413
|
+
return r.v === 1 && typeof r.job_id === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.capability === "string" && (r.outcome === "completed" || r.outcome === "failed" || r.outcome === "cancelled") && typeof r.seq === "number" && typeof r.issued_at === "number" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string" && !!paid && typeof paid === "object" && !Array.isArray(paid) && typeof paid.msats === "number";
|
|
348
414
|
}
|
|
349
|
-
function
|
|
350
|
-
|
|
415
|
+
function signDrainReceipt(unsigned, secretHex) {
|
|
416
|
+
const bytes = canonicaliseForSigning(unsigned);
|
|
417
|
+
const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
|
|
418
|
+
return { ...unsigned, signature };
|
|
351
419
|
}
|
|
352
|
-
function
|
|
353
|
-
|
|
420
|
+
function signFundingReceipt(unsigned, secretHex) {
|
|
421
|
+
const bytes = canonicaliseForSigning(unsigned);
|
|
422
|
+
const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
|
|
423
|
+
return { ...unsigned, signature };
|
|
354
424
|
}
|
|
355
|
-
function
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
425
|
+
function isFundingReceipt(value) {
|
|
426
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
427
|
+
const r = value;
|
|
428
|
+
return r.v === 1 && r.kind === "credit_funding" && typeof r.credit_id === "string" && typeof r.fund_id === "string" && typeof r.funded_micro === "number" && typeof r.balance_after_micro === "number" && typeof r.ledger_seq === "number" && typeof r.issued_at === "number" && typeof r.caller_pubkey === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string";
|
|
429
|
+
}
|
|
430
|
+
function verifyFundingReceipt(receipt) {
|
|
431
|
+
try {
|
|
432
|
+
const { signature, ...unsigned } = receipt;
|
|
433
|
+
const bytes = canonicaliseForSigning(unsigned);
|
|
434
|
+
return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
|
|
435
|
+
} catch {
|
|
436
|
+
return false;
|
|
366
437
|
}
|
|
367
438
|
}
|
|
439
|
+
function isDrainReceipt(value) {
|
|
440
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
441
|
+
const r = value;
|
|
442
|
+
return r.v === 1 && r.kind === "credit_drain" && typeof r.credit_id === "string" && typeof r.drain_id === "string" && (r.event === "requested" || r.event === "parked" || r.event === "picked_up" || r.event === "sent" || r.event === "released") && typeof r.method === "string" && typeof r.amount_micro === "number" && typeof r.issued_at === "number" && typeof r.caller_pubkey === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string";
|
|
443
|
+
}
|
|
444
|
+
function verifyDrainReceipt(receipt) {
|
|
445
|
+
try {
|
|
446
|
+
const { signature, ...unsigned } = receipt;
|
|
447
|
+
const bytes = canonicaliseForSigning(unsigned);
|
|
448
|
+
return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
|
|
449
|
+
} catch {
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// node_modules/@dvmkit/sdk/dist/chunk-B2IROPQF.js
|
|
455
|
+
var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
|
|
456
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
|
|
457
|
+
import { dirname as dirname2 } from "path";
|
|
458
|
+
import { createHash } from "crypto";
|
|
459
|
+
import {
|
|
460
|
+
closeSync,
|
|
461
|
+
fsyncSync,
|
|
462
|
+
openSync,
|
|
463
|
+
readFileSync as readFileSync3,
|
|
464
|
+
writeSync,
|
|
465
|
+
ftruncateSync
|
|
466
|
+
} from "fs";
|
|
368
467
|
var RAIL_FLAGS = ["cashu", "tempo", "x402"];
|
|
369
468
|
var ADVERTISED_AMOUNT_TOLERANCE_BPS = 1000n;
|
|
370
469
|
function maxAdvertisedMicro(localMicro) {
|
|
@@ -374,9 +473,9 @@ function withinAdvertisedTolerance(advertisedMicro, localMicro) {
|
|
|
374
473
|
return advertisedMicro * 10000n <= localMicro * (10000n + ADVERTISED_AMOUNT_TOLERANCE_BPS);
|
|
375
474
|
}
|
|
376
475
|
var SUPPORTED_PROTOCOL_VERSION = 1;
|
|
377
|
-
function parseCreditTerms(
|
|
378
|
-
if (!
|
|
379
|
-
const credit =
|
|
476
|
+
function parseCreditTerms(raw) {
|
|
477
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
478
|
+
const credit = raw;
|
|
380
479
|
if (typeof credit.min_micro !== "number" || typeof credit.max_micro !== "number" || typeof credit.ttl_ms !== "number" || typeof credit.currency !== "string" || !Array.isArray(credit.funding) || !credit.funding.every((method) => typeof method === "string") || credit.lightning_min_micro !== void 0 && typeof credit.lightning_min_micro !== "number")
|
|
381
480
|
return void 0;
|
|
382
481
|
const tempo = credit.tempo === void 0 ? void 0 : parseCreditTempoTerms(credit.tempo);
|
|
@@ -396,10 +495,10 @@ function parseCreditTerms(raw2) {
|
|
|
396
495
|
}
|
|
397
496
|
};
|
|
398
497
|
}
|
|
399
|
-
function parseCreditMenu(
|
|
400
|
-
const terms = parseCreditTerms(
|
|
498
|
+
function parseCreditMenu(raw) {
|
|
499
|
+
const terms = parseCreditTerms(raw);
|
|
401
500
|
if (!terms) return void 0;
|
|
402
|
-
const credit =
|
|
501
|
+
const credit = raw;
|
|
403
502
|
return {
|
|
404
503
|
...terms,
|
|
405
504
|
...typeof credit.credit_id === "string" && { credit_id: credit.credit_id },
|
|
@@ -410,9 +509,9 @@ function parseCreditMenu(raw2) {
|
|
|
410
509
|
...typeof credit.expiry_ms === "number" && { expiry_ms: credit.expiry_ms }
|
|
411
510
|
};
|
|
412
511
|
}
|
|
413
|
-
function parseCreditTempoTerms(
|
|
414
|
-
if (!
|
|
415
|
-
const block =
|
|
512
|
+
function parseCreditTempoTerms(raw) {
|
|
513
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
514
|
+
const block = raw;
|
|
416
515
|
if (!Array.isArray(block.methods) || !block.methods.every(isCreditTempoMethod)) return void 0;
|
|
417
516
|
if (block.withheld !== void 0 && (!Array.isArray(block.withheld) || !block.withheld.every(isCreditTempoWithheldMethod)))
|
|
418
517
|
return void 0;
|
|
@@ -430,15 +529,15 @@ function parseCreditTempoTerms(raw2) {
|
|
|
430
529
|
}
|
|
431
530
|
};
|
|
432
531
|
}
|
|
433
|
-
function isCreditTempoMethod(
|
|
434
|
-
return !!
|
|
532
|
+
function isCreditTempoMethod(raw) {
|
|
533
|
+
return !!raw && typeof raw === "object" && typeof raw.method === "string" && (raw.intent === "charge" || raw.intent === "session");
|
|
435
534
|
}
|
|
436
|
-
function isCreditTempoWithheldMethod(
|
|
437
|
-
return isCreditTempoMethod(
|
|
535
|
+
function isCreditTempoWithheldMethod(raw) {
|
|
536
|
+
return isCreditTempoMethod(raw) && typeof raw.reason === "string";
|
|
438
537
|
}
|
|
439
|
-
function parseCreditX402Terms(
|
|
440
|
-
if (!
|
|
441
|
-
const schemes =
|
|
538
|
+
function parseCreditX402Terms(raw) {
|
|
539
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
540
|
+
const schemes = raw.schemes;
|
|
442
541
|
if (!Array.isArray(schemes) || !schemes.every(
|
|
443
542
|
(entry) => !!entry && typeof entry === "object" && typeof entry.scheme === "string" && typeof entry.network === "string"
|
|
444
543
|
))
|
|
@@ -450,6 +549,332 @@ function parseCreditX402Terms(raw2) {
|
|
|
450
549
|
}))
|
|
451
550
|
};
|
|
452
551
|
}
|
|
552
|
+
function historyPath() {
|
|
553
|
+
return `${CREDITS_FILE.slice(0, -5)}-history.jsonl`;
|
|
554
|
+
}
|
|
555
|
+
function hash(value) {
|
|
556
|
+
return createHash("sha256").update(value).digest("hex");
|
|
557
|
+
}
|
|
558
|
+
function fail(detail) {
|
|
559
|
+
throw new DvmError(
|
|
560
|
+
"credit_history_unavailable",
|
|
561
|
+
`Completed credit history could not be preserved: ${detail}`,
|
|
562
|
+
"Keep the credit store and history file intact, fix the file access or damage, and retry. Working evidence was not evicted."
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
var receiptKeys = /* @__PURE__ */ new Set([
|
|
566
|
+
"v",
|
|
567
|
+
"kind",
|
|
568
|
+
"credit_id",
|
|
569
|
+
"drain_id",
|
|
570
|
+
"event",
|
|
571
|
+
"method",
|
|
572
|
+
"amount_micro",
|
|
573
|
+
"balance_after_micro",
|
|
574
|
+
"ledger_seq",
|
|
575
|
+
"issued_at",
|
|
576
|
+
"caller_pubkey",
|
|
577
|
+
"dvm_id",
|
|
578
|
+
"dvm",
|
|
579
|
+
"receipt_pubkey",
|
|
580
|
+
"signature"
|
|
581
|
+
]);
|
|
582
|
+
var attestationKeys = /* @__PURE__ */ new Set([
|
|
583
|
+
"dvm_id",
|
|
584
|
+
"slug",
|
|
585
|
+
"capabilities_hash",
|
|
586
|
+
"builder_pubkey",
|
|
587
|
+
"receipt_pubkey",
|
|
588
|
+
"deployed_at"
|
|
589
|
+
]);
|
|
590
|
+
function safeReceipts(bundle) {
|
|
591
|
+
const receipts = [];
|
|
592
|
+
for (const receipt of bundle.receipts) {
|
|
593
|
+
if (!isDrainReceipt(receipt))
|
|
594
|
+
fail("a completed bundle contains an unrecognized receipt");
|
|
595
|
+
if (Object.keys(receipt).some((key) => !receiptKeys.has(key)))
|
|
596
|
+
fail("a receipt contains unsupported fields");
|
|
597
|
+
if (Object.values(receipt).some(
|
|
598
|
+
(value) => typeof value !== "string" && typeof value !== "number" || typeof value === "number" && (!Number.isSafeInteger(value) || value < 0)
|
|
599
|
+
))
|
|
600
|
+
fail("a receipt contains unsupported values");
|
|
601
|
+
receipts.push(receipt);
|
|
602
|
+
}
|
|
603
|
+
return receipts;
|
|
604
|
+
}
|
|
605
|
+
function safeAnchor(anchor) {
|
|
606
|
+
if (!anchor) return void 0;
|
|
607
|
+
if (typeof anchor.pubkey !== "string" || typeof anchor.signature !== "string" || !anchor.attestation || Object.keys(anchor.attestation).some((key) => !attestationKeys.has(key)) || Object.values(anchor.attestation).some(
|
|
608
|
+
(value) => typeof value !== "string" && typeof value !== "number"
|
|
609
|
+
))
|
|
610
|
+
fail("an advertisement contains unsupported fields");
|
|
611
|
+
return {
|
|
612
|
+
pubkey: anchor.pubkey,
|
|
613
|
+
signature: anchor.signature,
|
|
614
|
+
attestation: anchor.attestation
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
function hasAttestedIdentity(record) {
|
|
618
|
+
return Boolean(record.dvmId && record.attestedBuilderPubkey);
|
|
619
|
+
}
|
|
620
|
+
function compatibleLocations(left, right) {
|
|
621
|
+
if (hasAttestedIdentity(left) && hasAttestedIdentity(right))
|
|
622
|
+
return left.dvmId === right.dvmId && left.attestedBuilderPubkey === right.attestedBuilderPubkey;
|
|
623
|
+
return [left.endpoint, ...left.endpointAliases].some(
|
|
624
|
+
(origin) => [right.endpoint, ...right.endpointAliases].includes(origin)
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
function base(record, identity, occurredAt) {
|
|
628
|
+
return {
|
|
629
|
+
v: 1,
|
|
630
|
+
id: hash(
|
|
631
|
+
JSON.stringify([
|
|
632
|
+
record.callerPubkey,
|
|
633
|
+
hasAttestedIdentity(record) ? record.dvmId : record.endpoint,
|
|
634
|
+
hasAttestedIdentity(record) ? record.attestedBuilderPubkey : null,
|
|
635
|
+
record.creditId,
|
|
636
|
+
identity
|
|
637
|
+
])
|
|
638
|
+
),
|
|
639
|
+
endpoint: record.endpoint,
|
|
640
|
+
endpointAliases: record.endpointAliases ?? [],
|
|
641
|
+
dvmId: record.dvmId ?? null,
|
|
642
|
+
attestedBuilderPubkey: record.attestedBuilderPubkey ?? null,
|
|
643
|
+
callerPubkey: record.callerPubkey,
|
|
644
|
+
creditId: record.creditId,
|
|
645
|
+
occurredAt,
|
|
646
|
+
rail: null,
|
|
647
|
+
currency: null,
|
|
648
|
+
amountMicro: null,
|
|
649
|
+
feeMicro: null
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
function completedRefund(record, bundle) {
|
|
653
|
+
const receipts = safeReceipts(bundle);
|
|
654
|
+
const anchor = safeAnchor(bundle.anchor);
|
|
655
|
+
const receipt = receipts.find(
|
|
656
|
+
(r) => r.drain_id === bundle.drainId && r.credit_id === bundle.creditId
|
|
657
|
+
);
|
|
658
|
+
const metadata = bundle.settlement;
|
|
659
|
+
if (metadata && (metadata.rail !== null && typeof metadata.rail !== "string" || metadata.currency !== null && typeof metadata.currency !== "string" || [metadata.amountMicro, metadata.feeMicro].some(
|
|
660
|
+
(value) => value !== null && (!Number.isSafeInteger(value) || value < 0)
|
|
661
|
+
)))
|
|
662
|
+
fail("invalid settlement metadata");
|
|
663
|
+
return {
|
|
664
|
+
...base(
|
|
665
|
+
{ ...record, creditId: bundle.creditId },
|
|
666
|
+
`refund:${bundle.drainId}`,
|
|
667
|
+
bundle.settledAt
|
|
668
|
+
),
|
|
669
|
+
kind: "completed_refund",
|
|
670
|
+
outcome: "refunded",
|
|
671
|
+
drainId: bundle.drainId,
|
|
672
|
+
settledAt: bundle.settledAt,
|
|
673
|
+
collectedAt: bundle.collectedAt === 0 ? null : bundle.collectedAt,
|
|
674
|
+
rail: metadata?.rail ?? receipt?.method ?? null,
|
|
675
|
+
currency: metadata?.currency ?? null,
|
|
676
|
+
amountMicro: metadata?.amountMicro ?? receipt?.amount_micro ?? null,
|
|
677
|
+
feeMicro: metadata?.feeMicro ?? null,
|
|
678
|
+
receipts,
|
|
679
|
+
...anchor ? { anchor } : {},
|
|
680
|
+
provenance: {
|
|
681
|
+
settlement: "local_observation",
|
|
682
|
+
receipts: "unverified_observations",
|
|
683
|
+
advertisement: anchor ? "present" : "absent"
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
function completedLoss(record) {
|
|
688
|
+
return {
|
|
689
|
+
...base(record, "loss", record.updatedAt),
|
|
690
|
+
kind: "expired_credit_loss",
|
|
691
|
+
outcome: "lost",
|
|
692
|
+
rail: record.creditId.startsWith("imp:") ? record.creditId.split(":")[1] || null : null,
|
|
693
|
+
currency: record.currency,
|
|
694
|
+
amountMicro: record.remainingMicro,
|
|
695
|
+
reason: record.lossReason ?? "expired",
|
|
696
|
+
releasedAt: record.releasedAt,
|
|
697
|
+
expiryMs: record.expiryMs,
|
|
698
|
+
releasedByJobId: record.releasedByJobId
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
function validateHistoryRecord(row) {
|
|
702
|
+
if (!row || row.v !== 1 || typeof row.id !== "string" || !Number.isSafeInteger(row.occurredAt) || typeof row.endpoint !== "string" || typeof row.callerPubkey !== "string" || typeof row.creditId !== "string" || !Array.isArray(row.endpointAliases) || row.endpointAliases.some((value) => typeof value !== "string") || [row.dvmId, row.attestedBuilderPubkey, row.currency, row.rail].some(
|
|
703
|
+
(value) => value !== null && typeof value !== "string"
|
|
704
|
+
) || [row.amountMicro, row.feeMicro].some(
|
|
705
|
+
(value) => value !== null && (!Number.isSafeInteger(value) || value < 0)
|
|
706
|
+
))
|
|
707
|
+
fail("invalid complete journal entry");
|
|
708
|
+
if (row.kind === "completed_refund") {
|
|
709
|
+
if (row.outcome !== "refunded" || typeof row.drainId !== "string" || !Number.isSafeInteger(row.settledAt) || row.collectedAt !== null && !Number.isSafeInteger(row.collectedAt) || !Array.isArray(row.receipts) || row.provenance?.settlement !== "local_observation" || row.provenance.receipts !== "unverified_observations" || !["present", "absent"].includes(row.provenance.advertisement))
|
|
710
|
+
fail("invalid refund entry");
|
|
711
|
+
safeReceipts({
|
|
712
|
+
drainId: row.drainId,
|
|
713
|
+
creditId: row.creditId,
|
|
714
|
+
receipts: row.receipts,
|
|
715
|
+
collectedAt: row.collectedAt ?? 0
|
|
716
|
+
});
|
|
717
|
+
safeAnchor(row.anchor);
|
|
718
|
+
} else if (row.kind === "expired_credit_loss") {
|
|
719
|
+
if (row.outcome !== "lost" || !["expired", "not_found"].includes(row.reason) || !Number.isSafeInteger(row.releasedAt) || !Number.isSafeInteger(row.expiryMs) || typeof row.releasedByJobId !== "string")
|
|
720
|
+
fail("invalid loss entry");
|
|
721
|
+
} else fail("invalid complete journal entry");
|
|
722
|
+
}
|
|
723
|
+
function journal() {
|
|
724
|
+
let bytes;
|
|
725
|
+
try {
|
|
726
|
+
bytes = readFileSync3(historyPath());
|
|
727
|
+
} catch (error) {
|
|
728
|
+
if (error.code === "ENOENT")
|
|
729
|
+
return { bytes: Buffer.alloc(0), complete: 0, rows: [] };
|
|
730
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
731
|
+
}
|
|
732
|
+
const complete = bytes.lastIndexOf(10) + 1;
|
|
733
|
+
const rows = bytes.subarray(0, complete).toString("utf8").split("\n").filter(Boolean).map((line) => {
|
|
734
|
+
let row;
|
|
735
|
+
try {
|
|
736
|
+
row = JSON.parse(line);
|
|
737
|
+
} catch {
|
|
738
|
+
fail("damaged complete journal line");
|
|
739
|
+
}
|
|
740
|
+
validateHistoryRecord(row);
|
|
741
|
+
return row;
|
|
742
|
+
});
|
|
743
|
+
return { bytes, complete, rows };
|
|
744
|
+
}
|
|
745
|
+
function archiveCompletedCreditRecords(records) {
|
|
746
|
+
if (!records.length) return;
|
|
747
|
+
try {
|
|
748
|
+
const current = journal();
|
|
749
|
+
const latest = new Map(
|
|
750
|
+
current.rows.map((record) => [record.id, JSON.stringify(record)])
|
|
751
|
+
);
|
|
752
|
+
const observed = new Map(current.rows.map((record) => [record.id, record]));
|
|
753
|
+
const additions = [];
|
|
754
|
+
for (const incoming of records) {
|
|
755
|
+
const prior = [...observed.values()].reverse().find(
|
|
756
|
+
(row) => row.kind === incoming.kind && row.callerPubkey === incoming.callerPubkey && row.creditId === incoming.creditId && (row.kind !== "completed_refund" || incoming.kind === "completed_refund" && row.drainId === incoming.drainId) && compatibleLocations(row, incoming)
|
|
757
|
+
);
|
|
758
|
+
const newerPrior = prior && (incoming.kind === "completed_refund" && prior.kind === "completed_refund" ? (prior.collectedAt ?? 0) > (incoming.collectedAt ?? 0) : prior.occurredAt > incoming.occurredAt);
|
|
759
|
+
const facts = newerPrior ? prior : incoming;
|
|
760
|
+
const identity = prior && hasAttestedIdentity(prior) ? prior : hasAttestedIdentity(incoming) ? incoming : newerPrior || !incoming.dvmId && !incoming.attestedBuilderPubkey ? prior ?? incoming : incoming;
|
|
761
|
+
const record = prior ? {
|
|
762
|
+
...facts,
|
|
763
|
+
id: prior.id,
|
|
764
|
+
dvmId: identity.dvmId,
|
|
765
|
+
attestedBuilderPubkey: identity.attestedBuilderPubkey,
|
|
766
|
+
endpointAliases: [
|
|
767
|
+
.../* @__PURE__ */ new Set([
|
|
768
|
+
prior.endpoint,
|
|
769
|
+
...prior.endpointAliases,
|
|
770
|
+
incoming.endpoint,
|
|
771
|
+
...incoming.endpointAliases
|
|
772
|
+
])
|
|
773
|
+
].filter((origin) => origin !== facts.endpoint)
|
|
774
|
+
} : incoming;
|
|
775
|
+
validateHistoryRecord(record);
|
|
776
|
+
const encoded = JSON.stringify(record);
|
|
777
|
+
if (latest.get(record.id) === encoded) continue;
|
|
778
|
+
additions.push(encoded + "\n");
|
|
779
|
+
latest.set(record.id, encoded);
|
|
780
|
+
observed.set(record.id, record);
|
|
781
|
+
}
|
|
782
|
+
const fd = openSync(historyPath(), "a", 384);
|
|
783
|
+
try {
|
|
784
|
+
if (current.complete !== current.bytes.length)
|
|
785
|
+
ftruncateSync(fd, current.complete);
|
|
786
|
+
const bytes = Buffer.from(additions.join(""));
|
|
787
|
+
let written = 0;
|
|
788
|
+
while (written < bytes.length) {
|
|
789
|
+
const count = writeSync(fd, bytes, written, bytes.length - written);
|
|
790
|
+
if (!count) fail("zero-length append");
|
|
791
|
+
written += count;
|
|
792
|
+
}
|
|
793
|
+
fsyncSync(fd);
|
|
794
|
+
} finally {
|
|
795
|
+
closeSync(fd);
|
|
796
|
+
}
|
|
797
|
+
{
|
|
798
|
+
const directory = openSync(
|
|
799
|
+
historyPath().slice(0, historyPath().lastIndexOf("/")),
|
|
800
|
+
"r"
|
|
801
|
+
);
|
|
802
|
+
try {
|
|
803
|
+
fsyncSync(directory);
|
|
804
|
+
} finally {
|
|
805
|
+
closeSync(directory);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
} catch (error) {
|
|
809
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
function readCreditHistoryPage(query) {
|
|
813
|
+
const limit = query.limit ?? 50;
|
|
814
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
815
|
+
throw new DvmError(
|
|
816
|
+
"invalid_credit_history_query",
|
|
817
|
+
"History page limit must be an integer from 1 through 100."
|
|
818
|
+
);
|
|
819
|
+
const order = query.order ?? "asc";
|
|
820
|
+
if (order !== "asc" && order !== "desc")
|
|
821
|
+
throw new DvmError(
|
|
822
|
+
"invalid_credit_history_query",
|
|
823
|
+
"History order must be asc or desc."
|
|
824
|
+
);
|
|
825
|
+
const direction = order === "asc" ? 1 : -1;
|
|
826
|
+
const filter = JSON.stringify([
|
|
827
|
+
order,
|
|
828
|
+
query.endpoint ? new URL(query.endpoint).origin : null,
|
|
829
|
+
query.dvmId ?? null,
|
|
830
|
+
query.callerPubkey ?? null
|
|
831
|
+
]);
|
|
832
|
+
const current = journal();
|
|
833
|
+
let end = current.complete;
|
|
834
|
+
let after;
|
|
835
|
+
if (query.cursor) {
|
|
836
|
+
try {
|
|
837
|
+
const cursor = JSON.parse(
|
|
838
|
+
Buffer.from(query.cursor, "base64url").toString("utf8")
|
|
839
|
+
);
|
|
840
|
+
if (cursor.v !== 1 || !Number.isSafeInteger(cursor.end) || cursor.end < 0 || cursor.end > current.complete || cursor.end > 0 && current.bytes[cursor.end - 1] !== 10 || cursor.filter !== filter || cursor.prefix !== hash(current.bytes.subarray(0, cursor.end).toString("utf8")) || !Array.isArray(cursor.after) || !Number.isFinite(cursor.after[0]) || typeof cursor.after[1] !== "string")
|
|
841
|
+
throw new Error("cursor mismatch");
|
|
842
|
+
end = cursor.end;
|
|
843
|
+
after = cursor.after;
|
|
844
|
+
} catch {
|
|
845
|
+
throw new DvmError(
|
|
846
|
+
"invalid_credit_history_cursor",
|
|
847
|
+
"History cursor is invalid, stale, or belongs to different filters."
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
const rows = current.bytes.subarray(0, end).toString("utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
|
|
852
|
+
const endpoint = query.endpoint ? new URL(query.endpoint).origin : void 0;
|
|
853
|
+
const ordered = [...new Map(rows.map((row) => [row.id, row])).values()].filter(
|
|
854
|
+
(row) => (!endpoint || row.endpoint === endpoint || row.endpointAliases.includes(endpoint)) && (!query.dvmId || row.dvmId === query.dvmId) && (!query.callerPubkey || row.callerPubkey === query.callerPubkey)
|
|
855
|
+
).sort(
|
|
856
|
+
(a, b) => direction * (a.occurredAt - b.occurredAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
857
|
+
);
|
|
858
|
+
const remaining = ordered.filter(
|
|
859
|
+
(row) => !after || direction * (row.occurredAt - after[0]) > 0 || row.occurredAt === after[0] && (direction === 1 ? row.id > after[1] : row.id < after[1])
|
|
860
|
+
);
|
|
861
|
+
const records = remaining.slice(0, limit);
|
|
862
|
+
const last = records.at(-1);
|
|
863
|
+
return {
|
|
864
|
+
records,
|
|
865
|
+
...remaining.length > limit && last ? {
|
|
866
|
+
nextCursor: Buffer.from(
|
|
867
|
+
JSON.stringify({
|
|
868
|
+
v: 1,
|
|
869
|
+
end,
|
|
870
|
+
prefix: hash(current.bytes.subarray(0, end).toString("utf8")),
|
|
871
|
+
filter,
|
|
872
|
+
after: [last.occurredAt, last.id]
|
|
873
|
+
})
|
|
874
|
+
).toString("base64url")
|
|
875
|
+
} : {}
|
|
876
|
+
};
|
|
877
|
+
}
|
|
453
878
|
function withCreditLock(fn, opts = {}) {
|
|
454
879
|
if (lockDepth > 0) {
|
|
455
880
|
lockDepth += 1;
|
|
@@ -572,6 +997,12 @@ function clearCreditSelection(endpoint, callerPubkey, creditId, identity) {
|
|
|
572
997
|
return structuredClone(record);
|
|
573
998
|
});
|
|
574
999
|
}
|
|
1000
|
+
function readCompletedCreditHistory(query = {}) {
|
|
1001
|
+
return withCreditLock(() => {
|
|
1002
|
+
loadStore(true);
|
|
1003
|
+
return readCreditHistoryPage(query);
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
575
1006
|
function listCredits() {
|
|
576
1007
|
return withCreditLock(() => [...loadStore().credits].sort((a, b) => b.updatedAt - a.updatedAt));
|
|
577
1008
|
}
|
|
@@ -622,7 +1053,13 @@ function markImplicitCreditLost(args) {
|
|
|
622
1053
|
where: (candidate) => candidate.callerPubkey === args.callerPubkey && candidate.creditId === args.creditId
|
|
623
1054
|
});
|
|
624
1055
|
if (!record) return void 0;
|
|
625
|
-
attachDvmLocation(record, key, args.identity);
|
|
1056
|
+
const locationChanged = attachDvmLocation(record, key, args.identity);
|
|
1057
|
+
if (record.status === "lost" && !archiveOrKeep(
|
|
1058
|
+
() => archiveCompletedCreditRecords([completedLoss(record)])
|
|
1059
|
+
)) {
|
|
1060
|
+
if (locationChanged) saveStore(store);
|
|
1061
|
+
return record;
|
|
1062
|
+
}
|
|
626
1063
|
record.status = "lost";
|
|
627
1064
|
record.lossReason = args.reason;
|
|
628
1065
|
record.updatedAt = args.now ?? Date.now();
|
|
@@ -891,7 +1328,13 @@ function applyImplicitReceiptCredit(args) {
|
|
|
891
1328
|
saveStore(store);
|
|
892
1329
|
return store.implicitCredits.includes(record) ? { credit: record } : {};
|
|
893
1330
|
}
|
|
894
|
-
attachDvmLocation(record, key, args.identity);
|
|
1331
|
+
const locationChanged = attachDvmLocation(record, key, args.identity);
|
|
1332
|
+
if (record.status === "lost" && !archiveOrKeep(
|
|
1333
|
+
() => archiveCompletedCreditRecords([completedLoss(record)])
|
|
1334
|
+
)) {
|
|
1335
|
+
if (locationChanged) saveStore(store);
|
|
1336
|
+
return { credit: record };
|
|
1337
|
+
}
|
|
895
1338
|
let mismatch;
|
|
896
1339
|
const sequential = args.credit.ledger_seq === record.ledgerSeq + 1;
|
|
897
1340
|
if (sequential && args.outcome === "completed" && record.status === "active") {
|
|
@@ -1068,6 +1511,9 @@ function forgetCredit(endpoint, callerPubkey, identity) {
|
|
|
1068
1511
|
where: (c) => c.callerPubkey === callerPubkey
|
|
1069
1512
|
});
|
|
1070
1513
|
if (!record) return;
|
|
1514
|
+
archiveCompletedCreditRecords(
|
|
1515
|
+
(record.drainEvidence ?? []).filter((bundle) => bundle.settledAt !== void 0).map((bundle) => completedRefund(record, bundle))
|
|
1516
|
+
);
|
|
1071
1517
|
saveStore({ ...store, credits: store.credits.filter((c) => c !== record) });
|
|
1072
1518
|
});
|
|
1073
1519
|
}
|
|
@@ -1110,6 +1556,11 @@ function recordDrainReceipts(args) {
|
|
|
1110
1556
|
mutateCredit(mutationAt(endpoint, callerPubkey, identity), (record) => {
|
|
1111
1557
|
const evidence = record.drainEvidence ??= [];
|
|
1112
1558
|
let bundle = evidence.find((e) => e.drainId === drainId);
|
|
1559
|
+
if (bundle?.settledAt !== void 0 && !archiveOrKeep(
|
|
1560
|
+
() => archiveCompletedCreditRecords([completedRefund(record, bundle)])
|
|
1561
|
+
)) {
|
|
1562
|
+
return "skip";
|
|
1563
|
+
}
|
|
1113
1564
|
if (!bundle) {
|
|
1114
1565
|
bundle = { drainId, creditId, receipts: [], collectedAt: now };
|
|
1115
1566
|
evidence.push(bundle);
|
|
@@ -1117,9 +1568,15 @@ function recordDrainReceipts(args) {
|
|
|
1117
1568
|
bundle.creditId = creditId;
|
|
1118
1569
|
bundle.receipts = receipts;
|
|
1119
1570
|
bundle.collectedAt = now;
|
|
1571
|
+
bundle.settlement ??= {
|
|
1572
|
+
rail: null,
|
|
1573
|
+
currency: record.creditId === creditId ? record.currency : null,
|
|
1574
|
+
amountMicro: null,
|
|
1575
|
+
feeMicro: null
|
|
1576
|
+
};
|
|
1120
1577
|
if (read.anchor) bundle.anchor = read.anchor;
|
|
1121
1578
|
else if (read.reachable) delete bundle.anchor;
|
|
1122
|
-
record.drainEvidence =
|
|
1579
|
+
record.drainEvidence = evidence;
|
|
1123
1580
|
return void 0;
|
|
1124
1581
|
});
|
|
1125
1582
|
}
|
|
@@ -1130,7 +1587,8 @@ function settleDrainEvidence(args) {
|
|
|
1130
1587
|
const bundle = evidence.find((e) => e.drainId === drainId);
|
|
1131
1588
|
if (!bundle || bundle.settledAt !== void 0) return "skip";
|
|
1132
1589
|
bundle.settledAt = now;
|
|
1133
|
-
|
|
1590
|
+
if (args.settlement) bundle.settlement = args.settlement;
|
|
1591
|
+
record.drainEvidence = evidence;
|
|
1134
1592
|
return void 0;
|
|
1135
1593
|
});
|
|
1136
1594
|
}
|
|
@@ -1196,19 +1654,19 @@ function adoptCreditId(record, creditId) {
|
|
|
1196
1654
|
var MAX_SETTLED_DRAIN_EVIDENCE = 8;
|
|
1197
1655
|
var MAX_LOST_IMPLICIT_CREDITS = 8;
|
|
1198
1656
|
var MAX_DATE_MS = 864e13;
|
|
1199
|
-
function loadStore() {
|
|
1657
|
+
function loadStore(requireArchive = false) {
|
|
1200
1658
|
if (!existsSync2(CREDITS_FILE)) {
|
|
1201
1659
|
return { credits: [], implicitCredits: [], pendingFundings: [], fundingMenuSnapshots: [] };
|
|
1202
1660
|
}
|
|
1203
|
-
let
|
|
1661
|
+
let raw;
|
|
1204
1662
|
try {
|
|
1205
|
-
|
|
1663
|
+
raw = readFileSync2(CREDITS_FILE, "utf-8");
|
|
1206
1664
|
} catch (cause) {
|
|
1207
1665
|
throw unreadableStore(cause);
|
|
1208
1666
|
}
|
|
1209
1667
|
let data;
|
|
1210
1668
|
try {
|
|
1211
|
-
const parsed = JSON.parse(
|
|
1669
|
+
const parsed = JSON.parse(raw);
|
|
1212
1670
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1213
1671
|
throw new Error("the file parsed as JSON but is not a credit-store object");
|
|
1214
1672
|
}
|
|
@@ -1229,7 +1687,8 @@ function loadStore() {
|
|
|
1229
1687
|
Array.isArray(data.pendingFundings) ? data.pendingFundings.filter((funding) => isObjectRecord(funding)).map(normalizeRailKey) : []
|
|
1230
1688
|
);
|
|
1231
1689
|
const implicit = dedupeImplicitCredits(
|
|
1232
|
-
Array.isArray(data.implicitCredits) ? data.implicitCredits.filter(isStoredImplicitCredit) : []
|
|
1690
|
+
Array.isArray(data.implicitCredits) ? data.implicitCredits.filter(isStoredImplicitCredit) : [],
|
|
1691
|
+
requireArchive
|
|
1233
1692
|
);
|
|
1234
1693
|
const store = {
|
|
1235
1694
|
credits: merged.credits,
|
|
@@ -1237,14 +1696,16 @@ function loadStore() {
|
|
|
1237
1696
|
pendingFundings: fundings.fundings,
|
|
1238
1697
|
fundingMenuSnapshots: snapshots.snapshots
|
|
1239
1698
|
};
|
|
1699
|
+
if (requireArchive) archiveStore(store);
|
|
1240
1700
|
if (merged.changed || snapshots.changed || fundings.changed || implicit.changed) saveStore(store);
|
|
1701
|
+
else if (!requireArchive) archiveOrKeep(() => archiveStore(store));
|
|
1241
1702
|
return store;
|
|
1242
1703
|
}
|
|
1243
1704
|
function isStoredImplicitCredit(value) {
|
|
1244
1705
|
if (!isObjectRecord(value)) return false;
|
|
1245
1706
|
return typeof value.endpoint === "string" && typeof value.callerPubkey === "string" && typeof value.creditId === "string" && value.creditId.startsWith("imp:") && typeof value.currency === "string" && typeof value.remainingMicro === "number" && Number.isFinite(value.remainingMicro) && typeof value.ledgerSeq === "number" && Number.isInteger(value.ledgerSeq) && typeof value.expiryMs === "number" && Number.isFinite(value.expiryMs) && (value.status === "active" || value.status === "lost") && typeof value.releasedByJobId === "string" && typeof value.releasedAt === "number" && Number.isFinite(value.releasedAt) && typeof value.updatedAt === "number" && Number.isFinite(value.updatedAt);
|
|
1246
1707
|
}
|
|
1247
|
-
function dedupeImplicitCredits(credits) {
|
|
1708
|
+
function dedupeImplicitCredits(credits, requireArchive = false) {
|
|
1248
1709
|
const merged = [];
|
|
1249
1710
|
let changed = false;
|
|
1250
1711
|
for (const candidate of credits) {
|
|
@@ -1259,6 +1720,9 @@ function dedupeImplicitCredits(credits) {
|
|
|
1259
1720
|
merged.push(candidate);
|
|
1260
1721
|
continue;
|
|
1261
1722
|
}
|
|
1723
|
+
if (!archiveOrKeep(() => archiveCompletedCreditRecords(
|
|
1724
|
+
[existing, candidate].filter((record) => record.status === "lost").map(completedLoss)
|
|
1725
|
+
), requireArchive)) return { credits, changed: false };
|
|
1262
1726
|
changed = true;
|
|
1263
1727
|
for (const origin of dvmLocationOrigins(candidate)) {
|
|
1264
1728
|
attachDvmLocation(existing, origin, identity);
|
|
@@ -1280,7 +1744,7 @@ function dedupeImplicitCredits(credits) {
|
|
|
1280
1744
|
existing.releasedByJobId = candidate.releasedByJobId;
|
|
1281
1745
|
}
|
|
1282
1746
|
}
|
|
1283
|
-
const capped = capLostImplicitCredits(merged);
|
|
1747
|
+
const capped = capLostImplicitCredits(merged, requireArchive);
|
|
1284
1748
|
return { credits: capped.credits, changed: changed || capped.changed };
|
|
1285
1749
|
}
|
|
1286
1750
|
function ageImplicitCredits(credits, now) {
|
|
@@ -1295,7 +1759,14 @@ function ageImplicitCredits(credits, now) {
|
|
|
1295
1759
|
}
|
|
1296
1760
|
return changed;
|
|
1297
1761
|
}
|
|
1298
|
-
function capLostImplicitCredits(credits) {
|
|
1762
|
+
function capLostImplicitCredits(credits, requireArchive = false) {
|
|
1763
|
+
const archived = archiveOrKeep(
|
|
1764
|
+
() => archiveCompletedCreditRecords(
|
|
1765
|
+
credits.filter((credit) => credit.status === "lost").map(completedLoss)
|
|
1766
|
+
),
|
|
1767
|
+
requireArchive
|
|
1768
|
+
);
|
|
1769
|
+
if (!archived) return { credits, changed: false };
|
|
1299
1770
|
const lostByOwner = /* @__PURE__ */ new Map();
|
|
1300
1771
|
for (const credit of credits) {
|
|
1301
1772
|
if (credit.status !== "lost") continue;
|
|
@@ -1598,19 +2069,39 @@ function isEvidenceish(value) {
|
|
|
1598
2069
|
function isDrainish(value) {
|
|
1599
2070
|
return typeof value === "object" && value !== null && typeof value.drainId === "string";
|
|
1600
2071
|
}
|
|
1601
|
-
function
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
2072
|
+
function archiveOrKeep(action, requireArchive = false) {
|
|
2073
|
+
try {
|
|
2074
|
+
action();
|
|
2075
|
+
return true;
|
|
2076
|
+
} catch (error) {
|
|
2077
|
+
if (requireArchive || !(error instanceof DvmError) || error.code !== "credit_history_unavailable") {
|
|
2078
|
+
throw error;
|
|
2079
|
+
}
|
|
2080
|
+
return false;
|
|
1609
2081
|
}
|
|
2082
|
+
}
|
|
2083
|
+
function archiveStore(store) {
|
|
2084
|
+
archiveCompletedCreditRecords([
|
|
2085
|
+
...store.credits.flatMap(
|
|
2086
|
+
(credit) => (credit.drainEvidence ?? []).filter((bundle) => bundle.settledAt !== void 0).map((bundle) => completedRefund(credit, bundle))
|
|
2087
|
+
),
|
|
2088
|
+
...store.implicitCredits.filter((credit) => credit.status === "lost").map(completedLoss)
|
|
2089
|
+
]);
|
|
2090
|
+
}
|
|
2091
|
+
function capDrainEvidence(evidence) {
|
|
2092
|
+
const settled = evidence.filter((e) => e.settledAt !== void 0).sort((a, b) => a.settledAt - b.settledAt);
|
|
2093
|
+
const dropped = new Set(
|
|
2094
|
+
settled.slice(0, Math.max(0, settled.length - MAX_SETTLED_DRAIN_EVIDENCE))
|
|
2095
|
+
);
|
|
1610
2096
|
return evidence.filter((e) => !dropped.has(e));
|
|
1611
2097
|
}
|
|
1612
2098
|
function saveStore(store) {
|
|
1613
2099
|
ensureConfigDir();
|
|
2100
|
+
if (archiveOrKeep(() => archiveStore(store))) {
|
|
2101
|
+
for (const credit of store.credits) {
|
|
2102
|
+
if (credit.drainEvidence) credit.drainEvidence = capDrainEvidence(credit.drainEvidence);
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
1614
2105
|
const tmp = `${CREDITS_FILE}.${String(process.pid)}.tmp`;
|
|
1615
2106
|
writeFileSync2(tmp, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
|
|
1616
2107
|
try {
|
|
@@ -1742,6 +2233,9 @@ function sleepSync(ms) {
|
|
|
1742
2233
|
}
|
|
1743
2234
|
|
|
1744
2235
|
export {
|
|
2236
|
+
canonicalize,
|
|
2237
|
+
canonicaliseForSigning,
|
|
2238
|
+
verifyCanonicalSignedRequest,
|
|
1745
2239
|
fiatToSatsCeil,
|
|
1746
2240
|
satsToFiat,
|
|
1747
2241
|
InvalidUsdPriceError,
|
|
@@ -1770,12 +2264,16 @@ export {
|
|
|
1770
2264
|
getLastKnownBtcRate,
|
|
1771
2265
|
formatStaleness,
|
|
1772
2266
|
formatAmountBestEffort,
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
2267
|
+
computeResultHash,
|
|
2268
|
+
signReceipt,
|
|
2269
|
+
verifyReceipt,
|
|
2270
|
+
isSignedJobReceipt,
|
|
2271
|
+
signDrainReceipt,
|
|
2272
|
+
signFundingReceipt,
|
|
2273
|
+
isFundingReceipt,
|
|
2274
|
+
verifyFundingReceipt,
|
|
2275
|
+
isDrainReceipt,
|
|
2276
|
+
verifyDrainReceipt,
|
|
1779
2277
|
RAIL_FLAGS,
|
|
1780
2278
|
maxAdvertisedMicro,
|
|
1781
2279
|
withinAdvertisedTolerance,
|
|
@@ -1789,6 +2287,7 @@ export {
|
|
|
1789
2287
|
pendingDrainById,
|
|
1790
2288
|
loadCredit,
|
|
1791
2289
|
clearCreditSelection,
|
|
2290
|
+
readCompletedCreditHistory,
|
|
1792
2291
|
listCredits,
|
|
1793
2292
|
listImplicitCredits,
|
|
1794
2293
|
loadImplicitCredits,
|