@pacspace-io/check 0.5.3 → 0.5.5

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
@@ -2108,6 +2108,150 @@ var MIRROR_NODE_BY_CHAIN = Object.freeze({
2108
2108
  295: "https://mainnet-public.mirrornode.hedera.com"
2109
2109
  });
2110
2110
 
2111
+ // ../shared/src/records/ledger-write-search-v1.ts
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}$/;
2116
+ var HEX642 = /^0x[0-9a-f]{64}$/;
2117
+ var HEX_DATA = /^0x[0-9a-f]*$/;
2118
+ var TIMESTAMP = /^\d+(\.\d+)?$/;
2119
+ var REFUSAL_CODES = ["redirect", "too-large", "too-many-logs", "next-page"];
2120
+ var MirrorAnswerRefused = class extends Error {
2121
+ constructor(code, message) {
2122
+ super(message);
2123
+ this.name = "MirrorAnswerRefused";
2124
+ this.code = code;
2125
+ }
2126
+ };
2127
+ function mirrorRefusalOf(error) {
2128
+ if (!error || typeof error !== "object") return null;
2129
+ const { name, code } = error;
2130
+ return name === "MirrorAnswerRefused" && typeof code === "string" && REFUSAL_CODES.includes(code) ? code : null;
2131
+ }
2132
+ function pathLabel(path) {
2133
+ return path ? ` (${path.split("?")[0]})` : "";
2134
+ }
2135
+ var mirrorRefusal = {
2136
+ redirect: (path) => new MirrorAnswerRefused("redirect", `mirror node answered with a redirect, which is not followed${pathLabel(path)}`),
2137
+ tooLarge: (maxBytes, path) => new MirrorAnswerRefused("too-large", `mirror node answer is larger than ${maxBytes} bytes${pathLabel(path)}`),
2138
+ tooManyLogs: (asked, path) => new MirrorAnswerRefused("too-many-logs", `mirror node returned more logs than the ${asked} asked for${pathLabel(path)}`),
2139
+ nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log")
2140
+ };
2141
+ function isMirrorRedirect(response) {
2142
+ return response.redirected === true || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400;
2143
+ }
2144
+ async function readMirrorText(response, maxBytes = MIRROR_ANSWER_MAX_BYTES, path) {
2145
+ const declared = Number(response.headers?.get?.("content-length") ?? Number.NaN);
2146
+ const body = response.body;
2147
+ if (Number.isFinite(declared) && declared > maxBytes) {
2148
+ await body?.cancel?.().catch(() => void 0);
2149
+ throw mirrorRefusal.tooLarge(maxBytes, path);
2150
+ }
2151
+ if (body && typeof body.getReader === "function") {
2152
+ const reader = body.getReader();
2153
+ const decoder = new TextDecoder();
2154
+ let text2 = "";
2155
+ let read = 0;
2156
+ for (; ; ) {
2157
+ const { done, value } = await reader.read();
2158
+ if (done) break;
2159
+ read += value.byteLength;
2160
+ if (read > maxBytes) {
2161
+ await reader.cancel().catch(() => void 0);
2162
+ throw mirrorRefusal.tooLarge(maxBytes, path);
2163
+ }
2164
+ text2 += decoder.decode(value, { stream: true });
2165
+ }
2166
+ return text2 + decoder.decode();
2167
+ }
2168
+ const text = await response.text();
2169
+ if (new TextEncoder().encode(text).byteLength > maxBytes) throw mirrorRefusal.tooLarge(maxBytes, path);
2170
+ return text;
2171
+ }
2172
+ async function readMirrorJson(response, maxBytes = MIRROR_ANSWER_MAX_BYTES, path) {
2173
+ return JSON.parse(await readMirrorText(response, maxBytes, path));
2174
+ }
2175
+ function contractLogPath(contractAddress) {
2176
+ return `/api/v1/contracts/${contractAddress}/results/logs`;
2177
+ }
2178
+ function ledgerWriteSearchPath(input) {
2179
+ const query = `topic0=${input.topic0}&topic1=${input.recordKey}&timestamp=gte:${input.lower}&timestamp=lt:${input.upper}&order=desc&limit=${LEDGER_WRITE_SEARCH_PAGE_LIMIT}`;
2180
+ return `${contractLogPath(input.contractAddress)}?${query}`;
2181
+ }
2182
+ function nextLogPath(next, source) {
2183
+ if (typeof next !== "string" || next === "") return null;
2184
+ const contract = source.contract.toLowerCase();
2185
+ if (!HEX40.test(contract)) return null;
2186
+ if (!/^[\x21-\x5b\x5d-\x7e]+$/.test(next)) return null;
2187
+ if (next.startsWith("//")) return null;
2188
+ let base;
2189
+ let url;
2190
+ try {
2191
+ base = new URL(source.base);
2192
+ url = new URL(next, `${base.origin}/`);
2193
+ } catch {
2194
+ return null;
2195
+ }
2196
+ if (base.protocol !== "https:" && base.protocol !== "http:") return null;
2197
+ if (url.origin !== base.origin || url.username !== "" || url.password !== "" || url.hash !== "" || next.includes("#")) return null;
2198
+ const written = (next.startsWith("/") ? next : next.slice(next.indexOf("/", next.indexOf("//") + 2))).split("?")[0];
2199
+ if (/(^|\/)\.{1,2}(\/|$)/.test(written) || /%2e/i.test(written) || written !== url.pathname) return null;
2200
+ if (url.search.length < 2) return null;
2201
+ const logs = contractLogPath(contract);
2202
+ const prefix = base.pathname.replace(/\/+$/, "");
2203
+ const path = url.pathname.toLowerCase();
2204
+ if (path !== logs && !(prefix !== "" && url.pathname.startsWith(`${prefix}/`) && url.pathname.slice(prefix.length).toLowerCase() === logs)) return null;
2205
+ return `${logs}${url.search}`;
2206
+ }
2207
+ function withLogPageLimit(path, limit) {
2208
+ const at = path.indexOf("?");
2209
+ const before = at === -1 ? path : path.slice(0, at);
2210
+ const parts = at === -1 ? [] : path.slice(at + 1).split("&").filter((part) => part !== "");
2211
+ let placed = false;
2212
+ const out = [];
2213
+ for (const part of parts) {
2214
+ if (!part.startsWith("limit=")) out.push(part);
2215
+ else if (!placed) {
2216
+ out.push(`limit=${limit}`);
2217
+ placed = true;
2218
+ }
2219
+ }
2220
+ if (!placed) out.push(`limit=${limit}`);
2221
+ return `${before}?${out.join("&")}`;
2222
+ }
2223
+ function parseLedgerWriteLog(log, expected) {
2224
+ if (!log || typeof log !== "object") return null;
2225
+ const raw = log;
2226
+ const address = typeof raw.address === "string" ? raw.address.toLowerCase() : "";
2227
+ if (!HEX40.test(address) || address !== String(expected.contractAddress).toLowerCase()) return null;
2228
+ const topics = Array.isArray(raw.topics) ? raw.topics.map((topic) => String(topic).toLowerCase()) : [];
2229
+ if (topics[0] !== expected.topic0 || topics[1] !== expected.recordKey) return null;
2230
+ const data = typeof raw.data === "string" ? raw.data.toLowerCase() : "";
2231
+ const transactionHash = typeof raw.transaction_hash === "string" ? raw.transaction_hash.toLowerCase() : "";
2232
+ const timestamp = typeof raw.timestamp === "string" ? raw.timestamp : "";
2233
+ if (!HEX_DATA.test(data) || data.length < 2 + 64 * 3) return null;
2234
+ if (!HEX642.test(transactionHash) || !TIMESTAMP.test(timestamp)) return null;
2235
+ const encodingVersion = Number.parseInt(data.slice(2, 2 + 64).slice(-8), 16);
2236
+ const previousWord = data.slice(2 + 64, 2 + 64 * 2);
2237
+ const newWord = data.slice(2 + 64 * 2, 2 + 64 * 3);
2238
+ const [seconds, fraction = ""] = timestamp.split(".");
2239
+ const ms = Number(seconds) * 1e3 + Number(fraction.slice(0, 3).padEnd(3, "0"));
2240
+ if (!Number.isFinite(ms) || Math.abs(ms) > 864e13) return null;
2241
+ return {
2242
+ transactionHash,
2243
+ timestamp,
2244
+ committedAt: new Date(ms).toISOString(),
2245
+ previousWord: `0x${previousWord}`,
2246
+ newWord: `0x${newWord}`,
2247
+ operator: HEX642.test(topics[2] ?? "") ? `0x${topics[2].slice(26)}` : "",
2248
+ encodingVersion,
2249
+ address,
2250
+ blockNumber: Number.isSafeInteger(raw.block_number) ? raw.block_number : null,
2251
+ logIndex: Number.isSafeInteger(raw.index) ? raw.index : null
2252
+ };
2253
+ }
2254
+
2111
2255
  // ../shared/src/demo/independent-verify-records.ts
2112
2256
  var import_ethers11 = require("ethers");
2113
2257
 
@@ -2365,6 +2509,67 @@ function createRpcRecordChainReader(options) {
2365
2509
  });
2366
2510
  }
2367
2511
  return out;
2512
+ },
2513
+ async findRecordWrites(recordKey, search) {
2514
+ const key = normalizeProofHash(recordKey, "recordKey");
2515
+ const now = search.now ?? Date.now;
2516
+ const deadline = now() + search.budgetMs;
2517
+ const writes = [];
2518
+ const blockTimes = /* @__PURE__ */ new Map();
2519
+ let requests = 0;
2520
+ const CUT = Symbol("cut");
2521
+ const within2 = async (p) => {
2522
+ const left = deadline - now();
2523
+ if (left <= 0) return CUT;
2524
+ let timer;
2525
+ const cut = new Promise((resolve) => {
2526
+ timer = setTimeout(() => resolve(CUT), left);
2527
+ });
2528
+ p.catch(() => void 0);
2529
+ try {
2530
+ return await Promise.race([p, cut]);
2531
+ } finally {
2532
+ if (timer) clearTimeout(timer);
2533
+ }
2534
+ };
2535
+ const end = (ended) => ({ writes, ended, requests });
2536
+ if (search.maxRequests < 1) return end("limit");
2537
+ requests += 1;
2538
+ const latest = await within2(provider.getBlockNumber());
2539
+ if (latest === CUT) return end("timeout");
2540
+ for (let to = latest; to >= 0; to -= chunk) {
2541
+ if (search.done(writes)) return end("done");
2542
+ if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2543
+ requests += 1;
2544
+ const logs = await within2(provider.getLogs({ address: contractAddress, topics: [RECORD_WRITTEN_TOPIC, key], fromBlock: Math.max(0, to - chunk + 1), toBlock: to }));
2545
+ if (logs === CUT) return end("timeout");
2546
+ for (const log of [...logs].reverse()) {
2547
+ const parsed = iface.parseLog({ topics: [...log.topics], data: log.data });
2548
+ if (!parsed) continue;
2549
+ let committedAt = blockTimes.get(log.blockNumber);
2550
+ if (committedAt === void 0) {
2551
+ if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2552
+ requests += 1;
2553
+ const block = await within2(provider.getBlock(log.blockNumber));
2554
+ if (block === CUT) return end("timeout");
2555
+ if (!block || !Number.isSafeInteger(block.timestamp)) throw new Error(`getBlock ${log.blockNumber} returned no time`);
2556
+ committedAt = new Date(block.timestamp * 1e3).toISOString();
2557
+ blockTimes.set(log.blockNumber, committedAt);
2558
+ }
2559
+ writes.push({
2560
+ previousWord: hex256(BigInt(parsed.args.previousWord)),
2561
+ newWord: hex256(BigInt(parsed.args.newWord)),
2562
+ operator: String(parsed.args.operator).toLowerCase(),
2563
+ encodingVersion: Number(parsed.args.encodingVersion),
2564
+ blockNumber: log.blockNumber,
2565
+ transactionHash: String(log.transactionHash).toLowerCase(),
2566
+ logIndex: log.index,
2567
+ committedAt,
2568
+ contractAddress: String(log.address).toLowerCase()
2569
+ });
2570
+ }
2571
+ }
2572
+ return end(search.done(writes) ? "done" : "limit");
2368
2573
  }
2369
2574
  };
2370
2575
  }
@@ -2445,6 +2650,31 @@ async function verifyBundleWithPublicLayer(input) {
2445
2650
  }
2446
2651
 
2447
2652
  // ../shared/src/demo/mirror-node-record-chain-reader.ts
2653
+ var RECORD_WRITE_SEARCH_WINDOW_SECONDS = 6 * 24 * 60 * 60;
2654
+ var DAY_SECONDS = 24 * 60 * 60;
2655
+ var CONSENSUS_TIMESTAMP = /^\d{1,12}\.\d{9}$/;
2656
+ function committedAtOf(timestamp) {
2657
+ if (typeof timestamp !== "string" || !CONSENSUS_TIMESTAMP.test(timestamp)) return void 0;
2658
+ const [seconds, fraction] = timestamp.split(".");
2659
+ return new Date(Number(seconds) * 1e3 + Number(fraction.slice(0, 3))).toISOString();
2660
+ }
2661
+ var KEPT_TOPICS = [RECORD_WRITTEN_TOPIC.toLowerCase(), LEDGER_HEAD_ADVANCED_TOPIC.toLowerCase()];
2662
+ function keptMirrorLog(raw) {
2663
+ if (!raw || typeof raw !== "object") return null;
2664
+ const log = raw;
2665
+ if (!Array.isArray(log.topics) || typeof log.data !== "string") return null;
2666
+ const topics = log.topics.map((topic) => String(topic));
2667
+ if (!KEPT_TOPICS.includes((topics[0] ?? "").toLowerCase())) return null;
2668
+ return {
2669
+ address: log.address,
2670
+ data: log.data,
2671
+ index: log.index,
2672
+ topics,
2673
+ block_number: log.block_number,
2674
+ transaction_hash: log.transaction_hash,
2675
+ timestamp: log.timestamp
2676
+ };
2677
+ }
2448
2678
  function createMirrorNodeRecordChainReader(options) {
2449
2679
  const chainId = options.chainId ?? 296;
2450
2680
  const base = (options.mirrorBaseUrl ?? MIRROR_NODE_BY_CHAIN[chainId] ?? "").replace(/\/+$/, "");
@@ -2456,22 +2686,28 @@ function createMirrorNodeRecordChainReader(options) {
2456
2686
  const fetchImpl = options.fetchImpl ?? fetch;
2457
2687
  const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
2458
2688
  async function request(path, init) {
2459
- const url = path.startsWith("http") ? path : `${base}${path.startsWith("/") ? "" : "/"}${path}`;
2689
+ const url = `${base}${path}`;
2460
2690
  let lastError = null;
2461
2691
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
2462
2692
  const controller = new AbortController();
2463
2693
  const timer = setTimeout(() => controller.abort(), timeoutMs);
2464
2694
  try {
2465
- const response = await fetchImpl(url, { ...init, signal: controller.signal });
2695
+ const response = await fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal });
2696
+ if (isMirrorRedirect(response)) {
2697
+ await response.body?.cancel?.().catch(() => void 0);
2698
+ throw mirrorRefusal.redirect(path);
2699
+ }
2466
2700
  if (response.status === 429 || response.status >= 500) {
2701
+ await response.body?.cancel?.().catch(() => void 0);
2467
2702
  lastError = new Error(`mirror node ${response.status} for ${path}`);
2468
2703
  } else if (!response.ok) {
2469
- const body = await response.text().catch(() => "");
2704
+ const body = await readMirrorText(response, MIRROR_ANSWER_MAX_BYTES, path).catch(() => "");
2470
2705
  throw new Error(`mirror node ${response.status} for ${path}${body ? `: ${body.slice(0, 200)}` : ""}`);
2471
2706
  } else {
2472
- return await response.json();
2707
+ return await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
2473
2708
  }
2474
2709
  } catch (error) {
2710
+ if (mirrorRefusalOf(error)) throw error;
2475
2711
  if (error.name === "AbortError") lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
2476
2712
  else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
2477
2713
  else lastError = error;
@@ -2498,28 +2734,86 @@ function createMirrorNodeRecordChainReader(options) {
2498
2734
  function matchesTopics(log, topics) {
2499
2735
  return topics.every((topic, index) => !topic || (log.topics[index] ?? "").toLowerCase() === topic.toLowerCase());
2500
2736
  }
2501
- async function scanLogs(topics, fromBlock, toBlock) {
2737
+ let keptLogs = null;
2738
+ function readAllLogs() {
2739
+ if (!options.keepLogPages) return readAllLogPages();
2740
+ if (!keptLogs) {
2741
+ keptLogs = readAllLogPages();
2742
+ keptLogs.catch(() => {
2743
+ keptLogs = null;
2744
+ });
2745
+ }
2746
+ return keptLogs;
2747
+ }
2748
+ async function readAllLogPages() {
2502
2749
  const params = new URLSearchParams();
2503
2750
  params.set("order", "asc");
2504
2751
  params.set("limit", String(pageSize));
2505
- let next = `/api/v1/contracts/${contractAddress}/results/logs?${params.toString()}`;
2752
+ let next = `${contractLogPath(contractAddress)}?${params.toString()}`;
2506
2753
  const out = [];
2507
2754
  let pages = 0;
2755
+ let size = pageSize;
2508
2756
  while (next) {
2509
- const page = await request(next);
2510
- for (const log of page.logs ?? []) {
2511
- if (!matchesTopics(log, topics)) continue;
2512
- if (log.block_number < fromBlock) continue;
2513
- if (toBlock !== "latest" && log.block_number > toBlock) continue;
2514
- out.push(log);
2757
+ const { page, asked } = await readLogPage(next, size);
2758
+ size = Math.min(pageSize, asked * 2);
2759
+ const logs = Array.isArray(page.logs) ? page.logs : [...page.logs ?? []];
2760
+ if (logs.length > asked) throw mirrorRefusal.tooManyLogs(asked, next);
2761
+ for (const raw of logs) {
2762
+ const log = keptMirrorLog(raw);
2763
+ if (log) out.push(log);
2764
+ }
2765
+ const link = page.links?.next;
2766
+ if (link === null || link === void 0 || link === "") {
2767
+ next = null;
2768
+ } else {
2769
+ const path = nextLogPath(link, { base, contract: contractAddress });
2770
+ if (!path) throw mirrorRefusal.nextPage();
2771
+ next = withLogPageLimit(path, size);
2515
2772
  }
2516
- next = page.links?.next ?? null;
2517
2773
  pages += 1;
2518
2774
  if (pages > 1e4) throw new Error("mirror node log scan exceeded 10,000 pages");
2519
2775
  }
2776
+ return out;
2777
+ }
2778
+ async function readLogPage(path, start) {
2779
+ let asked = start;
2780
+ for (; ; ) {
2781
+ try {
2782
+ return { page: await request(withLogPageLimit(path, asked)), asked };
2783
+ } catch (error) {
2784
+ if (mirrorRefusalOf(error) !== "too-large" || asked <= 1) throw error;
2785
+ asked = Math.max(1, Math.floor(asked / 2));
2786
+ }
2787
+ }
2788
+ }
2789
+ async function scanLogs(topics, fromBlock, toBlock) {
2790
+ const out = [];
2791
+ for (const log of await readAllLogs()) {
2792
+ if (!matchesTopics(log, topics)) continue;
2793
+ if (log.block_number < fromBlock) continue;
2794
+ if (toBlock !== "latest" && log.block_number > toBlock) continue;
2795
+ out.push(log);
2796
+ }
2520
2797
  out.sort((a, b) => a.block_number - b.block_number || a.index - b.index);
2521
2798
  return out;
2522
2799
  }
2800
+ async function searchPage(path, ms) {
2801
+ const controller = new AbortController();
2802
+ const timer = setTimeout(() => controller.abort(), ms);
2803
+ try {
2804
+ const response = await fetchImpl(`${base}${path}`, { headers: { accept: "application/json" }, redirect: "error", signal: controller.signal });
2805
+ if (isMirrorRedirect(response)) throw mirrorRefusal.redirect(path);
2806
+ if (!response.ok) throw new Error(`mirror node ${response.status} for a record's writes`);
2807
+ const page = await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
2808
+ if (Array.isArray(page.logs) && page.logs.length > LEDGER_WRITE_SEARCH_PAGE_LIMIT) throw mirrorRefusal.tooManyLogs(LEDGER_WRITE_SEARCH_PAGE_LIMIT, path);
2809
+ return page;
2810
+ } catch (error) {
2811
+ if (controller.signal.aborted) return "timeout";
2812
+ throw error;
2813
+ } finally {
2814
+ clearTimeout(timer);
2815
+ }
2816
+ }
2523
2817
  return {
2524
2818
  contractAddress,
2525
2819
  async getRecord(recordKey) {
@@ -2577,10 +2871,58 @@ function createMirrorNodeRecordChainReader(options) {
2577
2871
  encodingVersion: Number(parsed.args.encodingVersion),
2578
2872
  blockNumber: log.block_number,
2579
2873
  transactionHash: log.transaction_hash,
2580
- logIndex: log.index
2874
+ logIndex: log.index,
2875
+ committedAt: committedAtOf(log.timestamp),
2876
+ contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0
2581
2877
  });
2582
2878
  }
2583
2879
  return out;
2880
+ },
2881
+ async findRecordWrites(recordKey, search) {
2882
+ const key = normalizeProofHash(recordKey, "recordKey").toLowerCase();
2883
+ const topic0 = RECORD_WRITTEN_TOPIC.toLowerCase();
2884
+ const now = search.now ?? Date.now;
2885
+ const deadline = now() + search.budgetMs;
2886
+ const windowSeconds = Math.max(1, Math.floor(search.windowSeconds ?? RECORD_WRITE_SEARCH_WINDOW_SECONDS));
2887
+ const nowSeconds = Math.floor(now() / 1e3);
2888
+ const hint = search.startAt ? Date.parse(search.startAt) : Number.NaN;
2889
+ let upper = Math.min(Number.isFinite(hint) ? Math.floor(hint / 1e3) : nowSeconds, nowSeconds) + DAY_SECONDS;
2890
+ const writes = [];
2891
+ let requests = 0;
2892
+ const end = (ended) => ({ writes, ended, requests });
2893
+ while (!search.done(writes)) {
2894
+ if (upper <= 0) return end("limit");
2895
+ const lower = Math.max(0, upper - windowSeconds);
2896
+ let path = ledgerWriteSearchPath({ contractAddress, topic0, recordKey: key, lower, upper });
2897
+ while (path) {
2898
+ const left = deadline - now();
2899
+ if (requests >= search.maxRequests || left <= 0) return end("limit");
2900
+ requests += 1;
2901
+ const page = await searchPage(path, left);
2902
+ if (page === "timeout") return end("timeout");
2903
+ for (const log of Array.isArray(page?.logs) ? page.logs : []) {
2904
+ const write = parseLedgerWriteLog(log, { topic0, recordKey: key, contractAddress });
2905
+ if (!write || !CONSENSUS_TIMESTAMP.test(write.timestamp)) continue;
2906
+ writes.push({
2907
+ previousWord: write.previousWord,
2908
+ newWord: write.newWord,
2909
+ operator: write.operator,
2910
+ encodingVersion: write.encodingVersion,
2911
+ blockNumber: write.blockNumber ?? void 0,
2912
+ transactionHash: write.transactionHash,
2913
+ logIndex: write.logIndex ?? void 0,
2914
+ committedAt: write.committedAt,
2915
+ contractAddress: write.address
2916
+ });
2917
+ }
2918
+ if (search.done(writes)) return end("done");
2919
+ const link = page?.links?.next;
2920
+ path = nextLogPath(link, { base, contract: contractAddress });
2921
+ if (!path && link !== null && link !== void 0 && link !== "") throw mirrorRefusal.nextPage();
2922
+ }
2923
+ upper = lower;
2924
+ }
2925
+ return end("done");
2584
2926
  }
2585
2927
  };
2586
2928
  }
@@ -3150,6 +3492,12 @@ var SEP5 = new Uint8Array([0]);
3150
3492
 
3151
3493
  // src/report.ts
3152
3494
  var REPORT_SCHEMA = "pacspace-check-report/v1";
3495
+ var SOURCE_REFUSAL_REASONS = {
3496
+ redirect: "its source answered with a redirect, which is not followed",
3497
+ "too-large": "its source gave an answer larger than this checker reads",
3498
+ "too-many-logs": "its source returned a longer page than was asked for",
3499
+ "next-page": "its source pointed somewhere else for the next page"
3500
+ };
3153
3501
  var ENCRYPTED_OPENED_SENTENCE = "Each entry was opened on this machine and matches its sealed record hash.";
3154
3502
  function refusedUnopenedSentence(k) {
3155
3503
  return `${k} refused ${entryWord(k)} could not be opened with this record key. Their seals are checked.`;
@@ -3268,9 +3616,13 @@ function sealsVerdict(entries, v, queued = []) {
3268
3616
  }
3269
3617
  return { sentence: sealsPassedSentence(entries), passed: true };
3270
3618
  }
3619
+ function refusedOf(source) {
3620
+ return !source.compared && source.reason === "unreachable" ? source.refused : void 0;
3621
+ }
3271
3622
  function sourceSentence(source) {
3272
3623
  if (!source.compared) {
3273
- 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.";
3624
+ if (source.reason === "offline") return "Not compared with the proof layer. The check ran on this file alone.";
3625
+ 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.";
3274
3626
  }
3275
3627
  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}` : ""}`;
3276
3628
  }
@@ -3419,7 +3771,45 @@ function buildSealsReport(input) {
3419
3771
  exitCode
3420
3772
  };
3421
3773
  }
3422
- function renderReport(report) {
3774
+ var WRITES_HEADING = "Where each entry was committed on the proof layer:";
3775
+ 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.";
3776
+ var WRITES_LISTED_MAX = 25;
3777
+ function entriesLabel(numbers) {
3778
+ const sorted = [...numbers].sort((a, b) => a - b);
3779
+ const inARow = sorted.every((n, i) => i === 0 || n === sorted[i - 1] + 1);
3780
+ if (sorted.length >= 3 && inARow) return `Entries ${sorted[0]} to ${sorted[sorted.length - 1]}`;
3781
+ return listEntries(sorted);
3782
+ }
3783
+ function committedWhen(iso) {
3784
+ return `${dayOfUtc(iso)}, ${iso.slice(11, 19)} UTC`;
3785
+ }
3786
+ function writesNotFoundSentence(notFound, suggestFull) {
3787
+ const one = notFound.length === 1;
3788
+ return [
3789
+ `${entriesLabel(notFound)}: where ${one ? "it was" : "they were"} committed was not found in this read of the proof layer.`,
3790
+ ...suggestFull ? ["--full reads the record's whole history."] : [],
3791
+ "The check above does not depend on it."
3792
+ ].join(" ");
3793
+ }
3794
+ function writesNotListedSentence(count) {
3795
+ return `${count} more ${entryWord(count)} ${isAre(count)} not listed here. --json lists them all.`;
3796
+ }
3797
+ function writesLines(writes, suggestFull = true) {
3798
+ if (!writes) return [];
3799
+ if (!writes.read) return [WRITES_NOT_READ_SENTENCE];
3800
+ if (writes.entries.length === 0 && writes.notFound.length === 0) return [];
3801
+ const lines = [WRITES_HEADING];
3802
+ for (const write of writes.entries.slice(0, WRITES_LISTED_MAX)) {
3803
+ const line = `${entriesLabel(write.entries)}: committed ${committedWhen(write.committedAt)}`;
3804
+ if (write.link) lines.push(line, ` ${write.link}`);
3805
+ else lines.push(`${line}, write ${write.transactionHash}`);
3806
+ }
3807
+ const unlisted = writes.entries.slice(WRITES_LISTED_MAX).reduce((sum, write) => sum + write.entries.length, 0);
3808
+ if (unlisted > 0) lines.push(writesNotListedSentence(unlisted));
3809
+ if (writes.notFound.length > 0) lines.push(writesNotFoundSentence(writes.notFound, suggestFull));
3810
+ return lines;
3811
+ }
3812
+ function renderReport(report, options = {}) {
3423
3813
  const facts = [
3424
3814
  ["Reference", report.record.reference],
3425
3815
  ["Fingerprint of this history", report.file.fingerprint ?? "none"]
@@ -3429,14 +3819,128 @@ function renderReport(report) {
3429
3819
  const width = Math.max(...facts.map(([label]) => label.length));
3430
3820
  const lines = facts.map(([label, value]) => `${label.padEnd(width)} ${value}`);
3431
3821
  lines.push("");
3432
- lines.push(...report.sentences);
3822
+ const where = writesLines(report.writes, options.suggestFull ?? true);
3823
+ const after = where.length ? report.sentences.indexOf(sourceSentence(report.source)) : -1;
3824
+ if (after >= 0) lines.push(...report.sentences.slice(0, after + 1), ...where, ...report.sentences.slice(after + 1));
3825
+ else lines.push(...report.sentences, ...where);
3433
3826
  return `${lines.join("\n")}
3434
3827
  `;
3435
3828
  }
3436
3829
 
3830
+ // src/writes.ts
3831
+ var WRITES_LOOKUP_MAX_REQUESTS = 40;
3832
+ var WRITES_LOOKUP_DEFAULT_BUDGET_MS = 1e4;
3833
+ var HEX643 = /^0x[0-9a-f]{64}$/;
3834
+ var HEX402 = /^0x[0-9a-f]{40}$/;
3835
+ var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
3836
+ var WRITE_EXPLORERS = Object.freeze({
3837
+ 295: "https://hashscan.io/mainnet/transaction/",
3838
+ 296: "https://hashscan.io/testnet/transaction/"
3839
+ });
3840
+ function writeLinkFor(source, chainId) {
3841
+ const base = (source ?? "mirror") === "mirror" && typeof chainId === "number" && Object.prototype.hasOwnProperty.call(WRITE_EXPLORERS, chainId) ? WRITE_EXPLORERS[chainId] : null;
3842
+ return (transactionHash) => base === null || !HEX643.test(transactionHash) ? null : `${base}${transactionHash}`;
3843
+ }
3844
+ function wantedEntriesOf(receipts, verifiedSeqs) {
3845
+ const out = [];
3846
+ for (const receipt of Array.isArray(receipts) ? receipts : []) {
3847
+ const { seq, previousWord, newWord } = receipt ?? {};
3848
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0 || !verifiedSeqs.has(seq)) continue;
3849
+ if (typeof previousWord !== "string" || typeof newWord !== "string") continue;
3850
+ const previous = previousWord.toLowerCase();
3851
+ const next = newWord.toLowerCase();
3852
+ if (!HEX643.test(previous) || !HEX643.test(next)) continue;
3853
+ out.push({ entry: seq + 1, previousWord: previous, newWord: next });
3854
+ }
3855
+ return out.sort((a, b) => a.entry - b.entry);
3856
+ }
3857
+ function printable(write, contractAddress) {
3858
+ return !!write && typeof write === "object" && typeof write.contractAddress === "string" && write.contractAddress.toLowerCase() === contractAddress && typeof write.transactionHash === "string" && HEX643.test(write.transactionHash.toLowerCase()) && typeof write.committedAt === "string" && ISO_INSTANT.test(write.committedAt) && Number.isFinite(Date.parse(write.committedAt)) && typeof write.previousWord === "string" && typeof write.newWord === "string" && HEX643.test(write.previousWord.toLowerCase()) && HEX643.test(write.newWord.toLowerCase());
3859
+ }
3860
+ function hitsFor(entry, writes, contractAddress) {
3861
+ const seen = /* @__PURE__ */ new Map();
3862
+ for (const write of Array.isArray(writes) ? writes : []) {
3863
+ if (!printable(write, contractAddress)) continue;
3864
+ if (write.previousWord.toLowerCase() !== entry.previousWord || write.newWord.toLowerCase() !== entry.newWord) continue;
3865
+ seen.set(`${write.transactionHash.toLowerCase()}:${write.logIndex ?? ""}`, write);
3866
+ }
3867
+ return [...seen.values()];
3868
+ }
3869
+ async function within(p, ms) {
3870
+ let timer;
3871
+ const cut = new Promise((resolve) => {
3872
+ timer = setTimeout(() => resolve("cut"), Math.max(0, ms));
3873
+ });
3874
+ p.catch(() => void 0);
3875
+ try {
3876
+ return await Promise.race([p, cut]);
3877
+ } finally {
3878
+ if (timer) clearTimeout(timer);
3879
+ }
3880
+ }
3881
+ async function lookUpWrites(input) {
3882
+ try {
3883
+ const contractAddress = String(input.contractAddress ?? "").toLowerCase();
3884
+ if (!HEX402.test(contractAddress)) return { read: false, reason: "unreachable" };
3885
+ if (input.wanted.length === 0) return { read: true, entries: [], notFound: [] };
3886
+ const done = (writes2) => input.wanted.every((entry) => hitsFor(entry, writes2, contractAddress).length > 0);
3887
+ let writes;
3888
+ let cutOff = false;
3889
+ if (input.whole) {
3890
+ const all = await within(input.reader.getRecordWrites(input.recordKey), input.budgetMs);
3891
+ if (all === "cut") return { read: false, reason: "timeout" };
3892
+ writes = all;
3893
+ } else {
3894
+ if (!input.reader.findRecordWrites) return { read: false, reason: "unreachable" };
3895
+ const result = await within(
3896
+ input.reader.findRecordWrites(input.recordKey, {
3897
+ startAt: input.startAt,
3898
+ done,
3899
+ budgetMs: input.budgetMs,
3900
+ maxRequests: WRITES_LOOKUP_MAX_REQUESTS,
3901
+ windowSeconds: input.windowSeconds,
3902
+ now: input.now
3903
+ }),
3904
+ input.budgetMs + 250
3905
+ );
3906
+ if (result === "cut") return { read: false, reason: "timeout" };
3907
+ writes = result.writes;
3908
+ cutOff = result.ended === "timeout";
3909
+ }
3910
+ const byTransaction = /* @__PURE__ */ new Map();
3911
+ const notFound = [];
3912
+ for (const entry of input.wanted) {
3913
+ const hits = hitsFor(entry, writes, contractAddress);
3914
+ if (hits.length !== 1) {
3915
+ notFound.push(entry.entry);
3916
+ continue;
3917
+ }
3918
+ const transactionHash = hits[0].transactionHash.toLowerCase();
3919
+ const group = byTransaction.get(transactionHash);
3920
+ if (group) {
3921
+ group.entries.push(entry.entry);
3922
+ continue;
3923
+ }
3924
+ const link = input.linkFor(transactionHash);
3925
+ byTransaction.set(transactionHash, {
3926
+ entries: [entry.entry],
3927
+ committedAt: hits[0].committedAt,
3928
+ transactionHash,
3929
+ blockNumber: Number.isSafeInteger(hits[0].blockNumber) ? hits[0].blockNumber : null,
3930
+ link: typeof link === "string" ? link : null
3931
+ });
3932
+ }
3933
+ const entries = [...byTransaction.values()].sort((a, b) => a.entries[0] - b.entries[0]);
3934
+ if (cutOff && entries.length === 0) return { read: false, reason: "timeout" };
3935
+ return { read: true, entries, notFound };
3936
+ } catch {
3937
+ return { read: false, reason: "unreachable" };
3938
+ }
3939
+ }
3940
+
3437
3941
  // src/check.ts
3438
3942
  var CHECKER_NAME = "@pacspace-io/check";
3439
- var CHECKER_VERSION = true ? "0.5.3" : "0.0.0-dev";
3943
+ var CHECKER_VERSION = true ? "0.5.5" : "0.0.0-dev";
3440
3944
  var HISTORY_SCHEMAS = [
3441
3945
  RECORD_HISTORY_BUNDLE_SCHEMA_V1,
3442
3946
  RECORD_HISTORY_BUNDLE_SCHEMA_V2,
@@ -3541,11 +4045,36 @@ function readerFor(chain, options) {
3541
4045
  chainId,
3542
4046
  contractAddress,
3543
4047
  timeoutMs: options.timeoutMs,
3544
- fetchImpl: options.fetchImpl
4048
+ fetchImpl: options.fetchImpl,
4049
+ // With --full the run reads the contract's whole log once; the lookup then asks nothing more.
4050
+ keepLogPages: !!options.writes && !!options.full
3545
4051
  }),
3546
4052
  readsFrom: mirrorBaseUrl
3547
4053
  };
3548
4054
  }
4055
+ async function withWrites(report, bundle, verification, reader, options) {
4056
+ if (!options.writes || !reader || !report.passed || !report.file.intact || !report.source.compared || !report.source.matches) return report;
4057
+ let writes;
4058
+ try {
4059
+ const source = options.source ?? "mirror";
4060
+ const verified = new Set((verification.history?.perReceipt ?? []).filter((row) => row.result.verified).map((row) => row.seq));
4061
+ writes = await lookUpWrites({
4062
+ reader,
4063
+ recordKey: String(bundle.recordKey),
4064
+ contractAddress: String(bundle.chain?.contractAddress ?? ""),
4065
+ wanted: wantedEntriesOf(bundle.receipts, verified),
4066
+ startAt: typeof bundle.exportedAt === "string" ? bundle.exportedAt : null,
4067
+ whole: !!options.full && typeof source === "string",
4068
+ budgetMs: options.timeoutMs ?? WRITES_LOOKUP_DEFAULT_BUDGET_MS,
4069
+ linkFor: writeLinkFor(source, bundle.chain?.chainId),
4070
+ windowSeconds: options.writesWindowSeconds,
4071
+ now: options.writesNow
4072
+ });
4073
+ } catch {
4074
+ writes = { read: false, reason: "unreachable" };
4075
+ }
4076
+ return { ...report, writes };
4077
+ }
3549
4078
  var PAYLOAD_POINTER = /^\/payloads\/(0|[1-9][0-9]*)$/;
3550
4079
  function disclosureNamesAFile(disclosure) {
3551
4080
  const entries = disclosure?.entries;
@@ -3710,9 +4239,11 @@ async function checkBundle(file, options) {
3710
4239
  let source;
3711
4240
  let verification = offline;
3712
4241
  let sequence = null;
4242
+ let sourceReader = null;
3713
4243
  try {
3714
4244
  const found = readerFor(bundle.chain, options);
3715
4245
  const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
4246
+ sourceReader = reader;
3716
4247
  const level = options.full ? "ledger" : "semantic";
3717
4248
  const live = v2 ? await verifyBundleV2WithSource(reader, file, level, layouts) : await verifyBundleWithPublicLayer({ reader, bundle, level, layouts });
3718
4249
  if (options.full) {
@@ -3731,15 +4262,16 @@ async function checkBundle(file, options) {
3731
4262
  };
3732
4263
  } catch (error) {
3733
4264
  if (error instanceof HistoryFileError) throw error;
3734
- source = { compared: false, reason: "unreachable", detail: error.message };
4265
+ source = notReached(error);
3735
4266
  }
3736
- return buildReport({
4267
+ const report = buildReport({
3737
4268
  ...base,
3738
4269
  verification,
3739
4270
  source,
3740
4271
  dailyStatement: dailyStatementOf(file, verification.verified, sequence),
3741
4272
  heldFile: heldOf(verification, false)
3742
4273
  });
4274
+ return withWrites(report, bundle, verification, sourceReader, options);
3743
4275
  }
3744
4276
  function encryptedRefusalSentence(refusal) {
3745
4277
  const entry = typeof refusal.seq === "number" ? refusal.seq + 1 : null;
@@ -3820,9 +4352,11 @@ async function checkEncrypted(file, bundle, recordKey, options) {
3820
4352
  let source;
3821
4353
  let result = offline;
3822
4354
  let sequence = null;
4355
+ let sourceReader = null;
3823
4356
  try {
3824
4357
  const found = readerFor(bundle.chain, options);
3825
4358
  const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
4359
+ sourceReader = reader;
3826
4360
  const contractMatches = !!bundle.chain?.contractAddress && bundle.chain.contractAddress.toLowerCase() === reader.contractAddress.toLowerCase();
3827
4361
  const chainWord = await reader.getRecord(bundle.recordKey);
3828
4362
  const onChainLayout = await reader.getLayout(bundle.layout.layoutId);
@@ -3851,9 +4385,9 @@ async function checkEncrypted(file, bundle, recordKey, options) {
3851
4385
  };
3852
4386
  } catch (error) {
3853
4387
  if (error instanceof HistoryFileError) throw error;
3854
- source = { compared: false, reason: "unreachable", detail: error.message };
4388
+ source = notReached(error);
3855
4389
  }
3856
- return buildReport({
4390
+ const report = buildReport({
3857
4391
  ...base,
3858
4392
  verification: result.verification,
3859
4393
  source,
@@ -3861,6 +4395,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
3861
4395
  heldFile: heldOf(result.verification, result.opened, false),
3862
4396
  encrypted
3863
4397
  });
4398
+ return withWrites(report, bundle, result.verification, sourceReader, options);
3864
4399
  }
3865
4400
  function entryCountOf(form, layouts) {
3866
4401
  if (!form || typeof form.currentWord !== "string") return null;
@@ -3883,18 +4418,30 @@ function ledgerAgrees(form, material) {
3883
4418
  }
3884
4419
  function answeringReader(reader) {
3885
4420
  const answered = /* @__PURE__ */ new Set();
4421
+ let refused;
3886
4422
  return {
3887
4423
  answered,
4424
+ // The first refusal of the source's answer, when a root was not read for that and not for want of an answer.
4425
+ refused: () => refused,
3888
4426
  reader: {
3889
4427
  ...reader,
3890
4428
  getBatchRoot: async (batchId) => {
3891
- const root = await reader.getBatchRoot(batchId);
3892
- answered.add(String(batchId));
3893
- return root;
4429
+ try {
4430
+ const root = await reader.getBatchRoot(batchId);
4431
+ answered.add(String(batchId));
4432
+ return root;
4433
+ } catch (error) {
4434
+ refused ??= mirrorRefusalOf(error) ?? void 0;
4435
+ throw error;
4436
+ }
3894
4437
  }
3895
4438
  }
3896
4439
  };
3897
4440
  }
4441
+ function notReached(error) {
4442
+ const refused = mirrorRefusalOf(error);
4443
+ return { compared: false, reason: "unreachable", detail: error.message, ...refused ? { refused } : {} };
4444
+ }
3898
4445
  var pointerToken = (name) => name.replace(/~/g, "~0").replace(/\//g, "~1");
3899
4446
  async function checkDisclosure(form, disclosure, reader, onRevealed) {
3900
4447
  const sub = disclosureFormOfV1(form, disclosure);
@@ -3975,7 +4522,7 @@ async function checkSeals(formName, form, disclosure, options) {
3975
4522
  };
3976
4523
  } catch (error) {
3977
4524
  if (error instanceof HistoryFileError) throw error;
3978
- source = { compared: false, reason: "unreachable", detail: error.message };
4525
+ source = notReached(error);
3979
4526
  reader = null;
3980
4527
  }
3981
4528
  let disclosureOutcome = null;
@@ -4021,6 +4568,7 @@ var releaseWords = {
4021
4568
  notProductionRecord: "The ledger record here is not the production release record.",
4022
4569
  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.`,
4023
4570
  unreachable: (origin) => `Couldn't reach ${origin} or the ledger. Nothing was checked.`,
4571
+ refused: (code) => `The ledger was not read: ${SOURCE_REFUSAL_REASONS[code]}. Nothing was checked.`,
4024
4572
  total: (n) => n === 1 ? "1 difference from the release record." : `${n} differences from the release record.`
4025
4573
  };
4026
4574
  var ReleaseUsageError = class extends Error {
@@ -4154,11 +4702,12 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4154
4702
  files: 0,
4155
4703
  differences: []
4156
4704
  };
4157
- const unreachable = () => ({
4705
+ const unreachable = (refused) => ({
4158
4706
  ...base,
4159
4707
  outcome: "unreachable",
4160
- sentences: [releaseWords.unreachable(origin)],
4161
- exitCode: 2
4708
+ sentences: [refused ? releaseWords.refused(refused) : releaseWords.unreachable(origin)],
4709
+ exitCode: 2,
4710
+ ...refused ? { refused } : {}
4162
4711
  });
4163
4712
  const differs = (differences, extra = {}) => ({
4164
4713
  ...base,
@@ -4211,7 +4760,7 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4211
4760
  throw error;
4212
4761
  }
4213
4762
  if (report.exitCode === 3 || report.source.compared === false && report.source.reason === "unreachable") {
4214
- return unreachable();
4763
+ return unreachable(refusedOf(report.source));
4215
4764
  }
4216
4765
  if (!report.passed) return differs([{ kind: "differs", path: historyPath }]);
4217
4766
  const latest = report.record.entries;