@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/index.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));
2120
2198
  }
2121
- function nextLedgerWritePath(next) {
2122
- return typeof next === "string" && NEXT_PATH.test(next) ? next : null;
2199
+ function contractLogPath(contractAddress) {
2200
+ return `/api/v1/contracts/${contractAddress}/results/logs`;
2201
+ }
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((resolve) => {
@@ -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((resolve) => setTimeout(resolve, 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;
@@ -3339,6 +3727,14 @@ var SEP5 = new Uint8Array([0]);
3339
3727
 
3340
3728
  // src/report.ts
3341
3729
  var REPORT_SCHEMA = "pacspace-check-report/v1";
3730
+ var SOURCE_REFUSAL_REASONS = {
3731
+ redirect: "its source answered with a redirect, which is not followed",
3732
+ "too-large": "its source gave an answer larger than this checker reads",
3733
+ "too-many-logs": "its source returned a longer page than was asked for",
3734
+ "next-page": "its source pointed somewhere else for the next page",
3735
+ "too-slow": "its source did not finish answering in the time allowed",
3736
+ "too-long": "it holds more than this checker reads in one run"
3737
+ };
3342
3738
  var ENCRYPTED_OPENED_SENTENCE = "Each entry was opened on this machine and matches its sealed record hash.";
3343
3739
  function refusedUnopenedSentence(k) {
3344
3740
  return `${k} refused ${entryWord(k)} could not be opened with this record key. Their seals are checked.`;
@@ -3457,9 +3853,13 @@ function sealsVerdict(entries, v, queued = []) {
3457
3853
  }
3458
3854
  return { sentence: sealsPassedSentence(entries), passed: true };
3459
3855
  }
3856
+ function refusedOf(source) {
3857
+ return !source.compared && source.reason === "unreachable" ? source.refused : void 0;
3858
+ }
3460
3859
  function sourceSentence(source) {
3461
3860
  if (!source.compared) {
3462
- 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.";
3861
+ if (source.reason === "offline") return "Not compared with the proof layer. The check ran on this file alone.";
3862
+ 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.";
3463
3863
  }
3464
3864
  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}` : ""}`;
3465
3865
  }
@@ -3502,6 +3902,9 @@ function heldFileField(held) {
3502
3902
  return held ? { matched: held.matched, entries: held.entries, blinded: held.blinded } : void 0;
3503
3903
  }
3504
3904
  function buildReport(input) {
3905
+ return buildReportWithFacts(input).report;
3906
+ }
3907
+ function buildReportWithFacts(input) {
3505
3908
  const history = input.verification.history;
3506
3909
  const matched = history?.verifiedRecords ?? 0;
3507
3910
  const entries = history?.expectedRecords ?? (history ? matched : null);
@@ -3519,7 +3922,7 @@ function buildReport(input) {
3519
3922
  exportedAt: input.exportedAt
3520
3923
  };
3521
3924
  const statementFingerprint = statementFingerprintOf(input.statementFingerprint, intact, file.fingerprint);
3522
- const passed = input.verification.verified && (input.source.compared ? input.source.matches : true);
3925
+ const entriesMatch = input.verification.verified && (input.source.compared ? input.source.matches : true);
3523
3926
  const sentences = [];
3524
3927
  if (!intact) {
3525
3928
  sentences.push(FILE_CHANGED_SENTENCE);
@@ -3537,16 +3940,16 @@ function buildReport(input) {
3537
3940
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3538
3941
  if (fingerprintLine) sentences.push(fingerprintLine);
3539
3942
  if (input.heldFile) sentences.push(...heldFileSentences(input.heldFile));
3540
- const failed = !passed || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3943
+ const failed = !entriesMatch || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3541
3944
  const unreachable = !input.source.compared && input.source.reason === "unreachable";
3542
3945
  const exitCode = exitCodeOf(unreachable, failed);
3543
3946
  if (closesWithBoundary(exitCode)) sentences.push(HONESTY_SENTENCE);
3544
- return {
3947
+ const report = {
3545
3948
  schema: REPORT_SCHEMA,
3546
3949
  checker: input.checker,
3547
3950
  ...input.form ? { form: input.form } : {},
3548
3951
  record,
3549
- passed,
3952
+ passed: exitCode === 0,
3550
3953
  file,
3551
3954
  source: input.source,
3552
3955
  dailyStatement: input.dailyStatement,
@@ -3556,8 +3959,12 @@ function buildReport(input) {
3556
3959
  sentences,
3557
3960
  exitCode
3558
3961
  };
3962
+ return { report, entriesMatch };
3559
3963
  }
3560
3964
  function buildSealsReport(input) {
3965
+ return buildSealsReportWithFacts(input).report;
3966
+ }
3967
+ function buildSealsReportWithFacts(input) {
3561
3968
  const v = input.verification;
3562
3969
  const failedCount = v.failedSeq.length;
3563
3970
  const record = {
@@ -3573,7 +3980,7 @@ function buildSealsReport(input) {
3573
3980
  const verdict = sealsVerdict(input.entries, v, input.queued);
3574
3981
  const disclosure = input.disclosure;
3575
3982
  const disclosureOk = !disclosure || disclosure.kind === "verified";
3576
- const passed = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
3983
+ const entriesMatch = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
3577
3984
  const sentences = [intact ? verdict.sentence : FILE_CHANGED_SENTENCE];
3578
3985
  if (disclosure?.kind === "verified") {
3579
3986
  sentences.push(revealedLine(disclosure.revealed.length, input.entries ?? disclosure.revealed.length));
@@ -3587,16 +3994,16 @@ function buildSealsReport(input) {
3587
3994
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3588
3995
  if (fingerprintLine) sentences.push(fingerprintLine);
3589
3996
  if (input.heldFile && disclosure?.kind === "verified") sentences.push(...heldFileSentences(input.heldFile));
3590
- const failed = !passed || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3997
+ const failed = !entriesMatch || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3591
3998
  const unreachable = !input.source.compared && input.source.reason === "unreachable" || disclosure?.kind === "root-not-read";
3592
3999
  const exitCode = exitCodeOf(unreachable, failed);
3593
4000
  if (closesWithBoundary(exitCode)) sentences.push(SEALS_BOUNDARY_SENTENCE);
3594
- return {
4001
+ const report = {
3595
4002
  schema: REPORT_SCHEMA,
3596
4003
  checker: input.checker,
3597
4004
  form: input.form,
3598
4005
  record,
3599
- passed,
4006
+ passed: exitCode === 0,
3600
4007
  file,
3601
4008
  source: input.source,
3602
4009
  dailyStatement: null,
@@ -3607,6 +4014,7 @@ function buildSealsReport(input) {
3607
4014
  sentences,
3608
4015
  exitCode
3609
4016
  };
4017
+ return { report, entriesMatch };
3610
4018
  }
3611
4019
  var WRITES_HEADING = "Where each entry was committed on the proof layer:";
3612
4020
  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.";
@@ -3668,7 +4076,7 @@ function renderReport(report, options = {}) {
3668
4076
  var WRITES_LOOKUP_MAX_REQUESTS = 40;
3669
4077
  var WRITES_LOOKUP_DEFAULT_BUDGET_MS = 1e4;
3670
4078
  var HEX643 = /^0x[0-9a-f]{64}$/;
3671
- var HEX40 = /^0x[0-9a-f]{40}$/;
4079
+ var HEX402 = /^0x[0-9a-f]{40}$/;
3672
4080
  var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
3673
4081
  var WRITE_EXPLORERS = Object.freeze({
3674
4082
  295: "https://hashscan.io/mainnet/transaction/",
@@ -3718,7 +4126,7 @@ async function within(p, ms) {
3718
4126
  async function lookUpWrites(input) {
3719
4127
  try {
3720
4128
  const contractAddress = String(input.contractAddress ?? "").toLowerCase();
3721
- if (!HEX40.test(contractAddress)) return { read: false, reason: "unreachable" };
4129
+ if (!HEX402.test(contractAddress)) return { read: false, reason: "unreachable" };
3722
4130
  if (input.wanted.length === 0) return { read: true, entries: [], notFound: [] };
3723
4131
  const done = (writes2) => input.wanted.every((entry) => hitsFor(entry, writes2, contractAddress).length > 0);
3724
4132
  let writes;
@@ -3777,7 +4185,7 @@ async function lookUpWrites(input) {
3777
4185
 
3778
4186
  // src/check.ts
3779
4187
  var CHECKER_NAME = "@pacspace-io/check";
3780
- var CHECKER_VERSION = true ? "0.5.4" : "0.0.0-dev";
4188
+ var CHECKER_VERSION = true ? "0.5.6" : "0.0.0-dev";
3781
4189
  var HISTORY_SCHEMAS = [
3782
4190
  RECORD_HISTORY_BUNDLE_SCHEMA_V1,
3783
4191
  RECORD_HISTORY_BUNDLE_SCHEMA_V2,
@@ -3889,8 +4297,9 @@ function readerFor(chain, options) {
3889
4297
  readsFrom: mirrorBaseUrl
3890
4298
  };
3891
4299
  }
3892
- async function withWrites(report, bundle, verification, reader, options) {
3893
- if (!options.writes || !reader || !report.passed || !report.file.intact || !report.source.compared || !report.source.matches) return report;
4300
+ async function withWrites(checked, bundle, verification, reader, options) {
4301
+ const { report } = checked;
4302
+ if (!options.writes || !reader || !checked.entriesMatch || !report.file.intact || !report.source.compared || !report.source.matches) return checked;
3894
4303
  let writes;
3895
4304
  try {
3896
4305
  const source = options.source ?? "mirror";
@@ -3910,7 +4319,7 @@ async function withWrites(report, bundle, verification, reader, options) {
3910
4319
  } catch {
3911
4320
  writes = { read: false, reason: "unreachable" };
3912
4321
  }
3913
- return { ...report, writes };
4322
+ return { ...checked, report: { ...report, writes } };
3914
4323
  }
3915
4324
  var PAYLOAD_POINTER = /^\/payloads\/(0|[1-9][0-9]*)$/;
3916
4325
  function disclosureNamesAFile(disclosure) {
@@ -3941,6 +4350,9 @@ function refuseLayoutNotRead(result) {
3941
4350
  if (result.code === RECORDS_LAYOUT_NOT_READ) throw new HistoryFileError(RECORDS_LAYOUT_NOT_READ_SENTENCE);
3942
4351
  }
3943
4352
  async function checkHistory(file, options = {}) {
4353
+ return (await checkHistoryWithFacts(file, options)).report;
4354
+ }
4355
+ async function checkHistoryWithFacts(file, options = {}) {
3944
4356
  if (options.source === "offline" && needsLedgerRoots(file)) throw new HistoryFileError(DISCLOSURE_OFFLINE_SENTENCE);
3945
4357
  if (options.heldFile && !revealsFileFingerprint(file)) throw new HistoryFileError(NOTHING_REVEALED_SENTENCE);
3946
4358
  if (options.recordKey && file.schema !== RECORD_HISTORY_BUNDLE_SCHEMA_V3) throw new HistoryFileError(KEY_ONLY_FOR_ENCRYPTED_SENTENCE);
@@ -4065,7 +4477,7 @@ async function checkBundle(file, options) {
4065
4477
  };
4066
4478
  const heldOf = (verification2, offlineRun) => options.heldFile ? heldFileOutcome(options.heldFile, verifiedPayloads(file, verification2), offlineRun) : null;
4067
4479
  if (options.source === "offline" || !offline.schemaOk || !offline.digestOk) {
4068
- return buildReport({
4480
+ return buildReportWithFacts({
4069
4481
  ...base,
4070
4482
  verification: offline,
4071
4483
  source: { compared: false, reason: "offline" },
@@ -4099,9 +4511,9 @@ async function checkBundle(file, options) {
4099
4511
  };
4100
4512
  } catch (error) {
4101
4513
  if (error instanceof HistoryFileError) throw error;
4102
- source = { compared: false, reason: "unreachable", detail: error.message };
4514
+ source = notReached(error);
4103
4515
  }
4104
- const report = buildReport({
4516
+ const report = buildReportWithFacts({
4105
4517
  ...base,
4106
4518
  verification,
4107
4519
  source,
@@ -4151,7 +4563,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4151
4563
  const refused = (refusal) => {
4152
4564
  refuseLayoutNotRead(refusal);
4153
4565
  if (refusal.code === "RECORD_HISTORY_DIGEST") {
4154
- return buildReport({
4566
+ return buildReportWithFacts({
4155
4567
  ...base,
4156
4568
  verification: { verified: false, digestOk: false, reason: "", history: null },
4157
4569
  source: { compared: false, reason: "offline" },
@@ -4160,7 +4572,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4160
4572
  }
4161
4573
  const sentence = encryptedRefusalSentence(refusal);
4162
4574
  if (sentence === null) throw new HistoryFileError(notThisForm);
4163
- return buildReport({
4575
+ return buildReportWithFacts({
4164
4576
  ...base,
4165
4577
  verification: { verified: false, digestOk: true, reason: sentence, history: null },
4166
4578
  source: { compared: false, reason: "offline" },
@@ -4177,7 +4589,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4177
4589
  if (!offline.ok) return refused(offline);
4178
4590
  const encrypted = { refusedUnopened: offline.refused.filter((r) => !r.opened).length };
4179
4591
  if (options.source === "offline" || !offline.verification.schemaOk || !offline.verification.digestOk) {
4180
- return buildReport({
4592
+ return buildReportWithFacts({
4181
4593
  ...base,
4182
4594
  verification: offline.verification,
4183
4595
  source: { compared: false, reason: "offline" },
@@ -4222,9 +4634,9 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4222
4634
  };
4223
4635
  } catch (error) {
4224
4636
  if (error instanceof HistoryFileError) throw error;
4225
- source = { compared: false, reason: "unreachable", detail: error.message };
4637
+ source = notReached(error);
4226
4638
  }
4227
- const report = buildReport({
4639
+ const report = buildReportWithFacts({
4228
4640
  ...base,
4229
4641
  verification: result.verification,
4230
4642
  source,
@@ -4255,18 +4667,30 @@ function ledgerAgrees(form, material) {
4255
4667
  }
4256
4668
  function answeringReader(reader) {
4257
4669
  const answered = /* @__PURE__ */ new Set();
4670
+ let refused;
4258
4671
  return {
4259
4672
  answered,
4673
+ // The first refusal of the source's answer, when a root was not read for that and not for want of an answer.
4674
+ refused: () => refused,
4260
4675
  reader: {
4261
4676
  ...reader,
4262
4677
  getBatchRoot: async (batchId) => {
4263
- const root = await reader.getBatchRoot(batchId);
4264
- answered.add(String(batchId));
4265
- return root;
4678
+ try {
4679
+ const root = await reader.getBatchRoot(batchId);
4680
+ answered.add(String(batchId));
4681
+ return root;
4682
+ } catch (error) {
4683
+ refused ??= mirrorRefusalOf(error) ?? void 0;
4684
+ throw error;
4685
+ }
4266
4686
  }
4267
4687
  }
4268
4688
  };
4269
4689
  }
4690
+ function notReached(error) {
4691
+ const refused = mirrorRefusalOf(error);
4692
+ return { compared: false, reason: "unreachable", detail: error.message, ...refused ? { refused } : {} };
4693
+ }
4270
4694
  var pointerToken = (name) => name.replace(/~/g, "~0").replace(/\//g, "~1");
4271
4695
  async function checkDisclosure(form, disclosure, reader, onRevealed) {
4272
4696
  const sub = disclosureFormOfV1(form, disclosure);
@@ -4317,7 +4741,7 @@ async function checkSeals(formName, form, disclosure, options) {
4317
4741
  };
4318
4742
  const entries = entryCountOf(form, layouts);
4319
4743
  if (options.source === "offline" || !verification.schemaOk || !verification.digestOk) {
4320
- return buildSealsReport({
4744
+ return buildSealsReportWithFacts({
4321
4745
  ...base,
4322
4746
  entries,
4323
4747
  verification,
@@ -4347,7 +4771,7 @@ async function checkSeals(formName, form, disclosure, options) {
4347
4771
  };
4348
4772
  } catch (error) {
4349
4773
  if (error instanceof HistoryFileError) throw error;
4350
- source = { compared: false, reason: "unreachable", detail: error.message };
4774
+ source = notReached(error);
4351
4775
  reader = null;
4352
4776
  }
4353
4777
  let disclosureOutcome = null;
@@ -4355,7 +4779,7 @@ async function checkSeals(formName, form, disclosure, options) {
4355
4779
  disclosureOutcome = verification.verified ? await checkDisclosure(form, disclosure, reader, options.onRevealed) : { kind: "not-checked" };
4356
4780
  }
4357
4781
  const held = options.heldFile ? heldFileOutcome(options.heldFile, disclosureOutcome?.kind === "verified" ? disclosureOutcome.payloads : [], false) : null;
4358
- return buildSealsReport({
4782
+ return buildSealsReportWithFacts({
4359
4783
  ...base,
4360
4784
  entries,
4361
4785
  verification,
@@ -4393,6 +4817,7 @@ var releaseWords = {
4393
4817
  notProductionRecord: "The ledger record here is not the production release record.",
4394
4818
  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.`,
4395
4819
  unreachable: (origin) => `Couldn't reach ${origin} or the ledger. Nothing was checked.`,
4820
+ refused: (code) => `The ledger was not read: ${SOURCE_REFUSAL_REASONS[code]}. Nothing was checked.`,
4396
4821
  total: (n) => n === 1 ? "1 difference from the release record." : `${n} differences from the release record.`
4397
4822
  };
4398
4823
  var ReleaseUsageError = class extends Error {
@@ -4526,11 +4951,12 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4526
4951
  files: 0,
4527
4952
  differences: []
4528
4953
  };
4529
- const unreachable = () => ({
4954
+ const unreachable = (refused) => ({
4530
4955
  ...base,
4531
4956
  outcome: "unreachable",
4532
- sentences: [releaseWords.unreachable(origin)],
4533
- exitCode: 2
4957
+ sentences: [refused ? releaseWords.refused(refused) : releaseWords.unreachable(origin)],
4958
+ exitCode: 2,
4959
+ ...refused ? { refused } : {}
4534
4960
  });
4535
4961
  const differs = (differences, extra = {}) => ({
4536
4962
  ...base,
@@ -4571,21 +4997,22 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4571
4997
  }
4572
4998
  base.commit = manifest.commit;
4573
4999
  let report;
5000
+ let entriesMatch;
4574
5001
  try {
4575
- report = await checkHistory(history, {
5002
+ ({ report, entriesMatch } = await checkHistoryWithFacts(history, {
4576
5003
  source: source ?? "mirror",
4577
5004
  timeoutMs,
4578
5005
  fetchImpl,
4579
5006
  heldFile: { sha256: await sha256Hex(manifestRead.bytes), byteLength: String(manifestRead.bytes.length) }
4580
- });
5007
+ }));
4581
5008
  } catch (error) {
4582
5009
  if (error instanceof HistoryFileError) return differs([{ kind: "differs", path: historyPath }]);
4583
5010
  throw error;
4584
5011
  }
4585
5012
  if (report.exitCode === 3 || report.source.compared === false && report.source.reason === "unreachable") {
4586
- return unreachable();
5013
+ return unreachable(refusedOf(report.source));
4587
5014
  }
4588
- if (!report.passed) return differs([{ kind: "differs", path: historyPath }]);
5015
+ if (!entriesMatch) return differs([{ kind: "differs", path: historyPath }]);
4589
5016
  const latest = report.record.entries;
4590
5017
  base.latestEntry = latest;
4591
5018
  const matched = report.heldFile?.entries ?? [];