@pacspace-io/check 0.5.6 → 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/CHANGELOG.md +16 -0
- package/README.md +34 -0
- package/dist/cli.d.ts +5 -1
- package/dist/cli.js +1993 -121
- package/dist/index.js +196 -19
- package/dist/inputs.txt +11 -0
- package/dist/open-io.d.ts +38 -0
- package/dist/open.d.ts +16 -15
- package/dist/records-crypto-types/records/flag-threads-v1.d.ts +53 -0
- package/dist/records-crypto-types/records/labels.d.ts +37 -0
- package/dist/records-crypto-types/records/link-handle-v1.d.ts +16 -0
- package/dist/records-crypto-types/records/reader-crypto-v1.d.ts +198 -0
- package/dist/records-crypto-types/records/reader-link-v1.d.ts +164 -0
- package/dist/records-crypto-types/records/shared-record-ack-v2.d.ts +72 -0
- package/dist/records-crypto-types/records/trail-index-v1.d.ts +89 -0
- package/dist/records-crypto-types/records/trail-rule.d.ts +54 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/ack-flag-notes-v1.d.ts +57 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/flag-notes-v1.d.ts +55 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/index.d.ts +3 -0
- package/dist/records-crypto-types/records-crypto/asymmetric/reader-wraps-v1.d.ts +83 -0
- package/dist/records-crypto-types/records-crypto/disclosure-envelope-v1.d.ts +1 -1
- package/dist/records-crypto-types/records-crypto/index.d.ts +1 -1
- package/dist/records-crypto-types/records-crypto/records-encryption-v1.d.ts +1 -0
- package/dist/records-crypto.js +547 -66
- package/dist/shared-record-link.d.ts +121 -0
- package/dist/shared-record-words.d.ts +97 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -2102,12 +2102,6 @@ var import_ethers14 = require("ethers");
|
|
|
2102
2102
|
// ../shared/src/demo/mirror-node-record-chain-reader.ts
|
|
2103
2103
|
var import_ethers13 = require("ethers");
|
|
2104
2104
|
|
|
2105
|
-
// ../shared/src/records/inspect-record-calldata-v1.ts
|
|
2106
|
-
var MIRROR_NODE_BY_CHAIN = Object.freeze({
|
|
2107
|
-
296: "https://testnet.mirrornode.hedera.com",
|
|
2108
|
-
295: "https://mainnet-public.mirrornode.hedera.com"
|
|
2109
|
-
});
|
|
2110
|
-
|
|
2111
2105
|
// ../shared/src/records/ledger-write-search-v1.ts
|
|
2112
2106
|
var LEDGER_WRITE_SEARCH_WINDOW_LIMIT_SECONDS = 7 * 24 * 60 * 60;
|
|
2113
2107
|
var LEDGER_WRITE_SEARCH_PAGE_LIMIT = 100;
|
|
@@ -2276,6 +2270,12 @@ function parseLedgerWriteLog(log, expected) {
|
|
|
2276
2270
|
};
|
|
2277
2271
|
}
|
|
2278
2272
|
|
|
2273
|
+
// ../shared/src/records/inspect-record-calldata-v1.ts
|
|
2274
|
+
var MIRROR_NODE_BY_CHAIN = Object.freeze({
|
|
2275
|
+
296: "https://testnet.mirrornode.hedera.com",
|
|
2276
|
+
295: "https://mainnet-public.mirrornode.hedera.com"
|
|
2277
|
+
});
|
|
2278
|
+
|
|
2279
2279
|
// ../shared/src/demo/independent-verify-records.ts
|
|
2280
2280
|
var import_ethers12 = require("ethers");
|
|
2281
2281
|
|
|
@@ -2289,7 +2289,7 @@ var MIN_SECRET_LENGTH = 8;
|
|
|
2289
2289
|
var URL_IN_TEXT = /[a-z][a-z0-9+.-]*:\/\/[^\s"'<>\\`]+/gi;
|
|
2290
2290
|
var RAW_SEPARATORS = /[/?&=#;@:]/;
|
|
2291
2291
|
var ETHERS_ERROR_EXTRA_FIELDS = ["operation", "reason", "event"];
|
|
2292
|
-
function
|
|
2292
|
+
function rpcHttpUrl(value) {
|
|
2293
2293
|
const trimmed = value.trim();
|
|
2294
2294
|
if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
|
|
2295
2295
|
if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
|
|
@@ -2297,7 +2297,7 @@ function normalizeRpcUrl(value) {
|
|
|
2297
2297
|
}
|
|
2298
2298
|
function rpcEndpointLabel(value) {
|
|
2299
2299
|
try {
|
|
2300
|
-
return new URL(
|
|
2300
|
+
return new URL(rpcHttpUrl(value)).hostname.toLowerCase();
|
|
2301
2301
|
} catch {
|
|
2302
2302
|
return "unparseable-rpc-endpoint";
|
|
2303
2303
|
}
|
|
@@ -2396,6 +2396,90 @@ function redactRpcError(error, secrets) {
|
|
|
2396
2396
|
}
|
|
2397
2397
|
return new Error(cleanText(String(error), secrets));
|
|
2398
2398
|
}
|
|
2399
|
+
var RpcResultUnavailableError = class extends Error {
|
|
2400
|
+
constructor(what, reason) {
|
|
2401
|
+
super(`${what} from the RPC is incomplete: ${reason}`);
|
|
2402
|
+
this.code = "RPC_RESULT_UNAVAILABLE";
|
|
2403
|
+
this.name = "RpcResultUnavailableError";
|
|
2404
|
+
}
|
|
2405
|
+
};
|
|
2406
|
+
var HEX_QUANTITY = /^0x[0-9a-f]+$/i;
|
|
2407
|
+
function parseRpcQuantity(value, what) {
|
|
2408
|
+
if (typeof value !== "string" || !HEX_QUANTITY.test(value)) {
|
|
2409
|
+
throw new RpcResultUnavailableError(what, "not a hex quantity");
|
|
2410
|
+
}
|
|
2411
|
+
return BigInt(value);
|
|
2412
|
+
}
|
|
2413
|
+
var QUANTITY_RESULTS = {
|
|
2414
|
+
getBlockNumber: "eth_blockNumber",
|
|
2415
|
+
getTransactionCount: "eth_getTransactionCount",
|
|
2416
|
+
getBalance: "eth_getBalance",
|
|
2417
|
+
getGasPrice: "eth_gasPrice",
|
|
2418
|
+
getPriorityFee: "eth_maxPriorityFeePerGas",
|
|
2419
|
+
estimateGas: "eth_estimateGas"
|
|
2420
|
+
};
|
|
2421
|
+
function incompleteReason(error) {
|
|
2422
|
+
const short = String(error?.shortMessage ?? error?.message ?? error);
|
|
2423
|
+
const field = /^invalid value for value\.(\w+) \(([^(]*)/.exec(short);
|
|
2424
|
+
return field ? `${field[1]}: ${field[2].trim()}` : short.split(" (")[0];
|
|
2425
|
+
}
|
|
2426
|
+
function formatted(what, format) {
|
|
2427
|
+
try {
|
|
2428
|
+
return format();
|
|
2429
|
+
} catch (error) {
|
|
2430
|
+
throw new RpcResultUnavailableError(what, incompleteReason(error));
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
var SUBSCRIBE_METHODS = /* @__PURE__ */ new Set(["eth_subscribe", "eth_newFilter"]);
|
|
2434
|
+
var UNSUBSCRIBE_METHODS = /* @__PURE__ */ new Set(["eth_unsubscribe", "eth_uninstallFilter"]);
|
|
2435
|
+
var SUBSCRIBE_RETRY_BASE_MS = 1e3;
|
|
2436
|
+
var SUBSCRIBE_RETRY_MAX_MS = 6e4;
|
|
2437
|
+
var REJECTION_MESSAGE_MAX = 300;
|
|
2438
|
+
function rejectionMessage(error, secrets) {
|
|
2439
|
+
const inner = error?.error?.message;
|
|
2440
|
+
let text;
|
|
2441
|
+
if (typeof inner === "string") text = inner;
|
|
2442
|
+
else if (isEthersError(error)) text = error.shortMessage;
|
|
2443
|
+
else if (isErrorLike(error)) text = error.message;
|
|
2444
|
+
else text = String(error);
|
|
2445
|
+
return cleanText(text, secrets).slice(0, REJECTION_MESSAGE_MAX);
|
|
2446
|
+
}
|
|
2447
|
+
function pause(ms) {
|
|
2448
|
+
return new Promise((resolve3) => {
|
|
2449
|
+
const timer = setTimeout(resolve3, ms);
|
|
2450
|
+
timer.unref?.();
|
|
2451
|
+
});
|
|
2452
|
+
}
|
|
2453
|
+
async function guardSubscriptionSend(method, send, provider, retry, secrets) {
|
|
2454
|
+
const report = (rejection) => {
|
|
2455
|
+
try {
|
|
2456
|
+
retry.onRejected?.(rejection);
|
|
2457
|
+
} catch {
|
|
2458
|
+
}
|
|
2459
|
+
};
|
|
2460
|
+
if (UNSUBSCRIBE_METHODS.has(method)) {
|
|
2461
|
+
try {
|
|
2462
|
+
return await send();
|
|
2463
|
+
} catch (error) {
|
|
2464
|
+
report({ method, attempt: 1, retryInMs: null, message: rejectionMessage(error, secrets) });
|
|
2465
|
+
return false;
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
if (!SUBSCRIBE_METHODS.has(method)) return send();
|
|
2469
|
+
const base = retry.baseDelayMs ?? SUBSCRIBE_RETRY_BASE_MS;
|
|
2470
|
+
const max = retry.maxDelayMs ?? SUBSCRIBE_RETRY_MAX_MS;
|
|
2471
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
2472
|
+
try {
|
|
2473
|
+
return await send();
|
|
2474
|
+
} catch (error) {
|
|
2475
|
+
if (provider.destroyed) return new Promise(() => void 0);
|
|
2476
|
+
const retryInMs = Math.min(base * 2 ** (attempt - 1), max);
|
|
2477
|
+
report({ method, attempt, retryInMs, message: rejectionMessage(error, secrets) });
|
|
2478
|
+
await pause(retryInMs);
|
|
2479
|
+
if (provider.destroyed) return new Promise(() => void 0);
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2399
2483
|
function requestFor(url, options) {
|
|
2400
2484
|
const request = new import_ethers10.FetchRequest(url);
|
|
2401
2485
|
if (options.timeoutMs !== void 0) request.timeout = options.timeoutMs;
|
|
@@ -2413,7 +2497,7 @@ async function readRpcChainId(url, options = {}) {
|
|
|
2413
2497
|
response.assertOk();
|
|
2414
2498
|
const answer = response.bodyJson;
|
|
2415
2499
|
const result = answer !== null && typeof answer === "object" ? answer.result : void 0;
|
|
2416
|
-
if (typeof result !== "string" || !CHAIN_ID_RESULT.test(result)) throw new
|
|
2500
|
+
if (typeof result !== "string" || !CHAIN_ID_RESULT.test(result)) throw new RpcResultUnavailableError("eth_chainId", "not a chain id");
|
|
2417
2501
|
return Number.parseInt(result, 16);
|
|
2418
2502
|
} catch (error) {
|
|
2419
2503
|
throw redactRpcError(error, secrets);
|
|
@@ -2421,10 +2505,15 @@ async function readRpcChainId(url, options = {}) {
|
|
|
2421
2505
|
}
|
|
2422
2506
|
var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
|
|
2423
2507
|
#secrets;
|
|
2508
|
+
#subscriptionRetry;
|
|
2424
2509
|
constructor(url, network, options) {
|
|
2425
|
-
const { timeoutMs, prepareRequest, ...providerOptions } = options;
|
|
2510
|
+
const { timeoutMs, subscriptionRetry, prepareRequest, ...providerOptions } = options;
|
|
2426
2511
|
super(requestFor(url, { timeoutMs, prepareRequest }), network, providerOptions);
|
|
2427
2512
|
this.#secrets = rpcUrlSecrets(url);
|
|
2513
|
+
this.#subscriptionRetry = subscriptionRetry ?? {};
|
|
2514
|
+
}
|
|
2515
|
+
send(method, params) {
|
|
2516
|
+
return guardSubscriptionSend(method, () => super.send(method, params), this, this.#subscriptionRetry, this.#secrets);
|
|
2428
2517
|
}
|
|
2429
2518
|
async _send(payload) {
|
|
2430
2519
|
try {
|
|
@@ -2433,6 +2522,24 @@ var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
|
|
|
2433
2522
|
throw redactRpcError(error, this.#secrets);
|
|
2434
2523
|
}
|
|
2435
2524
|
}
|
|
2525
|
+
async _perform(req) {
|
|
2526
|
+
const result = await super._perform(req);
|
|
2527
|
+
const method = QUANTITY_RESULTS[req.method];
|
|
2528
|
+
if (method) parseRpcQuantity(result, method);
|
|
2529
|
+
return result;
|
|
2530
|
+
}
|
|
2531
|
+
_wrapTransactionResponse(tx, network) {
|
|
2532
|
+
return formatted("transaction", () => super._wrapTransactionResponse(tx, network));
|
|
2533
|
+
}
|
|
2534
|
+
_wrapTransactionReceipt(value, network) {
|
|
2535
|
+
return formatted("transaction receipt", () => super._wrapTransactionReceipt(value, network));
|
|
2536
|
+
}
|
|
2537
|
+
_wrapBlock(value, network) {
|
|
2538
|
+
return formatted("block", () => super._wrapBlock(value, network));
|
|
2539
|
+
}
|
|
2540
|
+
_wrapLog(value, network) {
|
|
2541
|
+
return formatted("log", () => super._wrapLog(value, network));
|
|
2542
|
+
}
|
|
2436
2543
|
};
|
|
2437
2544
|
function createRpcProvider(url, network, options = {}) {
|
|
2438
2545
|
return new RedactingJsonRpcProvider(url, network, options);
|
|
@@ -2550,7 +2657,7 @@ function checkLayoutOnChain(onChainLayout, published) {
|
|
|
2550
2657
|
const matchesPublished = !!published && onChainLayout.registered && onChainLayout.layoutDigest === published.digest;
|
|
2551
2658
|
return { ...onChainLayout, matchesPublished, failure: matchesPublished ? null : LAYOUT_NOT_REGISTERED };
|
|
2552
2659
|
}
|
|
2553
|
-
function
|
|
2660
|
+
function normalizeRpcUrl(url) {
|
|
2554
2661
|
const trimmed = String(url || "").trim();
|
|
2555
2662
|
if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
|
|
2556
2663
|
if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
|
|
@@ -2570,7 +2677,7 @@ async function withTimeout(p, ms, label) {
|
|
|
2570
2677
|
}
|
|
2571
2678
|
}
|
|
2572
2679
|
function createRpcRecordChainReader(options) {
|
|
2573
|
-
const rpcUrl =
|
|
2680
|
+
const rpcUrl = normalizeRpcUrl(options.rpcUrl);
|
|
2574
2681
|
if (!rpcUrl) throw new Error("rpcUrl is required.");
|
|
2575
2682
|
const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
|
|
2576
2683
|
const timeoutMs = Number(options.timeoutMs || 1e4);
|
|
@@ -2712,6 +2819,10 @@ function createRpcRecordChainReader(options) {
|
|
|
2712
2819
|
const writes = [];
|
|
2713
2820
|
const blockTimes = /* @__PURE__ */ new Map();
|
|
2714
2821
|
let requests = 0;
|
|
2822
|
+
const asked = () => {
|
|
2823
|
+
requests += 1;
|
|
2824
|
+
search.onRequest?.();
|
|
2825
|
+
};
|
|
2715
2826
|
const CUT = Symbol("cut");
|
|
2716
2827
|
const within2 = async (p) => {
|
|
2717
2828
|
const left = deadline - now2();
|
|
@@ -2732,13 +2843,13 @@ function createRpcRecordChainReader(options) {
|
|
|
2732
2843
|
const found = await within2(endpoint());
|
|
2733
2844
|
if (found === CUT) return end("timeout");
|
|
2734
2845
|
const { provider } = found;
|
|
2735
|
-
|
|
2846
|
+
asked();
|
|
2736
2847
|
const latest = await within2(provider.getBlockNumber());
|
|
2737
2848
|
if (latest === CUT) return end("timeout");
|
|
2738
2849
|
for (let to = latest; to >= 0; to -= chunk) {
|
|
2739
2850
|
if (search.done(writes)) return end("done");
|
|
2740
2851
|
if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
|
|
2741
|
-
|
|
2852
|
+
asked();
|
|
2742
2853
|
const logs = await within2(provider.getLogs({ address: contractAddress, topics: [RECORD_WRITTEN_TOPIC, key], fromBlock: Math.max(0, to - chunk + 1), toBlock: to }));
|
|
2743
2854
|
if (logs === CUT) return end("timeout");
|
|
2744
2855
|
for (const log of [...logs].reverse()) {
|
|
@@ -2747,7 +2858,7 @@ function createRpcRecordChainReader(options) {
|
|
|
2747
2858
|
let committedAt = blockTimes.get(log.blockNumber);
|
|
2748
2859
|
if (committedAt === void 0) {
|
|
2749
2860
|
if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
|
|
2750
|
-
|
|
2861
|
+
asked();
|
|
2751
2862
|
const block = await within2(provider.getBlock(log.blockNumber));
|
|
2752
2863
|
if (block === CUT) return end("timeout");
|
|
2753
2864
|
if (!block || !Number.isSafeInteger(block.timestamp)) throw new Error(`getBlock ${log.blockNumber} returned no time`);
|
|
@@ -2856,6 +2967,15 @@ function committedAtOf(timestamp) {
|
|
|
2856
2967
|
const [seconds, fraction] = timestamp.split(".");
|
|
2857
2968
|
return new Date(Number(seconds) * 1e3 + Number(fraction.slice(0, 3))).toISOString();
|
|
2858
2969
|
}
|
|
2970
|
+
var SearchLimited = class {
|
|
2971
|
+
constructor(retryAfterMs2) {
|
|
2972
|
+
this.retryAfterMs = retryAfterMs2;
|
|
2973
|
+
}
|
|
2974
|
+
};
|
|
2975
|
+
function retryAfterMsOf(response) {
|
|
2976
|
+
const value = response.headers?.get?.("retry-after");
|
|
2977
|
+
return typeof value === "string" && /^\d{1,6}$/.test(value.trim()) ? Number(value.trim()) * 1e3 : null;
|
|
2978
|
+
}
|
|
2859
2979
|
var KEPT_TOPICS = [RECORD_WRITTEN_TOPIC.toLowerCase(), LEDGER_HEAD_ADVANCED_TOPIC.toLowerCase()];
|
|
2860
2980
|
var HEX_DATA2 = /^0x[0-9a-fA-F]*$/;
|
|
2861
2981
|
function mirrorLogPosition(raw) {
|
|
@@ -3038,6 +3158,10 @@ function createMirrorNodeRecordChainReader(options) {
|
|
|
3038
3158
|
try {
|
|
3039
3159
|
const response = await fetchImpl(`${base}${path}`, { headers: { accept: "application/json" }, redirect: "error", signal: controller.signal });
|
|
3040
3160
|
if (isMirrorRedirect(response)) throw mirrorRefusal.redirect(path);
|
|
3161
|
+
if (response.status === 429) {
|
|
3162
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
3163
|
+
return new SearchLimited(retryAfterMsOf(response));
|
|
3164
|
+
}
|
|
3041
3165
|
if (!response.ok) throw new Error(`mirror node ${response.status} for a record's writes`);
|
|
3042
3166
|
const page = await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
|
|
3043
3167
|
if (Array.isArray(page.logs) && page.logs.length > LEDGER_WRITE_SEARCH_PAGE_LIMIT) throw mirrorRefusal.tooManyLogs(LEDGER_WRITE_SEARCH_PAGE_LIMIT, path);
|
|
@@ -3108,7 +3232,8 @@ function createMirrorNodeRecordChainReader(options) {
|
|
|
3108
3232
|
transactionHash: log.transaction_hash,
|
|
3109
3233
|
logIndex: log.index,
|
|
3110
3234
|
committedAt: committedAtOf(log.timestamp),
|
|
3111
|
-
contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0
|
|
3235
|
+
contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0,
|
|
3236
|
+
...typeof log.timestamp === "string" && CONSENSUS_TIMESTAMP.test(log.timestamp) ? { consensusTimestamp: log.timestamp } : {}
|
|
3112
3237
|
});
|
|
3113
3238
|
}
|
|
3114
3239
|
return out;
|
|
@@ -3124,6 +3249,7 @@ function createMirrorNodeRecordChainReader(options) {
|
|
|
3124
3249
|
let upper = Math.min(Number.isFinite(hint) ? Math.floor(hint / 1e3) : nowSeconds, nowSeconds) + DAY_SECONDS;
|
|
3125
3250
|
const writes = [];
|
|
3126
3251
|
let requests = 0;
|
|
3252
|
+
let waits = 0;
|
|
3127
3253
|
const end = (ended) => ({ writes, ended, requests });
|
|
3128
3254
|
while (!search.done(writes)) {
|
|
3129
3255
|
if (upper <= 0) return end("limit");
|
|
@@ -3133,8 +3259,18 @@ function createMirrorNodeRecordChainReader(options) {
|
|
|
3133
3259
|
const left = deadline - now2();
|
|
3134
3260
|
if (requests >= search.maxRequests || left <= 0) return end("limit");
|
|
3135
3261
|
requests += 1;
|
|
3262
|
+
search.onRequest?.();
|
|
3136
3263
|
const page = await searchPage(path, left);
|
|
3137
3264
|
if (page === "timeout") return end("timeout");
|
|
3265
|
+
if (page instanceof SearchLimited) {
|
|
3266
|
+
const waitOut = search.waitOut;
|
|
3267
|
+
if (!waitOut || waits >= waitOut.times) throw new Error("mirror node 429 for a record's writes");
|
|
3268
|
+
waits += 1;
|
|
3269
|
+
const wait = Math.max(0, Math.min(waitOut.maxWaitMs, page.retryAfterMs ?? waitOut.waitMs));
|
|
3270
|
+
if (wait >= deadline - now2()) return end("limit");
|
|
3271
|
+
await (waitOut.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms))))(wait);
|
|
3272
|
+
continue;
|
|
3273
|
+
}
|
|
3138
3274
|
for (const log of Array.isArray(page?.logs) ? page.logs : []) {
|
|
3139
3275
|
const write = parseLedgerWriteLog(log, { topic0, recordKey: key, contractAddress });
|
|
3140
3276
|
if (!write || !CONSENSUS_TIMESTAMP.test(write.timestamp)) continue;
|
|
@@ -3147,10 +3283,11 @@ function createMirrorNodeRecordChainReader(options) {
|
|
|
3147
3283
|
transactionHash: write.transactionHash,
|
|
3148
3284
|
logIndex: write.logIndex ?? void 0,
|
|
3149
3285
|
committedAt: write.committedAt,
|
|
3150
|
-
contractAddress: write.address
|
|
3286
|
+
contractAddress: write.address,
|
|
3287
|
+
consensusTimestamp: write.timestamp
|
|
3151
3288
|
});
|
|
3152
3289
|
}
|
|
3153
|
-
if (search.done(writes)) return end("done");
|
|
3290
|
+
if (!search.wholeWindows && search.done(writes)) return end("done");
|
|
3154
3291
|
const link = page?.links?.next;
|
|
3155
3292
|
path = nextLogPath(link, { base, contract: contractAddress });
|
|
3156
3293
|
if (!path && link !== null && link !== void 0 && link !== "") throw mirrorRefusal.nextPage();
|
|
@@ -3833,13 +3970,19 @@ async function aesKey2(key, usage) {
|
|
|
3833
3970
|
const subtle = (await platformCrypto()).subtle;
|
|
3834
3971
|
return subtle.importKey("raw", key, { name: "AES-GCM" }, false, [usage]);
|
|
3835
3972
|
}
|
|
3973
|
+
function isDecryptKey(key) {
|
|
3974
|
+
if (typeof CryptoKey === "undefined" || !(key instanceof CryptoKey) || key.type !== "secret" || !key.usages.includes("decrypt")) return false;
|
|
3975
|
+
const algorithm = key.algorithm;
|
|
3976
|
+
return algorithm.name === "AES-GCM" && algorithm.length === KEY_BYTES2 * 8;
|
|
3977
|
+
}
|
|
3836
3978
|
async function decryptDisclosureV1(input) {
|
|
3837
3979
|
try {
|
|
3838
3980
|
const shape = readDisclosureEnvelopeShapeV1(input?.envelope);
|
|
3839
3981
|
if (!shape.ok) return refuse4(shape.code);
|
|
3840
3982
|
const bytes2 = fromBase64Url(input.envelope);
|
|
3841
3983
|
const { key, handle } = input;
|
|
3842
|
-
|
|
3984
|
+
const held = isDecryptKey(key);
|
|
3985
|
+
if (!held && (!(key instanceof Uint8Array) || key.length !== KEY_BYTES2) || typeof handle !== "string") {
|
|
3843
3986
|
return refuse4("DISCLOSURE_ENVELOPE_AUTH_FAILED");
|
|
3844
3987
|
}
|
|
3845
3988
|
let plain;
|
|
@@ -3848,7 +3991,7 @@ async function decryptDisclosureV1(input) {
|
|
|
3848
3991
|
plain = new Uint8Array(
|
|
3849
3992
|
await subtle.decrypt(
|
|
3850
3993
|
{ name: "AES-GCM", iv: bytes2.subarray(1, HEADER_BYTES), additionalData: aadOf2(handle), tagLength: 128 },
|
|
3851
|
-
await aesKey2(key, "decrypt"),
|
|
3994
|
+
held ? key : await aesKey2(key, "decrypt"),
|
|
3852
3995
|
bytes2.subarray(HEADER_BYTES)
|
|
3853
3996
|
)
|
|
3854
3997
|
);
|
|
@@ -3872,6 +4015,1061 @@ async function decryptDisclosureV1(input) {
|
|
|
3872
4015
|
// ../shared/src/records-crypto/wrap-shapes-v1.ts
|
|
3873
4016
|
var SEP5 = new Uint8Array([0]);
|
|
3874
4017
|
|
|
4018
|
+
// ../shared/src/records/link-handle-v1.ts
|
|
4019
|
+
var LINK_HANDLE_PREFIX = "csh1_";
|
|
4020
|
+
var LIST_HANDLE_PREFIX = "csl1_";
|
|
4021
|
+
var LINK_HANDLE_PATTERN = /^cs[hl]1_[A-Za-z0-9_-]{1,80}$/;
|
|
4022
|
+
var LINK_HANDLE_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
|
|
4023
|
+
var WHOLE_HANDLE = /^(csh1_|csl1_)([a-z2-7]{52})([a-z2-7]{4})$/;
|
|
4024
|
+
var LIST_BODY = /^[a-z2-7]{51}[aq]$/;
|
|
4025
|
+
function normalizeLinkHandleV1(text) {
|
|
4026
|
+
if (typeof text !== "string") return null;
|
|
4027
|
+
let decoded;
|
|
4028
|
+
try {
|
|
4029
|
+
decoded = decodeURIComponent(text);
|
|
4030
|
+
} catch {
|
|
4031
|
+
return null;
|
|
4032
|
+
}
|
|
4033
|
+
return decoded.trim().toLowerCase();
|
|
4034
|
+
}
|
|
4035
|
+
function linkHandlePartsV1(handle) {
|
|
4036
|
+
const match = typeof handle === "string" ? WHOLE_HANDLE.exec(handle) : null;
|
|
4037
|
+
if (!match) return null;
|
|
4038
|
+
const [, prefix, body, checksum] = match;
|
|
4039
|
+
if (prefix === LIST_HANDLE_PREFIX && !LIST_BODY.test(body)) return null;
|
|
4040
|
+
return { handle, prefix, body, checksum };
|
|
4041
|
+
}
|
|
4042
|
+
function hasListHandlePrefixV1(handle) {
|
|
4043
|
+
return typeof handle === "string" && handle.startsWith(LIST_HANDLE_PREFIX);
|
|
4044
|
+
}
|
|
4045
|
+
|
|
4046
|
+
// ../shared/src/records/reader-crypto-v1.ts
|
|
4047
|
+
var ReaderCryptoError = class extends Error {
|
|
4048
|
+
constructor(code) {
|
|
4049
|
+
super(code);
|
|
4050
|
+
this.code = code;
|
|
4051
|
+
this.name = "ReaderCryptoError";
|
|
4052
|
+
}
|
|
4053
|
+
};
|
|
4054
|
+
var SEP6 = new Uint8Array([0]);
|
|
4055
|
+
var P256_SPKI_PREFIX = Uint8Array.from([
|
|
4056
|
+
48,
|
|
4057
|
+
89,
|
|
4058
|
+
48,
|
|
4059
|
+
19,
|
|
4060
|
+
6,
|
|
4061
|
+
7,
|
|
4062
|
+
42,
|
|
4063
|
+
134,
|
|
4064
|
+
72,
|
|
4065
|
+
206,
|
|
4066
|
+
61,
|
|
4067
|
+
2,
|
|
4068
|
+
1,
|
|
4069
|
+
6,
|
|
4070
|
+
8,
|
|
4071
|
+
42,
|
|
4072
|
+
134,
|
|
4073
|
+
72,
|
|
4074
|
+
206,
|
|
4075
|
+
61,
|
|
4076
|
+
3,
|
|
4077
|
+
1,
|
|
4078
|
+
7,
|
|
4079
|
+
3,
|
|
4080
|
+
66,
|
|
4081
|
+
0
|
|
4082
|
+
]);
|
|
4083
|
+
var HANDLE = LINK_HANDLE_PATTERN;
|
|
4084
|
+
var PART = /^[\x21-\x39\x3b-\x7e]{1,128}$/;
|
|
4085
|
+
function check(ok) {
|
|
4086
|
+
if (!ok) throw new ReaderCryptoError("READER_BINDING_INVALID");
|
|
4087
|
+
}
|
|
4088
|
+
var isEpoch = (n) => Number.isSafeInteger(n) && n >= 1;
|
|
4089
|
+
function revealBindingV1(handle, epoch, recordKey) {
|
|
4090
|
+
check(HANDLE.test(handle) && isEpoch(epoch) && PART.test(recordKey));
|
|
4091
|
+
return `reveal:${handle}:${epoch}:${recordKey}`;
|
|
4092
|
+
}
|
|
4093
|
+
function openRevealV1(input) {
|
|
4094
|
+
return decryptDisclosureV1({ envelope: input.envelope, key: input.linkKey, handle: revealBindingV1(input.handle, input.epoch, input.recordKey) });
|
|
4095
|
+
}
|
|
4096
|
+
|
|
4097
|
+
// ../shared/src/records/shared-record-list-v1.ts
|
|
4098
|
+
var import_ethers15 = require("ethers");
|
|
4099
|
+
var SHARED_RECORD_REVEAL_FIELDS_MAX_V1 = 32;
|
|
4100
|
+
var FIELD_POINTER = /^\/[A-Za-z][A-Za-z0-9_]{0,63}$/;
|
|
4101
|
+
var MODES = ["seals", "fields", "all"];
|
|
4102
|
+
var SharedRecordListError = class extends Error {
|
|
4103
|
+
constructor(code) {
|
|
4104
|
+
super(code);
|
|
4105
|
+
this.code = code;
|
|
4106
|
+
this.name = "SharedRecordListError";
|
|
4107
|
+
}
|
|
4108
|
+
};
|
|
4109
|
+
var isPlain = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
4110
|
+
var hasExactly3 = (v, keys) => Object.keys(v).length === keys.length && keys.every((k) => Object.prototype.hasOwnProperty.call(v, k));
|
|
4111
|
+
function isCanonicalRevealTermsV1(terms) {
|
|
4112
|
+
if (!isPlain(terms) || !hasExactly3(terms, ["mode", "fields", "time"])) return false;
|
|
4113
|
+
const { mode, fields, time } = terms;
|
|
4114
|
+
if (!MODES.includes(mode) || typeof time !== "boolean" || !Array.isArray(fields)) return false;
|
|
4115
|
+
if (mode === "seals") return fields.length === 0 && time === false;
|
|
4116
|
+
if (mode === "all") return fields.length === 0 && time === true;
|
|
4117
|
+
if (fields.length > SHARED_RECORD_REVEAL_FIELDS_MAX_V1) return false;
|
|
4118
|
+
return fields.every((f, i) => typeof f === "string" && FIELD_POINTER.test(f) && (i === 0 || fields[i - 1] < f));
|
|
4119
|
+
}
|
|
4120
|
+
function revealsFieldsV1(terms) {
|
|
4121
|
+
return terms.mode !== "seals";
|
|
4122
|
+
}
|
|
4123
|
+
var SHARED_RECORD_LIST_MAX_V1 = 200;
|
|
4124
|
+
var ROW_KEYS = ["number", "recordKey", "chainId", "contractAddress", "lastSeq", "lastSeal"];
|
|
4125
|
+
var HEX_32 = /^0x[0-9a-f]{64}$/;
|
|
4126
|
+
var HEX_20 = /^0x[0-9a-f]{40}$/;
|
|
4127
|
+
var HEX_64_BARE = /^[0-9a-f]{64}$/;
|
|
4128
|
+
var UINT32_MAX2 = 4294967295;
|
|
4129
|
+
var isUint = (v, max) => Number.isSafeInteger(v) && v >= 0 && v <= max;
|
|
4130
|
+
function readSharedRecordListV1(rows) {
|
|
4131
|
+
const refuse5 = () => new SharedRecordListError("SHARED_RECORD_LIST_INVALID");
|
|
4132
|
+
if (!Array.isArray(rows) || rows.length < 1 || rows.length > SHARED_RECORD_LIST_MAX_V1) throw refuse5();
|
|
4133
|
+
const keys = /* @__PURE__ */ new Set();
|
|
4134
|
+
let last = 0;
|
|
4135
|
+
return rows.map((row) => {
|
|
4136
|
+
if (!isPlain(row) || !hasExactly3(row, ROW_KEYS)) throw refuse5();
|
|
4137
|
+
const { number, recordKey, chainId, contractAddress, lastSeq, lastSeal } = row;
|
|
4138
|
+
if (!isUint(number, UINT32_MAX2) || number <= last) throw refuse5();
|
|
4139
|
+
if (typeof recordKey !== "string" || !HEX_32.test(recordKey) || keys.has(recordKey)) throw refuse5();
|
|
4140
|
+
if (!isUint(chainId, Number.MAX_SAFE_INTEGER) || chainId < 1) throw refuse5();
|
|
4141
|
+
if (typeof contractAddress !== "string" || !HEX_20.test(contractAddress)) throw refuse5();
|
|
4142
|
+
if (!isUint(lastSeq, UINT32_MAX2)) throw refuse5();
|
|
4143
|
+
if (typeof lastSeal !== "string" || !HEX_20.test(lastSeal)) throw refuse5();
|
|
4144
|
+
last = number;
|
|
4145
|
+
keys.add(recordKey);
|
|
4146
|
+
return { number, recordKey, chainId, contractAddress, lastSeq, lastSeal };
|
|
4147
|
+
});
|
|
4148
|
+
}
|
|
4149
|
+
var SHARED_RECORD_LIST_LABEL_V1 = "pacspace:shared-record-list:v1";
|
|
4150
|
+
var SHARED_RECORD_HANDLE_LABEL_V1 = "pacspace:shared-record-handle:v1";
|
|
4151
|
+
var MODE_BYTE = { seals: 0, fields: 1, all: 2 };
|
|
4152
|
+
var utf83 = (text) => import_ethers15.ethers.toUtf8Bytes(text);
|
|
4153
|
+
var uint = (value, bytes2) => import_ethers15.ethers.getBytes(import_ethers15.ethers.toBeHex(BigInt(value), bytes2));
|
|
4154
|
+
function sharedRecordListBytesV1(terms, rows) {
|
|
4155
|
+
if (!isCanonicalRevealTermsV1(terms)) throw new SharedRecordListError("SHARED_RECORD_TERMS_INVALID");
|
|
4156
|
+
const list = readSharedRecordListV1(rows);
|
|
4157
|
+
const parts = [utf83(SHARED_RECORD_LIST_LABEL_V1), Uint8Array.of(0), Uint8Array.of(MODE_BYTE[terms.mode], terms.time ? 1 : 0), uint(terms.fields.length, 2)];
|
|
4158
|
+
for (const field of terms.fields) {
|
|
4159
|
+
const text = utf83(field);
|
|
4160
|
+
parts.push(uint(text.length, 2), text);
|
|
4161
|
+
}
|
|
4162
|
+
parts.push(uint(list.length, 2));
|
|
4163
|
+
for (const row of list) {
|
|
4164
|
+
parts.push(uint(row.number, 4), import_ethers15.ethers.getBytes(row.recordKey), uint(row.chainId, 8), import_ethers15.ethers.getBytes(row.contractAddress), uint(row.lastSeq, 4), import_ethers15.ethers.getBytes(row.lastSeal));
|
|
4165
|
+
}
|
|
4166
|
+
return import_ethers15.ethers.getBytes(import_ethers15.ethers.concat(parts));
|
|
4167
|
+
}
|
|
4168
|
+
function sharedRecordListDigestV1(terms, rows) {
|
|
4169
|
+
return import_ethers15.ethers.sha256(sharedRecordListBytesV1(terms, rows)).slice(2);
|
|
4170
|
+
}
|
|
4171
|
+
function base32(bytes2) {
|
|
4172
|
+
let bits = 0;
|
|
4173
|
+
let value = 0;
|
|
4174
|
+
let out = "";
|
|
4175
|
+
for (const byte of bytes2) {
|
|
4176
|
+
value = (value << 8 | byte) & 65535;
|
|
4177
|
+
bits += 8;
|
|
4178
|
+
while (bits >= 5) {
|
|
4179
|
+
out += LINK_HANDLE_ALPHABET[value >>> bits - 5 & 31];
|
|
4180
|
+
bits -= 5;
|
|
4181
|
+
}
|
|
4182
|
+
}
|
|
4183
|
+
if (bits > 0) out += LINK_HANDLE_ALPHABET[value << 5 - bits & 31];
|
|
4184
|
+
return out;
|
|
4185
|
+
}
|
|
4186
|
+
function sharedRecordHandleBodyV1(listDigest, salt) {
|
|
4187
|
+
if (typeof listDigest !== "string" || !HEX_64_BARE.test(listDigest)) throw new SharedRecordListError("SHARED_RECORD_LIST_INVALID");
|
|
4188
|
+
if (typeof salt !== "string" || !HEX_64_BARE.test(salt)) throw new SharedRecordListError("SHARED_RECORD_SALT_INVALID");
|
|
4189
|
+
const digest = import_ethers15.ethers.sha256(import_ethers15.ethers.concat([utf83(SHARED_RECORD_HANDLE_LABEL_V1), Uint8Array.of(0), import_ethers15.ethers.getBytes(`0x${listDigest}`), import_ethers15.ethers.getBytes(`0x${salt}`)]));
|
|
4190
|
+
return base32(import_ethers15.ethers.getBytes(digest));
|
|
4191
|
+
}
|
|
4192
|
+
function sharedRecordListFingerprintV1(list) {
|
|
4193
|
+
const digest = sharedRecordListDigestV1(list.reveal, list.rows);
|
|
4194
|
+
return { digest, body: sharedRecordHandleBodyV1(digest, list.salt) };
|
|
4195
|
+
}
|
|
4196
|
+
function sharedRecordHandleNamesListV1(handle, list) {
|
|
4197
|
+
const parts = linkHandlePartsV1(handle);
|
|
4198
|
+
if (!parts || parts.prefix !== LIST_HANDLE_PREFIX) return false;
|
|
4199
|
+
try {
|
|
4200
|
+
return sharedRecordListFingerprintV1(list).body === parts.body;
|
|
4201
|
+
} catch {
|
|
4202
|
+
return false;
|
|
4203
|
+
}
|
|
4204
|
+
}
|
|
4205
|
+
|
|
4206
|
+
// ../shared/src/records/shared-record-v2.ts
|
|
4207
|
+
var SHARED_RECORD_SCHEMA_V2 = "shared-record/v2";
|
|
4208
|
+
var SHARED_RECORD_V2_KEYS = {
|
|
4209
|
+
"": {
|
|
4210
|
+
required: ["schema", "reference", "organization", "scope", "previousScope", "rule", "sharedOn", "link", "reveal", "members", "page"],
|
|
4211
|
+
optional: ["list"]
|
|
4212
|
+
},
|
|
4213
|
+
"previousScope[]": { required: ["scope", "until"] },
|
|
4214
|
+
rule: { required: ["committedOn", "last", "changes"] },
|
|
4215
|
+
"rule.last": { required: ["on", "what"] },
|
|
4216
|
+
"rule.changes[]": { required: ["on", "what", "reason"] },
|
|
4217
|
+
link: { required: ["endsOn", "extendedOn", "opens"] },
|
|
4218
|
+
reveal: { required: ["mode", "fields", "time"] },
|
|
4219
|
+
list: { required: ["reveal", "salt", "rows"] },
|
|
4220
|
+
"list.reveal": { required: ["mode", "fields", "time"] },
|
|
4221
|
+
"list.rows[]": { required: ["number", "recordKey", "chainId", "contractAddress", "lastSeq", "lastSeal"] },
|
|
4222
|
+
"members[]": {
|
|
4223
|
+
required: ["number", "openedOn", "closedOn", "entries", "closedBy", "lastSeq", "joinedOn", "removed", "ruleVersion", "recordKey", "chainId", "contractAddress", "lastSeal"],
|
|
4224
|
+
optional: ["revealed", "recordHashVersion", "committedAt", "writtenBy"]
|
|
4225
|
+
},
|
|
4226
|
+
"members[].removed": { required: ["on", "reason"] },
|
|
4227
|
+
"members[].revealed": { required: ["on", "later"] },
|
|
4228
|
+
"members[].writtenBy": { required: ["version", "model", "builtOn", "runtime", "guardrails"] },
|
|
4229
|
+
page: { required: ["after", "next"] }
|
|
4230
|
+
};
|
|
4231
|
+
var isPlain2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
4232
|
+
function sharedRecordV2KeyProblems(payload) {
|
|
4233
|
+
const problems = [];
|
|
4234
|
+
const walk = (value, path) => {
|
|
4235
|
+
if (Array.isArray(value)) {
|
|
4236
|
+
for (const item of value) walk(item, `${path}[]`);
|
|
4237
|
+
return;
|
|
4238
|
+
}
|
|
4239
|
+
if (!isPlain2(value)) return;
|
|
4240
|
+
const set = SHARED_RECORD_V2_KEYS[path];
|
|
4241
|
+
if (!set) {
|
|
4242
|
+
problems.push(`${path || "(root)"}: no object allowed here`);
|
|
4243
|
+
return;
|
|
4244
|
+
}
|
|
4245
|
+
const allowed = /* @__PURE__ */ new Set([...set.required, ...set.optional ?? []]);
|
|
4246
|
+
for (const key of set.required) if (value[key] === void 0) problems.push(`${path ? `${path}.` : ""}${key}: missing`);
|
|
4247
|
+
for (const key of Object.keys(value)) {
|
|
4248
|
+
if (!allowed.has(key)) problems.push(`${path ? `${path}.` : ""}${key}: not allowed`);
|
|
4249
|
+
else walk(value[key], path ? `${path}.${key}` : key);
|
|
4250
|
+
}
|
|
4251
|
+
};
|
|
4252
|
+
walk(payload, "");
|
|
4253
|
+
return problems;
|
|
4254
|
+
}
|
|
4255
|
+
|
|
4256
|
+
// ../shared/src/records/shared-record-check-v1.ts
|
|
4257
|
+
var SHARED_RECORD_CHECK_SCHEMA_V1 = "shared-record-check/v1";
|
|
4258
|
+
function readSharedRecordAddressV1(text) {
|
|
4259
|
+
if (typeof text !== "string") return null;
|
|
4260
|
+
let url;
|
|
4261
|
+
try {
|
|
4262
|
+
url = new URL(text.trim());
|
|
4263
|
+
} catch {
|
|
4264
|
+
return null;
|
|
4265
|
+
}
|
|
4266
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
4267
|
+
if (!(url.protocol === "https:" || url.protocol === "http:" && local) || url.username || url.password) return null;
|
|
4268
|
+
const match = /^\/c\/([^/]+)(?:\/.*)?$/i.exec(url.pathname);
|
|
4269
|
+
if (!match) return null;
|
|
4270
|
+
const handle = normalizeLinkHandleV1(match[1]);
|
|
4271
|
+
if (!handle) return null;
|
|
4272
|
+
let prefix = null;
|
|
4273
|
+
if (hasListHandlePrefixV1(handle)) {
|
|
4274
|
+
if (!linkHandlePartsV1(handle)) return null;
|
|
4275
|
+
prefix = LIST_HANDLE_PREFIX;
|
|
4276
|
+
} else if (handle.startsWith(LINK_HANDLE_PREFIX)) {
|
|
4277
|
+
prefix = LINK_HANDLE_PREFIX;
|
|
4278
|
+
}
|
|
4279
|
+
return { origin: url.origin, host: url.host, handle, prefix, fragment: url.hash.replace(/^#/, "") };
|
|
4280
|
+
}
|
|
4281
|
+
function sharedRecordAddressOpensV1(handle, answersAs) {
|
|
4282
|
+
if (hasListHandlePrefixV1(handle)) return answersAs === "trail" ? "list" : "fails";
|
|
4283
|
+
return answersAs;
|
|
4284
|
+
}
|
|
4285
|
+
var SharedRecordAnswerError = class extends Error {
|
|
4286
|
+
constructor(reason, message) {
|
|
4287
|
+
super(message ?? reason);
|
|
4288
|
+
this.reason = reason;
|
|
4289
|
+
this.name = "SharedRecordAnswerError";
|
|
4290
|
+
}
|
|
4291
|
+
};
|
|
4292
|
+
function answerErrorOf(error) {
|
|
4293
|
+
const { name, reason } = error ?? {};
|
|
4294
|
+
return name === "SharedRecordAnswerError" && reason === "refused" ? "refused" : "unreachable";
|
|
4295
|
+
}
|
|
4296
|
+
var RECORD_CODE_STATUS = {
|
|
4297
|
+
HISTORY_NOT_SERVED: "fails",
|
|
4298
|
+
HISTORY_INVALID: "fails",
|
|
4299
|
+
HISTORY_OTHER_RECORD: "fails",
|
|
4300
|
+
ENTRY_MISSING: "fails",
|
|
4301
|
+
ENTRY_NOT_COMMITTED: "fails",
|
|
4302
|
+
ENTRY_FAILED: "fails",
|
|
4303
|
+
CLOSE_SEAL_DIFFERS: "fails",
|
|
4304
|
+
ENTRY_NOT_WRITTEN: "fails",
|
|
4305
|
+
WRITE_NOT_SERVED: "fails",
|
|
4306
|
+
WRITE_BEFORE_FIRST: "fails",
|
|
4307
|
+
RECORD_SET_BACK: "fails",
|
|
4308
|
+
CURRENT_WORD_ZERO: "fails",
|
|
4309
|
+
CURRENT_WORD_EARLIER: "fails",
|
|
4310
|
+
REVEAL_MISSING: "fails",
|
|
4311
|
+
REVEAL_NOT_OPENED: "fails",
|
|
4312
|
+
FIELDS_DO_NOT_MATCH: "fails",
|
|
4313
|
+
HISTORY_NOT_READ: "not-checked",
|
|
4314
|
+
LAYOUT_NOT_READ: "not-checked",
|
|
4315
|
+
SOURCE_UNKNOWN: "not-checked",
|
|
4316
|
+
SOURCE_NOT_READ: "not-checked",
|
|
4317
|
+
BUDGET_SPENT: "not-checked",
|
|
4318
|
+
LOG_PAST_BOUNDS: "not-checked",
|
|
4319
|
+
REVEALS_NOT_READ: "not-checked",
|
|
4320
|
+
ROOT_NOT_READ: "not-checked"
|
|
4321
|
+
};
|
|
4322
|
+
var LINK_CODE_STATUS = {
|
|
4323
|
+
LINK_NOT_A_LIST: "fails",
|
|
4324
|
+
MANIFEST_INVALID: "fails",
|
|
4325
|
+
LIST_ON_LATER_PAGE: "fails",
|
|
4326
|
+
LIST_INVALID: "fails",
|
|
4327
|
+
TERMS_DIFFER: "fails",
|
|
4328
|
+
LIST_NOT_ADDRESS: "fails",
|
|
4329
|
+
RECORDS_NOT_LIST: "fails",
|
|
4330
|
+
PAGING_NOT_FORWARD: "fails",
|
|
4331
|
+
REVEALS_INVALID: "fails",
|
|
4332
|
+
REVEAL_OFF_LIST: "fails",
|
|
4333
|
+
LINK_HAS_NO_LIST: "not-checked",
|
|
4334
|
+
MANIFEST_NOT_READ: "not-checked"
|
|
4335
|
+
};
|
|
4336
|
+
var SHARED_RECORD_CHECK_RECORD_REQUESTS_V1 = 40;
|
|
4337
|
+
var SHARED_RECORD_CHECK_RUN_REQUESTS_V1 = 1e4;
|
|
4338
|
+
var SHARED_RECORD_CHECK_RECORD_MS_V1 = 6e4;
|
|
4339
|
+
var SHARED_RECORD_CHECK_WAITS_V1 = 3;
|
|
4340
|
+
var SHARED_RECORD_CHECK_UNANSWERED_V1 = 3;
|
|
4341
|
+
var HEX323 = /^0x[0-9a-f]{64}$/;
|
|
4342
|
+
var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
4343
|
+
var DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
4344
|
+
var INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/;
|
|
4345
|
+
var CONSENSUS = /^\d{1,12}\.\d{9}$/;
|
|
4346
|
+
var ZERO_WORD = `0x${"0".repeat(64)}`;
|
|
4347
|
+
var isPlain3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
4348
|
+
var sameTerms = (a, b) => isCanonicalRevealTermsV1(a) && a.mode === b.mode && a.time === b.time && a.fields.length === b.fields.length && a.fields.every((f, i) => f === b.fields[i]);
|
|
4349
|
+
var LinkStop = class extends Error {
|
|
4350
|
+
constructor(code) {
|
|
4351
|
+
super(code);
|
|
4352
|
+
this.code = code;
|
|
4353
|
+
}
|
|
4354
|
+
};
|
|
4355
|
+
var RecordStop = class extends Error {
|
|
4356
|
+
constructor(code, entry = null) {
|
|
4357
|
+
super(code);
|
|
4358
|
+
this.code = code;
|
|
4359
|
+
this.entry = entry;
|
|
4360
|
+
}
|
|
4361
|
+
};
|
|
4362
|
+
function readPage(raw) {
|
|
4363
|
+
if (!isPlain3(raw) || raw.schema !== SHARED_RECORD_SCHEMA_V2) return null;
|
|
4364
|
+
if (sharedRecordV2KeyProblems(raw).length > 0) return null;
|
|
4365
|
+
if (!Array.isArray(raw.members) || !isPlain3(raw.page) || !isPlain3(raw.link) || !isPlain3(raw.reveal)) return null;
|
|
4366
|
+
const { after, next } = raw.page;
|
|
4367
|
+
if (!Number.isSafeInteger(after) || next !== null && !Number.isSafeInteger(next)) return null;
|
|
4368
|
+
for (const member of raw.members) {
|
|
4369
|
+
if (!isPlain3(member) || !Number.isSafeInteger(member.number)) return null;
|
|
4370
|
+
}
|
|
4371
|
+
return raw;
|
|
4372
|
+
}
|
|
4373
|
+
async function readManifest(source) {
|
|
4374
|
+
let first = null;
|
|
4375
|
+
const members = [];
|
|
4376
|
+
let after = 0;
|
|
4377
|
+
for (; ; ) {
|
|
4378
|
+
let raw;
|
|
4379
|
+
try {
|
|
4380
|
+
raw = await source.page(after);
|
|
4381
|
+
} catch {
|
|
4382
|
+
throw new LinkStop("MANIFEST_NOT_READ");
|
|
4383
|
+
}
|
|
4384
|
+
const page = readPage(raw);
|
|
4385
|
+
if (!page) throw new LinkStop("MANIFEST_INVALID");
|
|
4386
|
+
if (page.page.after !== after) throw new LinkStop("PAGING_NOT_FORWARD");
|
|
4387
|
+
if (first === null) first = page;
|
|
4388
|
+
else if (page.list !== void 0) throw new LinkStop("LIST_ON_LATER_PAGE");
|
|
4389
|
+
let last = after;
|
|
4390
|
+
for (const member of page.members) {
|
|
4391
|
+
if (member.number <= last) throw new LinkStop("PAGING_NOT_FORWARD");
|
|
4392
|
+
last = member.number;
|
|
4393
|
+
members.push(member);
|
|
4394
|
+
if (members.length > SHARED_RECORD_LIST_MAX_V1) throw new LinkStop("RECORDS_NOT_LIST");
|
|
4395
|
+
}
|
|
4396
|
+
const next = page.page.next;
|
|
4397
|
+
if (next === null) break;
|
|
4398
|
+
if (page.members.length === 0 || next < last || next <= after) throw new LinkStop("PAGING_NOT_FORWARD");
|
|
4399
|
+
after = next;
|
|
4400
|
+
}
|
|
4401
|
+
let rows = null;
|
|
4402
|
+
if (first.list !== void 0) {
|
|
4403
|
+
try {
|
|
4404
|
+
rows = readSharedRecordListV1(first.list.rows);
|
|
4405
|
+
} catch {
|
|
4406
|
+
throw new LinkStop("LIST_INVALID");
|
|
4407
|
+
}
|
|
4408
|
+
if (!isCanonicalRevealTermsV1(first.list.reveal)) throw new LinkStop("LIST_INVALID");
|
|
4409
|
+
}
|
|
4410
|
+
return { first, members, rows };
|
|
4411
|
+
}
|
|
4412
|
+
var ROW_FIELDS = ["number", "recordKey", "chainId", "contractAddress", "lastSeq", "lastSeal"];
|
|
4413
|
+
function recordsAreList(members, rows) {
|
|
4414
|
+
if (members.length !== rows.length) return false;
|
|
4415
|
+
return rows.every((row, i) => ROW_FIELDS.every((field) => members[i][field] === row[field]));
|
|
4416
|
+
}
|
|
4417
|
+
function servedInstant(time) {
|
|
4418
|
+
if (typeof time !== "string") return null;
|
|
4419
|
+
const text = DAY.test(time) ? `${time}T23:59:59.999Z` : INSTANT.test(time) ? time : null;
|
|
4420
|
+
if (text === null) return null;
|
|
4421
|
+
const at = Date.parse(text);
|
|
4422
|
+
return Number.isFinite(at) ? at : null;
|
|
4423
|
+
}
|
|
4424
|
+
function readServedRecord(raw, row, layouts) {
|
|
4425
|
+
if (!isPlain3(raw) || raw.schema !== RECORD_SEAL_HISTORY_SCHEMA_V1) throw new RecordStop("HISTORY_INVALID");
|
|
4426
|
+
const verified = verifyRecordSealHistoryV1(raw, { layouts });
|
|
4427
|
+
if (verified.code === RECORDS_LAYOUT_NOT_READ) throw new RecordStop("LAYOUT_NOT_READ");
|
|
4428
|
+
if (!verified.schemaOk || !verified.digestOk || !verified.layoutOk) throw new RecordStop("HISTORY_INVALID");
|
|
4429
|
+
const history = raw;
|
|
4430
|
+
if (history.recordKey !== row.recordKey || history.chain.chainId !== row.chainId || history.chain.contractAddress !== row.contractAddress) {
|
|
4431
|
+
throw new RecordStop("HISTORY_OTHER_RECORD");
|
|
4432
|
+
}
|
|
4433
|
+
if (verified.perEntry.length !== history.entries.length) throw new RecordStop("HISTORY_INVALID");
|
|
4434
|
+
const bySeq = new Map(history.entries.map((e) => [e.seq, e]));
|
|
4435
|
+
const pending = /* @__PURE__ */ new Map();
|
|
4436
|
+
for (const p of history.pending) if (p.seq !== null) pending.set(p.seq, p.status);
|
|
4437
|
+
const failed = new Set(verified.perEntry.filter((e) => e.failedCheck !== null).map((e) => e.seq));
|
|
4438
|
+
for (let seq2 = 0; seq2 <= row.lastSeq; seq2 += 1) {
|
|
4439
|
+
if (!bySeq.has(seq2)) throw new RecordStop(pending.has(seq2) ? "ENTRY_NOT_COMMITTED" : "ENTRY_MISSING", seq2 + 1);
|
|
4440
|
+
if (failed.has(seq2)) throw new RecordStop("ENTRY_FAILED", seq2 + 1);
|
|
4441
|
+
}
|
|
4442
|
+
const close = bySeq.get(row.lastSeq);
|
|
4443
|
+
if (splitWordV1(close.newWord).sealTag !== row.lastSeal) throw new RecordStop("CLOSE_SEAL_DIFFERS", row.lastSeq + 1);
|
|
4444
|
+
const entries = [];
|
|
4445
|
+
let seq = 0;
|
|
4446
|
+
for (; bySeq.has(seq); seq += 1) {
|
|
4447
|
+
if (failed.has(seq)) throw new RecordStop("ENTRY_FAILED", seq + 1);
|
|
4448
|
+
const e = bySeq.get(seq);
|
|
4449
|
+
entries.push({ seq, previousWord: e.previousWord, newWord: e.newWord, batchId: e.batchId });
|
|
4450
|
+
}
|
|
4451
|
+
if (history.entries.some((e) => e.seq > seq)) throw new RecordStop("ENTRY_MISSING", seq + 1);
|
|
4452
|
+
let committingAfterClose = 0;
|
|
4453
|
+
for (const [at, status] of pending) if (at > row.lastSeq && status === "queued") committingAfterClose += 1;
|
|
4454
|
+
const times = new Map((history.ledger?.batches ?? []).map((b) => [b.batchId, servedInstant(b.blockTime)]));
|
|
4455
|
+
let latest = Number.NEGATIVE_INFINITY;
|
|
4456
|
+
for (const e of entries) {
|
|
4457
|
+
const at = times.get(e.batchId) ?? null;
|
|
4458
|
+
if (at === null) {
|
|
4459
|
+
latest = null;
|
|
4460
|
+
break;
|
|
4461
|
+
}
|
|
4462
|
+
latest = Math.max(latest, at);
|
|
4463
|
+
}
|
|
4464
|
+
return { history, entries, committingAfterClose, latest: latest === null ? null : new Date(latest).toISOString() };
|
|
4465
|
+
}
|
|
4466
|
+
function readLogWrites(raw, contractAddress) {
|
|
4467
|
+
if (!Array.isArray(raw)) return null;
|
|
4468
|
+
const byPlace = /* @__PURE__ */ new Map();
|
|
4469
|
+
const mirror = raw.length > 0 && raw.every((w) => isPlain3(w) && typeof w.consensusTimestamp === "string");
|
|
4470
|
+
for (const w of raw) {
|
|
4471
|
+
if (!isPlain3(w)) return null;
|
|
4472
|
+
const previousWord = typeof w.previousWord === "string" ? w.previousWord.toLowerCase() : "";
|
|
4473
|
+
const newWord = typeof w.newWord === "string" ? w.newWord.toLowerCase() : "";
|
|
4474
|
+
if (!HEX323.test(previousWord) || !HEX323.test(newWord)) return null;
|
|
4475
|
+
if (w.contractAddress !== void 0 && String(w.contractAddress).toLowerCase() !== contractAddress) return null;
|
|
4476
|
+
const index = w.logIndex;
|
|
4477
|
+
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
|
|
4478
|
+
let at;
|
|
4479
|
+
if (mirror) {
|
|
4480
|
+
const stamp = w.consensusTimestamp;
|
|
4481
|
+
if (!CONSENSUS.test(stamp)) return null;
|
|
4482
|
+
const [seconds, nanos] = stamp.split(".");
|
|
4483
|
+
at = BigInt(seconds) * 1000000000n + BigInt(nanos);
|
|
4484
|
+
} else {
|
|
4485
|
+
if (typeof w.blockNumber !== "number" || !Number.isSafeInteger(w.blockNumber) || w.blockNumber < 0) return null;
|
|
4486
|
+
at = BigInt(w.blockNumber);
|
|
4487
|
+
}
|
|
4488
|
+
const place = `${at}:${index}`;
|
|
4489
|
+
const seen = byPlace.get(place);
|
|
4490
|
+
if (seen) {
|
|
4491
|
+
if (seen.previousWord !== previousWord || seen.newWord !== newWord) return null;
|
|
4492
|
+
continue;
|
|
4493
|
+
}
|
|
4494
|
+
const hash = typeof w.transactionHash === "string" ? w.transactionHash.toLowerCase() : "";
|
|
4495
|
+
byPlace.set(place, {
|
|
4496
|
+
previousWord,
|
|
4497
|
+
newWord,
|
|
4498
|
+
committedAt: typeof w.committedAt === "string" && ISO_INSTANT.test(w.committedAt) ? w.committedAt : null,
|
|
4499
|
+
transactionHash: HEX323.test(hash) ? hash : null,
|
|
4500
|
+
at,
|
|
4501
|
+
index
|
|
4502
|
+
});
|
|
4503
|
+
}
|
|
4504
|
+
return [...byPlace.values()].sort((a, b) => a.at < b.at ? -1 : a.at > b.at ? 1 : a.index - b.index);
|
|
4505
|
+
}
|
|
4506
|
+
function holdToLog(entries, log, whole) {
|
|
4507
|
+
const isEntry = (w, e) => w.previousWord === e.previousWord && w.newWord === e.newWord;
|
|
4508
|
+
const anchor = log.findIndex((w) => entries.some((e) => isEntry(w, e)));
|
|
4509
|
+
if (anchor === -1) {
|
|
4510
|
+
if (whole) throw new RecordStop("ENTRY_NOT_WRITTEN", 1);
|
|
4511
|
+
throw new RecordStop("BUDGET_SPENT");
|
|
4512
|
+
}
|
|
4513
|
+
const start = entries.findIndex((e) => isEntry(log[anchor], e));
|
|
4514
|
+
if (anchor > 0) throw new RecordStop(start === 0 ? "WRITE_BEFORE_FIRST" : "WRITE_NOT_SERVED", start === 0 ? null : start);
|
|
4515
|
+
const writes = /* @__PURE__ */ new Map();
|
|
4516
|
+
let at = 0;
|
|
4517
|
+
for (let i = start; i < entries.length; i += 1, at += 1) {
|
|
4518
|
+
if (at >= log.length) throw new RecordStop("ENTRY_NOT_WRITTEN", entries[i].seq + 1);
|
|
4519
|
+
if (!isEntry(log[at], entries[i])) throw new RecordStop("WRITE_NOT_SERVED", entries[i].seq + 1);
|
|
4520
|
+
writes.set(entries[i].seq, log[at]);
|
|
4521
|
+
}
|
|
4522
|
+
const held = /* @__PURE__ */ new Set([ZERO_WORD, ...entries.map((e) => e.newWord)]);
|
|
4523
|
+
let before = entries[entries.length - 1].newWord;
|
|
4524
|
+
let laterWrites = 0;
|
|
4525
|
+
for (; at < log.length; at += 1) {
|
|
4526
|
+
const w = log[at];
|
|
4527
|
+
if (w.previousWord !== before || held.has(w.newWord)) throw new RecordStop("RECORD_SET_BACK");
|
|
4528
|
+
held.add(w.newWord);
|
|
4529
|
+
before = w.newWord;
|
|
4530
|
+
laterWrites += 1;
|
|
4531
|
+
}
|
|
4532
|
+
if (start > 0) {
|
|
4533
|
+
throw new RecordStop(whole ? "ENTRY_NOT_WRITTEN" : "BUDGET_SPENT", whole ? 1 : null);
|
|
4534
|
+
}
|
|
4535
|
+
return { writes, laterWrites };
|
|
4536
|
+
}
|
|
4537
|
+
function sourceStateOf(run, row) {
|
|
4538
|
+
const key = `${row.chainId}:${row.contractAddress}`;
|
|
4539
|
+
let state = run.sources.get(key);
|
|
4540
|
+
if (!state) {
|
|
4541
|
+
state = { unanswered: 0, wholeLog: null };
|
|
4542
|
+
run.sources.set(key, state);
|
|
4543
|
+
}
|
|
4544
|
+
return state;
|
|
4545
|
+
}
|
|
4546
|
+
function readerFor(run, row) {
|
|
4547
|
+
const key = `${row.chainId}:${row.contractAddress}`;
|
|
4548
|
+
if (!run.readers.has(key)) {
|
|
4549
|
+
let made = null;
|
|
4550
|
+
try {
|
|
4551
|
+
made = run.input.proofLayer({ chainId: row.chainId, contractAddress: row.contractAddress });
|
|
4552
|
+
} catch {
|
|
4553
|
+
made = null;
|
|
4554
|
+
}
|
|
4555
|
+
run.readers.set(key, made);
|
|
4556
|
+
}
|
|
4557
|
+
return run.readers.get(key) ?? null;
|
|
4558
|
+
}
|
|
4559
|
+
function emptyRecord(row) {
|
|
4560
|
+
return {
|
|
4561
|
+
number: row.number,
|
|
4562
|
+
recordKey: row.recordKey,
|
|
4563
|
+
chainId: row.chainId,
|
|
4564
|
+
contractAddress: row.contractAddress,
|
|
4565
|
+
status: "not-checked",
|
|
4566
|
+
code: null,
|
|
4567
|
+
failedEntry: null,
|
|
4568
|
+
closeEntry: row.lastSeq + 1,
|
|
4569
|
+
entries: [],
|
|
4570
|
+
committingAfterClose: 0,
|
|
4571
|
+
laterWrites: 0,
|
|
4572
|
+
changedSince: false,
|
|
4573
|
+
fields: { status: "none", entries: [] },
|
|
4574
|
+
source: null,
|
|
4575
|
+
requests: 0
|
|
4576
|
+
};
|
|
4577
|
+
}
|
|
4578
|
+
function rootFor(run, row, layer, batchId) {
|
|
4579
|
+
const key = `${row.chainId}:${row.contractAddress}:${batchId}`;
|
|
4580
|
+
let root = run.roots.get(key);
|
|
4581
|
+
if (!root) {
|
|
4582
|
+
if (run.left < 1) return Promise.resolve(null);
|
|
4583
|
+
run.left -= 1;
|
|
4584
|
+
run.spent += 1;
|
|
4585
|
+
root = readChainRootsV1(layer.reader, [batchId]).then((read) => read.chainRoots[String(batchId)] ?? null);
|
|
4586
|
+
run.roots.set(key, root);
|
|
4587
|
+
}
|
|
4588
|
+
return root;
|
|
4589
|
+
}
|
|
4590
|
+
async function checkFields(run, row, served, given, layer) {
|
|
4591
|
+
const none = (status, stop = null) => ({ fields: { status, entries: [] }, stop, disclosure: null });
|
|
4592
|
+
if (given.kind === "none") return none("none");
|
|
4593
|
+
if (given.kind === "not-opened") return none("not-opened");
|
|
4594
|
+
if (given.kind === "not-read") return none("not-checked", new RecordStop("REVEALS_NOT_READ"));
|
|
4595
|
+
if (given.disclosure === null) return none("fails", new RecordStop(given.served ? "REVEAL_NOT_OPENED" : "REVEAL_MISSING"));
|
|
4596
|
+
const disclosure = given.disclosure;
|
|
4597
|
+
const fails = { fields: { status: "fails", entries: [] }, stop: new RecordStop("FIELDS_DO_NOT_MATCH"), disclosure };
|
|
4598
|
+
if (!isPlain3(disclosure) || typeof disclosure.recordKey !== "string" || disclosure.recordKey.toLowerCase() !== row.recordKey) return fails;
|
|
4599
|
+
let form;
|
|
4600
|
+
try {
|
|
4601
|
+
form = disclosureFormOfV1(served.history, disclosure);
|
|
4602
|
+
} catch {
|
|
4603
|
+
form = null;
|
|
4604
|
+
}
|
|
4605
|
+
if (!form) return fails;
|
|
4606
|
+
if (!layer) return { fields: { status: "not-checked", entries: [] }, stop: new RecordStop("SOURCE_UNKNOWN"), disclosure };
|
|
4607
|
+
const chainRoots = {};
|
|
4608
|
+
for (const batchId of new Set(form.entries.map((e) => e.batchId))) {
|
|
4609
|
+
const root = await rootFor(run, row, layer, batchId);
|
|
4610
|
+
if (root === null) return { fields: { status: "not-checked", entries: [] }, stop: new RecordStop("ROOT_NOT_READ"), disclosure };
|
|
4611
|
+
chainRoots[String(batchId)] = root;
|
|
4612
|
+
}
|
|
4613
|
+
let result;
|
|
4614
|
+
try {
|
|
4615
|
+
result = await verifyRecordDisclosureV1({ form, chainRoots, disclosure });
|
|
4616
|
+
} catch {
|
|
4617
|
+
return fails;
|
|
4618
|
+
}
|
|
4619
|
+
if (!result.ok) return { ...fails, stop: new RecordStop("FIELDS_DO_NOT_MATCH", result.seq === null ? null : result.seq + 1) };
|
|
4620
|
+
const entries = result.entries.map((e) => ({ entry: e.seq + 1, fields: e.fields.map((f) => ({ pointer: f.pointer, value: f.value })), withheld: e.withheld }));
|
|
4621
|
+
return { fields: { status: "matches", entries }, stop: null, disclosure };
|
|
4622
|
+
}
|
|
4623
|
+
async function checkRecord(run, row, given, kept) {
|
|
4624
|
+
const { input } = run;
|
|
4625
|
+
const out = emptyRecord(row);
|
|
4626
|
+
const keep = kept ? { number: row.number, sealHistory: null, disclosure: null } : null;
|
|
4627
|
+
if (keep) kept.push(keep);
|
|
4628
|
+
let grant = 0;
|
|
4629
|
+
let used = 0;
|
|
4630
|
+
let read = false;
|
|
4631
|
+
let fieldsStop = null;
|
|
4632
|
+
const stopWith = (stop) => {
|
|
4633
|
+
const status = RECORD_CODE_STATUS[stop.code];
|
|
4634
|
+
if (out.code !== null && !(out.status === "not-checked" && status === "fails")) return;
|
|
4635
|
+
out.status = status;
|
|
4636
|
+
out.code = stop.code;
|
|
4637
|
+
out.failedEntry = stop.entry;
|
|
4638
|
+
};
|
|
4639
|
+
try {
|
|
4640
|
+
let raw;
|
|
4641
|
+
try {
|
|
4642
|
+
raw = await input.source.seals(row.number);
|
|
4643
|
+
} catch (error) {
|
|
4644
|
+
throw new RecordStop(answerErrorOf(error) === "refused" ? "HISTORY_NOT_SERVED" : "HISTORY_NOT_READ");
|
|
4645
|
+
}
|
|
4646
|
+
if (keep && isPlain3(raw) && raw.schema === RECORD_SEAL_HISTORY_SCHEMA_V1) keep.sealHistory = raw;
|
|
4647
|
+
const served = readServedRecord(raw, row, input.layouts);
|
|
4648
|
+
out.committingAfterClose = served.committingAfterClose;
|
|
4649
|
+
out.entries = served.entries.map((e) => ({ entry: e.seq + 1, afterClose: e.seq > row.lastSeq, committedAt: null, transactionHash: null }));
|
|
4650
|
+
const layer = readerFor(run, row);
|
|
4651
|
+
out.source = layer?.source ?? null;
|
|
4652
|
+
const fields = await checkFields(run, row, served, given, layer);
|
|
4653
|
+
out.fields = fields.fields;
|
|
4654
|
+
fieldsStop = fields.stop;
|
|
4655
|
+
if (keep) keep.disclosure = fields.disclosure;
|
|
4656
|
+
if (!layer) throw new RecordStop("SOURCE_UNKNOWN");
|
|
4657
|
+
const state = sourceStateOf(run, row);
|
|
4658
|
+
if (state.unanswered >= SHARED_RECORD_CHECK_UNANSWERED_V1) throw new RecordStop("SOURCE_NOT_READ");
|
|
4659
|
+
grant = Math.max(0, Math.min(run.budget.recordRequests, run.left));
|
|
4660
|
+
run.left -= grant;
|
|
4661
|
+
if (grant < 1) throw new RecordStop("BUDGET_SPENT");
|
|
4662
|
+
let log = null;
|
|
4663
|
+
let whole = false;
|
|
4664
|
+
let cutOff2 = false;
|
|
4665
|
+
let logStop = null;
|
|
4666
|
+
if (input.full) {
|
|
4667
|
+
whole = true;
|
|
4668
|
+
if (state.wholeLog !== null) {
|
|
4669
|
+
logStop = state.wholeLog;
|
|
4670
|
+
} else {
|
|
4671
|
+
try {
|
|
4672
|
+
log = readLogWrites(await layer.reader.getRecordWrites(row.recordKey), row.contractAddress);
|
|
4673
|
+
if (log === null) logStop = "SOURCE_NOT_READ";
|
|
4674
|
+
} catch (error) {
|
|
4675
|
+
const refusal = mirrorRefusalOf(error);
|
|
4676
|
+
logStop = refusal === "too-slow" || refusal === "too-long" ? "LOG_PAST_BOUNDS" : "SOURCE_NOT_READ";
|
|
4677
|
+
state.wholeLog = logStop;
|
|
4678
|
+
}
|
|
4679
|
+
}
|
|
4680
|
+
} else if (!layer.reader.findRecordWrites) {
|
|
4681
|
+
logStop = "SOURCE_NOT_READ";
|
|
4682
|
+
} else if (grant < 2) {
|
|
4683
|
+
logStop = "BUDGET_SPENT";
|
|
4684
|
+
} else {
|
|
4685
|
+
let asked = 0;
|
|
4686
|
+
try {
|
|
4687
|
+
const search = await layer.reader.findRecordWrites(row.recordKey, {
|
|
4688
|
+
startAt: served.latest,
|
|
4689
|
+
done: (writes) => writes.some((w) => typeof w?.previousWord === "string" && w.previousWord.toLowerCase() === ZERO_WORD),
|
|
4690
|
+
budgetMs: run.budget.recordMs,
|
|
4691
|
+
maxRequests: grant - 1,
|
|
4692
|
+
wholeWindows: true,
|
|
4693
|
+
waitOut: { times: SHARED_RECORD_CHECK_WAITS_V1, waitMs: 1e3, maxWaitMs: 1e4, ...input.sleep ? { sleep: input.sleep } : {} },
|
|
4694
|
+
onRequest: () => {
|
|
4695
|
+
asked += 1;
|
|
4696
|
+
},
|
|
4697
|
+
...input.now ? { now: input.now } : {}
|
|
4698
|
+
});
|
|
4699
|
+
if (asked === 0 && Number.isSafeInteger(search.requests) && search.requests > 0) asked = search.requests;
|
|
4700
|
+
log = readLogWrites(search.writes, row.contractAddress);
|
|
4701
|
+
if (log === null) logStop = "SOURCE_NOT_READ";
|
|
4702
|
+
whole = search.ended === "done";
|
|
4703
|
+
cutOff2 = search.ended === "timeout";
|
|
4704
|
+
} catch {
|
|
4705
|
+
logStop = "SOURCE_NOT_READ";
|
|
4706
|
+
state.unanswered += 1;
|
|
4707
|
+
}
|
|
4708
|
+
used += asked;
|
|
4709
|
+
}
|
|
4710
|
+
if (logStop === "SOURCE_NOT_READ") throw new RecordStop(logStop);
|
|
4711
|
+
if (logStop !== null) stopWith(new RecordStop(logStop));
|
|
4712
|
+
if (log !== null) {
|
|
4713
|
+
let held = null;
|
|
4714
|
+
try {
|
|
4715
|
+
held = holdToLog(served.entries, log, whole);
|
|
4716
|
+
} catch (error) {
|
|
4717
|
+
if (!(error instanceof RecordStop)) throw error;
|
|
4718
|
+
stopWith(error.code === "BUDGET_SPENT" && cutOff2 ? new RecordStop("SOURCE_NOT_READ") : error);
|
|
4719
|
+
}
|
|
4720
|
+
if (held) {
|
|
4721
|
+
out.laterWrites = held.laterWrites;
|
|
4722
|
+
for (const entry of out.entries) {
|
|
4723
|
+
const write = held.writes.get(entry.entry - 1);
|
|
4724
|
+
if (write) {
|
|
4725
|
+
entry.committedAt = write.committedAt;
|
|
4726
|
+
entry.transactionHash = write.transactionHash;
|
|
4727
|
+
}
|
|
4728
|
+
}
|
|
4729
|
+
}
|
|
4730
|
+
}
|
|
4731
|
+
let current;
|
|
4732
|
+
try {
|
|
4733
|
+
used += 1;
|
|
4734
|
+
current = String(await layer.reader.getRecord(row.recordKey)).toLowerCase();
|
|
4735
|
+
} catch {
|
|
4736
|
+
state.unanswered += 1;
|
|
4737
|
+
throw new RecordStop("SOURCE_NOT_READ");
|
|
4738
|
+
}
|
|
4739
|
+
state.unanswered = 0;
|
|
4740
|
+
if (!HEX323.test(current)) throw new RecordStop("SOURCE_NOT_READ");
|
|
4741
|
+
const last = served.entries[served.entries.length - 1];
|
|
4742
|
+
out.changedSince = current !== last.newWord;
|
|
4743
|
+
if (current === ZERO_WORD) throw new RecordStop("CURRENT_WORD_ZERO");
|
|
4744
|
+
if (served.entries.some((e) => e !== last && e.newWord === current)) throw new RecordStop("CURRENT_WORD_EARLIER");
|
|
4745
|
+
read = true;
|
|
4746
|
+
} catch (error) {
|
|
4747
|
+
if (error instanceof RecordStop) stopWith(error);
|
|
4748
|
+
else stopWith(new RecordStop("SOURCE_NOT_READ"));
|
|
4749
|
+
}
|
|
4750
|
+
if (fieldsStop) stopWith(fieldsStop);
|
|
4751
|
+
if (read && out.code === null) out.status = "matches";
|
|
4752
|
+
out.requests = used;
|
|
4753
|
+
run.spent += used;
|
|
4754
|
+
run.left += Math.max(0, grant - used);
|
|
4755
|
+
return out;
|
|
4756
|
+
}
|
|
4757
|
+
async function readReveals(input, rows, handle) {
|
|
4758
|
+
const onList = new Map(rows.map((row) => [row.number, row]));
|
|
4759
|
+
const out = /* @__PURE__ */ new Map();
|
|
4760
|
+
let after = 0;
|
|
4761
|
+
for (; ; ) {
|
|
4762
|
+
let raw;
|
|
4763
|
+
try {
|
|
4764
|
+
raw = await input.source.reveals(after);
|
|
4765
|
+
} catch {
|
|
4766
|
+
return "not-read";
|
|
4767
|
+
}
|
|
4768
|
+
if (!isPlain3(raw) || !Array.isArray(raw.reveals) || !isPlain3(raw.page)) throw new LinkStop("REVEALS_INVALID");
|
|
4769
|
+
const { next } = raw.page;
|
|
4770
|
+
let last = after;
|
|
4771
|
+
let lastEpoch = 0;
|
|
4772
|
+
for (const reveal of raw.reveals) {
|
|
4773
|
+
if (!isPlain3(reveal) || !Number.isSafeInteger(reveal.number) || !Number.isSafeInteger(reveal.epoch) || typeof reveal.envelope !== "string") throw new LinkStop("REVEALS_INVALID");
|
|
4774
|
+
const number = reveal.number;
|
|
4775
|
+
const epoch = reveal.epoch;
|
|
4776
|
+
if (number < last || number === last && epoch <= lastEpoch) throw new LinkStop("PAGING_NOT_FORWARD");
|
|
4777
|
+
if (number === after) throw new LinkStop("PAGING_NOT_FORWARD");
|
|
4778
|
+
last = number;
|
|
4779
|
+
lastEpoch = epoch;
|
|
4780
|
+
const row = onList.get(number);
|
|
4781
|
+
if (!row) throw new LinkStop("REVEAL_OFF_LIST");
|
|
4782
|
+
const seen = out.get(number);
|
|
4783
|
+
if (seen?.kind === "opened" && seen.disclosure !== null) continue;
|
|
4784
|
+
let disclosure = null;
|
|
4785
|
+
try {
|
|
4786
|
+
const opened = await openRevealV1({ envelope: reveal.envelope, linkKey: input.linkKey, handle, epoch, recordKey: row.recordKey });
|
|
4787
|
+
if (opened.ok) disclosure = opened.disclosure;
|
|
4788
|
+
} catch {
|
|
4789
|
+
disclosure = null;
|
|
4790
|
+
}
|
|
4791
|
+
out.set(number, { kind: "opened", disclosure, served: true });
|
|
4792
|
+
}
|
|
4793
|
+
if (next === null) break;
|
|
4794
|
+
if (!Number.isSafeInteger(next) || raw.reveals.length === 0 || next < last || next <= after) throw new LinkStop("PAGING_NOT_FORWARD");
|
|
4795
|
+
after = next;
|
|
4796
|
+
}
|
|
4797
|
+
return out;
|
|
4798
|
+
}
|
|
4799
|
+
var statusOf = (records2, collection) => {
|
|
4800
|
+
if (collection === "fails" || records2.some((r) => r.status === "fails")) return "fails";
|
|
4801
|
+
if (collection !== "matches" || records2.length === 0 || records2.some((r) => r.status !== "matches")) return "not-checked";
|
|
4802
|
+
return "matches";
|
|
4803
|
+
};
|
|
4804
|
+
async function checkSharedRecordV1(input) {
|
|
4805
|
+
const budget = {
|
|
4806
|
+
recordRequests: input.budget?.recordRequests ?? SHARED_RECORD_CHECK_RECORD_REQUESTS_V1,
|
|
4807
|
+
runRequests: input.budget?.runRequests ?? SHARED_RECORD_CHECK_RUN_REQUESTS_V1,
|
|
4808
|
+
recordMs: input.budget?.recordMs ?? SHARED_RECORD_CHECK_RECORD_MS_V1
|
|
4809
|
+
};
|
|
4810
|
+
const run = { input, budget, left: Math.max(0, budget.runRequests), spent: 0, readers: /* @__PURE__ */ new Map(), roots: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map() };
|
|
4811
|
+
const result = {
|
|
4812
|
+
schema: SHARED_RECORD_CHECK_SCHEMA_V1,
|
|
4813
|
+
status: "not-checked",
|
|
4814
|
+
code: null,
|
|
4815
|
+
mode: input.full ? "full" : "default",
|
|
4816
|
+
collection: { status: "not-checked", records: 0 },
|
|
4817
|
+
cover: null,
|
|
4818
|
+
reveal: null,
|
|
4819
|
+
fields: "none",
|
|
4820
|
+
counts: { records: 0, matches: 0, fails: 0, notChecked: 0 },
|
|
4821
|
+
records: [],
|
|
4822
|
+
sources: [],
|
|
4823
|
+
requests: 0
|
|
4824
|
+
};
|
|
4825
|
+
const stop = (code) => {
|
|
4826
|
+
result.code = code;
|
|
4827
|
+
result.status = LINK_CODE_STATUS[code];
|
|
4828
|
+
if (result.status === "fails") result.collection.status = "fails";
|
|
4829
|
+
return result;
|
|
4830
|
+
};
|
|
4831
|
+
let manifest;
|
|
4832
|
+
try {
|
|
4833
|
+
manifest = await readManifest(input.source);
|
|
4834
|
+
} catch (error) {
|
|
4835
|
+
return stop(error instanceof LinkStop ? error.code : "MANIFEST_NOT_READ");
|
|
4836
|
+
}
|
|
4837
|
+
const { first, members, rows } = manifest;
|
|
4838
|
+
if (typeof first.reference === "string" && typeof first.organization === "string" && typeof first.sharedOn === "string" && typeof first.link?.endsOn === "string") {
|
|
4839
|
+
result.cover = { reference: first.reference, organization: first.organization, sharedOn: first.sharedOn, endsOn: first.link.endsOn };
|
|
4840
|
+
}
|
|
4841
|
+
const listAddress = input.handle !== null && hasListHandlePrefixV1(input.handle);
|
|
4842
|
+
if (rows === null || first.list === void 0) return stop(listAddress ? "LINK_NOT_A_LIST" : "LINK_HAS_NO_LIST");
|
|
4843
|
+
const list = first.list;
|
|
4844
|
+
result.collection.records = rows.length;
|
|
4845
|
+
result.counts.records = rows.length;
|
|
4846
|
+
result.reveal = { mode: list.reveal.mode, fields: [...list.reveal.fields], time: list.reveal.time };
|
|
4847
|
+
if (!sameTerms(first.reveal, list.reveal)) return stop("TERMS_DIFFER");
|
|
4848
|
+
if (input.handle !== null && !sharedRecordHandleNamesListV1(input.handle, list)) return stop("LIST_NOT_ADDRESS");
|
|
4849
|
+
if (!recordsAreList(members, rows)) return stop("RECORDS_NOT_LIST");
|
|
4850
|
+
result.collection.status = input.handle === null ? "not-compared" : "matches";
|
|
4851
|
+
const reveals = revealsFieldsV1(list.reveal);
|
|
4852
|
+
let given;
|
|
4853
|
+
if (!reveals) {
|
|
4854
|
+
given = async () => ({ kind: "none" });
|
|
4855
|
+
} else if (input.source.disclosure) {
|
|
4856
|
+
result.fields = "opened";
|
|
4857
|
+
given = async (number) => {
|
|
4858
|
+
try {
|
|
4859
|
+
const disclosure = await input.source.disclosure(number);
|
|
4860
|
+
return { kind: "opened", disclosure: disclosure ?? null, served: false };
|
|
4861
|
+
} catch {
|
|
4862
|
+
return { kind: "not-read" };
|
|
4863
|
+
}
|
|
4864
|
+
};
|
|
4865
|
+
} else if (input.linkKey && input.source.reveals && input.handle !== null) {
|
|
4866
|
+
let read;
|
|
4867
|
+
try {
|
|
4868
|
+
read = await readReveals(input, rows, input.handle);
|
|
4869
|
+
} catch (error) {
|
|
4870
|
+
return stop(error instanceof LinkStop ? error.code : "REVEALS_INVALID");
|
|
4871
|
+
}
|
|
4872
|
+
const all = read;
|
|
4873
|
+
result.fields = all === "not-read" ? "not-read" : "opened";
|
|
4874
|
+
given = async (number) => all === "not-read" ? { kind: "not-read" } : all.get(number) ?? { kind: "opened", disclosure: null, served: false };
|
|
4875
|
+
} else {
|
|
4876
|
+
result.fields = "not-opened";
|
|
4877
|
+
given = async () => ({ kind: "not-opened" });
|
|
4878
|
+
}
|
|
4879
|
+
const kept = input.keep ? [] : null;
|
|
4880
|
+
const records2 = new Array(rows.length);
|
|
4881
|
+
let next = 0;
|
|
4882
|
+
let done = 0;
|
|
4883
|
+
const worker = async () => {
|
|
4884
|
+
for (; ; ) {
|
|
4885
|
+
const at = next;
|
|
4886
|
+
next += 1;
|
|
4887
|
+
if (at >= rows.length) return;
|
|
4888
|
+
const row = rows[at];
|
|
4889
|
+
let record;
|
|
4890
|
+
try {
|
|
4891
|
+
record = await checkRecord(run, row, await given(row.number), kept);
|
|
4892
|
+
} catch {
|
|
4893
|
+
record = { ...emptyRecord(row), code: "SOURCE_NOT_READ" };
|
|
4894
|
+
}
|
|
4895
|
+
records2[at] = record;
|
|
4896
|
+
done += 1;
|
|
4897
|
+
try {
|
|
4898
|
+
input.onRecord?.(record, { done, of: rows.length });
|
|
4899
|
+
} catch {
|
|
4900
|
+
}
|
|
4901
|
+
if (input.pause) await input.pause().catch(() => void 0);
|
|
4902
|
+
}
|
|
4903
|
+
};
|
|
4904
|
+
const inFlight = Math.max(1, Math.min(8, Math.floor(input.inFlight ?? 1)));
|
|
4905
|
+
await Promise.all(Array.from({ length: Math.min(inFlight, rows.length) }, worker));
|
|
4906
|
+
result.records = records2;
|
|
4907
|
+
result.counts.matches = records2.filter((r) => r.status === "matches").length;
|
|
4908
|
+
result.counts.fails = records2.filter((r) => r.status === "fails").length;
|
|
4909
|
+
result.counts.notChecked = records2.filter((r) => r.status === "not-checked").length;
|
|
4910
|
+
result.requests = run.spent;
|
|
4911
|
+
const sources = /* @__PURE__ */ new Map();
|
|
4912
|
+
for (const row of rows) {
|
|
4913
|
+
const key = `${row.chainId}:${row.contractAddress}`;
|
|
4914
|
+
const at = sources.get(key);
|
|
4915
|
+
if (at) at.records += 1;
|
|
4916
|
+
else sources.set(key, { chainId: row.chainId, contractAddress: row.contractAddress, source: run.readers.get(key)?.source ?? null, records: 1 });
|
|
4917
|
+
}
|
|
4918
|
+
result.sources = [...sources.values()];
|
|
4919
|
+
result.status = statusOf(records2, result.collection.status === "not-compared" ? "matches" : result.collection.status);
|
|
4920
|
+
if (kept) {
|
|
4921
|
+
const byNumber = new Map(kept.map((k) => [k.number, k]));
|
|
4922
|
+
result.kept = {
|
|
4923
|
+
manifest: { ...first, members, page: { after: 0, next: null } },
|
|
4924
|
+
records: rows.map((row) => byNumber.get(row.number) ?? { number: row.number, sealHistory: null, disclosure: null }),
|
|
4925
|
+
fields: result.fields === "not-read" ? "not-opened" : result.fields
|
|
4926
|
+
};
|
|
4927
|
+
}
|
|
4928
|
+
return result;
|
|
4929
|
+
}
|
|
4930
|
+
|
|
4931
|
+
// ../shared/src/records/shared-record-pace-v1.ts
|
|
4932
|
+
var SHARED_RECORD_CHECK_SOURCE_PACE_V1 = 25;
|
|
4933
|
+
var originOf = (input) => {
|
|
4934
|
+
try {
|
|
4935
|
+
return new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).origin;
|
|
4936
|
+
} catch {
|
|
4937
|
+
return "";
|
|
4938
|
+
}
|
|
4939
|
+
};
|
|
4940
|
+
var cutOff = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
|
|
4941
|
+
function unlessCutOff(wait, signal) {
|
|
4942
|
+
if (!signal) return wait;
|
|
4943
|
+
if (signal.aborted) return Promise.reject(cutOff(signal));
|
|
4944
|
+
return new Promise((resolve3, reject) => {
|
|
4945
|
+
const onAbort = () => reject(cutOff(signal));
|
|
4946
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
4947
|
+
wait.then(resolve3, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
4948
|
+
});
|
|
4949
|
+
}
|
|
4950
|
+
function sharedRecordPacedFetchV1(fetchImpl = fetch, options = {}) {
|
|
4951
|
+
const perSecond = options.perSecond ?? SHARED_RECORD_CHECK_SOURCE_PACE_V1;
|
|
4952
|
+
if (!Number.isFinite(perSecond) || perSecond <= 0) throw new RangeError("a pace is a number of requests a second above zero");
|
|
4953
|
+
const gap = 1e3 / perSecond;
|
|
4954
|
+
const now = options.now ?? Date.now;
|
|
4955
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
|
|
4956
|
+
const turns = /* @__PURE__ */ new Map();
|
|
4957
|
+
let read = -Infinity;
|
|
4958
|
+
const paced = async (input, init) => {
|
|
4959
|
+
if (init?.signal?.aborted) throw cutOff(init.signal);
|
|
4960
|
+
const origin = originOf(input);
|
|
4961
|
+
const at = now();
|
|
4962
|
+
if (at < read) for (const [key, owed] of turns) turns.set(key, owed - (read - at));
|
|
4963
|
+
read = at;
|
|
4964
|
+
const turn = Math.max(at, turns.get(origin) ?? -Infinity);
|
|
4965
|
+
turns.set(origin, turn + gap);
|
|
4966
|
+
if (turn > at) await unlessCutOff(sleep(turn - at), init?.signal);
|
|
4967
|
+
return fetchImpl(input, init);
|
|
4968
|
+
};
|
|
4969
|
+
return paced;
|
|
4970
|
+
}
|
|
4971
|
+
|
|
4972
|
+
// ../shared/src/records/shared-record-copy-v1.ts
|
|
4973
|
+
var import_ethers16 = require("ethers");
|
|
4974
|
+
var SHARED_RECORD_COPY_SCHEMA_V1 = "shared-record-copy/v1";
|
|
4975
|
+
var SHARED_RECORD_COPY_MAX_BYTES_V1 = 67108864;
|
|
4976
|
+
var SHARED_RECORD_COPY_SALT_LABEL_V1 = "pacspace:shared-record-copy-salt:v1";
|
|
4977
|
+
var SharedRecordCopyError = class extends Error {
|
|
4978
|
+
constructor(code) {
|
|
4979
|
+
super(code);
|
|
4980
|
+
this.code = code;
|
|
4981
|
+
this.name = "SharedRecordCopyError";
|
|
4982
|
+
}
|
|
4983
|
+
};
|
|
4984
|
+
var HEX_64_BARE2 = /^[0-9a-f]{64}$/;
|
|
4985
|
+
var COPY_KEYS = ["schema", "manifest", "list", "records", "fields"];
|
|
4986
|
+
var LIST_KEYS = ["reveal", "maskedSalt", "rows"];
|
|
4987
|
+
var RECORD_KEYS = ["number", "sealHistory", "disclosure"];
|
|
4988
|
+
var FIELDS2 = ["none", "not-opened", "opened"];
|
|
4989
|
+
var isPlain4 = (v) => !!v && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
|
|
4990
|
+
var hasExactly4 = (v, keys) => Object.keys(v).length === keys.length && keys.every((k) => Object.prototype.hasOwnProperty.call(v, k));
|
|
4991
|
+
function listBodyOf(handle) {
|
|
4992
|
+
const parts = typeof handle === "string" ? linkHandlePartsV1(handle) : null;
|
|
4993
|
+
return parts && parts.prefix === LIST_HANDLE_PREFIX ? parts.body : null;
|
|
4994
|
+
}
|
|
4995
|
+
function maskSharedRecordSaltV1(salt, handle) {
|
|
4996
|
+
const body = listBodyOf(handle);
|
|
4997
|
+
if (body === null) throw new SharedRecordCopyError("SHARED_RECORD_COPY_ADDRESS");
|
|
4998
|
+
if (typeof salt !== "string" || !HEX_64_BARE2.test(salt)) throw new SharedRecordCopyError("SHARED_RECORD_COPY_MALFORMED");
|
|
4999
|
+
const mask = import_ethers16.ethers.getBytes(import_ethers16.ethers.sha256(import_ethers16.ethers.concat([import_ethers16.ethers.toUtf8Bytes(SHARED_RECORD_COPY_SALT_LABEL_V1), Uint8Array.of(0), import_ethers16.ethers.toUtf8Bytes(body)])));
|
|
5000
|
+
const bytes2 = import_ethers16.ethers.getBytes(`0x${salt}`);
|
|
5001
|
+
return import_ethers16.ethers.hexlify(bytes2.map((b, i) => b ^ mask[i])).slice(2);
|
|
5002
|
+
}
|
|
5003
|
+
function buildSharedRecordCopyV1(input) {
|
|
5004
|
+
const malformed = () => new SharedRecordCopyError("SHARED_RECORD_COPY_MALFORMED");
|
|
5005
|
+
const { kept } = input;
|
|
5006
|
+
if (!isPlain4(kept) || !isPlain4(kept.manifest) || !Array.isArray(kept.records) || !FIELDS2.includes(kept.fields)) throw malformed();
|
|
5007
|
+
const { list, ...manifest } = kept.manifest;
|
|
5008
|
+
if (!isPlain4(list) || !isCanonicalRevealTermsV1(list.reveal)) throw malformed();
|
|
5009
|
+
let rows;
|
|
5010
|
+
try {
|
|
5011
|
+
rows = readSharedRecordListV1(list.rows);
|
|
5012
|
+
} catch {
|
|
5013
|
+
throw malformed();
|
|
5014
|
+
}
|
|
5015
|
+
if (kept.records.length !== rows.length || kept.records.some((r, i) => !isPlain4(r) || r.number !== rows[i].number)) throw malformed();
|
|
5016
|
+
const copy = {
|
|
5017
|
+
schema: SHARED_RECORD_COPY_SCHEMA_V1,
|
|
5018
|
+
manifest: { ...manifest, page: { after: 0, next: null } },
|
|
5019
|
+
list: { reveal: { mode: list.reveal.mode, fields: [...list.reveal.fields], time: list.reveal.time }, maskedSalt: maskSharedRecordSaltV1(list.salt, input.handle), rows },
|
|
5020
|
+
records: kept.records.map((r) => ({ number: r.number, sealHistory: r.sealHistory ?? null, disclosure: kept.fields === "opened" ? r.disclosure ?? null : null })),
|
|
5021
|
+
fields: kept.fields
|
|
5022
|
+
};
|
|
5023
|
+
if (!readSharedRecordCopyV1(copy).ok) throw malformed();
|
|
5024
|
+
const bytes2 = import_ethers16.ethers.toUtf8Bytes(canonicalizeJcs(copy));
|
|
5025
|
+
if (bytes2.length > SHARED_RECORD_COPY_MAX_BYTES_V1) throw new SharedRecordCopyError("SHARED_RECORD_COPY_TOO_LARGE");
|
|
5026
|
+
return { copy, bytes: bytes2, byteLength: bytes2.length };
|
|
5027
|
+
}
|
|
5028
|
+
function readSharedRecordCopyV1(json) {
|
|
5029
|
+
const refuse5 = { ok: false, code: "SHARED_RECORD_COPY_MALFORMED" };
|
|
5030
|
+
if (!isPlain4(json) || !hasExactly4(json, COPY_KEYS) || json.schema !== SHARED_RECORD_COPY_SCHEMA_V1) return refuse5;
|
|
5031
|
+
const { manifest, list, records: records2, fields } = json;
|
|
5032
|
+
if (!isPlain4(manifest) || manifest.schema !== SHARED_RECORD_SCHEMA_V2 || manifest.list !== void 0) return refuse5;
|
|
5033
|
+
if (sharedRecordV2KeyProblems(manifest).length > 0 || !Array.isArray(manifest.members)) return refuse5;
|
|
5034
|
+
if (!isPlain4(manifest.page) || manifest.page.after !== 0 || manifest.page.next !== null) return refuse5;
|
|
5035
|
+
if (!isPlain4(list) || !hasExactly4(list, LIST_KEYS) || !isCanonicalRevealTermsV1(list.reveal)) return refuse5;
|
|
5036
|
+
if (typeof list.maskedSalt !== "string" || !HEX_64_BARE2.test(list.maskedSalt)) return refuse5;
|
|
5037
|
+
let rows;
|
|
5038
|
+
try {
|
|
5039
|
+
rows = readSharedRecordListV1(list.rows);
|
|
5040
|
+
} catch {
|
|
5041
|
+
return refuse5;
|
|
5042
|
+
}
|
|
5043
|
+
if (typeof fields !== "string" || !FIELDS2.includes(fields)) return refuse5;
|
|
5044
|
+
if (fields === "none" !== !revealsFieldsV1(list.reveal)) return refuse5;
|
|
5045
|
+
if (!Array.isArray(records2) || records2.length !== rows.length) return refuse5;
|
|
5046
|
+
for (let i = 0; i < rows.length; i += 1) {
|
|
5047
|
+
const r = records2[i];
|
|
5048
|
+
if (!isPlain4(r) || !hasExactly4(r, RECORD_KEYS) || r.number !== rows[i].number) return refuse5;
|
|
5049
|
+
if (r.sealHistory !== null && (!isPlain4(r.sealHistory) || r.sealHistory.schema !== RECORD_SEAL_HISTORY_SCHEMA_V1)) return refuse5;
|
|
5050
|
+
if (r.disclosure !== null && (!isPlain4(r.disclosure) || fields !== "opened")) return refuse5;
|
|
5051
|
+
}
|
|
5052
|
+
return { ok: true, copy: json };
|
|
5053
|
+
}
|
|
5054
|
+
function sharedRecordCopySourceV1(copy, handle) {
|
|
5055
|
+
if (handle !== null && listBodyOf(handle) === null) throw new SharedRecordCopyError("SHARED_RECORD_COPY_ADDRESS");
|
|
5056
|
+
const salt = handle === null ? copy.list.maskedSalt : maskSharedRecordSaltV1(copy.list.maskedSalt, handle);
|
|
5057
|
+
const byNumber = new Map(copy.records.map((r) => [r.number, r]));
|
|
5058
|
+
const source = {
|
|
5059
|
+
async page(after) {
|
|
5060
|
+
if (after !== 0) throw new SharedRecordAnswerError("refused");
|
|
5061
|
+
return { ...copy.manifest, list: { reveal: copy.list.reveal, salt, rows: copy.list.rows }, page: { after: 0, next: null } };
|
|
5062
|
+
},
|
|
5063
|
+
async seals(number) {
|
|
5064
|
+
const history = byNumber.get(number)?.sealHistory ?? null;
|
|
5065
|
+
if (history === null) throw new SharedRecordAnswerError("unreachable");
|
|
5066
|
+
return history;
|
|
5067
|
+
}
|
|
5068
|
+
};
|
|
5069
|
+
if (copy.fields === "opened") source.disclosure = async (number) => byNumber.get(number)?.disclosure ?? null;
|
|
5070
|
+
return { handle, source };
|
|
5071
|
+
}
|
|
5072
|
+
|
|
3875
5073
|
// src/report.ts
|
|
3876
5074
|
var REPORT_SCHEMA = "pacspace-check-report/v1";
|
|
3877
5075
|
var SOURCE_REFUSAL_REASONS = {
|
|
@@ -4219,7 +5417,7 @@ var WRITES_LOOKUP_MAX_REQUESTS = 40;
|
|
|
4219
5417
|
var WRITES_LOOKUP_DEFAULT_BUDGET_MS = 1e4;
|
|
4220
5418
|
var HEX643 = /^0x[0-9a-f]{64}$/;
|
|
4221
5419
|
var HEX402 = /^0x[0-9a-f]{40}$/;
|
|
4222
|
-
var
|
|
5420
|
+
var ISO_INSTANT2 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
4223
5421
|
var WRITE_EXPLORERS = Object.freeze({
|
|
4224
5422
|
295: "https://hashscan.io/mainnet/transaction/",
|
|
4225
5423
|
296: "https://hashscan.io/testnet/transaction/"
|
|
@@ -4242,7 +5440,7 @@ function wantedEntriesOf(receipts, verifiedSeqs) {
|
|
|
4242
5440
|
return out.sort((a, b) => a.entry - b.entry);
|
|
4243
5441
|
}
|
|
4244
5442
|
function printable(write, contractAddress) {
|
|
4245
|
-
return !!write && typeof write === "object" && typeof write.contractAddress === "string" && write.contractAddress.toLowerCase() === contractAddress && typeof write.transactionHash === "string" && HEX643.test(write.transactionHash.toLowerCase()) && typeof write.committedAt === "string" &&
|
|
5443
|
+
return !!write && typeof write === "object" && typeof write.contractAddress === "string" && write.contractAddress.toLowerCase() === contractAddress && typeof write.transactionHash === "string" && HEX643.test(write.transactionHash.toLowerCase()) && typeof write.committedAt === "string" && ISO_INSTANT2.test(write.committedAt) && Number.isFinite(Date.parse(write.committedAt)) && typeof write.previousWord === "string" && typeof write.newWord === "string" && HEX643.test(write.previousWord.toLowerCase()) && HEX643.test(write.newWord.toLowerCase());
|
|
4246
5444
|
}
|
|
4247
5445
|
function hitsFor(entry, writes, contractAddress) {
|
|
4248
5446
|
const seen = /* @__PURE__ */ new Map();
|
|
@@ -4272,7 +5470,7 @@ async function lookUpWrites(input) {
|
|
|
4272
5470
|
if (input.wanted.length === 0) return { read: true, entries: [], notFound: [] };
|
|
4273
5471
|
const done = (writes2) => input.wanted.every((entry) => hitsFor(entry, writes2, contractAddress).length > 0);
|
|
4274
5472
|
let writes;
|
|
4275
|
-
let
|
|
5473
|
+
let cutOff2 = false;
|
|
4276
5474
|
if (input.whole) {
|
|
4277
5475
|
const all = await within(input.reader.getRecordWrites(input.recordKey), input.budgetMs);
|
|
4278
5476
|
if (all === "cut") return { read: false, reason: "timeout" };
|
|
@@ -4292,7 +5490,7 @@ async function lookUpWrites(input) {
|
|
|
4292
5490
|
);
|
|
4293
5491
|
if (result === "cut") return { read: false, reason: "timeout" };
|
|
4294
5492
|
writes = result.writes;
|
|
4295
|
-
|
|
5493
|
+
cutOff2 = result.ended === "timeout";
|
|
4296
5494
|
}
|
|
4297
5495
|
const byTransaction = /* @__PURE__ */ new Map();
|
|
4298
5496
|
const notFound = [];
|
|
@@ -4318,7 +5516,7 @@ async function lookUpWrites(input) {
|
|
|
4318
5516
|
});
|
|
4319
5517
|
}
|
|
4320
5518
|
const entries = [...byTransaction.values()].sort((a, b) => a.entries[0] - b.entries[0]);
|
|
4321
|
-
if (
|
|
5519
|
+
if (cutOff2 && entries.length === 0) return { read: false, reason: "timeout" };
|
|
4322
5520
|
return { read: true, entries, notFound };
|
|
4323
5521
|
} catch {
|
|
4324
5522
|
return { read: false, reason: "unreachable" };
|
|
@@ -4327,7 +5525,7 @@ async function lookUpWrites(input) {
|
|
|
4327
5525
|
|
|
4328
5526
|
// src/check.ts
|
|
4329
5527
|
var CHECKER_NAME = "@pacspace-io/check";
|
|
4330
|
-
var CHECKER_VERSION = true ? "0.
|
|
5528
|
+
var CHECKER_VERSION = true ? "0.6.0" : "0.0.0-dev";
|
|
4331
5529
|
var HISTORY_SCHEMAS = [
|
|
4332
5530
|
RECORD_HISTORY_BUNDLE_SCHEMA_V1,
|
|
4333
5531
|
RECORD_HISTORY_BUNDLE_SCHEMA_V2,
|
|
@@ -4407,7 +5605,7 @@ function memoizeSequenceReads(reader) {
|
|
|
4407
5605
|
}
|
|
4408
5606
|
};
|
|
4409
5607
|
}
|
|
4410
|
-
function
|
|
5608
|
+
function readerFor2(chain, options) {
|
|
4411
5609
|
const chainId = chain?.chainId;
|
|
4412
5610
|
const contractAddress = chain?.contractAddress;
|
|
4413
5611
|
if (!contractAddress) {
|
|
@@ -4632,7 +5830,7 @@ async function checkBundle(file, options) {
|
|
|
4632
5830
|
let sequence = null;
|
|
4633
5831
|
let sourceReader = null;
|
|
4634
5832
|
try {
|
|
4635
|
-
const found =
|
|
5833
|
+
const found = readerFor2(bundle.chain, options);
|
|
4636
5834
|
const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
|
|
4637
5835
|
sourceReader = reader;
|
|
4638
5836
|
const level = options.full ? "ledger" : "semantic";
|
|
@@ -4745,7 +5943,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
|
|
|
4745
5943
|
let sequence = null;
|
|
4746
5944
|
let sourceReader = null;
|
|
4747
5945
|
try {
|
|
4748
|
-
const found =
|
|
5946
|
+
const found = readerFor2(bundle.chain, options);
|
|
4749
5947
|
const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
|
|
4750
5948
|
sourceReader = reader;
|
|
4751
5949
|
const contractMatches = !!bundle.chain?.contractAddress && bundle.chain.contractAddress.toLowerCase() === reader.contractAddress.toLowerCase();
|
|
@@ -4895,7 +6093,7 @@ async function checkSeals(formName, form, disclosure, options) {
|
|
|
4895
6093
|
let source;
|
|
4896
6094
|
let reader = null;
|
|
4897
6095
|
try {
|
|
4898
|
-
const found =
|
|
6096
|
+
const found = readerFor2(form.chain, options);
|
|
4899
6097
|
reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
|
|
4900
6098
|
const chainWord = await reader.getRecord(form.recordKey);
|
|
4901
6099
|
verification = verifyRecordSealHistoryV1(form, { layouts, chainWord });
|
|
@@ -4931,33 +6129,646 @@ async function checkSeals(formName, form, disclosure, options) {
|
|
|
4931
6129
|
});
|
|
4932
6130
|
}
|
|
4933
6131
|
|
|
4934
|
-
// src/open.ts
|
|
6132
|
+
// src/open-io.ts
|
|
4935
6133
|
var import_node_path = require("node:path");
|
|
4936
|
-
var LINK_PROMPT = "Paste the link, then press Enter:";
|
|
4937
|
-
var LINK_IN_ARGV_SENTENCE = "The link was given on the command line, where your shell history and other programs on this machine can see it. Next time, run open and paste the link when it asks.";
|
|
4938
|
-
var NOT_A_LINK_SENTENCE = "This is not a PacSpace record link. A record link looks like https://<host>/c/<handle>/.";
|
|
4939
|
-
var ACCESS_CODE_PROMPT = "This link asks for an access code. Type it, then press Enter:";
|
|
4940
6134
|
var hostUnreachableSentence = (host) => `The link could not be read from ${host}. Check the connection and run it again.`;
|
|
4941
6135
|
var NO_KEY_SENTENCE = "This link reveals fields, but it has no key after #. Ask the sender for the whole link.";
|
|
4942
|
-
var KEY_DOES_NOT_OPEN_SENTENCE = "The revealed fields didn't open with this link's key. Ask the sender for the whole link.";
|
|
4943
|
-
var REVEALED_HEADER = "Revealed fields";
|
|
4944
|
-
var savedCopySentence = (path) => `Saved a kept copy to ${path}. Check it again at any time with: npx @pacspace-io/check ${path}`;
|
|
4945
6136
|
var pathExistsSentence = (path) => `${path} already exists. Choose another path.`;
|
|
4946
6137
|
var savedReportSentence = (path) => `Saved the report to ${path}. It opens in a browser without a network connection.`;
|
|
4947
|
-
var notShown = (k) => `${k} ${k === 1 ? "field" : "fields"} not shown.`;
|
|
4948
|
-
var STEP_UP_REQUIRED = "CUSTOMER_LINK_STEP_UP_REQUIRED";
|
|
4949
|
-
var LINK_NOT_FOUND = "CUSTOMER_LINK_NOT_FOUND";
|
|
4950
6138
|
var LINE_MAX_BYTES = 8192;
|
|
4951
|
-
var OpenUsageError = class extends Error {
|
|
4952
|
-
};
|
|
4953
6139
|
var OpenStop = class extends Error {
|
|
4954
6140
|
constructor(message, exitCode) {
|
|
4955
6141
|
super(message);
|
|
4956
6142
|
this.exitCode = exitCode;
|
|
4957
6143
|
}
|
|
4958
6144
|
};
|
|
6145
|
+
async function firstLineOf(io, path) {
|
|
6146
|
+
let bytes2;
|
|
6147
|
+
try {
|
|
6148
|
+
bytes2 = await io.readBytes((0, import_node_path.resolve)(path), LINE_MAX_BYTES);
|
|
6149
|
+
} catch (error) {
|
|
6150
|
+
throw new OpenStop(`The file could not be read: ${error.message}`, 2);
|
|
6151
|
+
}
|
|
6152
|
+
return new TextDecoder().decode(bytes2).split(/\r?\n/)[0] ?? "";
|
|
6153
|
+
}
|
|
6154
|
+
async function writeNew(io, path, bytes2) {
|
|
6155
|
+
if (!io.writeNewFile) throw new OpenStop(`The file could not be written: ${path}`, 2);
|
|
6156
|
+
try {
|
|
6157
|
+
await io.writeNewFile((0, import_node_path.resolve)(path), bytes2, 384);
|
|
6158
|
+
} catch (error) {
|
|
6159
|
+
if (error.code === "EEXIST") throw new OpenStop(pathExistsSentence(path), 2);
|
|
6160
|
+
throw new OpenStop(`The file could not be written: ${error.message}`, 2);
|
|
6161
|
+
}
|
|
6162
|
+
}
|
|
6163
|
+
var withoutControls = (text) => Array.from(text).filter((ch) => ch.charCodeAt(0) >= 32 && ch.charCodeAt(0) !== 127).join("");
|
|
6164
|
+
var escapeHtml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
6165
|
+
function refusalOfBody(body) {
|
|
6166
|
+
const outer = body ?? {};
|
|
6167
|
+
const code = outer.error?.code ?? outer.code;
|
|
6168
|
+
const message = outer.error?.message ?? outer.message;
|
|
6169
|
+
const wait = outer.error?.retryAfterSeconds ?? outer.retryAfterSeconds;
|
|
6170
|
+
return {
|
|
6171
|
+
code: typeof code === "string" ? code : null,
|
|
6172
|
+
message: typeof message === "string" ? withoutControls(message).trim() || null : null,
|
|
6173
|
+
retryAfterSeconds: typeof wait === "number" && Number.isFinite(wait) && wait >= 0 ? wait : null
|
|
6174
|
+
};
|
|
6175
|
+
}
|
|
6176
|
+
async function refusalOf(response) {
|
|
6177
|
+
try {
|
|
6178
|
+
return refusalOfBody(await response.json());
|
|
6179
|
+
} catch {
|
|
6180
|
+
return { code: null, message: null, retryAfterSeconds: null };
|
|
6181
|
+
}
|
|
6182
|
+
}
|
|
6183
|
+
async function bodyWithin(response, max) {
|
|
6184
|
+
const declared = Number(response.headers.get("content-length"));
|
|
6185
|
+
if (Number.isFinite(declared) && declared > max) {
|
|
6186
|
+
await response.body?.cancel().catch(() => void 0);
|
|
6187
|
+
return null;
|
|
6188
|
+
}
|
|
6189
|
+
if (!response.body) return new Uint8Array(0);
|
|
6190
|
+
const reader = response.body.getReader();
|
|
6191
|
+
const chunks = [];
|
|
6192
|
+
let total = 0;
|
|
6193
|
+
for (; ; ) {
|
|
6194
|
+
const { done, value } = await reader.read();
|
|
6195
|
+
if (done) break;
|
|
6196
|
+
total += value.length;
|
|
6197
|
+
if (total > max) {
|
|
6198
|
+
await reader.cancel().catch(() => void 0);
|
|
6199
|
+
return null;
|
|
6200
|
+
}
|
|
6201
|
+
chunks.push(value);
|
|
6202
|
+
}
|
|
6203
|
+
const bytes2 = new Uint8Array(total);
|
|
6204
|
+
let at = 0;
|
|
6205
|
+
for (const chunk of chunks) {
|
|
6206
|
+
bytes2.set(chunk, at);
|
|
6207
|
+
at += chunk.length;
|
|
6208
|
+
}
|
|
6209
|
+
return bytes2;
|
|
6210
|
+
}
|
|
6211
|
+
function retryAfterSecondsOf(response, refusal) {
|
|
6212
|
+
const header = response.headers.get("retry-after");
|
|
6213
|
+
if (header !== null && /^\d{1,6}$/.test(header.trim())) return Number(header.trim());
|
|
6214
|
+
return refusal.retryAfterSeconds;
|
|
6215
|
+
}
|
|
6216
|
+
|
|
6217
|
+
// src/shared-record-words.ts
|
|
6218
|
+
var plural = (n, one, many) => n === 1 ? one : many;
|
|
6219
|
+
var records = (n) => `${n} ${plural(n, "record", "records")}`;
|
|
6220
|
+
var SHARED_RECORD_WORDS = {
|
|
6221
|
+
// ---- before the code is asked for
|
|
6222
|
+
/** The origin every request of this run goes to. */
|
|
6223
|
+
readingFrom: (origin) => `Reading this link from ${origin}.`,
|
|
6224
|
+
/** Said before the code is asked for and again beside the result, when the origin is not one of PacSpace's. */
|
|
6225
|
+
notPacSpace: (origin) => `${origin} is not a PacSpace address. A code you type is sent to it, and a result here does not show who made the link.`,
|
|
6226
|
+
/** Said with the code prompt. A refused code is never sent again by this run. */
|
|
6227
|
+
codeOnce: (host) => `The code is sent to ${host} once. Five wrong codes stop this link's code for everyone, so a code it refuses is not sent again.`,
|
|
6228
|
+
/** No code was typed or found in the file given. Nothing was sent. */
|
|
6229
|
+
noCode: "No code was given, so the link was not opened.",
|
|
6230
|
+
/** The link's host answered 429 to opening it. */
|
|
6231
|
+
openLimited: (host, seconds) => seconds === null ? `${host} is limiting how often this link can be opened. Wait, then run this again.` : `${host} is limiting how often this link can be opened. Wait ${seconds} ${plural(seconds, "second", "seconds")}, then run this again.`,
|
|
6232
|
+
/** A `csl1_` address that its host answers as any other kind of link. Exit code 1. */
|
|
6233
|
+
notAListLink: "This address names a list of records, and its host answered it as another kind of link. It fails the check.",
|
|
6234
|
+
/** A trail link made before lists. Exit code 3; no code is asked for. */
|
|
6235
|
+
noList: "This link was made before links carried a list of their records, so there is no list to check its records against. It was not checked.",
|
|
6236
|
+
/** `--full` over JSON-RPC. */
|
|
6237
|
+
fullNeedsMirror: "--full reads a contract's whole log from a mirror. Use it without --rpc.",
|
|
6238
|
+
/** `open --full` on a link to one record. */
|
|
6239
|
+
fullOnlyForList: "With open, --full is used only with a link to a list of records.",
|
|
6240
|
+
/** `--html` beside `--json`'s own report is fine; `--copy` when the link gave nothing to keep. */
|
|
6241
|
+
copyNotSaved: "No copy was saved, because the link did not serve a list that could be kept.",
|
|
6242
|
+
/** A kept copy of a link with `--offline`. */
|
|
6243
|
+
copyOffline: "A copy of a link is checked against the proof layer, so it was not checked offline. Run this again without --offline.",
|
|
6244
|
+
copyNotRead: "This is not a copy of a link this version can read.",
|
|
6245
|
+
/** `--link-file` given with a copy, and the address in it does not name a list of records. */
|
|
6246
|
+
copyAddress: "The link given with this copy is not the address of a link with a list of records.",
|
|
6247
|
+
/** An option of a single record's file given with a copy of a link. */
|
|
6248
|
+
copyOption: (flag) => `${flag} is not used with a copy of a link.`,
|
|
6249
|
+
/** `--link-file` with a file that is not a copy of a link. */
|
|
6250
|
+
linkFileOnlyForCopy: "--link-file is used with open, or with a copy of a link.",
|
|
6251
|
+
savedCopy: (path) => `Saved a copy to ${path}. It holds the revealed fields in clear. Check it again at any time with: npx @pacspace-io/check ${path}`,
|
|
6252
|
+
savedCopyNoFields: (path) => `Saved a copy to ${path}. Check it again at any time with: npx @pacspace-io/check ${path}`,
|
|
6253
|
+
progress: (done, of) => `Checked ${done} of ${records(of)}.`,
|
|
6254
|
+
// ---- the report's facts
|
|
6255
|
+
title: "PacSpace link check",
|
|
6256
|
+
labels: {
|
|
6257
|
+
host: "Link host",
|
|
6258
|
+
readFrom: "Read from",
|
|
6259
|
+
reference: "Reference",
|
|
6260
|
+
sharedBy: "Shared by",
|
|
6261
|
+
sharedOn: "Shared on",
|
|
6262
|
+
records: "Records",
|
|
6263
|
+
proofLayer: "Proof layer"
|
|
6264
|
+
},
|
|
6265
|
+
/** The cover is PacSpace's report: nothing in it is held to the address. */
|
|
6266
|
+
coverNote: "The reference, who shared this link and when are as its host reports them. The check does not cover them.",
|
|
6267
|
+
proofLayerLine: (chainId, contract, source) => source === null ? `network ${chainId}, contract ${contract}, not read` : `network ${chainId}, contract ${contract}, read from ${source}`,
|
|
6268
|
+
// ---- the collection
|
|
6269
|
+
listMatches: (n) => n === 1 ? "This link's address names a list of 1 record. The list served is that list, and the record served is the one on it." : `This link's address names a list of ${n} records. The list served is that list, and the records served are the ones on it.`,
|
|
6270
|
+
listNotCompared: (n) => `This copy lists ${records(n)}. No link was given with it, so its list was not compared with a link's address. Pass the link with --link-file to compare it.`,
|
|
6271
|
+
// ---- the result line. It never says every record matches while one is not checked.
|
|
6272
|
+
// A list of one record says the registered lines for one record.
|
|
6273
|
+
allMatch: (n) => n === 1 ? "Compared with the proof layer for this record: it matches." : `Compared with the proof layer: all ${n} records match.`,
|
|
6274
|
+
someFail: (failed, n) => n === 1 ? "Compared with the proof layer for this record: it does not match." : `Compared with the proof layer: ${failed} of ${n} records ${plural(failed, "does", "do")} not match.`,
|
|
6275
|
+
/** No record fails and at least one was not checked. */
|
|
6276
|
+
someNotChecked: (matched, notChecked, n) => n === 1 ? "Compared with the proof layer for this record: it was not checked." : matched === 0 ? `Compared with the proof layer: none of the ${n} records was checked.` : `Compared with the proof layer: ${matched} of ${n} records ${plural(matched, "matches", "match")}. ${notChecked} ${plural(notChecked, "was", "were")} not checked.`,
|
|
6277
|
+
/** At least one record fails and at least one was not checked: a list of two or more. */
|
|
6278
|
+
failedAndNotChecked: (failed, notChecked, n) => `Compared with the proof layer: ${failed} of ${n} records ${plural(failed, "does", "do")} not match, and ${notChecked} ${plural(notChecked, "was", "were")} not checked.`,
|
|
6279
|
+
/** The default check's stated limit, said with a result that passed without `--full`. */
|
|
6280
|
+
spanLimit: "Each record's writes were read back to its first write. A record that was set back to empty and written again before that first write is shown only by --full, which reads the contract's whole log.",
|
|
6281
|
+
// ---- one record
|
|
6282
|
+
recordFails: (number, why) => `Record ${number}: does not match. ${why}`,
|
|
6283
|
+
recordNotChecked: (number, why) => `Record ${number}: not checked. ${why}`,
|
|
6284
|
+
/** A record that moved on after it was served. Reported, never a failure. */
|
|
6285
|
+
changedSince: (number, later) => later > 0 ? `Record ${number} has changed since what this link served: ${later} later ${plural(later, "write is", "writes are")} on the proof layer. Its entries up to its close match what was committed.` : `Record ${number} has changed since what this link served. Its entries up to its close match what was committed.`,
|
|
6286
|
+
afterClose: (number, entries) => `Record ${number}: ${entries} ${plural(entries, "entry", "entries")} after its close ${plural(entries, "was", "were")} served and checked the same way. ${plural(entries, "It is", "They are")} not part of this link's list.`,
|
|
6287
|
+
committingAfterClose: (number, entries) => `Record ${number}: ${entries} ${plural(entries, "entry", "entries")} after its close ${plural(entries, "is", "are")} still being committed.`,
|
|
6288
|
+
recordsNotListed: (count) => `${count} more ${plural(count, "record is", "records are")} not listed here. --json lists them all.`,
|
|
6289
|
+
/** Each entry's time on the proof layer. */
|
|
6290
|
+
committedHeading: "When each entry was committed on the proof layer:",
|
|
6291
|
+
committedLine: (number, entry, when) => `Record ${number}, entry ${entry}: committed ${when}`,
|
|
6292
|
+
committedNotListed: (count) => `${count} more ${plural(count, "entry is", "entries are")} not listed here. --json lists them all.`,
|
|
6293
|
+
// ---- revealed fields
|
|
6294
|
+
/** A copy kept when the fields were not opened. */
|
|
6295
|
+
copyFieldsNotKept: "This link reveals fields, and this copy was kept without them.",
|
|
6296
|
+
fieldsNotRead: "This link reveals fields, and they could not be read from the link's host, so none are shown.",
|
|
6297
|
+
fieldsOpened: (n) => n === 1 ? "The revealed fields of 1 record were opened on this machine. Each shown field was checked against its entry's seal." : `The revealed fields of ${n} records were opened on this machine. Each shown field was checked against its entry's seal.`,
|
|
6298
|
+
revealedHeading: (number) => `Record ${number}, revealed fields`
|
|
6299
|
+
};
|
|
6300
|
+
var NOT_A_FORM = "What the link served is not in a form this version reads. It fails the check.";
|
|
6301
|
+
var NOT_ITS_LIST = "The list served is not the one this link's address names. It fails the check.";
|
|
6302
|
+
var LINK_CODE_WORDS = {
|
|
6303
|
+
LINK_NOT_A_LIST: SHARED_RECORD_WORDS.notAListLink,
|
|
6304
|
+
MANIFEST_INVALID: NOT_A_FORM,
|
|
6305
|
+
LIST_ON_LATER_PAGE: NOT_A_FORM,
|
|
6306
|
+
LIST_INVALID: "The list served is not a list this version reads. It fails the check.",
|
|
6307
|
+
PAGING_NOT_FORWARD: "The pages served do not follow one another. It fails the check.",
|
|
6308
|
+
TERMS_DIFFER: NOT_ITS_LIST,
|
|
6309
|
+
LIST_NOT_ADDRESS: NOT_ITS_LIST,
|
|
6310
|
+
RECORDS_NOT_LIST: "The records served are not the records on the list. It fails the check.",
|
|
6311
|
+
REVEALS_INVALID: "The revealed fields served are not in a form this version reads. It fails the check.",
|
|
6312
|
+
REVEAL_OFF_LIST: "Revealed fields were served for a record that is not on the list. It fails the check.",
|
|
6313
|
+
LINK_HAS_NO_LIST: SHARED_RECORD_WORDS.noList,
|
|
6314
|
+
MANIFEST_NOT_READ: "The link could not be read, so nothing was checked."
|
|
6315
|
+
};
|
|
6316
|
+
var entryOf = (entry) => entry === null ? "An entry" : `Entry ${entry}`;
|
|
6317
|
+
function recordCodeWords(code, entry, context) {
|
|
6318
|
+
switch (code) {
|
|
6319
|
+
case "HISTORY_NOT_SERVED":
|
|
6320
|
+
return "Its history was not served.";
|
|
6321
|
+
case "HISTORY_INVALID":
|
|
6322
|
+
return "The history served for it is not whole, or was changed.";
|
|
6323
|
+
case "HISTORY_OTHER_RECORD":
|
|
6324
|
+
return "The history served for it is another record's.";
|
|
6325
|
+
case "ENTRY_MISSING":
|
|
6326
|
+
return `${entryOf(entry)} is missing from what was served.`;
|
|
6327
|
+
case "ENTRY_NOT_COMMITTED":
|
|
6328
|
+
return `${entryOf(entry)} is not yet committed.`;
|
|
6329
|
+
case "ENTRY_FAILED":
|
|
6330
|
+
return `${entryOf(entry)} does not match what was committed.`;
|
|
6331
|
+
case "CLOSE_SEAL_DIFFERS":
|
|
6332
|
+
return "Its closing entry is not the one the list names.";
|
|
6333
|
+
case "ENTRY_NOT_WRITTEN":
|
|
6334
|
+
return `${entryOf(entry)} has no write on the proof layer.`;
|
|
6335
|
+
case "WRITE_NOT_SERVED":
|
|
6336
|
+
return "The proof layer holds a write among its entries that was not served.";
|
|
6337
|
+
case "WRITE_BEFORE_FIRST":
|
|
6338
|
+
return "The proof layer holds writes of this record from before its first entry.";
|
|
6339
|
+
case "RECORD_SET_BACK":
|
|
6340
|
+
return "A later write on the proof layer set the record back.";
|
|
6341
|
+
case "CURRENT_WORD_ZERO":
|
|
6342
|
+
return "The record on the proof layer today is empty.";
|
|
6343
|
+
case "CURRENT_WORD_EARLIER":
|
|
6344
|
+
return "The record on the proof layer today is at an earlier entry.";
|
|
6345
|
+
case "REVEAL_MISSING":
|
|
6346
|
+
return "The link reveals fields and none were served for it.";
|
|
6347
|
+
case "REVEAL_NOT_OPENED":
|
|
6348
|
+
return "Its revealed fields didn't open with this link's key.";
|
|
6349
|
+
case "FIELDS_DO_NOT_MATCH":
|
|
6350
|
+
return "Its revealed fields do not match its entries' seals.";
|
|
6351
|
+
case "HISTORY_NOT_READ":
|
|
6352
|
+
return "Its history could not be read.";
|
|
6353
|
+
case "LAYOUT_NOT_READ":
|
|
6354
|
+
return "It was written under a record layout this version does not read.";
|
|
6355
|
+
case "SOURCE_UNKNOWN":
|
|
6356
|
+
return `The checker has no address for its network (${context.chainId}). Pass one with --source <url>.`;
|
|
6357
|
+
case "SOURCE_NOT_READ":
|
|
6358
|
+
return "The proof layer source did not answer.";
|
|
6359
|
+
case "BUDGET_SPENT":
|
|
6360
|
+
return context.full || context.requests === 0 ? "The run reached the most it asks of the proof layer." : "The record lived longer than this read reaches. --full reads the contract's whole log.";
|
|
6361
|
+
case "LOG_PAST_BOUNDS":
|
|
6362
|
+
return "The contract's log holds more than this checker reads in one run.";
|
|
6363
|
+
case "REVEALS_NOT_READ":
|
|
6364
|
+
return "Its revealed fields could not be read.";
|
|
6365
|
+
case "ROOT_NOT_READ":
|
|
6366
|
+
return "What its revealed fields are checked against could not be read from the proof layer.";
|
|
6367
|
+
}
|
|
6368
|
+
}
|
|
6369
|
+
|
|
6370
|
+
// src/shared-record-link.ts
|
|
6371
|
+
var KEY_HOST = "records.pacspace.io";
|
|
6372
|
+
var KEY_HOST_READS_FROM = "https://app.pacspace.io";
|
|
6373
|
+
function linkOriginOf(address) {
|
|
6374
|
+
const origin = address.host === KEY_HOST ? KEY_HOST_READS_FROM : address.origin;
|
|
6375
|
+
return { addressHost: address.host, origin, host: new URL(origin).host, pacspace: origin === KEY_HOST_READS_FROM };
|
|
6376
|
+
}
|
|
6377
|
+
function rpcNameOf(rpc) {
|
|
6378
|
+
try {
|
|
6379
|
+
return new URL(rpc).origin;
|
|
6380
|
+
} catch {
|
|
6381
|
+
return "an RPC endpoint";
|
|
6382
|
+
}
|
|
6383
|
+
}
|
|
6384
|
+
var paceOf = (io) => ({
|
|
6385
|
+
...io.now ? { now: () => io.now().getTime() } : {},
|
|
6386
|
+
...io.sleep ? { sleep: io.sleep } : {}
|
|
6387
|
+
});
|
|
6388
|
+
function proofLayerFor(options) {
|
|
6389
|
+
const paced = sharedRecordPacedFetchV1(options.fetchImpl, options.pace);
|
|
6390
|
+
return ({ chainId, contractAddress }) => {
|
|
6391
|
+
const { source } = options;
|
|
6392
|
+
try {
|
|
6393
|
+
if (typeof source === "object") {
|
|
6394
|
+
return { reader: createRpcRecordChainReader({ rpcUrl: source.rpc, contractAddress, chainId, timeoutMs: options.timeoutMs }), source: rpcNameOf(source.rpc) };
|
|
6395
|
+
}
|
|
6396
|
+
const mirrorBaseUrl = source === void 0 || source === "mirror" ? MIRROR_NODE_BY_CHAIN[chainId] : source;
|
|
6397
|
+
if (!mirrorBaseUrl || mirrorBaseUrl === "offline") return null;
|
|
6398
|
+
return {
|
|
6399
|
+
reader: createMirrorNodeRecordChainReader({
|
|
6400
|
+
mirrorBaseUrl,
|
|
6401
|
+
chainId,
|
|
6402
|
+
contractAddress,
|
|
6403
|
+
timeoutMs: options.timeoutMs,
|
|
6404
|
+
fetchImpl: paced,
|
|
6405
|
+
// --full reads the contract's whole log once and holds every record of it to that one read.
|
|
6406
|
+
keepLogPages: options.full
|
|
6407
|
+
}),
|
|
6408
|
+
source: mirrorBaseUrl.replace(/\/+$/, "")
|
|
6409
|
+
};
|
|
6410
|
+
} catch {
|
|
6411
|
+
return null;
|
|
6412
|
+
}
|
|
6413
|
+
};
|
|
6414
|
+
}
|
|
6415
|
+
var LINK_ANSWER_MAX_BYTES = 16 * 1024 * 1024;
|
|
6416
|
+
var LINK_RUN_MAX_BYTES = SHARED_RECORD_COPY_MAX_BYTES_V1;
|
|
6417
|
+
var LINK_GAP_MS = 250;
|
|
6418
|
+
var LINK_WAITS = 3;
|
|
6419
|
+
var LINK_WAIT_MAX_MS = 6e4;
|
|
6420
|
+
var LINK_TIMEOUT_MS = 3e4;
|
|
6421
|
+
function linkHostOf(base, io, timeoutMs) {
|
|
6422
|
+
const fetchImpl = io.fetchImpl ?? fetch;
|
|
6423
|
+
const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
6424
|
+
const clock = () => io.now ? io.now().getTime() : Date.now();
|
|
6425
|
+
let turn = Promise.resolve();
|
|
6426
|
+
let nextAt = 0;
|
|
6427
|
+
let readBytes = 0;
|
|
6428
|
+
const paced = () => {
|
|
6429
|
+
const mine = turn.then(async () => {
|
|
6430
|
+
const wait = nextAt - clock();
|
|
6431
|
+
if (wait > 0) await sleep(Math.min(wait, LINK_GAP_MS));
|
|
6432
|
+
nextAt = clock() + LINK_GAP_MS;
|
|
6433
|
+
});
|
|
6434
|
+
turn = mine.catch(() => void 0);
|
|
6435
|
+
return mine;
|
|
6436
|
+
};
|
|
6437
|
+
return {
|
|
6438
|
+
sleep,
|
|
6439
|
+
async ask(path, init = {}) {
|
|
6440
|
+
await paced();
|
|
6441
|
+
const headers = { Accept: "application/json" };
|
|
6442
|
+
if (init.body !== void 0) headers["Content-Type"] = "application/json";
|
|
6443
|
+
if (init.bearer) headers.Authorization = `Bearer ${init.bearer}`;
|
|
6444
|
+
const response = await fetchImpl(`${base}${path}`, {
|
|
6445
|
+
method: init.method ?? "GET",
|
|
6446
|
+
headers,
|
|
6447
|
+
body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
|
|
6448
|
+
redirect: "error",
|
|
6449
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
6450
|
+
});
|
|
6451
|
+
const bytes2 = await bodyWithin(response, Math.min(LINK_ANSWER_MAX_BYTES, LINK_RUN_MAX_BYTES - readBytes));
|
|
6452
|
+
if (bytes2 === null) throw new Error("answer too large");
|
|
6453
|
+
readBytes += bytes2.length;
|
|
6454
|
+
let json = null;
|
|
6455
|
+
try {
|
|
6456
|
+
json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes2));
|
|
6457
|
+
} catch {
|
|
6458
|
+
json = null;
|
|
6459
|
+
}
|
|
6460
|
+
const refusal = refusalOfBody(json);
|
|
6461
|
+
return { status: response.status, json, refusal, retryAfterSeconds: retryAfterSecondsOf(response, refusal) };
|
|
6462
|
+
}
|
|
6463
|
+
};
|
|
6464
|
+
}
|
|
6465
|
+
function linkSourceOf(host, token) {
|
|
6466
|
+
const read = async (path) => {
|
|
6467
|
+
for (let waited = 0; ; waited += 1) {
|
|
6468
|
+
let answer;
|
|
6469
|
+
try {
|
|
6470
|
+
answer = await host.ask(path, { bearer: token });
|
|
6471
|
+
} catch {
|
|
6472
|
+
throw new SharedRecordAnswerError("unreachable");
|
|
6473
|
+
}
|
|
6474
|
+
if (answer.status === 200 && answer.json !== null) return answer.json;
|
|
6475
|
+
if (answer.status === 429 && waited < LINK_WAITS) {
|
|
6476
|
+
const seconds = answer.retryAfterSeconds ?? 2 ** waited;
|
|
6477
|
+
await host.sleep(Math.min(LINK_WAIT_MAX_MS, Math.max(1, seconds) * 1e3));
|
|
6478
|
+
continue;
|
|
6479
|
+
}
|
|
6480
|
+
throw new SharedRecordAnswerError(answer.status === 404 ? "refused" : "unreachable");
|
|
6481
|
+
}
|
|
6482
|
+
};
|
|
6483
|
+
return {
|
|
6484
|
+
page: (after) => read(`/record.json?v=2&after=${after}`),
|
|
6485
|
+
seals: (number) => read(`/members/${number}/seals`),
|
|
6486
|
+
reveals: (after) => read(`/reveals?after=${after}`)
|
|
6487
|
+
};
|
|
6488
|
+
}
|
|
6489
|
+
var TOKEN = /^[\x21-\x7e]{16,1024}$/;
|
|
6490
|
+
function stopOn(answer, host) {
|
|
6491
|
+
if (answer.status === 429) {
|
|
6492
|
+
throw new OpenStop(SHARED_RECORD_WORDS.openLimited(host, answer.retryAfterSeconds === null ? null : Math.max(1, Math.ceil(answer.retryAfterSeconds))), 3);
|
|
6493
|
+
}
|
|
6494
|
+
if (answer.status >= 500 || !answer.refusal.message) throw new OpenStop(answer.refusal.message ?? hostUnreachableSentence(host), 3);
|
|
6495
|
+
throw new OpenStop(answer.refusal.message, 2);
|
|
6496
|
+
}
|
|
6497
|
+
var LINK_REPORT_SCHEMA = "pacspace-check-link-report/v1";
|
|
6498
|
+
var EXIT = { matches: 0, fails: 1, "not-checked": 3 };
|
|
6499
|
+
var RECORDS_LISTED_MAX = 25;
|
|
6500
|
+
function listed(lines) {
|
|
6501
|
+
if (lines.length <= RECORDS_LISTED_MAX) return lines;
|
|
6502
|
+
return [...lines.slice(0, RECORDS_LISTED_MAX), SHARED_RECORD_WORDS.recordsNotListed(lines.length - RECORDS_LISTED_MAX)];
|
|
6503
|
+
}
|
|
6504
|
+
function linkSentences(check2, link, copy) {
|
|
6505
|
+
const sentences = [];
|
|
6506
|
+
const n = check2.collection.records;
|
|
6507
|
+
if (check2.cover) sentences.push(SHARED_RECORD_WORDS.coverNote);
|
|
6508
|
+
if (check2.code !== null) {
|
|
6509
|
+
sentences.push(LINK_CODE_WORDS[check2.code]);
|
|
6510
|
+
} else {
|
|
6511
|
+
sentences.push(check2.collection.status === "not-compared" ? SHARED_RECORD_WORDS.listNotCompared(n) : SHARED_RECORD_WORDS.listMatches(n));
|
|
6512
|
+
const { matches, fails, notChecked } = check2.counts;
|
|
6513
|
+
if (fails > 0 && notChecked > 0) sentences.push(SHARED_RECORD_WORDS.failedAndNotChecked(fails, notChecked, n));
|
|
6514
|
+
else if (fails > 0) sentences.push(SHARED_RECORD_WORDS.someFail(fails, n));
|
|
6515
|
+
else if (notChecked > 0) sentences.push(SHARED_RECORD_WORDS.someNotChecked(matches, notChecked, n));
|
|
6516
|
+
else sentences.push(SHARED_RECORD_WORDS.allMatch(n));
|
|
6517
|
+
const full = check2.mode === "full";
|
|
6518
|
+
const why = (r) => recordCodeWords(r.code, r.failedEntry, { chainId: r.chainId, full, requests: r.requests });
|
|
6519
|
+
sentences.push(...listed(check2.records.filter((r) => r.status === "fails").map((r) => SHARED_RECORD_WORDS.recordFails(r.number, why(r)))));
|
|
6520
|
+
sentences.push(...listed(check2.records.filter((r) => r.status === "not-checked").map((r) => SHARED_RECORD_WORDS.recordNotChecked(r.number, why(r)))));
|
|
6521
|
+
sentences.push(...listed(check2.records.filter((r) => r.status === "matches" && r.changedSince).map((r) => SHARED_RECORD_WORDS.changedSince(r.number, r.laterWrites))));
|
|
6522
|
+
const after = [];
|
|
6523
|
+
for (const r of check2.records) {
|
|
6524
|
+
const served = r.entries.filter((e) => e.afterClose).length;
|
|
6525
|
+
if (served > 0) after.push(SHARED_RECORD_WORDS.afterClose(r.number, served));
|
|
6526
|
+
if (r.committingAfterClose > 0) after.push(SHARED_RECORD_WORDS.committingAfterClose(r.number, r.committingAfterClose));
|
|
6527
|
+
}
|
|
6528
|
+
sentences.push(...listed(after));
|
|
6529
|
+
if (check2.fields === "not-opened") sentences.push(copy ? SHARED_RECORD_WORDS.copyFieldsNotKept : NO_KEY_SENTENCE);
|
|
6530
|
+
else if (check2.fields === "not-read") sentences.push(SHARED_RECORD_WORDS.fieldsNotRead);
|
|
6531
|
+
else if (check2.fields === "opened") {
|
|
6532
|
+
const shown = check2.records.filter((r) => r.fields.status === "matches" && r.fields.entries.length > 0).length;
|
|
6533
|
+
if (shown > 0) sentences.push(SHARED_RECORD_WORDS.fieldsOpened(shown));
|
|
6534
|
+
}
|
|
6535
|
+
if (check2.status === "matches") {
|
|
6536
|
+
sentences.push(SEALS_BOUNDARY_SENTENCE);
|
|
6537
|
+
if (!full) sentences.push(SHARED_RECORD_WORDS.spanLimit);
|
|
6538
|
+
}
|
|
6539
|
+
}
|
|
6540
|
+
if (link && !link.pacspace) sentences.push(SHARED_RECORD_WORDS.notPacSpace(link.readFrom));
|
|
6541
|
+
return sentences;
|
|
6542
|
+
}
|
|
6543
|
+
function buildLinkReport(check2, link, copy) {
|
|
6544
|
+
const { kept: _kept, ...rest } = check2;
|
|
6545
|
+
void _kept;
|
|
6546
|
+
const exitCode = EXIT[check2.status];
|
|
6547
|
+
return {
|
|
6548
|
+
schema: LINK_REPORT_SCHEMA,
|
|
6549
|
+
checker: { name: CHECKER_NAME, version: CHECKER_VERSION },
|
|
6550
|
+
link,
|
|
6551
|
+
passed: exitCode === 0,
|
|
6552
|
+
check: rest,
|
|
6553
|
+
sentences: linkSentences(check2, link, copy),
|
|
6554
|
+
exitCode
|
|
6555
|
+
};
|
|
6556
|
+
}
|
|
6557
|
+
function factsOf(report) {
|
|
6558
|
+
const { check: check2, link } = report;
|
|
6559
|
+
const facts = [];
|
|
6560
|
+
if (link) {
|
|
6561
|
+
facts.push([SHARED_RECORD_WORDS.labels.host, link.host]);
|
|
6562
|
+
if (link.readFrom !== `https://${link.host}`) facts.push([SHARED_RECORD_WORDS.labels.readFrom, link.readFrom]);
|
|
6563
|
+
}
|
|
6564
|
+
if (check2.cover) {
|
|
6565
|
+
facts.push([SHARED_RECORD_WORDS.labels.reference, withoutControls(check2.cover.reference)]);
|
|
6566
|
+
facts.push([SHARED_RECORD_WORDS.labels.sharedBy, withoutControls(check2.cover.organization)]);
|
|
6567
|
+
facts.push([SHARED_RECORD_WORDS.labels.sharedOn, `${dayOfUtc(check2.cover.sharedOn)} (UTC)`]);
|
|
6568
|
+
}
|
|
6569
|
+
if (check2.code === null) facts.push([SHARED_RECORD_WORDS.labels.records, String(check2.collection.records)]);
|
|
6570
|
+
for (const source of check2.sources) facts.push([SHARED_RECORD_WORDS.labels.proofLayer, SHARED_RECORD_WORDS.proofLayerLine(source.chainId, source.contractAddress, source.source)]);
|
|
6571
|
+
return facts;
|
|
6572
|
+
}
|
|
6573
|
+
function committedLines(check2) {
|
|
6574
|
+
const all = [];
|
|
6575
|
+
for (const record of check2.records) {
|
|
6576
|
+
for (const entry of record.entries) {
|
|
6577
|
+
if (!entry.afterClose && entry.committedAt) all.push(SHARED_RECORD_WORDS.committedLine(record.number, entry.entry, committedWhen(entry.committedAt)));
|
|
6578
|
+
}
|
|
6579
|
+
}
|
|
6580
|
+
if (all.length === 0) return [];
|
|
6581
|
+
const lines = [SHARED_RECORD_WORDS.committedHeading, ...all.slice(0, WRITES_LISTED_MAX)];
|
|
6582
|
+
if (all.length > WRITES_LISTED_MAX) lines.push(SHARED_RECORD_WORDS.committedNotListed(all.length - WRITES_LISTED_MAX));
|
|
6583
|
+
return lines;
|
|
6584
|
+
}
|
|
6585
|
+
function revealedOf(check2) {
|
|
6586
|
+
return check2.records.filter((r) => r.fields.status === "matches" && r.fields.entries.length > 0).map((r) => ({ number: r.number, entries: r.fields.entries }));
|
|
6587
|
+
}
|
|
6588
|
+
var notShown = (k) => `${k} ${k === 1 ? "field" : "fields"} not shown.`;
|
|
6589
|
+
function renderLinkReport(report) {
|
|
6590
|
+
const facts = factsOf(report);
|
|
6591
|
+
const width = Math.max(0, ...facts.map(([label]) => label.length));
|
|
6592
|
+
const lines = facts.map(([label, value]) => `${label.padEnd(width)} ${value}`);
|
|
6593
|
+
if (lines.length > 0) lines.push("");
|
|
6594
|
+
lines.push(...report.sentences);
|
|
6595
|
+
const committed = committedLines(report.check);
|
|
6596
|
+
if (committed.length > 0) lines.push("", ...committed);
|
|
6597
|
+
for (const record of revealedOf(report.check)) {
|
|
6598
|
+
lines.push("", SHARED_RECORD_WORDS.revealedHeading(record.number));
|
|
6599
|
+
for (const entry of record.entries) {
|
|
6600
|
+
lines.push(`Entry ${entry.entry}`);
|
|
6601
|
+
for (const field of entry.fields) lines.push(` ${field.pointer}: ${JSON.stringify(field.value)}`);
|
|
6602
|
+
if (entry.withheld > 0) lines.push(` ${notShown(entry.withheld)}`);
|
|
6603
|
+
}
|
|
6604
|
+
}
|
|
6605
|
+
return `${lines.join("\n")}
|
|
6606
|
+
`;
|
|
6607
|
+
}
|
|
6608
|
+
function renderLinkHtml(input) {
|
|
6609
|
+
const { report } = input;
|
|
6610
|
+
const body = [
|
|
6611
|
+
`<h1>${escapeHtml(SHARED_RECORD_WORDS.title)}</h1>`,
|
|
6612
|
+
"<table>",
|
|
6613
|
+
...factsOf(report).map(([label, value]) => `<tr><th>${escapeHtml(label)}</th><td>${escapeHtml(value)}</td></tr>`),
|
|
6614
|
+
"</table>",
|
|
6615
|
+
...report.sentences.map((sentence) => `<p>${escapeHtml(sentence)}</p>`)
|
|
6616
|
+
];
|
|
6617
|
+
const committed = committedLines(report.check);
|
|
6618
|
+
if (committed.length > 0) {
|
|
6619
|
+
body.push(`<h2>${escapeHtml(committed[0])}</h2>`, "<ul>", ...committed.slice(1).map((line) => `<li>${escapeHtml(line)}</li>`), "</ul>");
|
|
6620
|
+
}
|
|
6621
|
+
for (const record of revealedOf(report.check)) {
|
|
6622
|
+
body.push(`<h2>${escapeHtml(SHARED_RECORD_WORDS.revealedHeading(record.number))}</h2>`);
|
|
6623
|
+
for (const entry of record.entries) {
|
|
6624
|
+
body.push(`<h3>Entry ${entry.entry}</h3>`, "<table>");
|
|
6625
|
+
for (const field of entry.fields) body.push(`<tr><th>${escapeHtml(field.pointer)}</th><td>${escapeHtml(JSON.stringify(field.value))}</td></tr>`);
|
|
6626
|
+
body.push("</table>");
|
|
6627
|
+
if (entry.withheld > 0) body.push(`<p>${escapeHtml(notShown(entry.withheld))}</p>`);
|
|
6628
|
+
}
|
|
6629
|
+
}
|
|
6630
|
+
body.push(`<footer>Made by ${CHECKER_NAME} ${escapeHtml(input.version)} on ${dayOfUtc(input.now.toISOString())} (UTC).</footer>`);
|
|
6631
|
+
return [
|
|
6632
|
+
"<!DOCTYPE html>",
|
|
6633
|
+
'<html lang="en">',
|
|
6634
|
+
"<head>",
|
|
6635
|
+
'<meta charset="utf-8">',
|
|
6636
|
+
`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">`,
|
|
6637
|
+
'<meta name="referrer" content="no-referrer">',
|
|
6638
|
+
`<title>${escapeHtml(SHARED_RECORD_WORDS.title)}</title>`,
|
|
6639
|
+
"<style>body{font-family:system-ui,sans-serif;max-width:52rem;margin:2rem auto;padding:0 1rem;line-height:1.5}th{text-align:left;padding-right:1rem;vertical-align:top;font-weight:600}td{word-break:break-all}footer{margin-top:2rem;color:#555}</style>",
|
|
6640
|
+
"</head>",
|
|
6641
|
+
"<body>",
|
|
6642
|
+
...body,
|
|
6643
|
+
"</body>",
|
|
6644
|
+
"</html>",
|
|
6645
|
+
""
|
|
6646
|
+
].join("\n");
|
|
6647
|
+
}
|
|
6648
|
+
async function finish(io, args, report, copy) {
|
|
6649
|
+
io.stdout(args.json ? `${JSON.stringify(report, null, 2)}
|
|
6650
|
+
` : renderLinkReport(report));
|
|
6651
|
+
if (args.copy) {
|
|
6652
|
+
if (copy) {
|
|
6653
|
+
await writeNew(io, args.copy, copy.bytes);
|
|
6654
|
+
io.stderr(`${copy.fields === "opened" ? SHARED_RECORD_WORDS.savedCopy(args.copy) : SHARED_RECORD_WORDS.savedCopyNoFields(args.copy)}
|
|
6655
|
+
`);
|
|
6656
|
+
} else {
|
|
6657
|
+
io.stderr(`${SHARED_RECORD_WORDS.copyNotSaved}
|
|
6658
|
+
`);
|
|
6659
|
+
}
|
|
6660
|
+
}
|
|
6661
|
+
if (args.html) {
|
|
6662
|
+
const page = renderLinkHtml({ report, version: CHECKER_VERSION, now: io.now ? io.now() : /* @__PURE__ */ new Date() });
|
|
6663
|
+
await writeNew(io, args.html, new TextEncoder().encode(page));
|
|
6664
|
+
io.stderr(`${savedReportSentence(args.html)}
|
|
6665
|
+
`);
|
|
6666
|
+
}
|
|
6667
|
+
return report.exitCode;
|
|
6668
|
+
}
|
|
6669
|
+
function progressOf(io) {
|
|
6670
|
+
return (done, of) => {
|
|
6671
|
+
if (of > RECORDS_LISTED_MAX && done < of && done % RECORDS_LISTED_MAX === 0) io.stderr(`${SHARED_RECORD_WORDS.progress(done, of)}
|
|
6672
|
+
`);
|
|
6673
|
+
};
|
|
6674
|
+
}
|
|
6675
|
+
async function runSharedRecordLink(input) {
|
|
6676
|
+
const { address, origin, args, io } = input;
|
|
6677
|
+
if (args.full && typeof args.source === "object") throw new OpenStop(SHARED_RECORD_WORDS.fullNeedsMirror, 2);
|
|
6678
|
+
const host = linkHostOf(`${origin.origin}/api/v1/s/${encodeURIComponent(address.handle)}`, io, args.timeoutMs ?? LINK_TIMEOUT_MS);
|
|
6679
|
+
const ask = async (path, init) => {
|
|
6680
|
+
try {
|
|
6681
|
+
return await host.ask(path, init);
|
|
6682
|
+
} catch {
|
|
6683
|
+
throw new OpenStop(hostUnreachableSentence(origin.host), 3);
|
|
6684
|
+
}
|
|
6685
|
+
};
|
|
6686
|
+
const state = await ask("");
|
|
6687
|
+
if (state.status !== 200) stopOn(state, origin.host);
|
|
6688
|
+
const serving = state.json?.state;
|
|
6689
|
+
if (serving === "off" || serving === "ended") {
|
|
6690
|
+
const refused = await ask("/record.json?v=2");
|
|
6691
|
+
if (refused.status !== 200) stopOn(refused, origin.host);
|
|
6692
|
+
}
|
|
6693
|
+
if (serving !== "open") throw new OpenStop(LINK_CODE_WORDS.MANIFEST_INVALID, 1);
|
|
6694
|
+
const code = await input.askCode(SHARED_RECORD_WORDS.codeOnce(origin.host));
|
|
6695
|
+
if (!code || !code.trim()) throw new OpenStop(SHARED_RECORD_WORDS.noCode, 2);
|
|
6696
|
+
const opened = await ask("/open", { method: "POST", body: { code: code.trim() } });
|
|
6697
|
+
if (opened.status !== 200) stopOn(opened, origin.host);
|
|
6698
|
+
const token = opened.json?.token;
|
|
6699
|
+
if (typeof token !== "string" || !TOKEN.test(token)) throw new OpenStop(hostUnreachableSentence(origin.host), 3);
|
|
6700
|
+
const linkKey = readDisclosureFragmentV1(`#${address.fragment}`);
|
|
6701
|
+
try {
|
|
6702
|
+
const progress = progressOf(io);
|
|
6703
|
+
const check2 = await checkSharedRecordV1({
|
|
6704
|
+
handle: address.handle,
|
|
6705
|
+
source: linkSourceOf(host, token),
|
|
6706
|
+
linkKey,
|
|
6707
|
+
layouts: getPublishedLayoutRegistry(),
|
|
6708
|
+
proofLayer: proofLayerFor({ source: args.source, full: args.full, timeoutMs: args.timeoutMs, fetchImpl: io.fetchImpl, pace: paceOf(io) }),
|
|
6709
|
+
full: args.full,
|
|
6710
|
+
inFlight: 4,
|
|
6711
|
+
keep: !!args.copy,
|
|
6712
|
+
onRecord: (_record, at) => progress(at.done, at.of),
|
|
6713
|
+
...io.sleep ? { sleep: io.sleep } : {},
|
|
6714
|
+
...io.now ? { now: () => io.now().getTime() } : {}
|
|
6715
|
+
});
|
|
6716
|
+
const report = buildLinkReport(check2, { host: origin.addressHost, readFrom: origin.origin, pacspace: origin.pacspace }, false);
|
|
6717
|
+
let copy = null;
|
|
6718
|
+
if (args.copy && check2.kept) {
|
|
6719
|
+
try {
|
|
6720
|
+
const built = buildSharedRecordCopyV1({ kept: check2.kept, handle: address.handle });
|
|
6721
|
+
copy = { bytes: built.bytes, fields: built.copy.fields };
|
|
6722
|
+
} catch {
|
|
6723
|
+
copy = null;
|
|
6724
|
+
}
|
|
6725
|
+
}
|
|
6726
|
+
return await finish(io, args, report, copy);
|
|
6727
|
+
} finally {
|
|
6728
|
+
linkKey?.fill(0);
|
|
6729
|
+
await host.ask("/sign-out", { method: "POST", bearer: token }).catch(() => void 0);
|
|
6730
|
+
}
|
|
6731
|
+
}
|
|
6732
|
+
async function runSharedRecordCopy(input) {
|
|
6733
|
+
const { args, io } = input;
|
|
6734
|
+
if (args.source === "offline") throw new OpenStop(SHARED_RECORD_WORDS.copyOffline, 2);
|
|
6735
|
+
if (args.full && typeof args.source === "object") throw new OpenStop(SHARED_RECORD_WORDS.fullNeedsMirror, 2);
|
|
6736
|
+
let read;
|
|
6737
|
+
try {
|
|
6738
|
+
read = sharedRecordCopySourceV1(input.copy, input.address ? input.address.handle : null);
|
|
6739
|
+
} catch {
|
|
6740
|
+
throw new OpenStop(SHARED_RECORD_WORDS.copyAddress, 2);
|
|
6741
|
+
}
|
|
6742
|
+
const progress = progressOf(io);
|
|
6743
|
+
const check2 = await checkSharedRecordV1({
|
|
6744
|
+
handle: read.handle,
|
|
6745
|
+
source: read.source,
|
|
6746
|
+
layouts: getPublishedLayoutRegistry(),
|
|
6747
|
+
proofLayer: proofLayerFor({ source: args.source, full: args.full, timeoutMs: args.timeoutMs, fetchImpl: io.fetchImpl, pace: paceOf(io) }),
|
|
6748
|
+
full: args.full,
|
|
6749
|
+
inFlight: 4,
|
|
6750
|
+
onRecord: (_record, at) => progress(at.done, at.of),
|
|
6751
|
+
...io.sleep ? { sleep: io.sleep } : {},
|
|
6752
|
+
...io.now ? { now: () => io.now().getTime() } : {}
|
|
6753
|
+
});
|
|
6754
|
+
return finish(io, { copy: null, html: null, json: args.json }, buildLinkReport(check2, null, true), null);
|
|
6755
|
+
}
|
|
6756
|
+
|
|
6757
|
+
// src/open.ts
|
|
6758
|
+
var LINK_PROMPT = "Paste the link, then press Enter:";
|
|
6759
|
+
var LINK_IN_ARGV_SENTENCE = "The link was given on the command line, where your shell history and other programs on this machine can see it. Next time, run open and paste the link when it asks.";
|
|
6760
|
+
var NOT_A_LINK_SENTENCE = "This is not a PacSpace record link. A record link looks like https://<host>/c/<handle>/.";
|
|
6761
|
+
var ACCESS_CODE_PROMPT = "This link asks for an access code. Type it, then press Enter:";
|
|
6762
|
+
var KEY_DOES_NOT_OPEN_SENTENCE = "The revealed fields didn't open with this link's key. Ask the sender for the whole link.";
|
|
6763
|
+
var REVEALED_HEADER = "Revealed fields";
|
|
6764
|
+
var savedCopySentence = (path) => `Saved a kept copy to ${path}. Check it again at any time with: npx @pacspace-io/check ${path}`;
|
|
6765
|
+
var notShown2 = (k) => `${k} ${k === 1 ? "field" : "fields"} not shown.`;
|
|
6766
|
+
var STEP_UP_REQUIRED = "CUSTOMER_LINK_STEP_UP_REQUIRED";
|
|
6767
|
+
var LINK_NOT_FOUND = "CUSTOMER_LINK_NOT_FOUND";
|
|
6768
|
+
var OpenUsageError = class extends Error {
|
|
6769
|
+
};
|
|
4959
6770
|
function parseOpenArgs(argv) {
|
|
4960
|
-
const args = { link: null, linkFile: null, accessCodeFile: null, copy: null, html: null, source: "mirror", timeoutMs: void 0, json: false };
|
|
6771
|
+
const args = { link: null, linkFile: null, accessCodeFile: null, copy: null, html: null, source: "mirror", full: false, timeoutMs: void 0, json: false };
|
|
4961
6772
|
const takeValue = (flag, index) => {
|
|
4962
6773
|
const value = argv[index + 1];
|
|
4963
6774
|
if (value === void 0 || value.startsWith("--")) throw new OpenUsageError(`${flag} needs a value.`);
|
|
@@ -4990,6 +6801,9 @@ function parseOpenArgs(argv) {
|
|
|
4990
6801
|
args.source = { rpc: takeValue(arg, index) };
|
|
4991
6802
|
index += 1;
|
|
4992
6803
|
break;
|
|
6804
|
+
case "--full":
|
|
6805
|
+
args.full = true;
|
|
6806
|
+
break;
|
|
4993
6807
|
case "--timeout": {
|
|
4994
6808
|
const parsed = Number(takeValue(arg, index));
|
|
4995
6809
|
if (!Number.isFinite(parsed) || parsed <= 0) throw new OpenUsageError("--timeout needs a number of milliseconds.");
|
|
@@ -5008,62 +6822,16 @@ function parseOpenArgs(argv) {
|
|
|
5008
6822
|
}
|
|
5009
6823
|
return args;
|
|
5010
6824
|
}
|
|
5011
|
-
async function firstLineOf(io, path) {
|
|
5012
|
-
let bytes2;
|
|
5013
|
-
try {
|
|
5014
|
-
bytes2 = await io.readBytes((0, import_node_path.resolve)(path), LINE_MAX_BYTES);
|
|
5015
|
-
} catch (error) {
|
|
5016
|
-
throw new OpenStop(`The file could not be read: ${error.message}`, 2);
|
|
5017
|
-
}
|
|
5018
|
-
return new TextDecoder().decode(bytes2).split(/\r?\n/)[0] ?? "";
|
|
5019
|
-
}
|
|
5020
|
-
function readLink(text) {
|
|
5021
|
-
let url;
|
|
5022
|
-
try {
|
|
5023
|
-
url = new URL((text ?? "").trim());
|
|
5024
|
-
} catch {
|
|
5025
|
-
throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
|
|
5026
|
-
}
|
|
5027
|
-
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
5028
|
-
if (!(url.protocol === "https:" || url.protocol === "http:" && local) || url.username || url.password) {
|
|
5029
|
-
throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
|
|
5030
|
-
}
|
|
5031
|
-
const match = /^\/c\/([^/]+)(?:\/.*)?$/.exec(url.pathname);
|
|
5032
|
-
if (!match) throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
|
|
5033
|
-
let handle = match[1];
|
|
5034
|
-
try {
|
|
5035
|
-
handle = decodeURIComponent(handle);
|
|
5036
|
-
} catch {
|
|
5037
|
-
}
|
|
5038
|
-
handle = handle.trim().toLowerCase();
|
|
5039
|
-
if (!handle) throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
|
|
5040
|
-
return { origin: url.origin, host: url.host, handle, key: readDisclosureFragmentV1(url.hash) };
|
|
5041
|
-
}
|
|
5042
|
-
var withoutControls = (text) => Array.from(text).filter((ch) => ch.charCodeAt(0) >= 32 && ch.charCodeAt(0) !== 127).join("");
|
|
5043
|
-
async function refusalOf(response) {
|
|
5044
|
-
try {
|
|
5045
|
-
const body = await response.json();
|
|
5046
|
-
const code = body?.error?.code ?? body?.code;
|
|
5047
|
-
const message = body?.error?.message ?? body?.message;
|
|
5048
|
-
return {
|
|
5049
|
-
code: typeof code === "string" ? code : null,
|
|
5050
|
-
message: typeof message === "string" ? withoutControls(message).trim() || null : null
|
|
5051
|
-
};
|
|
5052
|
-
} catch {
|
|
5053
|
-
return { code: null, message: null };
|
|
5054
|
-
}
|
|
5055
|
-
}
|
|
5056
6825
|
function renderRevealed(entries) {
|
|
5057
6826
|
const lines = [REVEALED_HEADER];
|
|
5058
6827
|
for (const entry of entries) {
|
|
5059
6828
|
lines.push(`Entry ${entry.entry}`);
|
|
5060
6829
|
for (const field of entry.fields) lines.push(` ${field.pointer}: ${JSON.stringify(field.value)}`);
|
|
5061
|
-
if (entry.withheld > 0) lines.push(` ${
|
|
6830
|
+
if (entry.withheld > 0) lines.push(` ${notShown2(entry.withheld)}`);
|
|
5062
6831
|
}
|
|
5063
6832
|
return `${lines.join("\n")}
|
|
5064
6833
|
`;
|
|
5065
6834
|
}
|
|
5066
|
-
var escapeHtml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
5067
6835
|
function renderOpenHtml(input) {
|
|
5068
6836
|
const { report, revealed } = input;
|
|
5069
6837
|
const facts = [
|
|
@@ -5076,7 +6844,8 @@ function renderOpenHtml(input) {
|
|
|
5076
6844
|
"<table>",
|
|
5077
6845
|
...facts.map(([label, value]) => `<tr><th>${escapeHtml(label)}</th><td>${escapeHtml(value)}</td></tr>`),
|
|
5078
6846
|
"</table>",
|
|
5079
|
-
...report.sentences.map((sentence) => `<p>${escapeHtml(sentence)}</p>`)
|
|
6847
|
+
...report.sentences.map((sentence) => `<p>${escapeHtml(sentence)}</p>`),
|
|
6848
|
+
...input.notice ? [`<p>${escapeHtml(input.notice)}</p>`] : []
|
|
5080
6849
|
];
|
|
5081
6850
|
if (revealed.length > 0) {
|
|
5082
6851
|
body.push(`<h2>${REVEALED_HEADER}</h2>`);
|
|
@@ -5086,7 +6855,7 @@ function renderOpenHtml(input) {
|
|
|
5086
6855
|
body.push(`<tr><th>${escapeHtml(field.pointer)}</th><td>${escapeHtml(JSON.stringify(field.value))}</td></tr>`);
|
|
5087
6856
|
}
|
|
5088
6857
|
body.push("</table>");
|
|
5089
|
-
if (entry.withheld > 0) body.push(`<p>${escapeHtml(
|
|
6858
|
+
if (entry.withheld > 0) body.push(`<p>${escapeHtml(notShown2(entry.withheld))}</p>`);
|
|
5090
6859
|
}
|
|
5091
6860
|
}
|
|
5092
6861
|
body.push(`<footer>Made by ${CHECKER_NAME} ${escapeHtml(input.version)} on ${dayOfUtc(input.now.toISOString())} (UTC).</footer>`);
|
|
@@ -5107,15 +6876,14 @@ function renderOpenHtml(input) {
|
|
|
5107
6876
|
""
|
|
5108
6877
|
].join("\n");
|
|
5109
6878
|
}
|
|
5110
|
-
|
|
5111
|
-
if (
|
|
5112
|
-
|
|
5113
|
-
|
|
5114
|
-
|
|
5115
|
-
|
|
5116
|
-
throw new OpenStop(`The file could not be written: ${error.message}`, 2);
|
|
5117
|
-
}
|
|
6879
|
+
function answersAsOf(status, body) {
|
|
6880
|
+
if (status !== 200 || !body || typeof body !== "object" || Array.isArray(body)) return null;
|
|
6881
|
+
const answer = body;
|
|
6882
|
+
if (answer.subjectKind === "TRAIL") return "trail";
|
|
6883
|
+
if (answer.state === "retired") return "balance";
|
|
6884
|
+
return "record";
|
|
5118
6885
|
}
|
|
6886
|
+
var FIRST_ANSWER_MAX_BYTES = 1024 * 1024;
|
|
5119
6887
|
async function runOpen(argv, io) {
|
|
5120
6888
|
let args;
|
|
5121
6889
|
try {
|
|
@@ -5137,30 +6905,69 @@ async function runOpen(argv, io) {
|
|
|
5137
6905
|
} else {
|
|
5138
6906
|
linkText = io.readLine ? await io.readLine({ prompt: LINK_PROMPT }) : null;
|
|
5139
6907
|
}
|
|
5140
|
-
const
|
|
6908
|
+
const address = readSharedRecordAddressV1(linkText);
|
|
6909
|
+
if (!address) throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
|
|
6910
|
+
const origin = linkOriginOf(address);
|
|
6911
|
+
io.stderr(`${SHARED_RECORD_WORDS.readingFrom(origin.origin)}
|
|
6912
|
+
`);
|
|
6913
|
+
const notice = origin.pacspace ? null : SHARED_RECORD_WORDS.notPacSpace(origin.origin);
|
|
6914
|
+
if (notice) io.stderr(`${notice}
|
|
6915
|
+
`);
|
|
5141
6916
|
const fetchImpl = io.fetchImpl ?? fetch;
|
|
5142
6917
|
const timeoutMs = args.timeoutMs ?? 1e4;
|
|
5143
|
-
const base = `${
|
|
6918
|
+
const base = `${origin.origin}/api/v1/c/${encodeURIComponent(address.handle)}`;
|
|
5144
6919
|
const request = async (tail, init = {}) => {
|
|
5145
6920
|
const headers = { Accept: "application/json", ...init.headers ?? {} };
|
|
5146
6921
|
if (cookie) headers.Cookie = cookie;
|
|
5147
6922
|
try {
|
|
5148
6923
|
return await fetchImpl(`${base}${tail}`, { method: init.method ?? "GET", headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
|
|
5149
6924
|
} catch {
|
|
5150
|
-
throw new OpenStop(hostUnreachableSentence(
|
|
6925
|
+
throw new OpenStop(hostUnreachableSentence(origin.host), 3);
|
|
5151
6926
|
}
|
|
5152
6927
|
};
|
|
5153
6928
|
const stopWith = async (response) => {
|
|
5154
6929
|
const refusal = await refusalOf(response);
|
|
5155
6930
|
if (refusal.message) throw new OpenStop(refusal.message, 2);
|
|
5156
|
-
throw new OpenStop(hostUnreachableSentence(
|
|
6931
|
+
throw new OpenStop(hostUnreachableSentence(origin.host), 3);
|
|
5157
6932
|
};
|
|
6933
|
+
const codeOf = async () => args.accessCodeFile ? firstLineOf(io, args.accessCodeFile) : io.readLine ? io.readLine({ prompt: ACCESS_CODE_PROMPT, hidden: true }) : null;
|
|
6934
|
+
const first = await request("");
|
|
6935
|
+
let firstBody = null;
|
|
6936
|
+
try {
|
|
6937
|
+
const bytes2 = await bodyWithin(first, FIRST_ANSWER_MAX_BYTES);
|
|
6938
|
+
firstBody = bytes2 === null ? null : JSON.parse(new TextDecoder().decode(bytes2));
|
|
6939
|
+
} catch {
|
|
6940
|
+
firstBody = null;
|
|
6941
|
+
}
|
|
6942
|
+
const answersAs = answersAsOf(first.status, firstBody);
|
|
6943
|
+
const listAddress = sharedRecordAddressOpensV1(address.handle, "trail") === "list";
|
|
6944
|
+
if (listAddress) {
|
|
6945
|
+
if (!first.ok) {
|
|
6946
|
+
const refusal = refusalOfBody(firstBody);
|
|
6947
|
+
throw refusal.message && first.status < 500 ? new OpenStop(refusal.message, 2) : new OpenStop(hostUnreachableSentence(origin.host), 3);
|
|
6948
|
+
}
|
|
6949
|
+
if (answersAs === null || sharedRecordAddressOpensV1(address.handle, answersAs) !== "list") throw new OpenStop(SHARED_RECORD_WORDS.notAListLink, 1);
|
|
6950
|
+
return await runSharedRecordLink({
|
|
6951
|
+
address,
|
|
6952
|
+
origin,
|
|
6953
|
+
args,
|
|
6954
|
+
io,
|
|
6955
|
+
askCode: async (said) => {
|
|
6956
|
+
io.stderr(`${said}
|
|
6957
|
+
`);
|
|
6958
|
+
return codeOf();
|
|
6959
|
+
}
|
|
6960
|
+
});
|
|
6961
|
+
}
|
|
6962
|
+
if (answersAs === "trail") throw new OpenStop(SHARED_RECORD_WORDS.noList, 3);
|
|
6963
|
+
if (args.full) throw new OpenStop(SHARED_RECORD_WORDS.fullOnlyForList, 2);
|
|
6964
|
+
const key = readDisclosureFragmentV1(`#${address.fragment}`);
|
|
5158
6965
|
let history = await request("/history", { headers: { "X-Record-Entries": "all" } });
|
|
5159
6966
|
if (history.status === 401) {
|
|
5160
6967
|
const refusal = await refusalOf(history.clone());
|
|
5161
6968
|
if (refusal.code === STEP_UP_REQUIRED) {
|
|
5162
|
-
const code =
|
|
5163
|
-
if (!code || !code.trim()) throw new OpenStop(refusal.message ?? hostUnreachableSentence(
|
|
6969
|
+
const code = await codeOf();
|
|
6970
|
+
if (!code || !code.trim()) throw new OpenStop(refusal.message ?? hostUnreachableSentence(origin.host), 2);
|
|
5164
6971
|
const verified = await request("/access/verify", {
|
|
5165
6972
|
method: "POST",
|
|
5166
6973
|
headers: { "Content-Type": "application/json" },
|
|
@@ -5185,15 +6992,15 @@ async function runOpen(argv, io) {
|
|
|
5185
6992
|
if (answer.ok) {
|
|
5186
6993
|
const envelope = (await answer.json().catch(() => null))?.envelope;
|
|
5187
6994
|
if (typeof envelope === "string") {
|
|
5188
|
-
if (!
|
|
5189
|
-
const opened = await decryptDisclosureV1({ envelope, key
|
|
6995
|
+
if (!key) throw new OpenStop(NO_KEY_SENTENCE, 2);
|
|
6996
|
+
const opened = await decryptDisclosureV1({ envelope, key, handle: address.handle });
|
|
5190
6997
|
if (!opened.ok) throw new OpenStop(KEY_DOES_NOT_OPEN_SENTENCE, 2);
|
|
5191
6998
|
disclosure = opened.disclosure;
|
|
5192
6999
|
}
|
|
5193
7000
|
} else if (answer.status !== 404 || (await refusalOf(answer.clone())).code !== LINK_NOT_FOUND) {
|
|
5194
7001
|
await stopWith(answer);
|
|
5195
7002
|
}
|
|
5196
|
-
|
|
7003
|
+
key?.fill(0);
|
|
5197
7004
|
let copy;
|
|
5198
7005
|
try {
|
|
5199
7006
|
copy = await buildRecordLinkCopyV1({ sealHistory, disclosure });
|
|
@@ -5210,10 +7017,13 @@ async function runOpen(argv, io) {
|
|
|
5210
7017
|
}
|
|
5211
7018
|
});
|
|
5212
7019
|
if (args.json) {
|
|
5213
|
-
|
|
7020
|
+
const link = { host: origin.addressHost, readFrom: origin.origin, pacspace: origin.pacspace };
|
|
7021
|
+
io.stdout(`${JSON.stringify({ ...report, revealedFields: revealed, link }, null, 2)}
|
|
5214
7022
|
`);
|
|
5215
7023
|
} else {
|
|
5216
7024
|
io.stdout(renderReport(report));
|
|
7025
|
+
if (notice) io.stdout(`${notice}
|
|
7026
|
+
`);
|
|
5217
7027
|
if (revealed.length > 0) io.stdout(`
|
|
5218
7028
|
${renderRevealed(revealed)}`);
|
|
5219
7029
|
}
|
|
@@ -5223,7 +7033,7 @@ ${renderRevealed(revealed)}`);
|
|
|
5223
7033
|
`);
|
|
5224
7034
|
}
|
|
5225
7035
|
if (args.html) {
|
|
5226
|
-
const page = renderOpenHtml({ report, revealed, version: CHECKER_VERSION, now: io.now ? io.now() : /* @__PURE__ */ new Date() });
|
|
7036
|
+
const page = renderOpenHtml({ report, revealed, version: CHECKER_VERSION, now: io.now ? io.now() : /* @__PURE__ */ new Date(), notice });
|
|
5227
7037
|
await writeNew(io, args.html, new TextEncoder().encode(page));
|
|
5228
7038
|
io.stderr(`${savedReportSentence(args.html)}
|
|
5229
7039
|
`);
|
|
@@ -5561,7 +7371,8 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
|
|
|
5561
7371
|
// src/cli.ts
|
|
5562
7372
|
var USAGE = `Usage: pacspace-check <history.json> [options]
|
|
5563
7373
|
pacspace-check <history.json> --key <path>
|
|
5564
|
-
pacspace-check
|
|
7374
|
+
pacspace-check <link-copy.json> [--link-file <path>] [--full] [--source <url> | --rpc <url>] [--timeout <ms>] [--json]
|
|
7375
|
+
pacspace-check open [--link-file <path>] [--access-code-file <path>] [--copy <path>] [--html <path>] [--full] [--source <url> | --rpc <url>] [--timeout <ms>] [--json]
|
|
5565
7376
|
pacspace-check release [--origin <url>] [--source <url> | --rpc <url>] [--timeout <ms>] [--json]
|
|
5566
7377
|
pacspace-check release --origin <url> --release-record <record key>,<network id>,<contract>
|
|
5567
7378
|
|
|
@@ -5569,6 +7380,10 @@ Checks a PacSpace record history file: every entry against what was
|
|
|
5569
7380
|
committed, the file against its own fingerprint, and the record against
|
|
5570
7381
|
the proof layer. open reads the record from the link's host, and release reads the key pages from the host it checks. Checking a file sends nothing to PacSpace.
|
|
5571
7382
|
|
|
7383
|
+
A link may show one record or a list of records. open checks every record
|
|
7384
|
+
of a list against the proof layer, and --copy keeps a copy of the list that
|
|
7385
|
+
can be checked again as a file.
|
|
7386
|
+
|
|
5572
7387
|
Options:
|
|
5573
7388
|
--fingerprint <0x...> the fingerprint printed on a statement; the checker
|
|
5574
7389
|
says whether it names this file
|
|
@@ -5577,6 +7392,7 @@ Options:
|
|
|
5577
7392
|
--history <path> the seal history or kept copy a disclosure is checked against
|
|
5578
7393
|
--key <path> the record key for an encrypted history, read from this file (- for stdin)
|
|
5579
7394
|
--link-file <path> open: read the link from this file instead of asking
|
|
7395
|
+
copy of a link: compare its list with the address of the link in this file
|
|
5580
7396
|
--access-code-file <path> open: read the access code from this file instead of asking
|
|
5581
7397
|
--copy <path> open: save a kept copy of what the link shows to a new file
|
|
5582
7398
|
--html <path> open: save the report as a page that opens without a network connection
|
|
@@ -5585,13 +7401,16 @@ Options:
|
|
|
5585
7401
|
the one known for the record's network
|
|
5586
7402
|
--rpc <url> read the proof layer over JSON-RPC at this URL
|
|
5587
7403
|
--full also read every daily statement
|
|
7404
|
+
list of records, or a copy of one: read each contract's whole log
|
|
5588
7405
|
--no-lookup do not look up where each entry was committed
|
|
5589
7406
|
--timeout <ms> network timeout per read (default 10000)
|
|
7407
|
+
list of records: a read of the link's host (default 30000)
|
|
5590
7408
|
--json print the report as JSON
|
|
5591
7409
|
--version print the checker's version
|
|
5592
7410
|
--help print this text
|
|
5593
7411
|
|
|
5594
7412
|
Exit codes: 0 the check passed as asked; 1 it did not, or the file you hold is not in it; 2 the history file, the link, a key, the file you hold, its blinding file or the arguments could not be used; 3 the proof layer or the link's host could not be reached. When more than one applies, 2 comes before 3, and 3 before 1.
|
|
7413
|
+
For a list of records, or a copy of one: 3 also when a record was not checked, and 1 comes before 3, so a record that does not match is reported even when another was not checked.
|
|
5595
7414
|
`;
|
|
5596
7415
|
var BLINDING_FILE_INVALID_SENTENCE = "This is not a valid blinding file.";
|
|
5597
7416
|
var BLINDING_NEEDS_HELD_FILE_SENTENCE = "--blinding needs --held-file.";
|
|
@@ -5610,7 +7429,8 @@ function parseArgs(argv) {
|
|
|
5610
7429
|
blinding: null,
|
|
5611
7430
|
history: null,
|
|
5612
7431
|
key: null,
|
|
5613
|
-
noLookup: false
|
|
7432
|
+
noLookup: false,
|
|
7433
|
+
linkFile: null
|
|
5614
7434
|
};
|
|
5615
7435
|
const takeValue = (flag, index) => {
|
|
5616
7436
|
const value = argv[index + 1];
|
|
@@ -5620,6 +7440,10 @@ function parseArgs(argv) {
|
|
|
5620
7440
|
for (let index = 0; index < argv.length; index += 1) {
|
|
5621
7441
|
const arg = argv[index];
|
|
5622
7442
|
switch (arg) {
|
|
7443
|
+
case "--link-file":
|
|
7444
|
+
args.linkFile = takeValue(arg, index);
|
|
7445
|
+
index += 1;
|
|
7446
|
+
break;
|
|
5623
7447
|
case "--help":
|
|
5624
7448
|
case "-h":
|
|
5625
7449
|
args.help = true;
|
|
@@ -5749,13 +7573,14 @@ async function readRecordKey(io, from) {
|
|
|
5749
7573
|
if (bytes2.length !== 32 || Buffer.from(bytes2).toString("base64url") !== trimmed) throw new ExitTwo(NOT_A_RECORD_KEY_SENTENCE);
|
|
5750
7574
|
return bytes2;
|
|
5751
7575
|
}
|
|
5752
|
-
async function
|
|
5753
|
-
let bytes2;
|
|
7576
|
+
async function readFileWithin(io, path, max) {
|
|
5754
7577
|
try {
|
|
5755
|
-
|
|
7578
|
+
return await io.readBytes((0, import_node_path2.resolve)(path), max + 1);
|
|
5756
7579
|
} catch (error) {
|
|
5757
7580
|
throw new ExitTwo(`The file could not be read: ${error.message}`);
|
|
5758
7581
|
}
|
|
7582
|
+
}
|
|
7583
|
+
function historyOfBytes(bytes2) {
|
|
5759
7584
|
if (bytes2.length > RECORD_LINK_COPY_MAX_BYTES_V1) throw new ExitTwo(TOO_LARGE_SENTENCE);
|
|
5760
7585
|
const file = parseHistoryFile(new TextDecoder().decode(bytes2));
|
|
5761
7586
|
if ((file.schema === RECORD_DISCLOSURE_SCHEMA_V1 || file.schema === RECORD_DISCLOSURE_SCHEMA_V2) && bytes2.length > RECORD_DISCLOSURE_MAX_BYTES_V1) {
|
|
@@ -5763,6 +7588,45 @@ async function readHistoryFile(io, path) {
|
|
|
5763
7588
|
}
|
|
5764
7589
|
return { file, byteLength: bytes2.length };
|
|
5765
7590
|
}
|
|
7591
|
+
async function readHistoryFile(io, path) {
|
|
7592
|
+
return historyOfBytes(await readFileWithin(io, path, RECORD_LINK_COPY_MAX_BYTES_V1));
|
|
7593
|
+
}
|
|
7594
|
+
var LINK_COPY_MARK = Buffer.from(`"${SHARED_RECORD_COPY_SCHEMA_V1}"`, "utf8");
|
|
7595
|
+
async function readFileToCheck(io, path) {
|
|
7596
|
+
let bytes2 = await readFileWithin(io, path, RECORD_LINK_COPY_MAX_BYTES_V1);
|
|
7597
|
+
if (bytes2.length > RECORD_LINK_COPY_MAX_BYTES_V1) {
|
|
7598
|
+
bytes2 = await readFileWithin(io, path, SHARED_RECORD_COPY_MAX_BYTES_V1);
|
|
7599
|
+
if (bytes2.length > SHARED_RECORD_COPY_MAX_BYTES_V1) throw new ExitTwo(TOO_LARGE_SENTENCE);
|
|
7600
|
+
}
|
|
7601
|
+
if (!Buffer.from(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength).includes(LINK_COPY_MARK)) return { bytes: bytes2 };
|
|
7602
|
+
let json;
|
|
7603
|
+
try {
|
|
7604
|
+
json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes2));
|
|
7605
|
+
} catch {
|
|
7606
|
+
return { bytes: bytes2 };
|
|
7607
|
+
}
|
|
7608
|
+
if (!json || typeof json !== "object" || json.schema !== SHARED_RECORD_COPY_SCHEMA_V1) return { bytes: bytes2 };
|
|
7609
|
+
const read = readSharedRecordCopyV1(json);
|
|
7610
|
+
if (!read.ok) throw new ExitTwo(SHARED_RECORD_WORDS.copyNotRead);
|
|
7611
|
+
return { linkCopy: read.copy };
|
|
7612
|
+
}
|
|
7613
|
+
async function runLinkCopy(copy, args, io) {
|
|
7614
|
+
const unused = [
|
|
7615
|
+
["--fingerprint", args.statementFingerprint !== null],
|
|
7616
|
+
["--held-file", args.heldFile !== null],
|
|
7617
|
+
["--history", args.history !== null],
|
|
7618
|
+
["--key", args.key !== null],
|
|
7619
|
+
["--no-lookup", args.noLookup]
|
|
7620
|
+
];
|
|
7621
|
+
const given = unused.find(([, set]) => set);
|
|
7622
|
+
if (given) throw new ExitTwo(SHARED_RECORD_WORDS.copyOption(given[0]));
|
|
7623
|
+
let address = null;
|
|
7624
|
+
if (args.linkFile) {
|
|
7625
|
+
address = readSharedRecordAddressV1(await firstLineOf(io, args.linkFile));
|
|
7626
|
+
if (!address) throw new ExitTwo(NOT_A_LINK_SENTENCE);
|
|
7627
|
+
}
|
|
7628
|
+
return runSharedRecordCopy({ copy, address, args: { source: args.source, full: args.full, timeoutMs: args.timeoutMs, json: args.json }, io });
|
|
7629
|
+
}
|
|
5766
7630
|
async function heldFileDigests(io, heldPath, blindingPath) {
|
|
5767
7631
|
let blinding = null;
|
|
5768
7632
|
if (blindingPath) {
|
|
@@ -5912,7 +7776,10 @@ ${USAGE}`);
|
|
|
5912
7776
|
return 2;
|
|
5913
7777
|
}
|
|
5914
7778
|
try {
|
|
5915
|
-
const
|
|
7779
|
+
const read = await readFileToCheck(io, args.file);
|
|
7780
|
+
if ("linkCopy" in read) return await runLinkCopy(read.linkCopy, args, io);
|
|
7781
|
+
if (args.linkFile) throw new ExitTwo(SHARED_RECORD_WORDS.linkFileOnlyForCopy);
|
|
7782
|
+
const { file } = historyOfBytes(read.bytes);
|
|
5916
7783
|
let history;
|
|
5917
7784
|
if (args.history) {
|
|
5918
7785
|
if (file.schema !== RECORD_DISCLOSURE_SCHEMA_V1 && file.schema !== RECORD_DISCLOSURE_SCHEMA_V2) throw new ExitTwo(`${HISTORY_ONLY_FOR_DISCLOSURE_SENTENCE}
|
|
@@ -5959,6 +7826,11 @@ ${USAGE}`.trimEnd());
|
|
|
5959
7826
|
`);
|
|
5960
7827
|
return 2;
|
|
5961
7828
|
}
|
|
7829
|
+
if (error instanceof OpenStop) {
|
|
7830
|
+
io.stderr(`${error.message}
|
|
7831
|
+
`);
|
|
7832
|
+
return error.exitCode;
|
|
7833
|
+
}
|
|
5962
7834
|
io.stderr(`The check could not run: ${error.message}
|
|
5963
7835
|
`);
|
|
5964
7836
|
return 2;
|
|
@@ -5983,7 +7855,7 @@ function readTerminalLine(hidden) {
|
|
|
5983
7855
|
const stdin = process.stdin;
|
|
5984
7856
|
return new Promise((resolveLine) => {
|
|
5985
7857
|
let line = "";
|
|
5986
|
-
const
|
|
7858
|
+
const finish2 = (value) => {
|
|
5987
7859
|
stdin.off("data", onData);
|
|
5988
7860
|
stdin.setRawMode(false);
|
|
5989
7861
|
stdin.pause();
|
|
@@ -5992,13 +7864,13 @@ function readTerminalLine(hidden) {
|
|
|
5992
7864
|
};
|
|
5993
7865
|
const onData = (chunk) => {
|
|
5994
7866
|
for (const ch of chunk) {
|
|
5995
|
-
if (ch === "\r" || ch === "\n") return
|
|
7867
|
+
if (ch === "\r" || ch === "\n") return finish2(line);
|
|
5996
7868
|
if (ch === "") {
|
|
5997
7869
|
stdin.setRawMode(false);
|
|
5998
7870
|
process.stderr.write("\n");
|
|
5999
7871
|
process.exit(130);
|
|
6000
7872
|
}
|
|
6001
|
-
if (ch === "") return
|
|
7873
|
+
if (ch === "") return finish2(line.length > 0 ? line : null);
|
|
6002
7874
|
if (ch === "\x7F" || ch === "\b") {
|
|
6003
7875
|
if (line.length > 0) {
|
|
6004
7876
|
line = line.slice(0, -1);
|