@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/cli.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((resolve3) => {
2526
+ timer = setTimeout(() => resolve3(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
  }
@@ -3297,6 +3639,12 @@ var SEP5 = new Uint8Array([0]);
3297
3639
 
3298
3640
  // src/report.ts
3299
3641
  var REPORT_SCHEMA = "pacspace-check-report/v1";
3642
+ var SOURCE_REFUSAL_REASONS = {
3643
+ redirect: "its source answered with a redirect, which is not followed",
3644
+ "too-large": "its source gave an answer larger than this checker reads",
3645
+ "too-many-logs": "its source returned a longer page than was asked for",
3646
+ "next-page": "its source pointed somewhere else for the next page"
3647
+ };
3300
3648
  var ENCRYPTED_OPENED_SENTENCE = "Each entry was opened on this machine and matches its sealed record hash.";
3301
3649
  function refusedUnopenedSentence(k) {
3302
3650
  return `${k} refused ${entryWord(k)} could not be opened with this record key. Their seals are checked.`;
@@ -3416,9 +3764,13 @@ function sealsVerdict(entries, v, queued = []) {
3416
3764
  }
3417
3765
  return { sentence: sealsPassedSentence(entries), passed: true };
3418
3766
  }
3767
+ function refusedOf(source) {
3768
+ return !source.compared && source.reason === "unreachable" ? source.refused : void 0;
3769
+ }
3419
3770
  function sourceSentence(source) {
3420
3771
  if (!source.compared) {
3421
- 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.";
3772
+ if (source.reason === "offline") return "Not compared with the proof layer. The check ran on this file alone.";
3773
+ 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.";
3422
3774
  }
3423
3775
  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}` : ""}`;
3424
3776
  }
@@ -3567,7 +3919,45 @@ function buildSealsReport(input) {
3567
3919
  exitCode
3568
3920
  };
3569
3921
  }
3570
- function renderReport(report) {
3922
+ var WRITES_HEADING = "Where each entry was committed on the proof layer:";
3923
+ 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.";
3924
+ var WRITES_LISTED_MAX = 25;
3925
+ function entriesLabel(numbers) {
3926
+ const sorted = [...numbers].sort((a, b) => a - b);
3927
+ const inARow = sorted.every((n, i) => i === 0 || n === sorted[i - 1] + 1);
3928
+ if (sorted.length >= 3 && inARow) return `Entries ${sorted[0]} to ${sorted[sorted.length - 1]}`;
3929
+ return listEntries(sorted);
3930
+ }
3931
+ function committedWhen(iso) {
3932
+ return `${dayOfUtc(iso)}, ${iso.slice(11, 19)} UTC`;
3933
+ }
3934
+ function writesNotFoundSentence(notFound, suggestFull) {
3935
+ const one = notFound.length === 1;
3936
+ return [
3937
+ `${entriesLabel(notFound)}: where ${one ? "it was" : "they were"} committed was not found in this read of the proof layer.`,
3938
+ ...suggestFull ? ["--full reads the record's whole history."] : [],
3939
+ "The check above does not depend on it."
3940
+ ].join(" ");
3941
+ }
3942
+ function writesNotListedSentence(count) {
3943
+ return `${count} more ${entryWord(count)} ${isAre(count)} not listed here. --json lists them all.`;
3944
+ }
3945
+ function writesLines(writes, suggestFull = true) {
3946
+ if (!writes) return [];
3947
+ if (!writes.read) return [WRITES_NOT_READ_SENTENCE];
3948
+ if (writes.entries.length === 0 && writes.notFound.length === 0) return [];
3949
+ const lines = [WRITES_HEADING];
3950
+ for (const write of writes.entries.slice(0, WRITES_LISTED_MAX)) {
3951
+ const line = `${entriesLabel(write.entries)}: committed ${committedWhen(write.committedAt)}`;
3952
+ if (write.link) lines.push(line, ` ${write.link}`);
3953
+ else lines.push(`${line}, write ${write.transactionHash}`);
3954
+ }
3955
+ const unlisted = writes.entries.slice(WRITES_LISTED_MAX).reduce((sum, write) => sum + write.entries.length, 0);
3956
+ if (unlisted > 0) lines.push(writesNotListedSentence(unlisted));
3957
+ if (writes.notFound.length > 0) lines.push(writesNotFoundSentence(writes.notFound, suggestFull));
3958
+ return lines;
3959
+ }
3960
+ function renderReport(report, options = {}) {
3571
3961
  const facts = [
3572
3962
  ["Reference", report.record.reference],
3573
3963
  ["Fingerprint of this history", report.file.fingerprint ?? "none"]
@@ -3577,14 +3967,128 @@ function renderReport(report) {
3577
3967
  const width = Math.max(...facts.map(([label]) => label.length));
3578
3968
  const lines = facts.map(([label, value]) => `${label.padEnd(width)} ${value}`);
3579
3969
  lines.push("");
3580
- lines.push(...report.sentences);
3970
+ const where = writesLines(report.writes, options.suggestFull ?? true);
3971
+ const after = where.length ? report.sentences.indexOf(sourceSentence(report.source)) : -1;
3972
+ if (after >= 0) lines.push(...report.sentences.slice(0, after + 1), ...where, ...report.sentences.slice(after + 1));
3973
+ else lines.push(...report.sentences, ...where);
3581
3974
  return `${lines.join("\n")}
3582
3975
  `;
3583
3976
  }
3584
3977
 
3978
+ // src/writes.ts
3979
+ var WRITES_LOOKUP_MAX_REQUESTS = 40;
3980
+ var WRITES_LOOKUP_DEFAULT_BUDGET_MS = 1e4;
3981
+ var HEX643 = /^0x[0-9a-f]{64}$/;
3982
+ var HEX402 = /^0x[0-9a-f]{40}$/;
3983
+ var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
3984
+ var WRITE_EXPLORERS = Object.freeze({
3985
+ 295: "https://hashscan.io/mainnet/transaction/",
3986
+ 296: "https://hashscan.io/testnet/transaction/"
3987
+ });
3988
+ function writeLinkFor(source, chainId) {
3989
+ const base = (source ?? "mirror") === "mirror" && typeof chainId === "number" && Object.prototype.hasOwnProperty.call(WRITE_EXPLORERS, chainId) ? WRITE_EXPLORERS[chainId] : null;
3990
+ return (transactionHash) => base === null || !HEX643.test(transactionHash) ? null : `${base}${transactionHash}`;
3991
+ }
3992
+ function wantedEntriesOf(receipts, verifiedSeqs) {
3993
+ const out = [];
3994
+ for (const receipt of Array.isArray(receipts) ? receipts : []) {
3995
+ const { seq, previousWord, newWord } = receipt ?? {};
3996
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0 || !verifiedSeqs.has(seq)) continue;
3997
+ if (typeof previousWord !== "string" || typeof newWord !== "string") continue;
3998
+ const previous = previousWord.toLowerCase();
3999
+ const next = newWord.toLowerCase();
4000
+ if (!HEX643.test(previous) || !HEX643.test(next)) continue;
4001
+ out.push({ entry: seq + 1, previousWord: previous, newWord: next });
4002
+ }
4003
+ return out.sort((a, b) => a.entry - b.entry);
4004
+ }
4005
+ function printable(write, contractAddress) {
4006
+ 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());
4007
+ }
4008
+ function hitsFor(entry, writes, contractAddress) {
4009
+ const seen = /* @__PURE__ */ new Map();
4010
+ for (const write of Array.isArray(writes) ? writes : []) {
4011
+ if (!printable(write, contractAddress)) continue;
4012
+ if (write.previousWord.toLowerCase() !== entry.previousWord || write.newWord.toLowerCase() !== entry.newWord) continue;
4013
+ seen.set(`${write.transactionHash.toLowerCase()}:${write.logIndex ?? ""}`, write);
4014
+ }
4015
+ return [...seen.values()];
4016
+ }
4017
+ async function within(p, ms) {
4018
+ let timer;
4019
+ const cut = new Promise((resolve3) => {
4020
+ timer = setTimeout(() => resolve3("cut"), Math.max(0, ms));
4021
+ });
4022
+ p.catch(() => void 0);
4023
+ try {
4024
+ return await Promise.race([p, cut]);
4025
+ } finally {
4026
+ if (timer) clearTimeout(timer);
4027
+ }
4028
+ }
4029
+ async function lookUpWrites(input) {
4030
+ try {
4031
+ const contractAddress = String(input.contractAddress ?? "").toLowerCase();
4032
+ if (!HEX402.test(contractAddress)) return { read: false, reason: "unreachable" };
4033
+ if (input.wanted.length === 0) return { read: true, entries: [], notFound: [] };
4034
+ const done = (writes2) => input.wanted.every((entry) => hitsFor(entry, writes2, contractAddress).length > 0);
4035
+ let writes;
4036
+ let cutOff = false;
4037
+ if (input.whole) {
4038
+ const all = await within(input.reader.getRecordWrites(input.recordKey), input.budgetMs);
4039
+ if (all === "cut") return { read: false, reason: "timeout" };
4040
+ writes = all;
4041
+ } else {
4042
+ if (!input.reader.findRecordWrites) return { read: false, reason: "unreachable" };
4043
+ const result = await within(
4044
+ input.reader.findRecordWrites(input.recordKey, {
4045
+ startAt: input.startAt,
4046
+ done,
4047
+ budgetMs: input.budgetMs,
4048
+ maxRequests: WRITES_LOOKUP_MAX_REQUESTS,
4049
+ windowSeconds: input.windowSeconds,
4050
+ now: input.now
4051
+ }),
4052
+ input.budgetMs + 250
4053
+ );
4054
+ if (result === "cut") return { read: false, reason: "timeout" };
4055
+ writes = result.writes;
4056
+ cutOff = result.ended === "timeout";
4057
+ }
4058
+ const byTransaction = /* @__PURE__ */ new Map();
4059
+ const notFound = [];
4060
+ for (const entry of input.wanted) {
4061
+ const hits = hitsFor(entry, writes, contractAddress);
4062
+ if (hits.length !== 1) {
4063
+ notFound.push(entry.entry);
4064
+ continue;
4065
+ }
4066
+ const transactionHash = hits[0].transactionHash.toLowerCase();
4067
+ const group = byTransaction.get(transactionHash);
4068
+ if (group) {
4069
+ group.entries.push(entry.entry);
4070
+ continue;
4071
+ }
4072
+ const link = input.linkFor(transactionHash);
4073
+ byTransaction.set(transactionHash, {
4074
+ entries: [entry.entry],
4075
+ committedAt: hits[0].committedAt,
4076
+ transactionHash,
4077
+ blockNumber: Number.isSafeInteger(hits[0].blockNumber) ? hits[0].blockNumber : null,
4078
+ link: typeof link === "string" ? link : null
4079
+ });
4080
+ }
4081
+ const entries = [...byTransaction.values()].sort((a, b) => a.entries[0] - b.entries[0]);
4082
+ if (cutOff && entries.length === 0) return { read: false, reason: "timeout" };
4083
+ return { read: true, entries, notFound };
4084
+ } catch {
4085
+ return { read: false, reason: "unreachable" };
4086
+ }
4087
+ }
4088
+
3585
4089
  // src/check.ts
3586
4090
  var CHECKER_NAME = "@pacspace-io/check";
3587
- var CHECKER_VERSION = true ? "0.5.3" : "0.0.0-dev";
4091
+ var CHECKER_VERSION = true ? "0.5.5" : "0.0.0-dev";
3588
4092
  var HISTORY_SCHEMAS = [
3589
4093
  RECORD_HISTORY_BUNDLE_SCHEMA_V1,
3590
4094
  RECORD_HISTORY_BUNDLE_SCHEMA_V2,
@@ -3689,11 +4193,36 @@ function readerFor(chain, options) {
3689
4193
  chainId,
3690
4194
  contractAddress,
3691
4195
  timeoutMs: options.timeoutMs,
3692
- fetchImpl: options.fetchImpl
4196
+ fetchImpl: options.fetchImpl,
4197
+ // With --full the run reads the contract's whole log once; the lookup then asks nothing more.
4198
+ keepLogPages: !!options.writes && !!options.full
3693
4199
  }),
3694
4200
  readsFrom: mirrorBaseUrl
3695
4201
  };
3696
4202
  }
4203
+ async function withWrites(report, bundle, verification, reader, options) {
4204
+ if (!options.writes || !reader || !report.passed || !report.file.intact || !report.source.compared || !report.source.matches) return report;
4205
+ let writes;
4206
+ try {
4207
+ const source = options.source ?? "mirror";
4208
+ const verified = new Set((verification.history?.perReceipt ?? []).filter((row) => row.result.verified).map((row) => row.seq));
4209
+ writes = await lookUpWrites({
4210
+ reader,
4211
+ recordKey: String(bundle.recordKey),
4212
+ contractAddress: String(bundle.chain?.contractAddress ?? ""),
4213
+ wanted: wantedEntriesOf(bundle.receipts, verified),
4214
+ startAt: typeof bundle.exportedAt === "string" ? bundle.exportedAt : null,
4215
+ whole: !!options.full && typeof source === "string",
4216
+ budgetMs: options.timeoutMs ?? WRITES_LOOKUP_DEFAULT_BUDGET_MS,
4217
+ linkFor: writeLinkFor(source, bundle.chain?.chainId),
4218
+ windowSeconds: options.writesWindowSeconds,
4219
+ now: options.writesNow
4220
+ });
4221
+ } catch {
4222
+ writes = { read: false, reason: "unreachable" };
4223
+ }
4224
+ return { ...report, writes };
4225
+ }
3697
4226
  var PAYLOAD_POINTER = /^\/payloads\/(0|[1-9][0-9]*)$/;
3698
4227
  function disclosureNamesAFile(disclosure) {
3699
4228
  const entries = disclosure?.entries;
@@ -3858,9 +4387,11 @@ async function checkBundle(file, options) {
3858
4387
  let source;
3859
4388
  let verification = offline;
3860
4389
  let sequence = null;
4390
+ let sourceReader = null;
3861
4391
  try {
3862
4392
  const found = readerFor(bundle.chain, options);
3863
4393
  const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
4394
+ sourceReader = reader;
3864
4395
  const level = options.full ? "ledger" : "semantic";
3865
4396
  const live = v2 ? await verifyBundleV2WithSource(reader, file, level, layouts) : await verifyBundleWithPublicLayer({ reader, bundle, level, layouts });
3866
4397
  if (options.full) {
@@ -3879,15 +4410,16 @@ async function checkBundle(file, options) {
3879
4410
  };
3880
4411
  } catch (error) {
3881
4412
  if (error instanceof HistoryFileError) throw error;
3882
- source = { compared: false, reason: "unreachable", detail: error.message };
4413
+ source = notReached(error);
3883
4414
  }
3884
- return buildReport({
4415
+ const report = buildReport({
3885
4416
  ...base,
3886
4417
  verification,
3887
4418
  source,
3888
4419
  dailyStatement: dailyStatementOf(file, verification.verified, sequence),
3889
4420
  heldFile: heldOf(verification, false)
3890
4421
  });
4422
+ return withWrites(report, bundle, verification, sourceReader, options);
3891
4423
  }
3892
4424
  function encryptedRefusalSentence(refusal) {
3893
4425
  const entry = typeof refusal.seq === "number" ? refusal.seq + 1 : null;
@@ -3968,9 +4500,11 @@ async function checkEncrypted(file, bundle, recordKey, options) {
3968
4500
  let source;
3969
4501
  let result = offline;
3970
4502
  let sequence = null;
4503
+ let sourceReader = null;
3971
4504
  try {
3972
4505
  const found = readerFor(bundle.chain, options);
3973
4506
  const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
4507
+ sourceReader = reader;
3974
4508
  const contractMatches = !!bundle.chain?.contractAddress && bundle.chain.contractAddress.toLowerCase() === reader.contractAddress.toLowerCase();
3975
4509
  const chainWord = await reader.getRecord(bundle.recordKey);
3976
4510
  const onChainLayout = await reader.getLayout(bundle.layout.layoutId);
@@ -3999,9 +4533,9 @@ async function checkEncrypted(file, bundle, recordKey, options) {
3999
4533
  };
4000
4534
  } catch (error) {
4001
4535
  if (error instanceof HistoryFileError) throw error;
4002
- source = { compared: false, reason: "unreachable", detail: error.message };
4536
+ source = notReached(error);
4003
4537
  }
4004
- return buildReport({
4538
+ const report = buildReport({
4005
4539
  ...base,
4006
4540
  verification: result.verification,
4007
4541
  source,
@@ -4009,6 +4543,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4009
4543
  heldFile: heldOf(result.verification, result.opened, false),
4010
4544
  encrypted
4011
4545
  });
4546
+ return withWrites(report, bundle, result.verification, sourceReader, options);
4012
4547
  }
4013
4548
  function entryCountOf(form, layouts) {
4014
4549
  if (!form || typeof form.currentWord !== "string") return null;
@@ -4031,18 +4566,30 @@ function ledgerAgrees(form, material) {
4031
4566
  }
4032
4567
  function answeringReader(reader) {
4033
4568
  const answered = /* @__PURE__ */ new Set();
4569
+ let refused;
4034
4570
  return {
4035
4571
  answered,
4572
+ // The first refusal of the source's answer, when a root was not read for that and not for want of an answer.
4573
+ refused: () => refused,
4036
4574
  reader: {
4037
4575
  ...reader,
4038
4576
  getBatchRoot: async (batchId) => {
4039
- const root = await reader.getBatchRoot(batchId);
4040
- answered.add(String(batchId));
4041
- return root;
4577
+ try {
4578
+ const root = await reader.getBatchRoot(batchId);
4579
+ answered.add(String(batchId));
4580
+ return root;
4581
+ } catch (error) {
4582
+ refused ??= mirrorRefusalOf(error) ?? void 0;
4583
+ throw error;
4584
+ }
4042
4585
  }
4043
4586
  }
4044
4587
  };
4045
4588
  }
4589
+ function notReached(error) {
4590
+ const refused = mirrorRefusalOf(error);
4591
+ return { compared: false, reason: "unreachable", detail: error.message, ...refused ? { refused } : {} };
4592
+ }
4046
4593
  var pointerToken = (name) => name.replace(/~/g, "~0").replace(/\//g, "~1");
4047
4594
  async function checkDisclosure(form, disclosure, reader, onRevealed) {
4048
4595
  const sub = disclosureFormOfV1(form, disclosure);
@@ -4123,7 +4670,7 @@ async function checkSeals(formName, form, disclosure, options) {
4123
4670
  };
4124
4671
  } catch (error) {
4125
4672
  if (error instanceof HistoryFileError) throw error;
4126
- source = { compared: false, reason: "unreachable", detail: error.message };
4673
+ source = notReached(error);
4127
4674
  reader = null;
4128
4675
  }
4129
4676
  let disclosureOutcome = null;
@@ -4490,6 +5037,7 @@ var releaseWords = {
4490
5037
  notProductionRecord: "The ledger record here is not the production release record.",
4491
5038
  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.`,
4492
5039
  unreachable: (origin) => `Couldn't reach ${origin} or the ledger. Nothing was checked.`,
5040
+ refused: (code) => `The ledger was not read: ${SOURCE_REFUSAL_REASONS[code]}. Nothing was checked.`,
4493
5041
  total: (n) => n === 1 ? "1 difference from the release record." : `${n} differences from the release record.`
4494
5042
  };
4495
5043
  var ReleaseUsageError = class extends Error {
@@ -4623,11 +5171,12 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4623
5171
  files: 0,
4624
5172
  differences: []
4625
5173
  };
4626
- const unreachable = () => ({
5174
+ const unreachable = (refused) => ({
4627
5175
  ...base,
4628
5176
  outcome: "unreachable",
4629
- sentences: [releaseWords.unreachable(origin)],
4630
- exitCode: 2
5177
+ sentences: [refused ? releaseWords.refused(refused) : releaseWords.unreachable(origin)],
5178
+ exitCode: 2,
5179
+ ...refused ? { refused } : {}
4631
5180
  });
4632
5181
  const differs = (differences, extra = {}) => ({
4633
5182
  ...base,
@@ -4680,7 +5229,7 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4680
5229
  throw error;
4681
5230
  }
4682
5231
  if (report.exitCode === 3 || report.source.compared === false && report.source.reason === "unreachable") {
4683
- return unreachable();
5232
+ return unreachable(refusedOf(report.source));
4684
5233
  }
4685
5234
  if (!report.passed) return differs([{ kind: "differs", path: historyPath }]);
4686
5235
  const latest = report.record.entries;
@@ -4792,6 +5341,7 @@ Options:
4792
5341
  the one known for the record's network
4793
5342
  --rpc <url> read the proof layer over JSON-RPC at this URL
4794
5343
  --full also read every daily statement
5344
+ --no-lookup do not look up where each entry was committed
4795
5345
  --timeout <ms> network timeout per read (default 10000)
4796
5346
  --json print the report as JSON
4797
5347
  --version print the checker's version
@@ -4815,7 +5365,8 @@ function parseArgs(argv) {
4815
5365
  heldFile: null,
4816
5366
  blinding: null,
4817
5367
  history: null,
4818
- key: null
5368
+ key: null,
5369
+ noLookup: false
4819
5370
  };
4820
5371
  const takeValue = (flag, index) => {
4821
5372
  const value = argv[index + 1];
@@ -4841,6 +5392,9 @@ function parseArgs(argv) {
4841
5392
  case "--full":
4842
5393
  args.full = true;
4843
5394
  break;
5395
+ case "--no-lookup":
5396
+ args.noLookup = true;
5397
+ break;
4844
5398
  case "--fingerprint":
4845
5399
  args.statementFingerprint = takeValue(arg, index);
4846
5400
  index += 1;
@@ -5144,10 +5698,13 @@ ${USAGE}`.trimEnd());
5144
5698
  fetchImpl: io.fetchImpl,
5145
5699
  history,
5146
5700
  heldFile,
5147
- recordKey
5701
+ recordKey,
5702
+ // Where each entry was committed: asked only here, for a check that reads the proof layer.
5703
+ writes: args.source !== "offline" && !args.noLookup
5148
5704
  });
5705
+ const suggestFull = !(args.full && typeof args.source === "string");
5149
5706
  io.stdout(args.json ? `${JSON.stringify(report, null, 2)}
5150
- ` : renderReport(report));
5707
+ ` : renderReport(report, { suggestFull }));
5151
5708
  return report.exitCode;
5152
5709
  } finally {
5153
5710
  recordKey?.fill(0);