@odatano/core 2.0.0-rc.2 → 2.0.0-rc.20

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 (132) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +224 -0
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. package/srv/utils/validators.js +31 -138
@@ -7,7 +7,9 @@ exports.CardanoCrawler = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const errors_1 = require("../../utils/errors");
9
9
  const collections_1 = require("../../utils/collections");
10
+ const const_1 = require("../../utils/const");
10
11
  const hooks_1 = require("./hooks");
12
+ const ledger_state_1 = require("../ledger-state");
11
13
  const cardano_1 = require("#cds-models/odatano/cardano");
12
14
  const sync_state_1 = require("./sync-state");
13
15
  const { SELECT, DELETE, INSERT } = cds_1.default.ql;
@@ -20,19 +22,9 @@ class CrawlerLeaseLostError extends Error {
20
22
  constructor() { super('Crawler DB lease lost'); this.name = 'CrawlerLeaseLostError'; }
21
23
  }
22
24
  /**
23
- * CardanoCrawler — pre-sync engine (v2.0). Streams the chain forward from a configured
24
- * start block and bulk-indexes Blocks + Transactions (+ inputs/outputs/assets) into the
25
- * DB, so consumers can query local data instead of hitting a backend per request.
26
- *
27
- * Two sources (see CRAWLER_DESIGN.md):
28
- * - **Ogmios chain-sync** (primary): ordered rollForward + native rollBackward (reorg).
29
- * - **Blockfrost/Koios pagination** (fallback): forward walk + parent-hash reorg recovery.
30
- *
31
- * Lifecycle: start() launches the ingest pipeline detached so the HTTP server binds
32
- * immediately, but the pipeline promise is retained — stop() halts the loops (waking
33
- * any pending poll sleep) and AWAITS the pipeline, so shutdown never races in-flight
34
- * block writes. All per-block writes are atomic. The crawler NEVER crawls from genesis
35
- * implicitly — it requires an explicit configured start point or an existing cursor.
25
+ * Pre-sync engine: streams the chain forward from a start block and bulk-indexes it. Sources:
26
+ * Ogmios chain-sync (primary, native rollBackward) or Blockfrost/Koios pagination (fallback).
27
+ * Per-block writes are atomic; stop() awaits the detached pipeline; no implicit genesis crawl.
36
28
  */
37
29
  class CardanoCrawler {
38
30
  client;
@@ -42,10 +34,42 @@ class CardanoCrawler {
42
34
  leaseOwner;
43
35
  /** Transient-failure retries per block before giving up. */
44
36
  static PERSIST_RETRIES = 3;
37
+ /** Final persist failures for the same block across restarts before the crawler latches off (poison block). */
38
+ static POISON_BLOCK_THRESHOLD = 5;
39
+ /** Process-wide, survives instance restarts: the block currently failing and how often. */
40
+ static poison = null;
41
+ /**
42
+ * Errors deterministic for the block's data — only these count towards the poison latch.
43
+ * Outages, statement timeouts and exhausted pools are fixed by a restart and must not latch.
44
+ */
45
+ static DATA_REJECTION_PATTERNS = [
46
+ /unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
47
+ /invalid byte sequence for encoding/i, // PostgreSQL: bytes that are not valid UTF-8
48
+ /out of range for type/i, // PostgreSQL: bigint / integer overflow
49
+ /invalid input syntax for type/i, // PostgreSQL: NaN or text in a numeric column
50
+ /value too long for type/i, // PostgreSQL: varchar(n) exceeded
51
+ /numeric value out of range/i, // HANA / SQL-92
52
+ /inserted value too large for column/i, // HANA
53
+ /string or blob too big/i, // SQLite
54
+ /datatype mismatch/i, // SQLite
55
+ ];
45
56
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
46
57
  static CALL_TIMEOUT_MS = 60_000;
58
+ /** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
59
+ static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
60
+ /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
61
+ static SNAPSHOT_RETRY_BASE_MS = 30_000;
62
+ static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
63
+ /** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
64
+ static CHAIN_SYNC_RETRY_MS = 30_000;
47
65
  running = false;
48
66
  chainSyncHandle = null;
67
+ /** What the ingest loop is currently reading from; null while stopped. */
68
+ activeSource = null;
69
+ /** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
70
+ chainSyncProbeTimer = null;
71
+ chainSyncProbe = null;
72
+ chainSyncRecovered = false;
49
73
  /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
50
74
  pipeline = null;
51
75
  /** Resolver that cancels a pending poll sleep (set while sleeping). */
@@ -55,9 +79,19 @@ class CardanoCrawler {
55
79
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
56
80
  inFlightCallbacks = new Set();
57
81
  haltPromise = null;
82
+ /** An unparseable chain-sync frame; the ingest loop fetches that block via pagination, then reopens chain-sync. */
83
+ frameFailure = null;
84
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
85
+ streamEnded = null;
58
86
  finalStatus = 'stopped';
59
87
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
60
88
  latchOnHalt = false;
89
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
90
+ snapshotedEpoch = null;
91
+ snapshotInFlight = null;
92
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
93
+ snapshotFailures = 0;
94
+ snapshotRetryAfter = 0;
61
95
  leaseHeld = false;
62
96
  leaseHeartbeat = null;
63
97
  leaseWake = null;
@@ -73,6 +107,14 @@ class CardanoCrawler {
73
107
  isRunning() {
74
108
  return this.running;
75
109
  }
110
+ /** True once the crawler halted because of a failure (not via stop() or a lost lease). */
111
+ haltedWithError() {
112
+ return !this.running && this.finalStatus === 'error';
113
+ }
114
+ /** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
115
+ getActiveSource() {
116
+ return this.running ? this.activeSource : null;
117
+ }
76
118
  /**
77
119
  * Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
78
120
  * Refuses to start without a resume point: an explicit configured start block or an
@@ -102,6 +144,39 @@ class CardanoCrawler {
102
144
  }
103
145
  }
104
146
  this.running = true;
147
+ // Hand the analytics coverage to the indexer before the first block is written.
148
+ this.indexer.configureCrawlCoverage({
149
+ assetHistory: this.config.assetHistory,
150
+ assetCatalogue: this.config.assetCatalogue,
151
+ assetEnrichRate: this.config.assetEnrichRate,
152
+ certificates: this.config.certificates,
153
+ utxoSet: this.config.utxoSet,
154
+ });
155
+ // Ledger state is only ever applied from a known anchor — no snapshot, no writes.
156
+ if (this.config.utxoSet) {
157
+ const u = cursor.utxoSet;
158
+ // Blocks crawled while the mode was off never reached the ledger tables: the cursor is
159
+ // ahead of the last applied slot and the set cannot be caught up — invalidate it.
160
+ const lastApplied = u.appliedSlot ?? u.anchorSlot;
161
+ if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
162
+ const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied} — blocks were crawled without the set; re-import`;
163
+ await cds_1.default.tx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error }));
164
+ u.status = 'invalid';
165
+ u.error = error;
166
+ }
167
+ if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
168
+ this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
169
+ logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash} — ledger tables are maintained`);
170
+ }
171
+ else {
172
+ this.indexer.setUtxoAnchor(null);
173
+ logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''} — ` +
174
+ 'ledger tables are not maintained until importUtxoSet has run (pause the crawler first)');
175
+ }
176
+ }
177
+ else {
178
+ this.indexer.setUtxoAnchor(null);
179
+ }
105
180
  this.startLeaseHeartbeat();
106
181
  // A pipeline crash (e.g. chain-sync intersection not found after downtime) must
107
182
  // surface on the cursor — otherwise the crawler looks healthy while doing nothing.
@@ -116,10 +191,8 @@ class CardanoCrawler {
116
191
  });
117
192
  }
118
193
  /**
119
- * Stop crawling and WAIT for the pipeline to finish its in-flight step: halts the
120
- * loops (waking any pending poll sleep), closes the chain-sync stream, records the
121
- * final status, then awaits the detached pipeline so callers (shutdownAppContext)
122
- * can safely tear down backends/DB afterwards.
194
+ * Stop crawling and await the pipeline's in-flight step, so callers can tear down
195
+ * backends/DB afterwards.
123
196
  */
124
197
  async stop(finalStatus = 'stopped') {
125
198
  this.beginHalt(finalStatus);
@@ -128,24 +201,14 @@ class CardanoCrawler {
128
201
  this.pipeline = null;
129
202
  }
130
203
  /**
131
- * Halt without awaiting the pipeline — the variant safe to call FROM INSIDE the
132
- * pipeline (persistBlock failure, stream onError), where awaiting the pipeline
133
- * would deadlock.
134
- */
135
- /**
136
- * @param latch clears `desiredRunning`, so NO restart brings the crawler back —
137
- * only an operator's resumeCrawler does. Reserved for failures a restart cannot
138
- * fix (misconfiguration, missing resume point). Runtime failures — a dropped
139
- * chain-sync socket, a provider outage, a node restart — must leave it false,
140
- * otherwise a routine node restart silently disables the pre-sync for good.
204
+ * Halt without awaiting the pipeline — safe to call from inside it.
205
+ * @param latch clears `desiredRunning` so no restart brings the crawler back; only for failures
206
+ * a restart cannot fix (misconfiguration, missing resume point), never for runtime outages.
141
207
  */
142
208
  async halt(finalStatus = 'stopped', latch = false) {
143
209
  this.beginHalt(finalStatus, latch);
144
210
  }
145
- /**
146
- * Start teardown without awaiting it. Internal callers can therefore halt from
147
- * inside a tracked callback/pipeline without waiting on their own promise.
148
- */
211
+ /** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
149
212
  beginHalt(finalStatus, latch = false) {
150
213
  if (latch)
151
214
  this.latchOnHalt = true;
@@ -153,7 +216,12 @@ class CardanoCrawler {
153
216
  if (this.finalStatus !== 'error' || finalStatus === 'error')
154
217
  this.finalStatus = finalStatus;
155
218
  this.running = false;
219
+ this.activeSource = null;
220
+ // Background asset enrichment belongs to the crawl — it must not outlive it.
221
+ this.indexer.stopAssetEnrichment();
156
222
  this.wake?.(); // cancel a pending poll sleep so the loop exits now
223
+ this.stopChainSyncProbing();
224
+ this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
157
225
  this.leaseWake?.();
158
226
  for (const cancel of [...this.callCancels])
159
227
  cancel();
@@ -180,6 +248,8 @@ class CardanoCrawler {
180
248
  }
181
249
  if (this.leaseHeartbeat)
182
250
  await this.leaseHeartbeat.catch(() => undefined);
251
+ if (this.chainSyncProbe)
252
+ await this.chainSyncProbe.catch(() => undefined);
183
253
  try {
184
254
  if (this.leaseOwner && this.leaseHeld) {
185
255
  await cds_1.default.tx((tx) => (0, sync_state_1.releaseCrawlerLease)(tx, this.leaseOwner, this.finalStatus, this.latchOnHalt));
@@ -193,19 +263,81 @@ class CardanoCrawler {
193
263
  });
194
264
  }
195
265
  async runIngestPipeline() {
196
- const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
197
- if (chainSync) {
198
- await this.runChainSync(chainSync);
199
- return;
266
+ while (this.running) {
267
+ const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
268
+ if (chainSync) {
269
+ // One pass per chain-sync stream. An unparseable frame ends the stream, not the crawler:
270
+ // pagination fetches that block, then chain-sync takes over again. Other errors halt.
271
+ while (this.running) {
272
+ const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
273
+ await this.runChainSync(chainSync);
274
+ if (!this.chainSyncHandle)
275
+ return; // open refused, halted, or stop() raced us
276
+ await streamEnd;
277
+ const failure = this.takeFrameFailure();
278
+ if (!this.running || failure?.height == null)
279
+ return;
280
+ logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
281
+ await this.runPagination({ untilHeight: failure.height + 1 });
282
+ }
283
+ return;
284
+ }
285
+ if (this.config.source === 'ogmios') {
286
+ // 'ogmios' means chain-sync ONLY — never silently degrade to the weaker
287
+ // pagination reorg handling the operator explicitly opted out of.
288
+ logger.error("Crawler source is 'ogmios' but no chain-sync backend is available — crawler not started (use source 'auto' to allow pagination fallback).");
289
+ await this.halt('error', true); // config error: a restart cannot fix it
290
+ return;
291
+ }
292
+ if (this.config.source === 'pagination') {
293
+ await this.runPagination();
294
+ return;
295
+ }
296
+ // 'auto' with no usable chain-sync backend (typical while the node still replays after a
297
+ // restart): crawl on pagination and keep retrying chain-sync.
298
+ logger.warn('No chain-sync backend usable — crawling on pagination and retrying chain-sync periodically');
299
+ await this.runPagination({ untilChainSync: true });
300
+ // Returned because chain-sync came back (or we stopped): the loop reopens it.
200
301
  }
201
- if (this.config.source === 'ogmios') {
202
- // 'ogmios' means chain-sync ONLY — never silently degrade to the weaker
203
- // pagination reorg handling the operator explicitly opted out of.
204
- logger.error("Crawler source is 'ogmios' but no chain-sync backend is available — crawler not started (use source 'auto' to allow pagination fallback).");
205
- await this.halt('error', true); // config error: a restart cannot fix it
302
+ }
303
+ /**
304
+ * Retry the init of a chain-sync backend on its own timer (a poll sleep can be an hour long),
305
+ * one probe at a time. On success `chainSyncRecovered` is set and a pending sleep is cut short;
306
+ * the pagination loop leaves at its next check and the ingest loop reopens chain-sync.
307
+ */
308
+ startChainSyncProbing() {
309
+ this.chainSyncRecovered = false;
310
+ // The startup init has only just failed — give the node a full interval first.
311
+ this.scheduleChainSyncProbe();
312
+ }
313
+ scheduleChainSyncProbe() {
314
+ if (!this.running || this.chainSyncRecovered || this.chainSyncProbeTimer)
206
315
  return;
207
- }
208
- await this.runPagination();
316
+ const timer = setTimeout(() => {
317
+ this.chainSyncProbeTimer = null;
318
+ if (!this.running || this.chainSyncRecovered)
319
+ return;
320
+ this.chainSyncProbe = this.client.recoverChainSyncBackend()
321
+ .then((backend) => {
322
+ if (!backend || !this.running)
323
+ return;
324
+ this.chainSyncRecovered = true;
325
+ this.wake?.(); // a poll sleep must not hold the handover back
326
+ })
327
+ .catch((err) => logger.debug('chain-sync probe failed:', err))
328
+ .finally(() => {
329
+ this.chainSyncProbe = null;
330
+ this.scheduleChainSyncProbe();
331
+ });
332
+ }, CardanoCrawler.CHAIN_SYNC_RETRY_MS);
333
+ timer.unref?.(); // never keep the process alive for a probe
334
+ this.chainSyncProbeTimer = timer;
335
+ }
336
+ stopChainSyncProbing() {
337
+ if (!this.chainSyncProbeTimer)
338
+ return;
339
+ clearTimeout(this.chainSyncProbeTimer);
340
+ this.chainSyncProbeTimer = null;
209
341
  }
210
342
  /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
211
343
  withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS) {
@@ -262,6 +394,12 @@ class CardanoCrawler {
262
394
  onError: (err) => this.trackCallback(async () => {
263
395
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
264
396
  return;
397
+ // A frame the client's parser cannot handle is a fault of that one block, not of the
398
+ // crawler or the node — pagination can still fetch it, so degrade instead of halting.
399
+ if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
400
+ await this.degradeToPagination(err);
401
+ return;
402
+ }
265
403
  // The stream is stalled (mapping/callback failure) — record and halt cleanly
266
404
  // so the cursor status shows 'error' instead of a healthy-looking hang.
267
405
  const streak = await this.recordCrawlerError(err);
@@ -278,19 +416,52 @@ class CardanoCrawler {
278
416
  return;
279
417
  }
280
418
  this.chainSyncHandle = handle;
419
+ this.activeSource = 'chain-sync';
281
420
  logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
282
421
  }
422
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
423
+ takeFrameFailure() {
424
+ const failure = this.frameFailure;
425
+ this.frameFailure = null;
426
+ return failure;
427
+ }
428
+ /**
429
+ * Whether an unparseable frame can be worked around over HTTP: needs a height, a paginating
430
+ * backend, and a source not pinned to 'ogmios' (chain-sync only).
431
+ */
432
+ canDegradeToPagination(err) {
433
+ return err.height != null
434
+ && this.config.source !== 'ogmios'
435
+ && !!this.client.getPaginatingBackend();
436
+ }
437
+ /**
438
+ * End the chain-sync stream and hand back to the ingest loop, which continues on pagination
439
+ * past the offending block. The error is recorded first so `lastError` names the block.
440
+ */
441
+ async degradeToPagination(err) {
442
+ const streak = await this.recordCrawlerError(err);
443
+ if (streak < 0) {
444
+ await this.halt('stopped');
445
+ return;
446
+ }
447
+ logger.error('Chain-sync frame unusable — continuing on pagination:', err.message);
448
+ this.frameFailure = err;
449
+ const handle = this.chainSyncHandle;
450
+ this.chainSyncHandle = null;
451
+ if (handle) {
452
+ try {
453
+ await handle.close();
454
+ }
455
+ catch (e) {
456
+ logger.warn('chain-sync close failed:', e);
457
+ }
458
+ }
459
+ this.streamEnded?.();
460
+ }
283
461
  /**
284
- * Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
285
- * spaced ladder of our own already-crawled ancestors, then the configured start
286
- * block as the deepest anchor.
287
- *
288
- * Why more than the cursor: if the cursor's block was orphaned while the crawler
289
- * was down, a single-point intersection fails outright ("No intersection found")
290
- * and the stream never opens. With ancestors on the list the node intersects at
291
- * the last common block and reports it as a rollBackward — the ordinary reorg path
292
- * that handleReorg already implements. Doubling offsets cover ~32k blocks with 16
293
- * points; anything deeper is past any realistic rollback and should fail loudly.
462
+ * Candidate intersection points, newest first: the cursor, a ladder of already-crawled
463
+ * ancestors, then the configured start block. If the cursor's block was orphaned while the
464
+ * crawler was down, the node intersects at the last common ancestor and reports a rollBackward.
294
465
  */
295
466
  async buildIntersectionPoints(cursor) {
296
467
  const points = [];
@@ -303,11 +474,8 @@ class CardanoCrawler {
303
474
  };
304
475
  if (cursor?.lastBlockHash) {
305
476
  add({ slot: cursor.lastSlot, hash: cursor.lastBlockHash, height: cursor.lastHeight });
306
- // Dense over the last DENSE_DEPTH blocks, doubling after that. Real rollbacks
307
- // are a handful of blocks deep, and those must intersect EXACTLY — a gap in
308
- // the ladder is not wrong (rolling back too far only re-crawls), but it costs
309
- // needless work on the common case. The doubling tail keeps the deep-reorg
310
- // reach without sending hundreds of points.
477
+ // Dense over the last DENSE_DEPTH blocks (real rollbacks are shallow and must intersect
478
+ // exactly), doubling after that for deep-reorg reach without hundreds of points.
311
479
  const DENSE_DEPTH = 10;
312
480
  const heights = [];
313
481
  const pushHeight = (height) => { if (height > 0 && !heights.includes(height))
@@ -339,27 +507,51 @@ class CardanoCrawler {
339
507
  // ---------------------------------------------------------------------------
340
508
  // Pagination (Blockfrost/Koios) — fallback
341
509
  // ---------------------------------------------------------------------------
342
- async runPagination() {
510
+ /**
511
+ * @param untilHeight return once the cursor reaches it — walks past a block chain-sync
512
+ * cannot deliver, then hands back.
513
+ * @param untilChainSync retry a chain-sync backend in the background; return once one is usable.
514
+ */
515
+ async runPagination(opts = {}) {
516
+ if (opts.untilChainSync)
517
+ this.startChainSyncProbing();
518
+ try {
519
+ await this.paginate(opts);
520
+ }
521
+ finally {
522
+ this.stopChainSyncProbing();
523
+ }
524
+ }
525
+ async paginate({ untilHeight, untilChainSync = false }) {
343
526
  const backend = this.client.getPaginatingBackend();
344
527
  if (!backend) {
345
528
  logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
346
529
  await this.halt('error', true); // config error: a restart cannot fix it
347
530
  return;
348
531
  }
532
+ backend.configureCrawl?.({ certificates: this.config.certificates });
533
+ this.activeSource = 'pagination';
349
534
  logger.info('Crawler running (pagination)');
350
- // Tip cache: during deep catch-up the exact tip is irrelevant (only "am I still
351
- // behind the target" matters) — refetching it every round wasted one HTTP call
352
- // per batch. Refresh only when the cursor reaches the cached target.
535
+ // Tip cache, refreshed only when the cursor reaches the cached target; during catch-up
536
+ // the exact tip is irrelevant.
353
537
  let tip = null;
354
538
  let target = Number.NEGATIVE_INFINITY;
355
539
  while (this.running) {
356
540
  try {
541
+ if (untilChainSync && this.chainSyncRecovered) {
542
+ logger.info('chain-sync backend usable again — leaving pagination');
543
+ return;
544
+ }
357
545
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
358
546
  if (!cursor?.lastBlockHash) {
359
547
  logger.error('Pagination refused: cursor has no resume block hash.');
360
548
  await this.halt('error', true); // broken precondition: a restart cannot fix it
361
549
  return;
362
550
  }
551
+ if (untilHeight != null && cursor.lastHeight >= untilHeight) {
552
+ logger.info(`pagination reached block ${cursor.lastHeight} — handing back to chain-sync`);
553
+ return;
554
+ }
363
555
  if (!tip || cursor.lastHeight >= target) {
364
556
  tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
365
557
  target = (tip.height ?? 0) - this.config.confirmationDepth;
@@ -381,7 +573,7 @@ class CardanoCrawler {
381
573
  await this.halt('stopped');
382
574
  return;
383
575
  }
384
- await this.sleep(this.config.pollIntervalMs);
576
+ await this.pollPause(untilChainSync);
385
577
  continue;
386
578
  }
387
579
  const blocks = await this.withTimeout(
@@ -389,7 +581,7 @@ class CardanoCrawler {
389
581
  // on a fresh start without configured startHeight)
390
582
  backend.getNextBlocks(cursor.lastBlockHash, this.config.batchSize, cursor.lastHeight > 0 ? cursor.lastHeight : undefined), 'getNextBlocks');
391
583
  if (!blocks.length) {
392
- await this.sleep(this.config.pollIntervalMs);
584
+ await this.pollPause(untilChainSync);
393
585
  continue;
394
586
  }
395
587
  for (const block of blocks) {
@@ -401,6 +593,10 @@ class CardanoCrawler {
401
593
  const ok = await this.persistBlock(block, txs, tipPoint);
402
594
  if (!ok)
403
595
  return; // persistBlock already recorded + halted
596
+ // Chain-sync came back mid-batch: the block just written is complete and on the
597
+ // cursor, the rest of the batch is cheaper to stream than to fetch one by one.
598
+ if (untilChainSync && this.chainSyncRecovered)
599
+ break;
404
600
  }
405
601
  }
406
602
  catch (err) {
@@ -426,10 +622,19 @@ class CardanoCrawler {
426
622
  await this.halt('error');
427
623
  return;
428
624
  }
429
- await this.sleep(this.config.pollIntervalMs);
625
+ await this.pollPause(untilChainSync);
430
626
  }
431
627
  }
432
628
  }
629
+ /**
630
+ * Poll pause between pagination rounds; skipped when a chain-sync handover is already due,
631
+ * since the probe's wake-up only reaches a sleep that has begun.
632
+ */
633
+ async pollPause(untilChainSync) {
634
+ if (untilChainSync && this.chainSyncRecovered)
635
+ return;
636
+ await this.sleep(this.config.pollIntervalMs);
637
+ }
433
638
  /**
434
639
  * Pagination reorg recovery: walk back by height comparing the on-chain block hash with
435
640
  * our stored one until they agree — that height is the fork point. If the last-indexed
@@ -461,10 +666,8 @@ class CardanoCrawler {
461
666
  if (ours?.hash && onChain.hash === ours.hash) {
462
667
  if (h === cursor.lastHeight)
463
668
  return false; // tip still matches → not a reorg
464
- // handleReorg deletes everything with slot > forkSlot. A null provider slot
465
- // (BlockData.slot is nullable) would make forkSlot 0 and wipe the ENTIRE
466
- // crawled dataset — abort this round instead; the next round can retry with
467
- // a healthy provider response. (Same guard philosophy as the height axis.)
669
+ // A null provider slot would make forkSlot 0 and wipe the entire crawled dataset —
670
+ // abort this round instead.
468
671
  if (onChain.slot == null)
469
672
  return false;
470
673
  await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
@@ -477,10 +680,8 @@ class CardanoCrawler {
477
680
  // Persist + reorg (shared)
478
681
  // ---------------------------------------------------------------------------
479
682
  /**
480
- * Persist one block atomically and advance the cursor. Transient failures are retried
481
- * a few times (recording the error streak); only repeated failure stops the crawler —
482
- * the cursor is not advanced on failure, so a resume re-syncs cleanly from it.
483
- * Marks the cursor 'synced' when the block is at the reported tip.
683
+ * Persist one block atomically and advance the cursor. Transient failures are retried; the
684
+ * cursor is not advanced on failure, so a resume re-syncs from it. Marks 'synced' at the tip.
484
685
  * @returns true when the block was persisted, false when the crawler was stopped
485
686
  */
486
687
  async persistBlock(block, txs, tip) {
@@ -504,8 +705,20 @@ class CardanoCrawler {
504
705
  throw new CrawlerLeaseLostError();
505
706
  }
506
707
  await this.indexer.indexBlockFull(tx, block, txs);
507
- await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing');
708
+ // Ledger progress marker: written in the same statement as the cursor, so "the
709
+ // cursor is ahead of the marker" always means blocks went by without the set.
710
+ const anchor = this.indexer.getUtxoAnchor();
711
+ const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
712
+ await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing', ledgerApplied ? { utxoAppliedSlot: block.slot ?? 0 } : undefined);
508
713
  });
714
+ if (CardanoCrawler.poison?.hash === block.hash)
715
+ CardanoCrawler.poison = null;
716
+ // A ledger invalidation decided inside the block transaction takes effect in memory
717
+ // only now, after the commit that carries it — a rolled-back attempt changes nothing.
718
+ const invalidation = this.indexer.takeLedgerInvalidation();
719
+ if (invalidation) {
720
+ logger.error(`UTxO set invalidated: ${invalidation} — ledger tables stop updating until importUtxoSet runs again`);
721
+ }
509
722
  // Notify observers (wallet-worker confirmation tracker) AFTER the commit —
510
723
  // listener failures are swallowed inside emitBlockIndexed.
511
724
  (0, hooks_1.emitBlockIndexed)({
@@ -516,6 +729,7 @@ class CardanoCrawler {
516
729
  tipSlot: tip?.slot ?? null,
517
730
  tipHeight: tip?.height ?? null,
518
731
  });
732
+ this.maybeSnapshotEpoch(block, tip);
519
733
  return true;
520
734
  }
521
735
  catch (err) {
@@ -534,27 +748,90 @@ class CardanoCrawler {
534
748
  await this.sleep(1000 * attempt);
535
749
  continue;
536
750
  }
537
- logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts — stopping crawler (resume re-syncs from cursor):`, err);
751
+ const dataRejection = CardanoCrawler.isDataRejection(err);
752
+ const failures = dataRejection ? CardanoCrawler.notePersistFailure(block.hash) : 0;
753
+ if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
754
+ const cause = err instanceof Error ? err.message : String(err);
755
+ const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
756
+ logger.error(`persistBlock failed for ${block.hash} (height ${block.height}) ${failures}x across restarts — poison block, latching the crawler off. Fix the cause, then resumeCrawler():`, err);
757
+ // Lease-independent on purpose (see latchPoisonBlock); the memory is only forgotten
758
+ // once the latch is durable, so a failed write is retried after the next restart.
759
+ const latched = await cds_1.default.tx((tx) => (0, sync_state_1.latchPoisonBlock)(tx, message)).then(() => true, (e) => { logger.error('poison-block latch could not be written — retried after the next restart:', e); return false; });
760
+ if (latched)
761
+ CardanoCrawler.poison = null;
762
+ await this.halt('error', true);
763
+ return false;
764
+ }
765
+ const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
766
+ logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock} — stopping crawler (resume re-syncs from cursor):`, err);
538
767
  await this.halt('error');
539
768
  return false;
540
769
  }
541
770
  }
542
771
  }
772
+ /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
773
+ epochOfSlot(slot) {
774
+ const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]
775
+ ?? const_1.EPOCH_CONFIG_BY_NETWORK.preview;
776
+ return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
777
+ }
778
+ /**
779
+ * Pool/DRep snapshot once per epoch, detached from the triggering block and ONLY at the tip:
780
+ * the enumerating providers report current state (no epoch parameter), so epochs passed
781
+ * during a backfill are skipped permanently. Authority is the `PoolEpochSnapshots` row.
782
+ */
783
+ maybeSnapshotEpoch(block, tip) {
784
+ if (!this.config.epochSnapshots || block.epoch == null)
785
+ return;
786
+ if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
787
+ return;
788
+ // No tip reported = we cannot prove we are live, so we do not pretend to be.
789
+ if (tip == null) {
790
+ logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
791
+ return;
792
+ }
793
+ const tipEpoch = this.epochOfSlot(tip.slot);
794
+ if (block.epoch !== tipEpoch) {
795
+ logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
796
+ `the pool/DRep set can only be observed as it is now, never as it was`);
797
+ return;
798
+ }
799
+ if (Date.now() < this.snapshotRetryAfter)
800
+ return;
801
+ const epoch = block.epoch;
802
+ const at = { slot: block.slot ?? 0, time: block.time ?? 0 };
803
+ this.snapshotInFlight = this.trackCallback(async () => {
804
+ const existing = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch })));
805
+ if (!existing) {
806
+ await this.withTimeout(this.indexer.snapshotEpoch(epoch, at), `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
807
+ }
808
+ this.snapshotedEpoch = epoch;
809
+ this.snapshotFailures = 0;
810
+ this.snapshotRetryAfter = 0;
811
+ })
812
+ .catch((err) => {
813
+ // Never fatal: the crawl keeps its data, the epoch is retried on a later block —
814
+ // but not on the very next one, or an outage would re-enumerate per block.
815
+ this.snapshotFailures++;
816
+ const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
817
+ this.snapshotRetryAfter = Date.now() + backoff;
818
+ if (this.running)
819
+ logger.error(`epoch ${epoch} snapshot failed (retry in ${backoff} ms):`, err);
820
+ })
821
+ .finally(() => { this.snapshotInFlight = null; });
822
+ }
543
823
  /**
544
- * Handle a chain rollback: in one transaction, delete every block after the fork point
545
- * and exactly the transactions belonging to those blocks (plus their child rows), reset
546
- * the cursor to the fork, and write a CardanoReorgLog audit row.
547
- *
548
- * The cut runs on the absolute-slot axis of Blocks (same axis as the fork point), and
549
- * transactions are resolved via their blockHash — so:
550
- * - an unresolvable fork height can never widen the delete (no height-0 fallback), and
551
- * - lazily-indexed transactions of blocks the crawler never wrote are left untouched.
824
+ * Chain rollback in one transaction: delete blocks with slot > fork (absolute-slot axis, never
825
+ * height), their transactions resolved via blockHash (lazily indexed txs of other blocks are
826
+ * untouched), reset the cursor to the fork and write a CardanoReorgLog row.
552
827
  */
553
828
  async handleReorg(point) {
554
829
  const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
555
830
  let blocksRolledBack = 0;
556
831
  let txsRolledBack = 0;
557
832
  let emittedForkHeight = null;
833
+ const rolledBackTxHashes = [];
834
+ let ledgerInvalidated = false;
558
835
  try {
559
836
  await cds_1.default.tx(async (tx) => {
560
837
  if (this.leaseOwner) {
@@ -580,6 +857,7 @@ class CardanoCrawler {
580
857
  const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash').where({ blockHash: { in: blockChunk } }));
581
858
  const txHashes = staleTxs.map((t) => t.hash);
582
859
  txsRolledBack += txHashes.length;
860
+ rolledBackTxHashes.push(...txHashes);
583
861
  for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
584
862
  // These denormalized/lazy indexes have no generated FK cascades. Remove
585
863
  // them before their parent tx/output rows so orphan data cannot leak via OData.
@@ -592,10 +870,30 @@ class CardanoCrawler {
592
870
  await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ tx_hash: { in: txChunk } }));
593
871
  await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ tx_hash: { in: txChunk } }));
594
872
  await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: txChunk } }));
873
+ await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: txChunk } }));
874
+ await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: txChunk } }));
595
875
  await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: txChunk } }));
596
876
  }
597
877
  await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
598
878
  }
879
+ // Ledger state, driven by the PERSISTED status: a fork after the anchor is undone and the
880
+ // progress marker follows the cursor back; a fork before the anchor invalidates the set.
881
+ const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
882
+ if (persisted?.status === 'active' && persisted.anchorSlot != null) {
883
+ if (forkSlot < persisted.anchorSlot) {
884
+ await (0, sync_state_1.setUtxoSetState)(tx, {
885
+ status: 'invalid',
886
+ error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot} — re-import the set`,
887
+ });
888
+ ledgerInvalidated = true;
889
+ }
890
+ else {
891
+ await (0, ledger_state_1.undoLedgerForTransactions)(tx, rolledBackTxHashes);
892
+ if (persisted.appliedSlot != null && persisted.appliedSlot > forkSlot) {
893
+ await (0, sync_state_1.setUtxoSetState)(tx, { appliedSlot: forkSlot });
894
+ }
895
+ }
896
+ }
599
897
  await (0, sync_state_1.resetCursorTo)(tx, point === 'origin'
600
898
  ? { slot: forkSlot, hash: this.config.startBlockHash ?? '', height: 0 }
601
899
  : { slot: point.slot, hash: point.hash, height: forkHeight ?? 0 });
@@ -618,6 +916,10 @@ class CardanoCrawler {
618
916
  }
619
917
  throw err;
620
918
  }
919
+ if (ledgerInvalidated) {
920
+ this.indexer.setUtxoAnchor(null);
921
+ logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor — ledger tables stop updating until importUtxoSet runs again`);
922
+ }
621
923
  // Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
622
924
  // the rollback commit.
623
925
  (0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
@@ -650,6 +952,24 @@ class CardanoCrawler {
650
952
  }
651
953
  })();
652
954
  }
955
+ /** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
956
+ static isDataRejection(err) {
957
+ // RangeError: BigInt / number conversions in the mappers; SyntaxError: JSON of the block
958
+ if (err instanceof RangeError || err instanceof SyntaxError)
959
+ return true;
960
+ const message = err instanceof Error ? err.message : String(err);
961
+ return CardanoCrawler.DATA_REJECTION_PATTERNS.some((p) => p.test(message));
962
+ }
963
+ /** Count final persist failures per block hash (a different hash resets the count). */
964
+ static notePersistFailure(hash) {
965
+ const p = CardanoCrawler.poison;
966
+ CardanoCrawler.poison = p && p.hash === hash ? { hash, failures: p.failures + 1 } : { hash, failures: 1 };
967
+ return CardanoCrawler.poison.failures;
968
+ }
969
+ /** Test seam: forget the poison-block memory (process-wide state). */
970
+ static resetPoisonMemory() {
971
+ CardanoCrawler.poison = null;
972
+ }
653
973
  /** Record state only while this instance still owns the lease. */
654
974
  async recordCrawlerError(err) {
655
975
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {