@pacspace-io/check 0.5.4 → 0.5.6

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/dist/cli.js CHANGED
@@ -2097,10 +2097,10 @@ async function readRecordCopyV1(file) {
2097
2097
  }
2098
2098
 
2099
2099
  // ../shared/src/records/record-seal-history-v1.ts
2100
- var import_ethers13 = require("ethers");
2100
+ var import_ethers14 = require("ethers");
2101
2101
 
2102
2102
  // ../shared/src/demo/mirror-node-record-chain-reader.ts
2103
- var import_ethers12 = require("ethers");
2103
+ var import_ethers13 = require("ethers");
2104
2104
 
2105
2105
  // ../shared/src/records/inspect-record-calldata-v1.ts
2106
2106
  var MIRROR_NODE_BY_CHAIN = Object.freeze({
@@ -2110,20 +2110,145 @@ var MIRROR_NODE_BY_CHAIN = Object.freeze({
2110
2110
 
2111
2111
  // ../shared/src/records/ledger-write-search-v1.ts
2112
2112
  var LEDGER_WRITE_SEARCH_WINDOW_LIMIT_SECONDS = 7 * 24 * 60 * 60;
2113
+ var LEDGER_WRITE_SEARCH_PAGE_LIMIT = 100;
2114
+ var MIRROR_ANSWER_MAX_BYTES = 1048576;
2115
+ var HEX40 = /^0x[0-9a-f]{40}$/;
2113
2116
  var HEX642 = /^0x[0-9a-f]{64}$/;
2114
2117
  var HEX_DATA = /^0x[0-9a-f]*$/;
2115
2118
  var TIMESTAMP = /^\d+(\.\d+)?$/;
2116
- var NEXT_PATH = /^\/api\/v1\/contracts\//;
2117
- function ledgerWriteSearchPath(input) {
2118
- const query = `topic0=${input.topic0}&topic1=${input.recordKey}&timestamp=gte:${input.lower}&timestamp=lt:${input.upper}&order=desc&limit=100`;
2119
- return `/api/v1/contracts/${input.contractAddress}/results/logs?${query}`;
2119
+ var REFUSAL_CODES = {
2120
+ redirect: true,
2121
+ "too-large": true,
2122
+ "too-many-logs": true,
2123
+ "next-page": true,
2124
+ "too-slow": true,
2125
+ "too-long": true
2126
+ };
2127
+ var MIRROR_REFUSAL_CODES = Object.keys(REFUSAL_CODES);
2128
+ var MirrorAnswerRefused = class extends Error {
2129
+ constructor(code, message) {
2130
+ super(message);
2131
+ this.name = "MirrorAnswerRefused";
2132
+ this.code = code;
2133
+ }
2134
+ };
2135
+ function mirrorRefusalOf(error) {
2136
+ if (!error || typeof error !== "object") return null;
2137
+ const { name, code } = error;
2138
+ return name === "MirrorAnswerRefused" && typeof code === "string" && Object.prototype.hasOwnProperty.call(REFUSAL_CODES, code) ? code : null;
2139
+ }
2140
+ function pathLabel(path) {
2141
+ return path ? ` (${path.split("?")[0]})` : "";
2142
+ }
2143
+ var mirrorRefusal = {
2144
+ redirect: (path) => new MirrorAnswerRefused("redirect", `mirror node answered with a redirect, which is not followed${pathLabel(path)}`),
2145
+ tooLarge: (maxBytes, path) => new MirrorAnswerRefused("too-large", `mirror node answer is larger than ${maxBytes} bytes${pathLabel(path)}`),
2146
+ tooManyLogs: (asked, path) => new MirrorAnswerRefused("too-many-logs", `mirror node returned more logs than the ${asked} asked for${pathLabel(path)}`),
2147
+ nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log"),
2148
+ /** A page whose logs do not come after the last log read. */
2149
+ notForward: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that does not follow the last"),
2150
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `mirror node log scan did not finish in ${budgetMs}ms`),
2151
+ scanTooManyRequests: (requests) => new MirrorAnswerRefused("too-long", `mirror node log scan passed ${requests} requests`),
2152
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `mirror node log scan kept more than ${logs} logs`)
2153
+ };
2154
+ var rpcRefusal = {
2155
+ redirect: () => new MirrorAnswerRefused("redirect", "RPC endpoint answered with a redirect, which is not followed"),
2156
+ tooLarge: (maxBytes) => new MirrorAnswerRefused("too-large", `RPC endpoint answer is larger than ${maxBytes} bytes`),
2157
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `RPC log scan did not finish in ${budgetMs}ms`),
2158
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `RPC log scan kept more than ${logs} logs`)
2159
+ };
2160
+ var LOG_SCAN_BUDGET_TIMEOUTS = 60;
2161
+ var LOG_SCAN_MAX_REQUESTS = 1e4;
2162
+ var LOG_SCAN_MAX_KEPT_LOGS = 1e6;
2163
+ var KEPT_LOG_DATA_MAX_CHARS = 2 + 64 * 3;
2164
+ var KEPT_LOG_MAX_TOPICS = 3;
2165
+ function isMirrorRedirect(response) {
2166
+ return response.redirected === true || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400;
2167
+ }
2168
+ async function readMirrorText(response, maxBytes = MIRROR_ANSWER_MAX_BYTES, path) {
2169
+ const declared = Number(response.headers?.get?.("content-length") ?? Number.NaN);
2170
+ const body = response.body;
2171
+ if (Number.isFinite(declared) && declared > maxBytes) {
2172
+ await body?.cancel?.().catch(() => void 0);
2173
+ throw mirrorRefusal.tooLarge(maxBytes, path);
2174
+ }
2175
+ if (body && typeof body.getReader === "function") {
2176
+ const reader = body.getReader();
2177
+ const decoder = new TextDecoder();
2178
+ let text2 = "";
2179
+ let read = 0;
2180
+ for (; ; ) {
2181
+ const { done, value } = await reader.read();
2182
+ if (done) break;
2183
+ read += value.byteLength;
2184
+ if (read > maxBytes) {
2185
+ await reader.cancel().catch(() => void 0);
2186
+ throw mirrorRefusal.tooLarge(maxBytes, path);
2187
+ }
2188
+ text2 += decoder.decode(value, { stream: true });
2189
+ }
2190
+ return text2 + decoder.decode();
2191
+ }
2192
+ const text = await response.text();
2193
+ if (new TextEncoder().encode(text).byteLength > maxBytes) throw mirrorRefusal.tooLarge(maxBytes, path);
2194
+ return text;
2195
+ }
2196
+ async function readMirrorJson(response, maxBytes = MIRROR_ANSWER_MAX_BYTES, path) {
2197
+ return JSON.parse(await readMirrorText(response, maxBytes, path));
2198
+ }
2199
+ function contractLogPath(contractAddress) {
2200
+ return `/api/v1/contracts/${contractAddress}/results/logs`;
2120
2201
  }
2121
- function nextLedgerWritePath(next) {
2122
- return typeof next === "string" && NEXT_PATH.test(next) ? next : null;
2202
+ function ledgerWriteSearchPath(input) {
2203
+ const query = `topic0=${input.topic0}&topic1=${input.recordKey}&timestamp=gte:${input.lower}&timestamp=lt:${input.upper}&order=desc&limit=${LEDGER_WRITE_SEARCH_PAGE_LIMIT}`;
2204
+ return `${contractLogPath(input.contractAddress)}?${query}`;
2205
+ }
2206
+ function nextLogPath(next, source) {
2207
+ if (typeof next !== "string" || next === "") return null;
2208
+ const contract = source.contract.toLowerCase();
2209
+ if (!HEX40.test(contract)) return null;
2210
+ if (!/^[\x21-\x5b\x5d-\x7e]+$/.test(next)) return null;
2211
+ if (next.startsWith("//")) return null;
2212
+ let base;
2213
+ let url;
2214
+ try {
2215
+ base = new URL(source.base);
2216
+ url = new URL(next, `${base.origin}/`);
2217
+ } catch {
2218
+ return null;
2219
+ }
2220
+ if (base.protocol !== "https:" && base.protocol !== "http:") return null;
2221
+ if (url.origin !== base.origin || url.username !== "" || url.password !== "" || url.hash !== "" || next.includes("#")) return null;
2222
+ const written = (next.startsWith("/") ? next : next.slice(next.indexOf("/", next.indexOf("//") + 2))).split("?")[0];
2223
+ if (/(^|\/)\.{1,2}(\/|$)/.test(written) || /%2e/i.test(written) || written !== url.pathname) return null;
2224
+ if (url.search.length < 2) return null;
2225
+ const logs = contractLogPath(contract);
2226
+ const prefix = base.pathname.replace(/\/+$/, "");
2227
+ const path = url.pathname.toLowerCase();
2228
+ if (path !== logs && !(prefix !== "" && url.pathname.startsWith(`${prefix}/`) && url.pathname.slice(prefix.length).toLowerCase() === logs)) return null;
2229
+ return `${logs}${url.search}`;
2230
+ }
2231
+ function withLogPageLimit(path, limit) {
2232
+ const at = path.indexOf("?");
2233
+ const before = at === -1 ? path : path.slice(0, at);
2234
+ const parts = at === -1 ? [] : path.slice(at + 1).split("&").filter((part) => part !== "");
2235
+ let placed = false;
2236
+ const out = [];
2237
+ for (const part of parts) {
2238
+ if (!part.startsWith("limit=")) out.push(part);
2239
+ else if (!placed) {
2240
+ out.push(`limit=${limit}`);
2241
+ placed = true;
2242
+ }
2243
+ }
2244
+ if (!placed) out.push(`limit=${limit}`);
2245
+ return `${before}?${out.join("&")}`;
2123
2246
  }
2124
2247
  function parseLedgerWriteLog(log, expected) {
2125
2248
  if (!log || typeof log !== "object") return null;
2126
2249
  const raw = log;
2250
+ const address = typeof raw.address === "string" ? raw.address.toLowerCase() : "";
2251
+ if (!HEX40.test(address) || address !== String(expected.contractAddress).toLowerCase()) return null;
2127
2252
  const topics = Array.isArray(raw.topics) ? raw.topics.map((topic) => String(topic).toLowerCase()) : [];
2128
2253
  if (topics[0] !== expected.topic0 || topics[1] !== expected.recordKey) return null;
2129
2254
  const data = typeof raw.data === "string" ? raw.data.toLowerCase() : "";
@@ -2137,7 +2262,6 @@ function parseLedgerWriteLog(log, expected) {
2137
2262
  const [seconds, fraction = ""] = timestamp.split(".");
2138
2263
  const ms = Number(seconds) * 1e3 + Number(fraction.slice(0, 3).padEnd(3, "0"));
2139
2264
  if (!Number.isFinite(ms) || Math.abs(ms) > 864e13) return null;
2140
- const address = typeof raw.address === "string" ? raw.address.toLowerCase() : null;
2141
2265
  return {
2142
2266
  transactionHash,
2143
2267
  timestamp,
@@ -2153,6 +2277,9 @@ function parseLedgerWriteLog(log, expected) {
2153
2277
  }
2154
2278
 
2155
2279
  // ../shared/src/demo/independent-verify-records.ts
2280
+ var import_ethers12 = require("ethers");
2281
+
2282
+ // ../shared/src/chain/rpc-guarded-send.ts
2156
2283
  var import_ethers11 = require("ethers");
2157
2284
 
2158
2285
  // ../shared/src/chain/rpc-provider.ts
@@ -2269,13 +2396,34 @@ function redactRpcError(error, secrets) {
2269
2396
  }
2270
2397
  return new Error(cleanText(String(error), secrets));
2271
2398
  }
2399
+ function requestFor(url, options) {
2400
+ const request = new import_ethers10.FetchRequest(url);
2401
+ if (options.timeoutMs !== void 0) request.timeout = options.timeoutMs;
2402
+ options.prepareRequest?.(request);
2403
+ return request;
2404
+ }
2405
+ var CHAIN_ID_RESULT = /^0x[0-9a-f]{1,13}$/i;
2406
+ async function readRpcChainId(url, options = {}) {
2407
+ const secrets = rpcUrlSecrets(url);
2408
+ try {
2409
+ const request = requestFor(url, options);
2410
+ request.body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_chainId", params: [] });
2411
+ request.setHeader("content-type", "application/json");
2412
+ const response = await request.send();
2413
+ response.assertOk();
2414
+ const answer = response.bodyJson;
2415
+ const result = answer !== null && typeof answer === "object" ? answer.result : void 0;
2416
+ if (typeof result !== "string" || !CHAIN_ID_RESULT.test(result)) throw new Error("eth_chainId from the RPC is incomplete: not a chain id");
2417
+ return Number.parseInt(result, 16);
2418
+ } catch (error) {
2419
+ throw redactRpcError(error, secrets);
2420
+ }
2421
+ }
2272
2422
  var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
2273
2423
  #secrets;
2274
2424
  constructor(url, network, options) {
2275
- const { timeoutMs, ...providerOptions } = options;
2276
- const request = new import_ethers10.FetchRequest(url);
2277
- if (timeoutMs !== void 0) request.timeout = timeoutMs;
2278
- super(request, network, providerOptions);
2425
+ const { timeoutMs, prepareRequest, ...providerOptions } = options;
2426
+ super(requestFor(url, { timeoutMs, prepareRequest }), network, providerOptions);
2279
2427
  this.#secrets = rpcUrlSecrets(url);
2280
2428
  }
2281
2429
  async _send(payload) {
@@ -2290,6 +2438,100 @@ function createRpcProvider(url, network, options = {}) {
2290
2438
  return new RedactingJsonRpcProvider(url, network, options);
2291
2439
  }
2292
2440
 
2441
+ // ../shared/src/chain/rpc-guarded-send.ts
2442
+ var RPC_READER_MAX_TRIES = 3;
2443
+ function basicAuthorization(username, password) {
2444
+ const decoded = (value) => {
2445
+ try {
2446
+ return decodeURIComponent(value);
2447
+ } catch {
2448
+ return value;
2449
+ }
2450
+ };
2451
+ const bytes2 = new TextEncoder().encode(`${decoded(username)}:${decoded(password)}`);
2452
+ let binary = "";
2453
+ for (const byte of bytes2) binary += String.fromCharCode(byte);
2454
+ return `Basic ${btoa(binary)}`;
2455
+ }
2456
+ function createGuardedRpcSend(options = {}) {
2457
+ const maxBytes = options.maxBytes ?? MIRROR_ANSWER_MAX_BYTES;
2458
+ return async (req, signal) => {
2459
+ if (signal?.cancelled) throw (0, import_ethers11.makeError)("request cancelled before sending", "CANCELLED");
2460
+ const fetchImpl = options.fetchImpl ?? fetch;
2461
+ const secrets = rpcUrlSecrets(req.url);
2462
+ const url = new URL(req.url);
2463
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2464
+ throw (0, import_ethers11.makeError)(`unsupported protocol ${url.protocol.replace(/:$/, "")}`, "UNSUPPORTED_OPERATION", { operation: "request" });
2465
+ }
2466
+ const headers = {};
2467
+ for (const [name, value] of Object.entries(req.headers)) {
2468
+ const lower = name.toLowerCase();
2469
+ if (lower === "content-length" || lower === "accept-encoding") continue;
2470
+ headers[lower] = value;
2471
+ }
2472
+ if (url.username !== "" || url.password !== "") {
2473
+ if (headers.authorization === void 0) headers.authorization = basicAuthorization(url.username, url.password);
2474
+ url.username = "";
2475
+ url.password = "";
2476
+ }
2477
+ const controller = new AbortController();
2478
+ let timedOut = false;
2479
+ const timer = setTimeout(() => {
2480
+ timedOut = true;
2481
+ controller.abort();
2482
+ }, req.timeout);
2483
+ let cancelled = false;
2484
+ signal?.addListener(() => {
2485
+ cancelled = true;
2486
+ controller.abort();
2487
+ });
2488
+ try {
2489
+ const body = req.body;
2490
+ const response = await fetchImpl(url.toString(), {
2491
+ method: req.method,
2492
+ headers,
2493
+ ...body ? { body } : {},
2494
+ redirect: "manual",
2495
+ signal: controller.signal
2496
+ });
2497
+ if (isMirrorRedirect(response)) {
2498
+ await response.body?.cancel?.().catch(() => void 0);
2499
+ throw rpcRefusal.redirect();
2500
+ }
2501
+ let text;
2502
+ try {
2503
+ text = await readMirrorText(response, maxBytes);
2504
+ } catch (error) {
2505
+ if (mirrorRefusalOf(error) === "too-large") throw rpcRefusal.tooLarge(maxBytes);
2506
+ throw error;
2507
+ }
2508
+ const answered = {};
2509
+ response.headers.forEach((value, name) => {
2510
+ answered[name.toLowerCase()] = value;
2511
+ });
2512
+ return { statusCode: response.status, statusMessage: response.statusText, headers: answered, body: new TextEncoder().encode(replaceRpcSecrets(text, secrets)) };
2513
+ } catch (error) {
2514
+ if (mirrorRefusalOf(error)) throw error;
2515
+ if (cancelled) throw (0, import_ethers11.makeError)("request cancelled", "CANCELLED");
2516
+ if (timedOut) throw (0, import_ethers11.makeError)("request timeout", "TIMEOUT", { operation: "request.send", reason: "timeout" });
2517
+ throw error;
2518
+ } finally {
2519
+ clearTimeout(timer);
2520
+ }
2521
+ };
2522
+ }
2523
+ function retryAfterMs(value) {
2524
+ return typeof value === "string" && /^[1-9][0-9]*$/.test(value) ? Number.parseInt(value, 10) : null;
2525
+ }
2526
+ function holdRpcRequest(request, options = {}) {
2527
+ request.getUrlFunc = createGuardedRpcSend(options);
2528
+ request.retryFunc = async (req, response, attempt) => {
2529
+ if (attempt >= RPC_READER_MAX_TRIES - 1) return false;
2530
+ const wait = retryAfterMs(response.headers["retry-after"]);
2531
+ return wait === null || wait <= req.timeout;
2532
+ };
2533
+ }
2534
+
2293
2535
  // ../shared/src/demo/independent-verify-records.ts
2294
2536
  var RECORD_LANE_ABI_V38 = [
2295
2537
  "function getRecord(bytes32 recordKey) view returns (uint256)",
@@ -2301,8 +2543,8 @@ var RECORD_LANE_ABI_V38 = [
2301
2543
  "event RecordWritten(bytes32 indexed recordKey, address indexed operator, uint8 encodingVersion, uint256 previousWord, uint256 newWord)",
2302
2544
  "event LedgerHeadAdvanced(uint256 indexed batchId, bytes32 merkleRoot, bytes32 previousHead, bytes32 newHead)"
2303
2545
  ];
2304
- var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers11.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
2305
- var RECORD_WRITTEN_TOPIC = import_ethers11.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
2546
+ var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers12.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
2547
+ var RECORD_WRITTEN_TOPIC = import_ethers12.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
2306
2548
  var LAYOUT_NOT_REGISTERED = "layout-not-registered";
2307
2549
  function checkLayoutOnChain(onChainLayout, published) {
2308
2550
  const matchesPublished = !!published && onChainLayout.registered && onChainLayout.layoutDigest === published.digest;
@@ -2314,10 +2556,12 @@ function normalizeRpcUrl2(url) {
2314
2556
  if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
2315
2557
  return trimmed;
2316
2558
  }
2559
+ var ReadTimedOut = class extends Error {
2560
+ };
2317
2561
  async function withTimeout(p, ms, label) {
2318
2562
  let timer;
2319
2563
  const timeout = new Promise((_, reject) => {
2320
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
2564
+ timer = setTimeout(() => reject(new ReadTimedOut(`${label} timed out after ${ms}ms`)), ms);
2321
2565
  });
2322
2566
  try {
2323
2567
  return await Promise.race([p, timeout]);
@@ -2328,24 +2572,71 @@ async function withTimeout(p, ms, label) {
2328
2572
  function createRpcRecordChainReader(options) {
2329
2573
  const rpcUrl = normalizeRpcUrl2(options.rpcUrl);
2330
2574
  if (!rpcUrl) throw new Error("rpcUrl is required.");
2331
- const contractAddress = import_ethers11.ethers.getAddress(options.contractAddress).toLowerCase();
2575
+ const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
2332
2576
  const timeoutMs = Number(options.timeoutMs || 1e4);
2333
2577
  const chunk = Math.max(1, Number(options.logsChunkSize || 2e3));
2334
- const network = options.chainId != null ? new import_ethers11.ethers.Network(`chain-${options.chainId}`, options.chainId) : void 0;
2335
- const provider = network ? createRpcProvider(rpcUrl, network, { staticNetwork: network }) : createRpcProvider(rpcUrl);
2336
- const contract = new import_ethers11.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider);
2337
- const iface = new import_ethers11.ethers.Interface(RECORD_LANE_ABI_V38);
2578
+ const now = options.scan?.now ?? Date.now;
2579
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
2580
+ const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
2581
+ const prepareRequest = (request) => holdRpcRequest(request);
2582
+ const endpointFor = (chainId) => {
2583
+ const network = new import_ethers12.ethers.Network(`chain-${chainId}`, chainId);
2584
+ const provider = createRpcProvider(rpcUrl, network, { staticNetwork: network, timeoutMs, prepareRequest });
2585
+ return { provider, contract: new import_ethers12.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider) };
2586
+ };
2587
+ let ready = options.chainId != null ? Promise.resolve(endpointFor(options.chainId)) : null;
2588
+ function endpoint() {
2589
+ if (!ready) {
2590
+ const pending = readRpcChainId(rpcUrl, { timeoutMs, prepareRequest }).then(endpointFor);
2591
+ ready = pending;
2592
+ pending.catch(() => {
2593
+ if (ready === pending) ready = null;
2594
+ });
2595
+ }
2596
+ return ready;
2597
+ }
2598
+ function keptLog(log, topic0) {
2599
+ return String(log.address).toLowerCase() === contractAddress && log.topics.length <= KEPT_LOG_MAX_TOPICS && String(log.topics[0] ?? "").toLowerCase() === topic0 && typeof log.data === "string" && log.data.length <= KEPT_LOG_DATA_MAX_CHARS;
2600
+ }
2338
2601
  async function scanLogs(topics, fromBlock, toBlock, label) {
2339
- const latest = toBlock === "latest" ? await withTimeout(provider.getBlockNumber(), timeoutMs, "getBlockNumber") : toBlock;
2602
+ const { provider } = await endpoint();
2603
+ const budgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
2604
+ const deadline = now() + budgetMs;
2605
+ const topic0 = String(topics[0] ?? "").toLowerCase();
2606
+ const ask = async (send, what) => {
2607
+ const left = deadline - now();
2608
+ if (left <= 0) throw rpcRefusal.scanTooSlow(budgetMs);
2609
+ const allowed = Math.min(timeoutMs, left);
2610
+ try {
2611
+ return await withTimeout(send(), allowed, what);
2612
+ } catch (error) {
2613
+ if (error instanceof ReadTimedOut && allowed < timeoutMs) throw rpcRefusal.scanTooSlow(budgetMs);
2614
+ if (!mirrorRefusalOf(error) && now() >= deadline) throw rpcRefusal.scanTooSlow(budgetMs);
2615
+ throw error;
2616
+ }
2617
+ };
2618
+ const latest = toBlock === "latest" ? await ask(() => provider.getBlockNumber(), "getBlockNumber") : toBlock;
2340
2619
  const out = [];
2620
+ const pending = [];
2341
2621
  for (let start = fromBlock; start <= latest; start += chunk) {
2342
- const end = Math.min(latest, start + chunk - 1);
2343
- const logs = await withTimeout(
2344
- provider.getLogs({ address: contractAddress, topics, fromBlock: start, toBlock: end }),
2345
- timeoutMs,
2346
- `getLogs ${label} (${start}-${end})`
2347
- );
2348
- out.push(...logs);
2622
+ pending.push([start, Math.min(latest, start + chunk - 1)]);
2623
+ while (pending.length > 0) {
2624
+ const [from, to] = pending.pop();
2625
+ let logs;
2626
+ try {
2627
+ logs = await ask(() => provider.getLogs({ address: contractAddress, topics, fromBlock: from, toBlock: to }), `getLogs ${label} (${from}-${to})`);
2628
+ } catch (error) {
2629
+ if (mirrorRefusalOf(error) !== "too-large" || from >= to) throw error;
2630
+ const middle = from + Math.floor((to - from) / 2);
2631
+ pending.push([middle + 1, to], [from, middle]);
2632
+ continue;
2633
+ }
2634
+ for (const log of logs) {
2635
+ if (!keptLog(log, topic0)) continue;
2636
+ if (out.length >= maxKeptLogs) throw rpcRefusal.scanTooManyLogs(maxKeptLogs);
2637
+ out.push(log);
2638
+ }
2639
+ }
2349
2640
  }
2350
2641
  return out;
2351
2642
  }
@@ -2353,10 +2644,12 @@ function createRpcRecordChainReader(options) {
2353
2644
  contractAddress,
2354
2645
  async getRecord(recordKey) {
2355
2646
  const key = normalizeProofHash(recordKey, "recordKey");
2647
+ const { contract } = await endpoint();
2356
2648
  const word = await withTimeout(contract.getRecord(key), timeoutMs, "getRecord");
2357
2649
  return hex256(BigInt(word));
2358
2650
  },
2359
2651
  async getLayout(layoutId) {
2652
+ const { contract } = await endpoint();
2360
2653
  const l = await withTimeout(contract.getLayout(layoutId), timeoutMs, "getLayout");
2361
2654
  return {
2362
2655
  layoutDigest: String(l[0]).toLowerCase(),
@@ -2366,10 +2659,12 @@ function createRpcRecordChainReader(options) {
2366
2659
  };
2367
2660
  },
2368
2661
  async getBatchRoot(batchId) {
2662
+ const { contract } = await endpoint();
2369
2663
  const root = await withTimeout(contract.getBatchRoot(BigInt(batchId)), timeoutMs, "getBatchRoot");
2370
2664
  return normalizeProofHash(String(root), "observedProofRoot");
2371
2665
  },
2372
2666
  async getLedgerHead() {
2667
+ const { contract } = await endpoint();
2373
2668
  const head = await withTimeout(contract.getLedgerHead(), timeoutMs, "getLedgerHead");
2374
2669
  return normalizeProofHash(String(head), "ledgerHead");
2375
2670
  },
@@ -2412,14 +2707,14 @@ function createRpcRecordChainReader(options) {
2412
2707
  },
2413
2708
  async findRecordWrites(recordKey, search) {
2414
2709
  const key = normalizeProofHash(recordKey, "recordKey");
2415
- const now = search.now ?? Date.now;
2416
- const deadline = now() + search.budgetMs;
2710
+ const now2 = search.now ?? Date.now;
2711
+ const deadline = now2() + search.budgetMs;
2417
2712
  const writes = [];
2418
2713
  const blockTimes = /* @__PURE__ */ new Map();
2419
2714
  let requests = 0;
2420
2715
  const CUT = Symbol("cut");
2421
2716
  const within2 = async (p) => {
2422
- const left = deadline - now();
2717
+ const left = deadline - now2();
2423
2718
  if (left <= 0) return CUT;
2424
2719
  let timer;
2425
2720
  const cut = new Promise((resolve3) => {
@@ -2434,12 +2729,15 @@ function createRpcRecordChainReader(options) {
2434
2729
  };
2435
2730
  const end = (ended) => ({ writes, ended, requests });
2436
2731
  if (search.maxRequests < 1) return end("limit");
2732
+ const found = await within2(endpoint());
2733
+ if (found === CUT) return end("timeout");
2734
+ const { provider } = found;
2437
2735
  requests += 1;
2438
2736
  const latest = await within2(provider.getBlockNumber());
2439
2737
  if (latest === CUT) return end("timeout");
2440
2738
  for (let to = latest; to >= 0; to -= chunk) {
2441
2739
  if (search.done(writes)) return end("done");
2442
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2740
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
2443
2741
  requests += 1;
2444
2742
  const logs = await within2(provider.getLogs({ address: contractAddress, topics: [RECORD_WRITTEN_TOPIC, key], fromBlock: Math.max(0, to - chunk + 1), toBlock: to }));
2445
2743
  if (logs === CUT) return end("timeout");
@@ -2448,7 +2746,7 @@ function createRpcRecordChainReader(options) {
2448
2746
  if (!parsed) continue;
2449
2747
  let committedAt = blockTimes.get(log.blockNumber);
2450
2748
  if (committedAt === void 0) {
2451
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2749
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
2452
2750
  requests += 1;
2453
2751
  const block = await within2(provider.getBlock(log.blockNumber));
2454
2752
  if (block === CUT) return end("timeout");
@@ -2493,7 +2791,7 @@ async function readLedgerMaterial(reader, log, options) {
2493
2791
  log,
2494
2792
  `eth_getLogs LedgerHeadAdvanced from block ${options.fromBlock ?? 0}`
2495
2793
  );
2496
- const genesisHead = options.genesisHead ?? (advances[0]?.previousHead ?? import_ethers11.ethers.ZeroHash);
2794
+ const genesisHead = options.genesisHead ?? (advances[0]?.previousHead ?? import_ethers12.ethers.ZeroHash);
2497
2795
  return {
2498
2796
  genesisHead,
2499
2797
  batches: advances.map((a) => ({ batchId: a.batchId, merkleRoot: a.merkleRoot })),
@@ -2558,41 +2856,94 @@ function committedAtOf(timestamp) {
2558
2856
  const [seconds, fraction] = timestamp.split(".");
2559
2857
  return new Date(Number(seconds) * 1e3 + Number(fraction.slice(0, 3))).toISOString();
2560
2858
  }
2859
+ var KEPT_TOPICS = [RECORD_WRITTEN_TOPIC.toLowerCase(), LEDGER_HEAD_ADVANCED_TOPIC.toLowerCase()];
2860
+ var HEX_DATA2 = /^0x[0-9a-fA-F]*$/;
2861
+ function mirrorLogPosition(raw) {
2862
+ if (!raw || typeof raw !== "object") return null;
2863
+ const { timestamp, index } = raw;
2864
+ if (typeof timestamp !== "string" || !CONSENSUS_TIMESTAMP.test(timestamp)) return null;
2865
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
2866
+ const [seconds, fraction] = timestamp.split(".");
2867
+ return { nanos: BigInt(seconds) * 1000000000n + BigInt(fraction), index };
2868
+ }
2869
+ function mirrorLogFollows(last, next) {
2870
+ return last === null || next.nanos > last.nanos || next.nanos === last.nanos && next.index > last.index;
2871
+ }
2872
+ function keptMirrorLog(raw, contract) {
2873
+ if (!raw || typeof raw !== "object") return null;
2874
+ const log = raw;
2875
+ if (!Array.isArray(log.topics) || typeof log.data !== "string") return null;
2876
+ if (log.topics.length > KEPT_LOG_MAX_TOPICS || log.data.length > KEPT_LOG_DATA_MAX_CHARS || !HEX_DATA2.test(log.data)) return null;
2877
+ const topics = log.topics.map((topic) => String(topic));
2878
+ if (!KEPT_TOPICS.includes((topics[0] ?? "").toLowerCase())) return null;
2879
+ if (topics.some((topic) => topic.length > 66)) return null;
2880
+ if (contract !== void 0) {
2881
+ if (typeof log.address !== "string" || log.address.toLowerCase() !== contract) return null;
2882
+ if (!mirrorLogPosition(raw)) return null;
2883
+ if (typeof log.block_number !== "number" || !Number.isSafeInteger(log.block_number)) return null;
2884
+ if (typeof log.transaction_hash !== "string" || log.transaction_hash.length > 98) return null;
2885
+ }
2886
+ return {
2887
+ address: log.address,
2888
+ data: log.data,
2889
+ index: log.index,
2890
+ topics,
2891
+ block_number: log.block_number,
2892
+ transaction_hash: log.transaction_hash,
2893
+ timestamp: log.timestamp
2894
+ };
2895
+ }
2561
2896
  function createMirrorNodeRecordChainReader(options) {
2562
2897
  const chainId = options.chainId ?? 296;
2563
2898
  const base = (options.mirrorBaseUrl ?? MIRROR_NODE_BY_CHAIN[chainId] ?? "").replace(/\/+$/, "");
2564
2899
  if (!base) throw new Error(`No mirror node known for chain ${chainId}; pass mirrorBaseUrl.`);
2565
- const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
2900
+ const contractAddress = import_ethers13.ethers.getAddress(options.contractAddress).toLowerCase();
2566
2901
  const timeoutMs = Number(options.timeoutMs || 1e4);
2567
2902
  const pageSize = Math.min(100, Math.max(1, Number(options.pageSize || 100)));
2568
2903
  const attempts = Math.max(1, options.attempts ?? 3);
2569
2904
  const fetchImpl = options.fetchImpl ?? fetch;
2570
- const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
2571
- async function request(path, init) {
2572
- const url = path.startsWith("http") ? path : `${base}${path.startsWith("/") ? "" : "/"}${path}`;
2905
+ const iface = new import_ethers13.ethers.Interface(RECORD_LANE_ABI_V38);
2906
+ const now = options.scan?.now ?? Date.now;
2907
+ const maxScanRequests = options.scan?.maxRequests ?? LOG_SCAN_MAX_REQUESTS;
2908
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
2909
+ const scanBudgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
2910
+ async function request(path, init, deadline) {
2911
+ const url = `${base}${path}`;
2573
2912
  let lastError = null;
2574
2913
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
2914
+ const left = deadline === void 0 ? timeoutMs : deadline - now();
2915
+ if (left <= 0) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
2916
+ const allowed = Math.min(timeoutMs, left);
2575
2917
  const controller = new AbortController();
2576
- const timer = setTimeout(() => controller.abort(), timeoutMs);
2918
+ const timer = setTimeout(() => controller.abort(), allowed);
2577
2919
  try {
2578
- const response = await fetchImpl(url, { ...init, signal: controller.signal });
2920
+ const response = await fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal });
2921
+ if (isMirrorRedirect(response)) {
2922
+ await response.body?.cancel?.().catch(() => void 0);
2923
+ throw mirrorRefusal.redirect(path);
2924
+ }
2579
2925
  if (response.status === 429 || response.status >= 500) {
2926
+ await response.body?.cancel?.().catch(() => void 0);
2580
2927
  lastError = new Error(`mirror node ${response.status} for ${path}`);
2581
2928
  } else if (!response.ok) {
2582
- const body = await response.text().catch(() => "");
2929
+ const body = await readMirrorText(response, MIRROR_ANSWER_MAX_BYTES, path).catch(() => "");
2583
2930
  throw new Error(`mirror node ${response.status} for ${path}${body ? `: ${body.slice(0, 200)}` : ""}`);
2584
2931
  } else {
2585
- return await response.json();
2932
+ return await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
2586
2933
  }
2587
2934
  } catch (error) {
2588
- if (error.name === "AbortError") lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
2589
- else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
2935
+ if (mirrorRefusalOf(error)) throw error;
2936
+ if (error.name === "AbortError") {
2937
+ if (deadline !== void 0 && allowed < timeoutMs) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
2938
+ lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
2939
+ } else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
2590
2940
  else lastError = error;
2591
2941
  } finally {
2592
2942
  clearTimeout(timer);
2593
2943
  }
2594
2944
  if (attempt < attempts) await new Promise((resolve3) => setTimeout(resolve3, 250 * attempt));
2595
2945
  }
2946
+ if (deadline !== void 0 && now() >= deadline) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
2596
2947
  throw lastError ?? new Error(`mirror node request failed (${path})`);
2597
2948
  }
2598
2949
  async function call(fn, args = []) {
@@ -2626,18 +2977,50 @@ function createMirrorNodeRecordChainReader(options) {
2626
2977
  const params = new URLSearchParams();
2627
2978
  params.set("order", "asc");
2628
2979
  params.set("limit", String(pageSize));
2629
- let next = `/api/v1/contracts/${contractAddress}/results/logs?${params.toString()}`;
2980
+ let next = `${contractLogPath(contractAddress)}?${params.toString()}`;
2630
2981
  const out = [];
2631
- let pages = 0;
2982
+ const scan = { deadline: now() + scanBudgetMs, requests: 0 };
2983
+ let last = null;
2984
+ let size = pageSize;
2632
2985
  while (next) {
2633
- const page = await request(next);
2634
- out.push(...page.logs ?? []);
2635
- next = page.links?.next ?? null;
2636
- pages += 1;
2637
- if (pages > 1e4) throw new Error("mirror node log scan exceeded 10,000 pages");
2986
+ const { page, asked } = await readLogPage(next, size, scan);
2987
+ size = Math.min(pageSize, asked * 2);
2988
+ const logs = Array.isArray(page.logs) ? page.logs : [...page.logs ?? []];
2989
+ if (logs.length > asked) throw mirrorRefusal.tooManyLogs(asked, next);
2990
+ for (const raw of logs) {
2991
+ const position = mirrorLogPosition(raw);
2992
+ if (!position) continue;
2993
+ if (!mirrorLogFollows(last, position)) throw mirrorRefusal.notForward();
2994
+ last = position;
2995
+ const log = keptMirrorLog(raw, contractAddress);
2996
+ if (!log) continue;
2997
+ if (out.length >= maxKeptLogs) throw mirrorRefusal.scanTooManyLogs(maxKeptLogs);
2998
+ out.push(log);
2999
+ }
3000
+ const link = page.links?.next;
3001
+ if (link === null || link === void 0 || link === "") {
3002
+ next = null;
3003
+ } else {
3004
+ const path = nextLogPath(link, { base, contract: contractAddress });
3005
+ if (!path) throw mirrorRefusal.nextPage();
3006
+ next = withLogPageLimit(path, size);
3007
+ }
2638
3008
  }
2639
3009
  return out;
2640
3010
  }
3011
+ async function readLogPage(path, start, scan) {
3012
+ let asked = start;
3013
+ for (; ; ) {
3014
+ if (scan.requests >= maxScanRequests) throw mirrorRefusal.scanTooManyRequests(maxScanRequests);
3015
+ scan.requests += 1;
3016
+ try {
3017
+ return { page: await request(withLogPageLimit(path, asked), void 0, scan.deadline), asked };
3018
+ } catch (error) {
3019
+ if (mirrorRefusalOf(error) !== "too-large" || asked <= 1) throw error;
3020
+ asked = Math.max(1, Math.floor(asked / 2));
3021
+ }
3022
+ }
3023
+ }
2641
3024
  async function scanLogs(topics, fromBlock, toBlock) {
2642
3025
  const out = [];
2643
3026
  for (const log of await readAllLogs()) {
@@ -2654,8 +3037,11 @@ function createMirrorNodeRecordChainReader(options) {
2654
3037
  const timer = setTimeout(() => controller.abort(), ms);
2655
3038
  try {
2656
3039
  const response = await fetchImpl(`${base}${path}`, { headers: { accept: "application/json" }, redirect: "error", signal: controller.signal });
3040
+ if (isMirrorRedirect(response)) throw mirrorRefusal.redirect(path);
2657
3041
  if (!response.ok) throw new Error(`mirror node ${response.status} for a record's writes`);
2658
- return await response.json();
3042
+ const page = await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
3043
+ if (Array.isArray(page.logs) && page.logs.length > LEDGER_WRITE_SEARCH_PAGE_LIMIT) throw mirrorRefusal.tooManyLogs(LEDGER_WRITE_SEARCH_PAGE_LIMIT, path);
3044
+ return page;
2659
3045
  } catch (error) {
2660
3046
  if (controller.signal.aborted) return "timeout";
2661
3047
  throw error;
@@ -2730,10 +3116,10 @@ function createMirrorNodeRecordChainReader(options) {
2730
3116
  async findRecordWrites(recordKey, search) {
2731
3117
  const key = normalizeProofHash(recordKey, "recordKey").toLowerCase();
2732
3118
  const topic0 = RECORD_WRITTEN_TOPIC.toLowerCase();
2733
- const now = search.now ?? Date.now;
2734
- const deadline = now() + search.budgetMs;
3119
+ const now2 = search.now ?? Date.now;
3120
+ const deadline = now2() + search.budgetMs;
2735
3121
  const windowSeconds = Math.max(1, Math.floor(search.windowSeconds ?? RECORD_WRITE_SEARCH_WINDOW_SECONDS));
2736
- const nowSeconds = Math.floor(now() / 1e3);
3122
+ const nowSeconds = Math.floor(now2() / 1e3);
2737
3123
  const hint = search.startAt ? Date.parse(search.startAt) : Number.NaN;
2738
3124
  let upper = Math.min(Number.isFinite(hint) ? Math.floor(hint / 1e3) : nowSeconds, nowSeconds) + DAY_SECONDS;
2739
3125
  const writes = [];
@@ -2744,14 +3130,14 @@ function createMirrorNodeRecordChainReader(options) {
2744
3130
  const lower = Math.max(0, upper - windowSeconds);
2745
3131
  let path = ledgerWriteSearchPath({ contractAddress, topic0, recordKey: key, lower, upper });
2746
3132
  while (path) {
2747
- const left = deadline - now();
3133
+ const left = deadline - now2();
2748
3134
  if (requests >= search.maxRequests || left <= 0) return end("limit");
2749
3135
  requests += 1;
2750
3136
  const page = await searchPage(path, left);
2751
3137
  if (page === "timeout") return end("timeout");
2752
- for (const log of Array.isArray(page.logs) ? page.logs : []) {
2753
- const write = parseLedgerWriteLog(log, { topic0, recordKey: key });
2754
- if (!write || write.address !== contractAddress || !CONSENSUS_TIMESTAMP.test(write.timestamp)) continue;
3138
+ for (const log of Array.isArray(page?.logs) ? page.logs : []) {
3139
+ const write = parseLedgerWriteLog(log, { topic0, recordKey: key, contractAddress });
3140
+ if (!write || !CONSENSUS_TIMESTAMP.test(write.timestamp)) continue;
2755
3141
  writes.push({
2756
3142
  previousWord: write.previousWord,
2757
3143
  newWord: write.newWord,
@@ -2765,7 +3151,9 @@ function createMirrorNodeRecordChainReader(options) {
2765
3151
  });
2766
3152
  }
2767
3153
  if (search.done(writes)) return end("done");
2768
- path = nextLedgerWritePath(page.links?.next);
3154
+ const link = page?.links?.next;
3155
+ path = nextLogPath(link, { base, contract: contractAddress });
3156
+ if (!path && link !== null && link !== void 0 && link !== "") throw mirrorRefusal.nextPage();
2769
3157
  }
2770
3158
  upper = lower;
2771
3159
  }
@@ -2998,7 +3386,7 @@ var hasOnly = (v, required, optional = []) => required.every((k) => Object.proto
2998
3386
  function computeSealHistoryDigestV1(form) {
2999
3387
  const rest = { ...form };
3000
3388
  delete rest.digest;
3001
- return import_ethers13.ethers.keccak256(import_ethers13.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
3389
+ return import_ethers14.ethers.keccak256(import_ethers14.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
3002
3390
  }
3003
3391
  function entryShapeOk2(e) {
3004
3392
  if (!isPlainObject4(e) || !hasOnly(e, ENTRY_KEYS, ["recordHash"])) return false;
@@ -3486,6 +3874,14 @@ var SEP5 = new Uint8Array([0]);
3486
3874
 
3487
3875
  // src/report.ts
3488
3876
  var REPORT_SCHEMA = "pacspace-check-report/v1";
3877
+ var SOURCE_REFUSAL_REASONS = {
3878
+ redirect: "its source answered with a redirect, which is not followed",
3879
+ "too-large": "its source gave an answer larger than this checker reads",
3880
+ "too-many-logs": "its source returned a longer page than was asked for",
3881
+ "next-page": "its source pointed somewhere else for the next page",
3882
+ "too-slow": "its source did not finish answering in the time allowed",
3883
+ "too-long": "it holds more than this checker reads in one run"
3884
+ };
3489
3885
  var ENCRYPTED_OPENED_SENTENCE = "Each entry was opened on this machine and matches its sealed record hash.";
3490
3886
  function refusedUnopenedSentence(k) {
3491
3887
  return `${k} refused ${entryWord(k)} could not be opened with this record key. Their seals are checked.`;
@@ -3605,9 +4001,13 @@ function sealsVerdict(entries, v, queued = []) {
3605
4001
  }
3606
4002
  return { sentence: sealsPassedSentence(entries), passed: true };
3607
4003
  }
4004
+ function refusedOf(source) {
4005
+ return !source.compared && source.reason === "unreachable" ? source.refused : void 0;
4006
+ }
3608
4007
  function sourceSentence(source) {
3609
4008
  if (!source.compared) {
3610
- return source.reason === "offline" ? "Not compared with the proof layer. The check ran on this file alone." : "The proof layer could not be reached. The check ran on this file alone.";
4009
+ if (source.reason === "offline") return "Not compared with the proof layer. The check ran on this file alone.";
4010
+ return source.refused ? `The proof layer was not read: ${SOURCE_REFUSAL_REASONS[source.refused]}. The check ran on this file alone.` : "The proof layer could not be reached. The check ran on this file alone.";
3611
4011
  }
3612
4012
  return source.matches ? "Compared with the proof layer for this record: it matches." : `Compared with the proof layer for this record: it does not match.${source.detail ? ` ${source.detail}` : ""}`;
3613
4013
  }
@@ -3649,7 +4049,7 @@ function statementFingerprintOf(given, intact, fingerprint) {
3649
4049
  function heldFileField(held) {
3650
4050
  return held ? { matched: held.matched, entries: held.entries, blinded: held.blinded } : void 0;
3651
4051
  }
3652
- function buildReport(input) {
4052
+ function buildReportWithFacts(input) {
3653
4053
  const history = input.verification.history;
3654
4054
  const matched = history?.verifiedRecords ?? 0;
3655
4055
  const entries = history?.expectedRecords ?? (history ? matched : null);
@@ -3667,7 +4067,7 @@ function buildReport(input) {
3667
4067
  exportedAt: input.exportedAt
3668
4068
  };
3669
4069
  const statementFingerprint = statementFingerprintOf(input.statementFingerprint, intact, file.fingerprint);
3670
- const passed = input.verification.verified && (input.source.compared ? input.source.matches : true);
4070
+ const entriesMatch = input.verification.verified && (input.source.compared ? input.source.matches : true);
3671
4071
  const sentences = [];
3672
4072
  if (!intact) {
3673
4073
  sentences.push(FILE_CHANGED_SENTENCE);
@@ -3685,16 +4085,16 @@ function buildReport(input) {
3685
4085
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3686
4086
  if (fingerprintLine) sentences.push(fingerprintLine);
3687
4087
  if (input.heldFile) sentences.push(...heldFileSentences(input.heldFile));
3688
- const failed = !passed || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
4088
+ const failed = !entriesMatch || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3689
4089
  const unreachable = !input.source.compared && input.source.reason === "unreachable";
3690
4090
  const exitCode = exitCodeOf(unreachable, failed);
3691
4091
  if (closesWithBoundary(exitCode)) sentences.push(HONESTY_SENTENCE);
3692
- return {
4092
+ const report = {
3693
4093
  schema: REPORT_SCHEMA,
3694
4094
  checker: input.checker,
3695
4095
  ...input.form ? { form: input.form } : {},
3696
4096
  record,
3697
- passed,
4097
+ passed: exitCode === 0,
3698
4098
  file,
3699
4099
  source: input.source,
3700
4100
  dailyStatement: input.dailyStatement,
@@ -3704,8 +4104,9 @@ function buildReport(input) {
3704
4104
  sentences,
3705
4105
  exitCode
3706
4106
  };
4107
+ return { report, entriesMatch };
3707
4108
  }
3708
- function buildSealsReport(input) {
4109
+ function buildSealsReportWithFacts(input) {
3709
4110
  const v = input.verification;
3710
4111
  const failedCount = v.failedSeq.length;
3711
4112
  const record = {
@@ -3721,7 +4122,7 @@ function buildSealsReport(input) {
3721
4122
  const verdict = sealsVerdict(input.entries, v, input.queued);
3722
4123
  const disclosure = input.disclosure;
3723
4124
  const disclosureOk = !disclosure || disclosure.kind === "verified";
3724
- const passed = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
4125
+ const entriesMatch = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
3725
4126
  const sentences = [intact ? verdict.sentence : FILE_CHANGED_SENTENCE];
3726
4127
  if (disclosure?.kind === "verified") {
3727
4128
  sentences.push(revealedLine(disclosure.revealed.length, input.entries ?? disclosure.revealed.length));
@@ -3735,16 +4136,16 @@ function buildSealsReport(input) {
3735
4136
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3736
4137
  if (fingerprintLine) sentences.push(fingerprintLine);
3737
4138
  if (input.heldFile && disclosure?.kind === "verified") sentences.push(...heldFileSentences(input.heldFile));
3738
- const failed = !passed || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
4139
+ const failed = !entriesMatch || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3739
4140
  const unreachable = !input.source.compared && input.source.reason === "unreachable" || disclosure?.kind === "root-not-read";
3740
4141
  const exitCode = exitCodeOf(unreachable, failed);
3741
4142
  if (closesWithBoundary(exitCode)) sentences.push(SEALS_BOUNDARY_SENTENCE);
3742
- return {
4143
+ const report = {
3743
4144
  schema: REPORT_SCHEMA,
3744
4145
  checker: input.checker,
3745
4146
  form: input.form,
3746
4147
  record,
3747
- passed,
4148
+ passed: exitCode === 0,
3748
4149
  file,
3749
4150
  source: input.source,
3750
4151
  dailyStatement: null,
@@ -3755,6 +4156,7 @@ function buildSealsReport(input) {
3755
4156
  sentences,
3756
4157
  exitCode
3757
4158
  };
4159
+ return { report, entriesMatch };
3758
4160
  }
3759
4161
  var WRITES_HEADING = "Where each entry was committed on the proof layer:";
3760
4162
  var WRITES_NOT_READ_SENTENCE = "Where each entry was committed could not be read from the proof layer this time. The check above does not depend on it.";
@@ -3816,7 +4218,7 @@ function renderReport(report, options = {}) {
3816
4218
  var WRITES_LOOKUP_MAX_REQUESTS = 40;
3817
4219
  var WRITES_LOOKUP_DEFAULT_BUDGET_MS = 1e4;
3818
4220
  var HEX643 = /^0x[0-9a-f]{64}$/;
3819
- var HEX40 = /^0x[0-9a-f]{40}$/;
4221
+ var HEX402 = /^0x[0-9a-f]{40}$/;
3820
4222
  var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
3821
4223
  var WRITE_EXPLORERS = Object.freeze({
3822
4224
  295: "https://hashscan.io/mainnet/transaction/",
@@ -3866,7 +4268,7 @@ async function within(p, ms) {
3866
4268
  async function lookUpWrites(input) {
3867
4269
  try {
3868
4270
  const contractAddress = String(input.contractAddress ?? "").toLowerCase();
3869
- if (!HEX40.test(contractAddress)) return { read: false, reason: "unreachable" };
4271
+ if (!HEX402.test(contractAddress)) return { read: false, reason: "unreachable" };
3870
4272
  if (input.wanted.length === 0) return { read: true, entries: [], notFound: [] };
3871
4273
  const done = (writes2) => input.wanted.every((entry) => hitsFor(entry, writes2, contractAddress).length > 0);
3872
4274
  let writes;
@@ -3925,7 +4327,7 @@ async function lookUpWrites(input) {
3925
4327
 
3926
4328
  // src/check.ts
3927
4329
  var CHECKER_NAME = "@pacspace-io/check";
3928
- var CHECKER_VERSION = true ? "0.5.4" : "0.0.0-dev";
4330
+ var CHECKER_VERSION = true ? "0.5.6" : "0.0.0-dev";
3929
4331
  var HISTORY_SCHEMAS = [
3930
4332
  RECORD_HISTORY_BUNDLE_SCHEMA_V1,
3931
4333
  RECORD_HISTORY_BUNDLE_SCHEMA_V2,
@@ -4037,8 +4439,9 @@ function readerFor(chain, options) {
4037
4439
  readsFrom: mirrorBaseUrl
4038
4440
  };
4039
4441
  }
4040
- async function withWrites(report, bundle, verification, reader, options) {
4041
- if (!options.writes || !reader || !report.passed || !report.file.intact || !report.source.compared || !report.source.matches) return report;
4442
+ async function withWrites(checked, bundle, verification, reader, options) {
4443
+ const { report } = checked;
4444
+ if (!options.writes || !reader || !checked.entriesMatch || !report.file.intact || !report.source.compared || !report.source.matches) return checked;
4042
4445
  let writes;
4043
4446
  try {
4044
4447
  const source = options.source ?? "mirror";
@@ -4058,7 +4461,7 @@ async function withWrites(report, bundle, verification, reader, options) {
4058
4461
  } catch {
4059
4462
  writes = { read: false, reason: "unreachable" };
4060
4463
  }
4061
- return { ...report, writes };
4464
+ return { ...checked, report: { ...report, writes } };
4062
4465
  }
4063
4466
  var PAYLOAD_POINTER = /^\/payloads\/(0|[1-9][0-9]*)$/;
4064
4467
  function disclosureNamesAFile(disclosure) {
@@ -4089,6 +4492,9 @@ function refuseLayoutNotRead(result) {
4089
4492
  if (result.code === RECORDS_LAYOUT_NOT_READ) throw new HistoryFileError(RECORDS_LAYOUT_NOT_READ_SENTENCE);
4090
4493
  }
4091
4494
  async function checkHistory(file, options = {}) {
4495
+ return (await checkHistoryWithFacts(file, options)).report;
4496
+ }
4497
+ async function checkHistoryWithFacts(file, options = {}) {
4092
4498
  if (options.source === "offline" && needsLedgerRoots(file)) throw new HistoryFileError(DISCLOSURE_OFFLINE_SENTENCE);
4093
4499
  if (options.heldFile && !revealsFileFingerprint(file)) throw new HistoryFileError(NOTHING_REVEALED_SENTENCE);
4094
4500
  if (options.recordKey && file.schema !== RECORD_HISTORY_BUNDLE_SCHEMA_V3) throw new HistoryFileError(KEY_ONLY_FOR_ENCRYPTED_SENTENCE);
@@ -4213,7 +4619,7 @@ async function checkBundle(file, options) {
4213
4619
  };
4214
4620
  const heldOf = (verification2, offlineRun) => options.heldFile ? heldFileOutcome(options.heldFile, verifiedPayloads(file, verification2), offlineRun) : null;
4215
4621
  if (options.source === "offline" || !offline.schemaOk || !offline.digestOk) {
4216
- return buildReport({
4622
+ return buildReportWithFacts({
4217
4623
  ...base,
4218
4624
  verification: offline,
4219
4625
  source: { compared: false, reason: "offline" },
@@ -4247,9 +4653,9 @@ async function checkBundle(file, options) {
4247
4653
  };
4248
4654
  } catch (error) {
4249
4655
  if (error instanceof HistoryFileError) throw error;
4250
- source = { compared: false, reason: "unreachable", detail: error.message };
4656
+ source = notReached(error);
4251
4657
  }
4252
- const report = buildReport({
4658
+ const report = buildReportWithFacts({
4253
4659
  ...base,
4254
4660
  verification,
4255
4661
  source,
@@ -4299,7 +4705,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4299
4705
  const refused = (refusal) => {
4300
4706
  refuseLayoutNotRead(refusal);
4301
4707
  if (refusal.code === "RECORD_HISTORY_DIGEST") {
4302
- return buildReport({
4708
+ return buildReportWithFacts({
4303
4709
  ...base,
4304
4710
  verification: { verified: false, digestOk: false, reason: "", history: null },
4305
4711
  source: { compared: false, reason: "offline" },
@@ -4308,7 +4714,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4308
4714
  }
4309
4715
  const sentence = encryptedRefusalSentence(refusal);
4310
4716
  if (sentence === null) throw new HistoryFileError(notThisForm);
4311
- return buildReport({
4717
+ return buildReportWithFacts({
4312
4718
  ...base,
4313
4719
  verification: { verified: false, digestOk: true, reason: sentence, history: null },
4314
4720
  source: { compared: false, reason: "offline" },
@@ -4325,7 +4731,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4325
4731
  if (!offline.ok) return refused(offline);
4326
4732
  const encrypted = { refusedUnopened: offline.refused.filter((r) => !r.opened).length };
4327
4733
  if (options.source === "offline" || !offline.verification.schemaOk || !offline.verification.digestOk) {
4328
- return buildReport({
4734
+ return buildReportWithFacts({
4329
4735
  ...base,
4330
4736
  verification: offline.verification,
4331
4737
  source: { compared: false, reason: "offline" },
@@ -4370,9 +4776,9 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4370
4776
  };
4371
4777
  } catch (error) {
4372
4778
  if (error instanceof HistoryFileError) throw error;
4373
- source = { compared: false, reason: "unreachable", detail: error.message };
4779
+ source = notReached(error);
4374
4780
  }
4375
- const report = buildReport({
4781
+ const report = buildReportWithFacts({
4376
4782
  ...base,
4377
4783
  verification: result.verification,
4378
4784
  source,
@@ -4403,18 +4809,30 @@ function ledgerAgrees(form, material) {
4403
4809
  }
4404
4810
  function answeringReader(reader) {
4405
4811
  const answered = /* @__PURE__ */ new Set();
4812
+ let refused;
4406
4813
  return {
4407
4814
  answered,
4815
+ // The first refusal of the source's answer, when a root was not read for that and not for want of an answer.
4816
+ refused: () => refused,
4408
4817
  reader: {
4409
4818
  ...reader,
4410
4819
  getBatchRoot: async (batchId) => {
4411
- const root = await reader.getBatchRoot(batchId);
4412
- answered.add(String(batchId));
4413
- return root;
4820
+ try {
4821
+ const root = await reader.getBatchRoot(batchId);
4822
+ answered.add(String(batchId));
4823
+ return root;
4824
+ } catch (error) {
4825
+ refused ??= mirrorRefusalOf(error) ?? void 0;
4826
+ throw error;
4827
+ }
4414
4828
  }
4415
4829
  }
4416
4830
  };
4417
4831
  }
4832
+ function notReached(error) {
4833
+ const refused = mirrorRefusalOf(error);
4834
+ return { compared: false, reason: "unreachable", detail: error.message, ...refused ? { refused } : {} };
4835
+ }
4418
4836
  var pointerToken = (name) => name.replace(/~/g, "~0").replace(/\//g, "~1");
4419
4837
  async function checkDisclosure(form, disclosure, reader, onRevealed) {
4420
4838
  const sub = disclosureFormOfV1(form, disclosure);
@@ -4465,7 +4883,7 @@ async function checkSeals(formName, form, disclosure, options) {
4465
4883
  };
4466
4884
  const entries = entryCountOf(form, layouts);
4467
4885
  if (options.source === "offline" || !verification.schemaOk || !verification.digestOk) {
4468
- return buildSealsReport({
4886
+ return buildSealsReportWithFacts({
4469
4887
  ...base,
4470
4888
  entries,
4471
4889
  verification,
@@ -4495,7 +4913,7 @@ async function checkSeals(formName, form, disclosure, options) {
4495
4913
  };
4496
4914
  } catch (error) {
4497
4915
  if (error instanceof HistoryFileError) throw error;
4498
- source = { compared: false, reason: "unreachable", detail: error.message };
4916
+ source = notReached(error);
4499
4917
  reader = null;
4500
4918
  }
4501
4919
  let disclosureOutcome = null;
@@ -4503,7 +4921,7 @@ async function checkSeals(formName, form, disclosure, options) {
4503
4921
  disclosureOutcome = verification.verified ? await checkDisclosure(form, disclosure, reader, options.onRevealed) : { kind: "not-checked" };
4504
4922
  }
4505
4923
  const held = options.heldFile ? heldFileOutcome(options.heldFile, disclosureOutcome?.kind === "verified" ? disclosureOutcome.payloads : [], false) : null;
4506
- return buildSealsReport({
4924
+ return buildSealsReportWithFacts({
4507
4925
  ...base,
4508
4926
  entries,
4509
4927
  verification,
@@ -4862,6 +5280,7 @@ var releaseWords = {
4862
5280
  notProductionRecord: "The ledger record here is not the production release record.",
4863
5281
  inProgress: (served, latest) => `The host serves ${served}; the release record's latest entry is ${latest}. A release may be in progress; run it again in a few minutes.`,
4864
5282
  unreachable: (origin) => `Couldn't reach ${origin} or the ledger. Nothing was checked.`,
5283
+ refused: (code) => `The ledger was not read: ${SOURCE_REFUSAL_REASONS[code]}. Nothing was checked.`,
4865
5284
  total: (n) => n === 1 ? "1 difference from the release record." : `${n} differences from the release record.`
4866
5285
  };
4867
5286
  var ReleaseUsageError = class extends Error {
@@ -4995,11 +5414,12 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4995
5414
  files: 0,
4996
5415
  differences: []
4997
5416
  };
4998
- const unreachable = () => ({
5417
+ const unreachable = (refused) => ({
4999
5418
  ...base,
5000
5419
  outcome: "unreachable",
5001
- sentences: [releaseWords.unreachable(origin)],
5002
- exitCode: 2
5420
+ sentences: [refused ? releaseWords.refused(refused) : releaseWords.unreachable(origin)],
5421
+ exitCode: 2,
5422
+ ...refused ? { refused } : {}
5003
5423
  });
5004
5424
  const differs = (differences, extra = {}) => ({
5005
5425
  ...base,
@@ -5040,21 +5460,22 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
5040
5460
  }
5041
5461
  base.commit = manifest.commit;
5042
5462
  let report;
5463
+ let entriesMatch;
5043
5464
  try {
5044
- report = await checkHistory(history, {
5465
+ ({ report, entriesMatch } = await checkHistoryWithFacts(history, {
5045
5466
  source: source ?? "mirror",
5046
5467
  timeoutMs,
5047
5468
  fetchImpl,
5048
5469
  heldFile: { sha256: await sha256Hex(manifestRead.bytes), byteLength: String(manifestRead.bytes.length) }
5049
- });
5470
+ }));
5050
5471
  } catch (error) {
5051
5472
  if (error instanceof HistoryFileError) return differs([{ kind: "differs", path: historyPath }]);
5052
5473
  throw error;
5053
5474
  }
5054
5475
  if (report.exitCode === 3 || report.source.compared === false && report.source.reason === "unreachable") {
5055
- return unreachable();
5476
+ return unreachable(refusedOf(report.source));
5056
5477
  }
5057
- if (!report.passed) return differs([{ kind: "differs", path: historyPath }]);
5478
+ if (!entriesMatch) return differs([{ kind: "differs", path: historyPath }]);
5058
5479
  const latest = report.record.entries;
5059
5480
  base.latestEntry = latest;
5060
5481
  const matched = report.heldFile?.entries ?? [];