@ocap/resolver 1.31.8 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/esm/_virtual/rolldown_runtime.mjs +7 -0
  2. package/esm/api.d.mts +33 -5
  3. package/esm/api.mjs +939 -53
  4. package/esm/dashboard.d.mts +199 -0
  5. package/esm/dashboard.mjs +2481 -0
  6. package/esm/explorer.d.mts +29 -0
  7. package/esm/explorer.mjs +227 -0
  8. package/esm/follower.d.mts +277 -0
  9. package/esm/follower.mjs +2428 -0
  10. package/esm/hooks.mjs +1 -1
  11. package/esm/hotstuff-runtime.d.mts +271 -0
  12. package/esm/hotstuff-runtime.mjs +2668 -0
  13. package/esm/index.d.mts +87 -4
  14. package/esm/index.mjs +937 -177
  15. package/esm/node-preferences.d.mts +203 -0
  16. package/esm/node-preferences.mjs +1021 -0
  17. package/esm/replayer.d.mts +74 -0
  18. package/esm/replayer.mjs +394 -0
  19. package/esm/token-distribution.mjs +2 -2
  20. package/esm/token-flow.mjs +1 -1
  21. package/esm/types.d.mts +25 -2
  22. package/lib/api.cjs +941 -52
  23. package/lib/api.d.cts +33 -5
  24. package/lib/dashboard.cjs +2491 -0
  25. package/lib/dashboard.d.cts +199 -0
  26. package/lib/explorer.cjs +227 -0
  27. package/lib/explorer.d.cts +29 -0
  28. package/lib/follower.cjs +2434 -0
  29. package/lib/follower.d.cts +277 -0
  30. package/lib/hooks.cjs +1 -1
  31. package/lib/hotstuff-runtime.cjs +2671 -0
  32. package/lib/hotstuff-runtime.d.cts +271 -0
  33. package/lib/index.cjs +972 -177
  34. package/lib/index.d.cts +87 -4
  35. package/lib/node-preferences.cjs +1043 -0
  36. package/lib/node-preferences.d.cts +203 -0
  37. package/lib/replayer.cjs +395 -0
  38. package/lib/replayer.d.cts +74 -0
  39. package/lib/token-distribution.cjs +2 -2
  40. package/lib/token-flow.cjs +1 -1
  41. package/lib/types.d.cts +25 -2
  42. package/package.json +20 -14
package/lib/api.cjs CHANGED
@@ -1,17 +1,267 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_node_preferences = require('./node-preferences.cjs');
3
+ const require_dashboard = require('./dashboard.cjs');
4
+ let _arcblock_ledger_core = require("@arcblock/ledger-core");
2
5
  let _arcblock_nft_display = require("@arcblock/nft-display");
6
+ let _ocap_mcrypto = require("@ocap/mcrypto");
3
7
  let express = require("express");
4
8
 
5
9
  //#region src/api.ts
10
+ const MAX_HOT_TAIL_LIMIT = 100;
11
+ const MAX_HOT_TAIL_RESPONSE_BYTES = 2 * 1024 * 1024;
12
+ const MAX_WITNESS_ATTESTATION_BODY_BYTES = 16 * 1024;
13
+ const MAX_FALLBACK_CONTIGUOUS_SCAN_ENTRIES = 500;
14
+ const MAX_BATCH_SIGNATURE_CACHE_ENTRIES = 64;
15
+ function resolveRetentionMode(explicit) {
16
+ if (explicit === "tiered" || explicit === "archive") return explicit;
17
+ return (process.env.CHAIN_RETENTION || "").trim().toLowerCase() === "tiered" ? "tiered" : "archive";
18
+ }
19
+ async function readBoundedJsonBody(req, maxBytes) {
20
+ const declaredLen = req.headers["content-length"];
21
+ if (typeof declaredLen === "string" && declaredLen.trim()) {
22
+ const parsedLen = Number(declaredLen);
23
+ if (Number.isFinite(parsedLen) && parsedLen > maxBytes) return {
24
+ ok: false,
25
+ status: 413,
26
+ code: "PAYLOAD_TOO_LARGE",
27
+ error: `Request body exceeds ${maxBytes}-byte limit`
28
+ };
29
+ }
30
+ if (req.body !== void 0 && !Buffer.isBuffer(req.body) && typeof req.body !== "string") {
31
+ if (req.body === null || typeof req.body !== "object" || Array.isArray(req.body)) return {
32
+ ok: false,
33
+ status: 400,
34
+ code: "INVALID_JSON",
35
+ error: "Request body must be a JSON object"
36
+ };
37
+ if (Buffer.byteLength(JSON.stringify(req.body), "utf8") > maxBytes) return {
38
+ ok: false,
39
+ status: 413,
40
+ code: "PAYLOAD_TOO_LARGE",
41
+ error: `Request body exceeds ${maxBytes}-byte limit`
42
+ };
43
+ return {
44
+ ok: true,
45
+ body: req.body
46
+ };
47
+ }
48
+ if (typeof req.body === "string" || Buffer.isBuffer(req.body)) {
49
+ const rawBuf = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.body, "utf8");
50
+ if (rawBuf.byteLength > maxBytes) return {
51
+ ok: false,
52
+ status: 413,
53
+ code: "PAYLOAD_TOO_LARGE",
54
+ error: `Request body exceeds ${maxBytes}-byte limit`
55
+ };
56
+ try {
57
+ return {
58
+ ok: true,
59
+ body: JSON.parse(rawBuf.toString("utf8"))
60
+ };
61
+ } catch {
62
+ return {
63
+ ok: false,
64
+ status: 400,
65
+ code: "INVALID_JSON",
66
+ error: "Malformed JSON body"
67
+ };
68
+ }
69
+ }
70
+ return new Promise((resolve) => {
71
+ const chunks = [];
72
+ let total = 0;
73
+ let settled = false;
74
+ const finish = (result) => {
75
+ if (settled) return;
76
+ settled = true;
77
+ resolve(result);
78
+ };
79
+ req.on("data", (chunk) => {
80
+ if (settled) return;
81
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
82
+ total += buf.byteLength;
83
+ if (total > maxBytes) {
84
+ req.pause();
85
+ finish({
86
+ ok: false,
87
+ status: 413,
88
+ code: "PAYLOAD_TOO_LARGE",
89
+ error: `Request body exceeds ${maxBytes}-byte limit`
90
+ });
91
+ return;
92
+ }
93
+ chunks.push(buf);
94
+ });
95
+ req.on("end", () => {
96
+ if (settled) return;
97
+ try {
98
+ const text = Buffer.concat(chunks, total).toString("utf8");
99
+ finish({
100
+ ok: true,
101
+ body: text ? JSON.parse(text) : null
102
+ });
103
+ } catch {
104
+ finish({
105
+ ok: false,
106
+ status: 400,
107
+ code: "INVALID_JSON",
108
+ error: "Malformed JSON body"
109
+ });
110
+ }
111
+ });
112
+ req.on("error", () => {
113
+ finish({
114
+ ok: false,
115
+ status: 400,
116
+ code: "STREAM_ERROR",
117
+ error: "Failed to read request body"
118
+ });
119
+ });
120
+ });
121
+ }
122
+ function parsePositiveSafeIntParam(raw) {
123
+ if (typeof raw !== "string" || !/^[1-9]\d*$/.test(raw)) return null;
124
+ const parsed = Number(raw);
125
+ return Number.isSafeInteger(parsed) && parsed >= 1 ? parsed : null;
126
+ }
127
+ function normalizeSnapshotBaseUrlString(rawInput) {
128
+ const raw = String(rawInput ?? "").trim();
129
+ if (!raw) return null;
130
+ try {
131
+ const parsed = new URL(raw);
132
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
133
+ parsed.username = "";
134
+ parsed.password = "";
135
+ parsed.search = "";
136
+ parsed.hash = "";
137
+ return parsed.toString().replace(/\/+$/g, "");
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+ function resolveSnapshotBaseUrl(explicit, env = process.env) {
143
+ if (explicit !== void 0) return normalizeSnapshotBaseUrlString(explicit);
144
+ return normalizeSnapshotBaseUrlString(env.LEDGER_SNAPSHOT_BASE_URL);
145
+ }
146
+ function sendNodeHaltedJson(res) {
147
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
148
+ res.setHeader("X-Content-Type-Options", "nosniff");
149
+ res.setHeader("Cache-Control", "no-store");
150
+ return res.status(503).json({
151
+ code: "NODE_HALTED",
152
+ error: "Chain node is halted fail-closed",
153
+ halted: true
154
+ });
155
+ }
156
+ function sendFollowerReconcilingJson(res) {
157
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
158
+ res.setHeader("X-Content-Type-Options", "nosniff");
159
+ res.setHeader("Cache-Control", "no-store");
160
+ return res.status(503).json({
161
+ code: "FOLLOWER_RECONCILING",
162
+ error: "Follower is reconciling local statedb with imported ledger segment",
163
+ halted: false,
164
+ writable: false
165
+ });
166
+ }
167
+ function formatEntryHashV2From(ledger) {
168
+ const rawV2From = typeof ledger.getEntryHashV2From === "function" ? ledger.getEntryHashV2From() : void 0;
169
+ return rawV2From === void 0 ? null : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
170
+ }
171
+ async function readHotEntriesRange(ledger, from, to) {
172
+ if (to < from || to < 1) return [];
173
+ const withStorage = ledger;
174
+ const storage = typeof withStorage.getStorage === "function" ? withStorage.getStorage() : void 0;
175
+ if (storage && typeof storage.getEntriesByRange === "function") return storage.getEntriesByRange(from, to);
176
+ return ledger.getRange(from, to);
177
+ }
178
+ async function resolveContiguousFinalizedSequence(ledger, rawLatestSeq, latestCheckpointSeq) {
179
+ if (rawLatestSeq <= 0) return 0;
180
+ if (rawLatestSeq <= latestCheckpointSeq) return rawLatestSeq;
181
+ const withStorage = ledger;
182
+ const storage = typeof withStorage.getStorage === "function" ? withStorage.getStorage() : void 0;
183
+ if (storage && typeof storage.hasUnfinalizedInRange === "function") {
184
+ const startSeq = latestCheckpointSeq + 1;
185
+ if (!await storage.hasUnfinalizedInRange(startSeq, rawLatestSeq)) return rawLatestSeq;
186
+ let lo = startSeq;
187
+ let hi = rawLatestSeq + 1;
188
+ while (lo < hi) {
189
+ const mid = lo + Math.floor((hi - lo) / 2);
190
+ if (await storage.hasUnfinalizedInRange(startSeq, mid)) hi = mid;
191
+ else lo = mid + 1;
192
+ }
193
+ return lo - 1;
194
+ }
195
+ const scanCeiling = Math.min(rawLatestSeq, latestCheckpointSeq + MAX_FALLBACK_CONTIGUOUS_SCAN_ENTRIES);
196
+ let cursor = latestCheckpointSeq + 1;
197
+ let lastContiguous = latestCheckpointSeq;
198
+ while (cursor <= scanCeiling) {
199
+ const pageEnd = Math.min(scanCeiling, cursor + 99);
200
+ const chunk = await readHotEntriesRange(ledger, cursor, pageEnd);
201
+ if (chunk.length === 0) break;
202
+ let stopped = false;
203
+ for (const entry of chunk) {
204
+ if (entry.sequence !== lastContiguous + 1 || entry.finalized !== true) {
205
+ stopped = true;
206
+ break;
207
+ }
208
+ lastContiguous = entry.sequence;
209
+ }
210
+ if (stopped || lastContiguous < pageEnd) break;
211
+ cursor = pageEnd + 1;
212
+ }
213
+ return lastContiguous;
214
+ }
215
+ function collectContiguousFinalizedEntryJsons(entries, from, maxSequence) {
216
+ const out = [];
217
+ for (const entry of entries) {
218
+ const expectedSeq = from + out.length;
219
+ if (entry.sequence !== expectedSeq || entry.finalized !== true || entry.sequence > maxSequence) break;
220
+ const normalizedEntry = {
221
+ ...entry,
222
+ timestamp: Math.trunc(Number(entry.timestamp)),
223
+ ...entry.txExtra !== void 0 ? { txExtra: entry.txExtra } : {}
224
+ };
225
+ const json = JSON.stringify(normalizedEntry);
226
+ const entryCommitment = (0, _arcblock_ledger_core.computeHotTailEntryCommitment)(normalizedEntry);
227
+ out.push({
228
+ json,
229
+ bytes: Buffer.byteLength(json, "utf8"),
230
+ entryCommitment
231
+ });
232
+ }
233
+ return out;
234
+ }
235
+ function buildEntriesEnvelopeJson(chainId, from, limit, latestSequence, entryJsons, attestation) {
236
+ const count = entryJsons.length;
237
+ const nextFrom = from + count;
238
+ const hasMore = nextFrom <= latestSequence;
239
+ const attestationFragment = attestation ? `,"entryHashV2From":${JSON.stringify(attestation.entryHashV2From)},"proposer":${JSON.stringify(attestation.proposer)},"proposerPublicKey":${JSON.stringify(attestation.proposerPublicKey)},"batchSignature":${JSON.stringify(attestation.batchSignature)}` : "";
240
+ return `{"chainId":${JSON.stringify(chainId)},"from":${from},"limit":${limit},"count":${count},"latestSequence":${latestSequence},"nextFrom":${nextFrom},"hasMore":${hasMore}${attestationFragment},"entries":[${entryJsons.join(",")}]}`;
241
+ }
6
242
  function sanitizeSvg(svgInput) {
7
243
  return svgInput.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<foreignObject[\s\S]*?<\/foreignObject>/gi, "").replace(/\son[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "").replace(/(?:href|xlink:href)\s*=\s*(?:"\s*javascript:[^"]*"|'\s*javascript:[^']*')/gi, "");
8
244
  }
9
245
  function escapeXmlText(input) {
10
246
  return String(input ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
11
247
  }
12
- function createAPIHandler({ resolver }) {
248
+ function createAPIHandler({ resolver, maxResponseBytes = MAX_HOT_TAIL_RESPONSE_BYTES, retentionMode: configuredRetentionMode, snapshotBaseUrl: configuredSnapshotBaseUrl, nodeId, preferencesManager, authGuard, nodeDashboardRouter, nodeDashboardOptions }) {
13
249
  const router = (0, express.Router)();
250
+ const effectiveMaxBytes = Number.isSafeInteger(maxResponseBytes) && maxResponseBytes > 1024 ? maxResponseBytes : MAX_HOT_TAIL_RESPONSE_BYTES;
251
+ const extLedger = resolver.ledger;
252
+ const apiAuthGuard = authGuard ?? nodeDashboardOptions?.authGuard ?? require_node_preferences.createAdminAuthGuard({ env: nodeDashboardOptions?.env });
253
+ const mountedDashboardRouter = nodeDashboardRouter ?? require_dashboard.createNodeDashboardRouter({
254
+ resolver,
255
+ retentionMode: configuredRetentionMode,
256
+ preferencesManager,
257
+ authGuard: apiAuthGuard,
258
+ ...nodeDashboardOptions
259
+ });
260
+ router.use("/node", mountedDashboardRouter);
14
261
  router.get("/token/display", async (req, res) => {
262
+ const runtime = resolver.getNodeRuntime?.();
263
+ if (runtime?.isHalted?.()) return sendNodeHaltedJson(res);
264
+ if (runtime?.isReconciling?.()) return sendFollowerReconcilingJson(res);
15
265
  const { address } = req.query;
16
266
  if (!address) return res.status(400).json({ error: "address is required" });
17
267
  const token = await resolver.getTokenState({ address });
@@ -59,63 +309,699 @@ function createAPIHandler({ resolver }) {
59
309
  res.send(svg);
60
310
  });
61
311
  router.get("/health/ledger", async (_req, res) => {
312
+ const runtime = resolver.getNodeRuntime?.();
313
+ const halted = Boolean(runtime?.isHalted?.());
314
+ const reconciling = !halted && Boolean(runtime?.isReconciling?.());
315
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
316
+ res.setHeader("X-Content-Type-Options", "nosniff");
317
+ if (halted || reconciling) res.setHeader("Cache-Control", "no-store");
62
318
  try {
63
- const health = await resolver.ledger.getHealth();
64
- const lagThreshold = Number(process.env.LEDGER_HEALTH_LAG_THRESHOLD) || 1e3;
65
- const ageThresholdMs = Number(process.env.LEDGER_HEALTH_AGE_THRESHOLD_MS) || 36e5;
66
- const unfinalizedAgeThresholdMs = Number(process.env.LEDGER_HEALTH_UNFINALIZED_AGE_THRESHOLD_MS) || 3e5;
67
- const now = Date.now();
68
- const oldestUnfinalizedAgeMs = health.oldestUnfinalizedTimestamp ? now - health.oldestUnfinalizedTimestamp : null;
69
- const lagViolation = health.checkpointLag > lagThreshold;
70
- const ageViolation = lagViolation && health.checkpointAgeMs != null && health.checkpointAgeMs > ageThresholdMs;
71
- const unfinalizedViolation = oldestUnfinalizedAgeMs != null && oldestUnfinalizedAgeMs > unfinalizedAgeThresholdMs;
72
- const healthy = !lagViolation && !ageViolation && !unfinalizedViolation;
73
- const formatDuration = (ms) => {
74
- if (ms == null) return null;
75
- const s = Math.floor(ms / 1e3);
76
- const d = Math.floor(s / 86400);
77
- const h = Math.floor(s % 86400 / 3600);
78
- const m = Math.floor(s % 3600 / 60);
79
- const sec = s % 60;
80
- const parts = [];
81
- if (d) parts.push(`${d}d`);
82
- if (h) parts.push(`${h}h`);
83
- if (m) parts.push(`${m}m`);
84
- if (sec || parts.length === 0) parts.push(`${sec}s`);
85
- return parts.join(" ");
86
- };
87
- const toIso = (ts) => ts ? new Date(ts).toISOString() : null;
88
- res.json({
89
- healthy,
90
- latestSequence: health.latestSequence,
91
- latestCheckpoint: health.latestCheckpoint ? {
92
- ...health.latestCheckpoint,
93
- timestampIso: toIso(health.latestCheckpoint.timestamp)
94
- } : null,
95
- checkpointLag: health.checkpointLag,
96
- checkpointAgeMs: health.checkpointAgeMs,
97
- checkpointAge: formatDuration(health.checkpointAgeMs),
98
- unfinalizedCount: health.unfinalizedCount,
99
- oldestUnfinalizedTimestamp: health.oldestUnfinalizedTimestamp,
100
- oldestUnfinalizedTimestampIso: toIso(health.oldestUnfinalizedTimestamp),
101
- oldestUnfinalizedAgeMs,
102
- oldestUnfinalizedAge: formatDuration(oldestUnfinalizedAgeMs),
103
- nowIso: new Date(now).toISOString(),
104
- violations: {
105
- lag: lagViolation,
106
- age: ageViolation,
107
- unfinalized: unfinalizedViolation
108
- },
109
- thresholds: {
110
- checkpointLag: lagThreshold,
111
- checkpointAgeMs: ageThresholdMs,
112
- unfinalizedAgeMs: unfinalizedAgeThresholdMs
319
+ const summary = await require_dashboard.collectLedgerHealthSummary({
320
+ ledger: resolver.ledger,
321
+ runtime,
322
+ retentionMode: configuredRetentionMode,
323
+ thresholds: preferencesManager?.getEffectiveHealthThresholds()
324
+ });
325
+ return res.status(halted || reconciling ? 503 : 200).json(summary);
326
+ } catch (error) {
327
+ const message = error instanceof Error ? error.message : String(error);
328
+ if (halted) {
329
+ const haltReason = runtime?.getHaltReason?.() ?? null;
330
+ return res.status(503).json({
331
+ healthy: false,
332
+ halted: true,
333
+ code: "NODE_HALTED",
334
+ haltReason,
335
+ error: haltReason || message || "Chain node is halted fail-closed"
336
+ });
337
+ }
338
+ if (reconciling) return res.status(503).json({
339
+ healthy: false,
340
+ halted: false,
341
+ reconciling: true,
342
+ code: "FOLLOWER_RECONCILING",
343
+ error: message || "Follower is reconciling local statedb with imported ledger segment"
344
+ });
345
+ return res.status(500).json({
346
+ healthy: false,
347
+ error: message
348
+ });
349
+ }
350
+ });
351
+ let cachedStatusSigKey = null;
352
+ let cachedStatusSigVal = null;
353
+ const batchSigCache = /* @__PURE__ */ new Map();
354
+ router.get("/ledger/status", async (req, res) => {
355
+ try {
356
+ const runtime = resolver.getNodeRuntime?.();
357
+ if (Boolean(runtime?.isHalted?.())) {
358
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
359
+ res.setHeader("X-Content-Type-Options", "nosniff");
360
+ res.setHeader("Cache-Control", "no-store");
361
+ return res.status(503).json({
362
+ code: "NODE_HALTED",
363
+ error: "Chain node is halted fail-closed",
364
+ halted: true,
365
+ writable: false
366
+ });
367
+ }
368
+ if (Boolean(runtime?.isReconciling?.())) {
369
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
370
+ res.setHeader("X-Content-Type-Options", "nosniff");
371
+ res.setHeader("Cache-Control", "no-store");
372
+ return res.status(503).json({
373
+ code: "FOLLOWER_RECONCILING",
374
+ error: "Follower is reconciling local statedb with imported ledger segment",
375
+ halted: false,
376
+ writable: false
377
+ });
378
+ }
379
+ const [latestCheckpoint, rawLatestSeq] = await Promise.all([resolver.ledger.getCheckpoint(), resolver.ledger.getLatestSequence()]);
380
+ const latestSequence = await resolveContiguousFinalizedSequence(resolver.ledger, rawLatestSeq, latestCheckpoint?.sequence ?? 0);
381
+ const chainId = resolver.config?.chainId || resolver.ledger.chainId;
382
+ const nodeRole = runtime?.role ?? "validator";
383
+ const followerAuthenticated = nodeRole === "follower" && typeof runtime?.isFollowerAuthenticated === "function" ? runtime.isFollowerAuthenticated() : void 0;
384
+ const trustedProposer = nodeRole === "follower" && typeof runtime?.getTrustedProposer === "function" ? runtime.getTrustedProposer() : void 0;
385
+ const trustedProposerPublicKey = nodeRole === "follower" && typeof runtime?.getTrustedProposerPublicKey === "function" ? runtime.getTrustedProposerPublicKey() : void 0;
386
+ const rawLedgerProposer = resolver.ledger.getProposer?.() || null;
387
+ const rawLedgerProposerPk = resolver.ledger.getProposerPublicKey?.() || null;
388
+ const proposer = nodeRole === "follower" ? trustedProposer || rawLedgerProposer : rawLedgerProposer;
389
+ const proposerPublicKey = nodeRole === "follower" ? trustedProposerPublicKey || (rawLedgerProposerPk && (!proposer || (0, _arcblock_ledger_core.verifyDidMatchesMultiCurvePublicKey)(proposer, rawLedgerProposerPk)) ? rawLedgerProposerPk : null) : rawLedgerProposerPk;
390
+ const signatureKeyType = proposerPublicKey ? (0, _arcblock_ledger_core.decodeMultiCurvePublicKey)(proposerPublicKey)?.curve ?? null : null;
391
+ const checkpointSigningEnabled = typeof resolver.ledger.isCheckpointSigningEnabled === "function" ? resolver.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
392
+ const writable = typeof runtime?.shouldHandleWriteLocally === "function" ? runtime.shouldHandleWriteLocally() : !runtime ? !resolver.readonly : runtime.role === "validator" && !resolver.readonly;
393
+ const entryHashV2From = formatEntryHashV2From(resolver.ledger);
394
+ let statusSignature = null;
395
+ if (proposer && typeof resolver.ledger.signConsensusDigest === "function") {
396
+ const cpHeight = latestCheckpoint?.height ?? 0;
397
+ const cpHash = latestCheckpoint?.hash ?? null;
398
+ const sigKey = `${chainId}|${latestSequence}|${cpHeight}|${cpHash ?? ""}|${writable ? 1 : 0}|${proposer}|${entryHashV2From ?? ""}`;
399
+ if (cachedStatusSigKey === sigKey && cachedStatusSigVal) statusSignature = cachedStatusSigVal;
400
+ else {
401
+ const digest = (0, _arcblock_ledger_core.computeHotTailStatusDigest)({
402
+ chainId,
403
+ latestSequence,
404
+ checkpointHeight: cpHeight,
405
+ checkpointHash: cpHash,
406
+ writable,
407
+ proposer,
408
+ entryHashV2From
409
+ });
410
+ statusSignature = await resolver.ledger.signConsensusDigest(digest);
411
+ if (statusSignature) {
412
+ cachedStatusSigKey = sigKey;
413
+ cachedStatusSigVal = statusSignature;
414
+ }
113
415
  }
416
+ }
417
+ const witnessRegistry = extLedger.getWitnessRegistry?.();
418
+ const consensusMode = runtime?.getConsensusMode?.();
419
+ const consensusView = runtime?.getConsensusView?.();
420
+ const highQC = runtime?.getHighQC?.();
421
+ const lastTC = runtime?.getLastTC?.();
422
+ const upstreamNodeId = runtime?.getUpstreamNodeId?.() ?? null;
423
+ const upstreamNodeRole = runtime?.getUpstreamNodeRole?.() ?? null;
424
+ const body = {
425
+ chainId,
426
+ latestSequence,
427
+ latestCheckpoint: latestCheckpoint ? {
428
+ ...latestCheckpoint,
429
+ timestamp: Math.trunc(Number(latestCheckpoint.timestamp))
430
+ } : null,
431
+ entryHashV2From,
432
+ proposer,
433
+ proposerPublicKey,
434
+ signatureKeyType,
435
+ checkpointSigningEnabled,
436
+ snapshotBaseUrl: resolveSnapshotBaseUrl(configuredSnapshotBaseUrl),
437
+ nodeRole,
438
+ ...nodeId !== void 0 ? { nodeId } : {},
439
+ ...followerAuthenticated !== void 0 ? { followerAuthenticated } : {},
440
+ ...trustedProposer !== void 0 ? { trustedProposer } : {},
441
+ ...trustedProposerPublicKey !== void 0 ? { trustedProposerPublicKey } : {},
442
+ upstreamNodeId,
443
+ upstreamNodeRole,
444
+ retentionMode: resolveRetentionMode(configuredRetentionMode),
445
+ witnessQuorum: witnessRegistry?.getQuorum() ?? 0,
446
+ writable,
447
+ halted: false,
448
+ statusSignature,
449
+ ...consensusMode ? { consensusMode } : {},
450
+ ...consensusView !== void 0 ? { consensusView } : {},
451
+ ...highQC !== void 0 ? { highQC } : {},
452
+ ...lastTC !== void 0 ? { lastTC } : {}
453
+ };
454
+ const reqCacheControl = String(req.headers["cache-control"] ?? "").toLowerCase();
455
+ const forceNoStore = reqCacheControl.includes("no-cache") || reqCacheControl.includes("no-store");
456
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
457
+ res.setHeader("X-Content-Type-Options", "nosniff");
458
+ res.setHeader("Cache-Control", forceNoStore ? "no-store" : "public, max-age=1, stale-while-revalidate=2");
459
+ res.status(200).json(body);
460
+ } catch (error) {
461
+ const message = error instanceof Error ? error.message : String(error);
462
+ res.status(500).json({
463
+ code: "INTERNAL_ERROR",
464
+ error: message
114
465
  });
466
+ }
467
+ });
468
+ router.get("/ledger/checkpoint", async (req, res) => {
469
+ const runtime = resolver.getNodeRuntime?.();
470
+ if (runtime?.isHalted?.()) return sendNodeHaltedJson(res);
471
+ if (runtime?.isReconciling?.()) return sendFollowerReconcilingJson(res);
472
+ const height = parsePositiveSafeIntParam(req.query.height);
473
+ if (height === null) {
474
+ res.setHeader("X-Content-Type-Options", "nosniff");
475
+ return res.status(400).json({
476
+ code: "INVALID_PARAMS",
477
+ error: "height is required and must be a positive safe integer >= 1"
478
+ });
479
+ }
480
+ try {
481
+ const checkpoint = await resolver.ledger.getCheckpoint(height);
482
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
483
+ res.setHeader("X-Content-Type-Options", "nosniff");
484
+ if (!checkpoint) {
485
+ res.setHeader("Cache-Control", "no-store");
486
+ return res.status(404).json({
487
+ code: "NOT_FOUND",
488
+ error: `Checkpoint at height ${height} not found`
489
+ });
490
+ }
491
+ const isFullySigned = !(typeof resolver.ledger.isCheckpointSigningEnabled === "function" ? resolver.ledger.isCheckpointSigningEnabled() : false) || Boolean(checkpoint.signature && checkpoint.signature !== "unsigned") && Boolean(checkpoint.segmentCommitmentSignature && checkpoint.segmentCommitmentSignature !== "unsigned");
492
+ res.setHeader("Cache-Control", isFullySigned ? "public, max-age=3600, immutable" : "no-store");
493
+ return res.status(200).json({
494
+ ...checkpoint,
495
+ timestamp: Math.trunc(Number(checkpoint.timestamp))
496
+ });
497
+ } catch (error) {
498
+ const message = error instanceof Error ? error.message : String(error);
499
+ return res.status(500).json({
500
+ code: "INTERNAL_ERROR",
501
+ error: message
502
+ });
503
+ }
504
+ });
505
+ router.get("/follower/status", async (req, res) => {
506
+ try {
507
+ let status = typeof resolver.getFollowerStatus === "function" ? await resolver.getFollowerStatus() : null;
508
+ if (!status) {
509
+ const [localSequence, latestCp, localStateCommitHash] = await Promise.all([
510
+ resolver.ledger.getLatestSequence(),
511
+ resolver.ledger.getCheckpoint(),
512
+ typeof resolver.statedb?.getCurrentCommitHash === "function" ? resolver.statedb.getCurrentCommitHash() : Promise.resolve("UNKNOWN")
513
+ ]);
514
+ status = {
515
+ chainId: resolver.config?.chainId || resolver.ledger.chainId,
516
+ nodeRole: "validator",
517
+ writePolicy: "reject",
518
+ syncMode: "primary",
519
+ synced: true,
520
+ halted: false,
521
+ haltReason: null,
522
+ localSequence,
523
+ upstreamSequence: localSequence,
524
+ syncLagEntries: 0,
525
+ verifiedCheckpointHeight: latestCp?.height ?? 0,
526
+ verifiedCheckpointHash: latestCp?.hash ?? null,
527
+ localStateCommitHash,
528
+ activeLeaderUrl: null,
529
+ lastUpstreamSuccessAt: null
530
+ };
531
+ }
532
+ const optionalState = apiAuthGuard.checkOptionalAdmin ? apiAuthGuard.checkOptionalAdmin(req, res) : apiAuthGuard.isAuthenticatedRequest(req) ? "admin" : "anonymous";
533
+ if (optionalState === "rate_limited") return;
534
+ const isAdmin = optionalState === "admin";
535
+ const redactedStatus = {
536
+ ...status,
537
+ activeLeaderUrl: isAdmin ? status.activeLeaderUrl ?? null : null
538
+ };
539
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
540
+ res.setHeader("X-Content-Type-Options", "nosniff");
541
+ res.setHeader("Cache-Control", "no-store");
542
+ return res.status(redactedStatus.halted ? 503 : 200).json(redactedStatus);
543
+ } catch (error) {
544
+ const message = error instanceof Error ? error.message : String(error);
545
+ return res.status(500).json({
546
+ code: "INTERNAL_ERROR",
547
+ error: message
548
+ });
549
+ }
550
+ });
551
+ router.get("/ledger/entries", async (req, res) => {
552
+ const runtime = resolver.getNodeRuntime?.();
553
+ if (runtime?.isHalted?.()) return sendNodeHaltedJson(res);
554
+ if (runtime?.isReconciling?.()) return sendFollowerReconcilingJson(res);
555
+ const from = parsePositiveSafeIntParam(req.query.from);
556
+ if (from === null || from > Number.MAX_SAFE_INTEGER - MAX_HOT_TAIL_LIMIT) {
557
+ res.setHeader("X-Content-Type-Options", "nosniff");
558
+ return res.status(400).json({
559
+ code: "INVALID_PARAMS",
560
+ error: "from is required and must be a positive safe integer >= 1"
561
+ });
562
+ }
563
+ let limit = MAX_HOT_TAIL_LIMIT;
564
+ if (req.query.limit !== void 0) {
565
+ const parsedLimit = parsePositiveSafeIntParam(req.query.limit);
566
+ if (parsedLimit === null || parsedLimit > MAX_HOT_TAIL_LIMIT) {
567
+ res.setHeader("X-Content-Type-Options", "nosniff");
568
+ return res.status(400).json({
569
+ code: "INVALID_PARAMS",
570
+ error: `limit must be a positive integer between 1 and ${MAX_HOT_TAIL_LIMIT}`
571
+ });
572
+ }
573
+ limit = parsedLimit;
574
+ }
575
+ try {
576
+ const to = from + limit - 1;
577
+ const latestCheckpointSeq = (await resolver.ledger.getCheckpoint())?.sequence ?? 0;
578
+ const [rawLatestSeq, rawEntries] = await Promise.all([resolver.ledger.getLatestSequence(), readHotEntriesRange(resolver.ledger, from, to)]);
579
+ const chainId = resolver.config?.chainId || resolver.ledger.chainId;
580
+ if ((rawEntries.length === 0 || rawEntries[0].sequence > from) && (from <= latestCheckpointSeq || rawEntries.length > 0)) {
581
+ if ((await readHotEntriesRange(resolver.ledger, from, from)).length === 0) {
582
+ res.setHeader("X-Content-Type-Options", "nosniff");
583
+ res.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=30");
584
+ return res.status(410).json({
585
+ code: "PRUNED_SEQUENCE",
586
+ error: "Requested sequence has been pruned from hot storage; fetch historical segments from cold archive",
587
+ from,
588
+ latestCheckpointSequence: latestCheckpointSeq,
589
+ snapshotBaseUrl: resolveSnapshotBaseUrl(configuredSnapshotBaseUrl)
590
+ });
591
+ }
592
+ }
593
+ let latestSequence = await resolveContiguousFinalizedSequence(resolver.ledger, rawLatestSeq, latestCheckpointSeq);
594
+ let candidateJsons = collectContiguousFinalizedEntryJsons(rawEntries, from, latestSequence);
595
+ if (candidateJsons.length === 0 && from <= latestSequence) {
596
+ const retryEntries = await readHotEntriesRange(resolver.ledger, from, to);
597
+ candidateJsons = collectContiguousFinalizedEntryJsons(retryEntries, from, latestSequence);
598
+ if (candidateJsons.length === 0) {
599
+ if ((retryEntries[0]?.sequence === from ? [retryEntries[0]] : await readHotEntriesRange(resolver.ledger, from, from)).length === 0) {
600
+ const refreshedCheckpoint = await resolver.ledger.getCheckpoint();
601
+ res.setHeader("X-Content-Type-Options", "nosniff");
602
+ res.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=30");
603
+ return res.status(410).json({
604
+ code: "PRUNED_SEQUENCE",
605
+ error: "Requested sequence has been pruned from hot storage; fetch historical segments from cold archive",
606
+ from,
607
+ latestCheckpointSequence: refreshedCheckpoint?.sequence ?? latestCheckpointSeq,
608
+ snapshotBaseUrl: resolveSnapshotBaseUrl(configuredSnapshotBaseUrl)
609
+ });
610
+ }
611
+ latestSequence = from - 1;
612
+ }
613
+ }
614
+ const entryHashV2From = formatEntryHashV2From(resolver.ledger);
615
+ const proposer = resolver.ledger.getProposer?.() || null;
616
+ const proposerPublicKey = resolver.ledger.getProposerPublicKey?.() || null;
617
+ const placeholderAttestation = {
618
+ entryHashV2From,
619
+ proposer,
620
+ proposerPublicKey,
621
+ batchSignature: proposer ? `0x${"0".repeat(130)}` : null
622
+ };
623
+ const acceptedItems = [];
624
+ let runningBytes = Buffer.byteLength(buildEntriesEnvelopeJson(chainId, from, limit, latestSequence, [], placeholderAttestation), "utf8") + 32;
625
+ for (let i = 0; i < candidateJsons.length; i++) {
626
+ const item = candidateJsons[i];
627
+ const commaBytes = acceptedItems.length > 0 ? 1 : 0;
628
+ if (runningBytes + commaBytes + item.bytes > effectiveMaxBytes) {
629
+ if (acceptedItems.length === 0) {
630
+ const singleEnvelope = buildEntriesEnvelopeJson(chainId, from, limit, latestSequence, [item.json], placeholderAttestation);
631
+ if (Buffer.byteLength(singleEnvelope, "utf8") <= effectiveMaxBytes) acceptedItems.push({
632
+ json: item.json,
633
+ entryCommitment: item.entryCommitment
634
+ });
635
+ else {
636
+ res.setHeader("X-Content-Type-Options", "nosniff");
637
+ res.setHeader("Cache-Control", "no-store");
638
+ return res.status(413).json({
639
+ code: "ENTRY_TOO_LARGE",
640
+ error: `Ledger entry at sequence ${from} exceeds ${effectiveMaxBytes}-byte hot-tail response limit`,
641
+ sequence: from
642
+ });
643
+ }
644
+ }
645
+ break;
646
+ }
647
+ acceptedItems.push({
648
+ json: item.json,
649
+ entryCommitment: item.entryCommitment
650
+ });
651
+ runningBytes += commaBytes + item.bytes;
652
+ }
653
+ const signBatchItems = async (items) => {
654
+ if (!proposer || typeof resolver.ledger.signConsensusDigest !== "function") return {
655
+ entryHashV2From,
656
+ proposer,
657
+ proposerPublicKey,
658
+ batchSignature: null
659
+ };
660
+ const entryCommitments = items.map((it) => it.entryCommitment);
661
+ const batchContentDigest = _ocap_mcrypto.Hasher.SHA2.hash256(Buffer.from(entryCommitments.join(","), "utf8"), 1, "hex");
662
+ const cacheKey = `${chainId}|${from}|${items.length}|${latestSequence}|${batchContentDigest}|${proposer}|${entryHashV2From ?? ""}`;
663
+ const cached = batchSigCache.get(cacheKey);
664
+ if (cached) return {
665
+ entryHashV2From,
666
+ proposer,
667
+ proposerPublicKey,
668
+ batchSignature: cached
669
+ };
670
+ const digest = (0, _arcblock_ledger_core.computeHotTailBatchDigest)({
671
+ chainId,
672
+ from,
673
+ count: items.length,
674
+ latestSequence,
675
+ entryCommitments,
676
+ proposer,
677
+ entryHashV2From
678
+ });
679
+ const sig = await resolver.ledger.signConsensusDigest(digest);
680
+ if (sig) {
681
+ if (batchSigCache.size >= MAX_BATCH_SIGNATURE_CACHE_ENTRIES) {
682
+ const oldestKey = batchSigCache.keys().next().value;
683
+ if (oldestKey !== void 0) batchSigCache.delete(oldestKey);
684
+ }
685
+ batchSigCache.set(cacheKey, sig);
686
+ }
687
+ return {
688
+ entryHashV2From,
689
+ proposer,
690
+ proposerPublicKey,
691
+ batchSignature: sig
692
+ };
693
+ };
694
+ let attestation = await signBatchItems(acceptedItems);
695
+ let responseBody = buildEntriesEnvelopeJson(chainId, from, limit, latestSequence, acceptedItems.map((it) => it.json), attestation);
696
+ while (acceptedItems.length > 1 && Buffer.byteLength(responseBody, "utf8") > effectiveMaxBytes) {
697
+ acceptedItems.pop();
698
+ attestation = await signBatchItems(acceptedItems);
699
+ responseBody = buildEntriesEnvelopeJson(chainId, from, limit, latestSequence, acceptedItems.map((it) => it.json), attestation);
700
+ }
701
+ if (Buffer.byteLength(responseBody, "utf8") > effectiveMaxBytes) {
702
+ res.setHeader("X-Content-Type-Options", "nosniff");
703
+ res.setHeader("Cache-Control", "no-store");
704
+ return res.status(413).json({
705
+ code: "ENTRY_TOO_LARGE",
706
+ error: `Ledger entry at sequence ${from} exceeds ${effectiveMaxBytes}-byte hot-tail response limit`,
707
+ sequence: from
708
+ });
709
+ }
710
+ const lastReturnedSeq = acceptedItems.length > 0 ? from + acceptedItems.length - 1 : 0;
711
+ const isSealedFullPage = acceptedItems.length === limit && lastReturnedSeq <= latestCheckpointSeq;
712
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
713
+ res.setHeader("X-Content-Type-Options", "nosniff");
714
+ res.setHeader("Cache-Control", isSealedFullPage ? "public, max-age=60, stale-while-revalidate=300" : "public, max-age=1, stale-while-revalidate=2");
715
+ return res.status(200).send(responseBody);
115
716
  } catch (error) {
116
717
  const message = error instanceof Error ? error.message : String(error);
117
718
  res.status(500).json({
118
- healthy: false,
719
+ code: "INTERNAL_ERROR",
720
+ error: message
721
+ });
722
+ }
723
+ });
724
+ router.post("/ledger/witness/attestations", async (req, res) => {
725
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
726
+ res.setHeader("X-Content-Type-Options", "nosniff");
727
+ res.setHeader("Cache-Control", "no-store");
728
+ const runtime = resolver.getNodeRuntime?.();
729
+ if (runtime?.isHalted?.()) return sendNodeHaltedJson(res);
730
+ if (runtime?.isReconciling?.()) return sendFollowerReconcilingJson(res);
731
+ const witnessRegistry = extLedger.getWitnessRegistry?.();
732
+ if (!witnessRegistry || !witnessRegistry.hasTrustedWitnessAllowlist()) return res.status(403).json({
733
+ code: "WITNESS_DISABLED",
734
+ accepted: false,
735
+ error: "Witness attestation ingestion is disabled on this node (no trustedWitnesses configured)"
736
+ });
737
+ const bodyRes = await readBoundedJsonBody(req, MAX_WITNESS_ATTESTATION_BODY_BYTES);
738
+ if (!bodyRes.ok) return res.status(bodyRes.status).json({
739
+ code: bodyRes.code,
740
+ accepted: false,
741
+ error: bodyRes.error
742
+ });
743
+ const checked = (0, _arcblock_ledger_core.validateWitnessAttestationStructure)(bodyRes.body && typeof bodyRes.body === "object" && !Array.isArray(bodyRes.body) && "attestation" in bodyRes.body ? bodyRes.body.attestation : bodyRes.body);
744
+ if (!checked.ok) return res.status(400).json({
745
+ code: "INVALID_ATTESTATION",
746
+ accepted: false,
747
+ error: checked.reason
748
+ });
749
+ try {
750
+ const maxAllowedHeight = ((await resolver.ledger.getCheckpoint())?.height ?? 0) + 4;
751
+ if (checked.attestation.height > maxAllowedHeight) return res.status(409).json({
752
+ code: "HEIGHT_AHEAD_OF_LEDGER",
753
+ accepted: false,
754
+ error: `Witness attestation height ${checked.attestation.height} exceeds local checkpoint horizon ${maxAllowedHeight}`
755
+ });
756
+ const submitRes = await witnessRegistry.submitAttestation(checked.attestation);
757
+ if (!submitRes.accepted) {
758
+ const reason = submitRes.reason || "Witness attestation rejected";
759
+ if (/horizon|ahead/i.test(reason)) return res.status(409).json({
760
+ code: "HEIGHT_AHEAD_OF_LEDGER",
761
+ accepted: false,
762
+ error: reason
763
+ });
764
+ const isAuthFailure = /untrusted|signature|public key|witnessPublicKey|allowlist/i.test(reason);
765
+ return res.status(isAuthFailure ? 403 : 400).json({
766
+ code: isAuthFailure ? "FORBIDDEN" : "INVALID_ATTESTATION",
767
+ accepted: false,
768
+ error: reason
769
+ });
770
+ }
771
+ const cp = await resolver.ledger.getCheckpoint(checked.attestation.height);
772
+ const quorum = cp ? await witnessRegistry.evaluateCheckpoint(cp) : void 0;
773
+ return res.status(200).json({
774
+ accepted: true,
775
+ height: checked.attestation.height,
776
+ ...quorum ? { quorum } : {}
777
+ });
778
+ } catch (error) {
779
+ const message = error instanceof Error ? error.message : String(error);
780
+ return res.status(500).json({
781
+ code: "INTERNAL_ERROR",
782
+ accepted: false,
783
+ error: message
784
+ });
785
+ }
786
+ });
787
+ router.get("/ledger/witness/quorum", async (req, res) => {
788
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
789
+ res.setHeader("X-Content-Type-Options", "nosniff");
790
+ res.setHeader("Cache-Control", "no-store");
791
+ const runtime = resolver.getNodeRuntime?.();
792
+ if (runtime?.isHalted?.()) return sendNodeHaltedJson(res);
793
+ if (runtime?.isReconciling?.()) return sendFollowerReconcilingJson(res);
794
+ let requestedHeight = null;
795
+ if (req.query.height !== void 0) {
796
+ requestedHeight = parsePositiveSafeIntParam(req.query.height);
797
+ if (requestedHeight === null) return res.status(400).json({
798
+ code: "INVALID_PARAMS",
799
+ error: "height must be a positive safe integer >= 1"
800
+ });
801
+ }
802
+ try {
803
+ const checkpoint = requestedHeight !== null ? await resolver.ledger.getCheckpoint(requestedHeight) : await resolver.ledger.getCheckpoint();
804
+ if (!checkpoint) return res.status(404).json({
805
+ code: "NOT_FOUND",
806
+ error: requestedHeight !== null ? `Checkpoint at height ${requestedHeight} not found` : "No checkpoint sealed yet"
807
+ });
808
+ const chainId = resolver.config?.chainId || resolver.ledger.chainId;
809
+ const witnessRegistry = extLedger.getWitnessRegistry?.();
810
+ const quorum = witnessRegistry ? await witnessRegistry.evaluateCheckpoint(checkpoint) : {
811
+ finalized: true,
812
+ validCount: 0,
813
+ requiredQuorum: 0,
814
+ circuitBroken: false,
815
+ fraudAlerts: []
816
+ };
817
+ const attestations = witnessRegistry ? typeof witnessRegistry.getAttestationsAsync === "function" ? await witnessRegistry.getAttestationsAsync(checkpoint.height) : witnessRegistry.getAttestations(checkpoint.height) : [];
818
+ return res.status(200).json({
819
+ chainId,
820
+ height: checkpoint.height,
821
+ checkpointHash: checkpoint.hash,
822
+ ...quorum,
823
+ attestations
824
+ });
825
+ } catch (error) {
826
+ const message = error instanceof Error ? error.message : String(error);
827
+ return res.status(500).json({
828
+ code: "INTERNAL_ERROR",
829
+ error: message
830
+ });
831
+ }
832
+ });
833
+ router.get("/ledger/anchors", async (req, res) => {
834
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
835
+ res.setHeader("X-Content-Type-Options", "nosniff");
836
+ res.setHeader("Cache-Control", "no-store");
837
+ const runtime = resolver.getNodeRuntime?.();
838
+ if (runtime?.isHalted?.()) return sendNodeHaltedJson(res);
839
+ if (runtime?.isReconciling?.()) return sendFollowerReconcilingJson(res);
840
+ let requestedHeight = null;
841
+ if (req.query.height !== void 0) {
842
+ requestedHeight = parsePositiveSafeIntParam(req.query.height);
843
+ if (requestedHeight === null) return res.status(400).json({
844
+ code: "INVALID_PARAMS",
845
+ error: "height must be a positive safe integer >= 1"
846
+ });
847
+ }
848
+ try {
849
+ const chainId = resolver.config?.chainId || resolver.ledger.chainId;
850
+ const anchorPublisher = extLedger.getAnchorPublisher?.();
851
+ const receipt = typeof anchorPublisher?.getReceiptAsync === "function" ? await anchorPublisher.getReceiptAsync(requestedHeight ?? void 0) : requestedHeight !== null ? anchorPublisher?.getReceipt?.(requestedHeight) ?? null : anchorPublisher?.getLatestReceipt?.() ?? null;
852
+ if (!receipt) return res.status(404).json({
853
+ code: "NOT_FOUND",
854
+ error: requestedHeight !== null ? `Anchor receipt at height ${requestedHeight} not found` : "No anchor receipt published yet"
855
+ });
856
+ return res.status(200).json({
857
+ chainId,
858
+ receipt
859
+ });
860
+ } catch (error) {
861
+ const message = error instanceof Error ? error.message : String(error);
862
+ return res.status(500).json({
863
+ code: "INTERNAL_ERROR",
864
+ error: message
865
+ });
866
+ }
867
+ });
868
+ router.get("/ledger/proof", async (req, res) => {
869
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
870
+ res.setHeader("X-Content-Type-Options", "nosniff");
871
+ const runtime = resolver.getNodeRuntime?.();
872
+ if (runtime?.isHalted?.()) return sendNodeHaltedJson(res);
873
+ if (runtime?.isReconciling?.()) return sendFollowerReconcilingJson(res);
874
+ const hasSeqParam = req.query.sequence !== void 0;
875
+ if (hasSeqParam === (req.query.hash !== void 0)) {
876
+ res.setHeader("Cache-Control", "no-store");
877
+ return res.status(400).json({
878
+ code: "INVALID_PARAMS",
879
+ error: "Exactly one of sequence or hash query parameters is required"
880
+ });
881
+ }
882
+ let requestedSeq = null;
883
+ let requestedHash = null;
884
+ if (hasSeqParam) {
885
+ requestedSeq = parsePositiveSafeIntParam(req.query.sequence);
886
+ if (requestedSeq === null) {
887
+ res.setHeader("Cache-Control", "no-store");
888
+ return res.status(400).json({
889
+ code: "INVALID_PARAMS",
890
+ error: "sequence must be a positive safe integer >= 1"
891
+ });
892
+ }
893
+ } else {
894
+ if (typeof req.query.hash !== "string" || !req.query.hash.trim() || req.query.hash.length > 256) {
895
+ res.setHeader("Cache-Control", "no-store");
896
+ return res.status(400).json({
897
+ code: "INVALID_PARAMS",
898
+ error: "hash must be a non-empty transaction hash string"
899
+ });
900
+ }
901
+ requestedHash = req.query.hash.trim();
902
+ }
903
+ try {
904
+ let latestCheckpoint = await resolver.ledger.getCheckpoint();
905
+ let entry = null;
906
+ if (requestedSeq !== null) {
907
+ if (!latestCheckpoint || requestedSeq > latestCheckpoint.sequence) {
908
+ const latestSeq = await resolver.ledger.getLatestSequence();
909
+ res.setHeader("Cache-Control", "no-store");
910
+ if (requestedSeq <= latestSeq) return res.status(409).json({
911
+ code: "CHECKPOINT_PENDING",
912
+ error: `Entry at sequence ${requestedSeq} is not yet sealed in a checkpoint`,
913
+ sequence: requestedSeq,
914
+ latestCheckpointSequence: latestCheckpoint?.sequence ?? 0
915
+ });
916
+ return res.status(404).json({
917
+ code: "NOT_FOUND",
918
+ error: `Entry at sequence ${requestedSeq} not found`
919
+ });
920
+ }
921
+ entry = await resolver.ledger.getBySequence(requestedSeq);
922
+ if (!entry) {
923
+ res.setHeader("Cache-Control", "no-store");
924
+ return res.status(404).json({
925
+ code: "NOT_FOUND",
926
+ error: `Entry at sequence ${requestedSeq} not found`
927
+ });
928
+ }
929
+ } else if (requestedHash !== null) {
930
+ entry = await resolver.ledger.get(requestedHash);
931
+ if (!entry) {
932
+ res.setHeader("Cache-Control", "no-store");
933
+ return res.status(404).json({
934
+ code: "NOT_FOUND",
935
+ error: `Transaction ${requestedHash} not found`
936
+ });
937
+ }
938
+ if (!latestCheckpoint || entry.sequence > latestCheckpoint.sequence) {
939
+ latestCheckpoint = await resolver.ledger.getCheckpoint();
940
+ if (!latestCheckpoint || entry.sequence > latestCheckpoint.sequence) {
941
+ res.setHeader("Cache-Control", "no-store");
942
+ return res.status(409).json({
943
+ code: "CHECKPOINT_PENDING",
944
+ error: `Transaction ${requestedHash} (sequence ${entry.sequence}) is not yet sealed in a checkpoint`,
945
+ sequence: entry.sequence,
946
+ latestCheckpointSequence: latestCheckpoint?.sequence ?? 0
947
+ });
948
+ }
949
+ }
950
+ }
951
+ if (!entry) {
952
+ res.setHeader("Cache-Control", "no-store");
953
+ return res.status(404).json({
954
+ code: "NOT_FOUND",
955
+ error: "Entry not found"
956
+ });
957
+ }
958
+ const [merkleProof, checkpoint] = await Promise.all([resolver.ledger.getMerkleProof(entry.sequence), typeof resolver.ledger.getCheckpointForSequence === "function" ? resolver.ledger.getCheckpointForSequence(entry.sequence) : resolver.ledger.getCheckpoint()]);
959
+ if (!merkleProof || !checkpoint) {
960
+ res.setHeader("Cache-Control", "no-store");
961
+ return res.status(404).json({
962
+ code: "NOT_FOUND",
963
+ error: `Merkle proof unavailable for sequence ${entry.sequence}`
964
+ });
965
+ }
966
+ const chainId = resolver.config?.chainId || resolver.ledger.chainId;
967
+ const entryHashV2From = formatEntryHashV2From(resolver.ledger);
968
+ const proposer = resolver.ledger.getProposer?.() || checkpoint.proposer || null;
969
+ const proposerPublicKey = resolver.ledger.getProposerPublicKey?.() || null;
970
+ const witnessRegistry = extLedger.getWitnessRegistry?.();
971
+ const anchorPublisher = extLedger.getAnchorPublisher?.();
972
+ const [witnessAttestations, anchorReceipt] = await Promise.all([witnessRegistry ? typeof witnessRegistry.getAttestationsAsync === "function" ? witnessRegistry.getAttestationsAsync(checkpoint.height) : Promise.resolve(witnessRegistry.getAttestations(checkpoint.height)) : Promise.resolve([]), typeof anchorPublisher?.getReceiptAsync === "function" ? anchorPublisher.getReceiptAsync(checkpoint.height) : Promise.resolve(anchorPublisher?.getReceipt?.(checkpoint.height) ?? null)]);
973
+ res.setHeader("Cache-Control", "public, max-age=5, stale-while-revalidate=30");
974
+ return res.status(200).json({
975
+ chainId,
976
+ entry: {
977
+ ...entry,
978
+ timestamp: Math.trunc(Number(entry.timestamp))
979
+ },
980
+ proof: merkleProof,
981
+ checkpoint: {
982
+ ...checkpoint,
983
+ timestamp: Math.trunc(Number(checkpoint.timestamp))
984
+ },
985
+ entryHashV2From,
986
+ proposer,
987
+ proposerPublicKey,
988
+ witnessQuorum: witnessRegistry?.getQuorum() ?? 0,
989
+ witnessAttestations,
990
+ anchorReceipt
991
+ });
992
+ } catch (error) {
993
+ res.setHeader("Cache-Control", "no-store");
994
+ if (error?.code === "COLD_READ_BUSY") {
995
+ res.setHeader("Retry-After", "1");
996
+ const message$1 = error instanceof Error ? error.message : "Cold archive read concurrency limit reached";
997
+ return res.status(503).json({
998
+ code: "COLD_READ_BUSY",
999
+ error: message$1
1000
+ });
1001
+ }
1002
+ const message = error instanceof Error ? error.message : String(error);
1003
+ return res.status(500).json({
1004
+ code: "INTERNAL_ERROR",
119
1005
  error: message
120
1006
  });
121
1007
  }
@@ -124,4 +1010,7 @@ function createAPIHandler({ resolver }) {
124
1010
  }
125
1011
 
126
1012
  //#endregion
1013
+ exports.MAX_HOT_TAIL_LIMIT = MAX_HOT_TAIL_LIMIT;
1014
+ exports.MAX_HOT_TAIL_RESPONSE_BYTES = MAX_HOT_TAIL_RESPONSE_BYTES;
1015
+ exports.MAX_WITNESS_ATTESTATION_BODY_BYTES = MAX_WITNESS_ATTESTATION_BODY_BYTES;
127
1016
  exports.createAPIHandler = createAPIHandler;