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