@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -7,8 +7,14 @@ 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");
11
+ const epoch_slots_1 = require("../../utils/epoch-slots");
10
12
  const hooks_1 = require("./hooks");
13
+ const ledger_state_1 = require("../ledger-state");
14
+ const transaction_rows_1 = require("../transaction-rows");
11
15
  const cardano_1 = require("#cds-models/odatano/cardano");
16
+ const account_snapshots_1 = require("./account-snapshots");
17
+ const call_signal_1 = require("../backends/call-signal");
12
18
  const sync_state_1 = require("./sync-state");
13
19
  const { SELECT, DELETE, INSERT } = cds_1.default.ql;
14
20
  const logger = cds_1.default.log('CardanoCrawler');
@@ -19,21 +25,8 @@ class CrawlerStoppedError extends Error {
19
25
  class CrawlerLeaseLostError extends Error {
20
26
  constructor() { super('Crawler DB lease lost'); this.name = 'CrawlerLeaseLostError'; }
21
27
  }
22
- /**
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.
36
- */
28
+ // Streams the chain forward from a start block and bulk-indexes it.
29
+ // Ogmios chain-sync is the primary source, provider pagination the fallback. Each block is written atomically.
37
30
  class CardanoCrawler {
38
31
  client;
39
32
  indexer;
@@ -42,11 +35,50 @@ class CardanoCrawler {
42
35
  leaseOwner;
43
36
  /** Transient-failure retries per block before giving up. */
44
37
  static PERSIST_RETRIES = 3;
38
+ /** Final persist failures for the same block across restarts before the crawler latches off (poison block). */
39
+ static POISON_BLOCK_THRESHOLD = 5;
40
+ /** Process-wide, survives instance restarts: the block currently failing and how often. */
41
+ static poison = null;
42
+ /** Errors caused by the block's data. Only these count towards the poison latch, outages never do. */
43
+ static DATA_REJECTION_PATTERNS = [
44
+ /unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
45
+ /invalid byte sequence for encoding/i, // PostgreSQL: bytes that are not valid UTF-8
46
+ /out of range for type/i, // PostgreSQL: bigint / integer overflow
47
+ /invalid input syntax for type/i, // PostgreSQL: NaN or text in a numeric column
48
+ /value too long for type/i, // PostgreSQL: varchar(n) exceeded
49
+ /numeric value out of range/i, // HANA / SQL-92
50
+ /inserted value too large for column/i, // HANA
51
+ /string or blob too big/i, // SQLite
52
+ /datatype mismatch/i, // SQLite
53
+ ];
45
54
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
46
55
  static CALL_TIMEOUT_MS = 60_000;
56
+ /** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
57
+ static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
58
+ /** One node request per 2000 known accounts; an hour covers a mainnet-sized set. */
59
+ static ACCOUNT_SNAPSHOT_TIMEOUT_MS = 60 * 60_000;
60
+ /** How long a timed-out snapshot may take to end before the next attempt is allowed. */
61
+ static SNAPSHOT_ABORT_GRACE_MS = 60_000;
62
+ /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
63
+ static SNAPSHOT_RETRY_BASE_MS = 30_000;
64
+ static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
65
+ /** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
66
+ static CHAIN_SYNC_RETRY_MS = 30_000;
67
+ /** Wait before chain-sync is reopened after the node was found behind the cursor. */
68
+ static NODE_BEHIND_RETRY_MS = 60_000;
69
+ /** Refused rollbacks that contradict the stored chain before the crawler halts with an error. */
70
+ static MAX_ROLLBACK_REFUSALS = 5;
71
+ /** At most one node-behind warning per this interval; the rest go to debug. */
72
+ static NODE_BEHIND_LOG_MS = 10 * 60_000;
47
73
  running = false;
48
74
  chainSyncHandle = null;
49
- /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
75
+ /** What the ingest loop is currently reading from; null while stopped. */
76
+ activeSource = null;
77
+ /** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
78
+ chainSyncProbeTimer = null;
79
+ chainSyncProbe = null;
80
+ chainSyncRecovered = false;
81
+ /** The detached ingest pipeline. stop() awaits it so teardown never races it. */
50
82
  pipeline = null;
51
83
  /** Resolver that cancels a pending poll sleep (set while sleeping). */
52
84
  wake = null;
@@ -55,11 +87,41 @@ class CardanoCrawler {
55
87
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
56
88
  inFlightCallbacks = new Set();
57
89
  haltPromise = null;
90
+ /** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
91
+ frameFailure = null;
92
+ /** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
93
+ reopenStream = false;
94
+ /** The stream ended on a refused rollback; the ingest loop retries later. */
95
+ streamRefused = false;
96
+ rollbackRefusals = 0;
97
+ nodeBehindLoggedAt = 0;
98
+ /** Blocks persisted by the current chain-sync stream. */
99
+ blocksThisStream = 0;
100
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
101
+ streamEnded = null;
102
+ /** An open stream that delivers nothing for this long is taken as dead and reopened at the cursor. */
103
+ static CHAIN_SYNC_IDLE_MS = 5 * 60 * 1000;
104
+ idleTimer = null;
105
+ /** Reopens since the last block, so a chain that stands still warns once. */
106
+ idleReopens = 0;
58
107
  finalStatus = 'stopped';
59
- /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
108
+ /** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
60
109
  latchOnHalt = false;
110
+ /** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
111
+ static SNAPSHOT_WINDOW_MARGIN = 10;
112
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
113
+ snapshotedEpoch = null;
114
+ snapshotInFlight = null;
115
+ /** The snapshot work itself. It can outlive a timed-out attempt until it sees its abort flag. */
116
+ snapshotWork = null;
117
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
118
+ snapshotFailures = 0;
119
+ accountSnapshotWarned = false;
120
+ snapshotRetryAfter = 0;
61
121
  leaseHeld = false;
62
122
  leaseHeartbeat = null;
123
+ /** Last successful lease renewal by a block commit (epoch ms). */
124
+ leaseRenewedAt = 0;
63
125
  leaseWake = null;
64
126
  constructor(client, indexer, network, config,
65
127
  /** Present for production instances created by index.ts; omitted in engine unit tests. */
@@ -73,11 +135,15 @@ class CardanoCrawler {
73
135
  isRunning() {
74
136
  return this.running;
75
137
  }
76
- /**
77
- * Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
78
- * Refuses to start without a resume point: an explicit configured start block or an
79
- * existing cursor — never an implicit full-chain sync from genesis.
80
- */
138
+ /** True once the crawler halted because of a failure (not via stop() or a lost lease). */
139
+ haltedWithError() {
140
+ return !this.running && this.finalStatus === 'error';
141
+ }
142
+ /** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
143
+ getActiveSource() {
144
+ return this.running ? this.activeSource : null;
145
+ }
146
+ /** Start crawling without awaiting the pipeline. Refuses without a start block or cursor, never syncs from genesis. */
81
147
  async start() {
82
148
  if (this.running)
83
149
  return;
@@ -90,7 +156,7 @@ class CardanoCrawler {
90
156
  // must never leave a healthy-looking crawler behind.
91
157
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.ensureSyncStateSingleton)(tx, this.network, start));
92
158
  if (!cursor.lastBlockHash && !start) {
93
- logger.error('Crawler start refused: no start block configured and no existing cursor — set crawler.startSlot + crawler.startBlockHash.');
159
+ logger.error('Crawler start refused: no start block configured and no existing cursor. Set crawler.startSlot + crawler.startBlockHash.');
94
160
  return;
95
161
  }
96
162
  if (this.leaseOwner) {
@@ -102,9 +168,43 @@ class CardanoCrawler {
102
168
  }
103
169
  }
104
170
  this.running = true;
171
+ // Hand the analytics coverage to the indexer before the first block is written.
172
+ this.indexer.configureCrawlCoverage({
173
+ assetHistory: this.config.assetHistory,
174
+ assetCatalogue: this.config.assetCatalogue,
175
+ assetEnrichRate: this.config.assetEnrichRate,
176
+ certificates: this.config.certificates,
177
+ utxoSet: this.config.utxoSet,
178
+ authoritative: this.config.authoritative ?? false,
179
+ inputAssetCopies: this.config.inputAssetCopies ?? false,
180
+ });
181
+ // Ledger state is only applied after an imported snapshot.
182
+ if (this.config.utxoSet) {
183
+ const u = cursor.utxoSet;
184
+ // Blocks crawled while the mode was off never reached the ledger tables, so the set is stale.
185
+ const lastApplied = u.appliedSlot ?? u.anchorSlot;
186
+ if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
187
+ const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied}: blocks were crawled without the set; re-import`;
188
+ await cds_1.default.tx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error }));
189
+ u.status = 'invalid';
190
+ u.error = error;
191
+ }
192
+ if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
193
+ this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
194
+ void this.indexer.paymentCredentialsReady();
195
+ logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash}, ledger tables are maintained`);
196
+ }
197
+ else {
198
+ this.indexer.setUtxoAnchor(null);
199
+ logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''}: ` +
200
+ 'ledger tables are not maintained until importUtxoSet has run (pause the crawler first)');
201
+ }
202
+ }
203
+ else {
204
+ this.indexer.setUtxoAnchor(null);
205
+ }
105
206
  this.startLeaseHeartbeat();
106
- // A pipeline crash (e.g. chain-sync intersection not found after downtime) must
107
- // surface on the cursor — otherwise the crawler looks healthy while doing nothing.
207
+ // A pipeline crash must show on the cursor, or the crawler looks healthy while idle.
108
208
  this.pipeline = this.runIngestPipeline().catch(async (err) => {
109
209
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
110
210
  await this.halt('stopped');
@@ -115,37 +215,19 @@ class CardanoCrawler {
115
215
  await this.halt(streak < 0 ? 'stopped' : 'error');
116
216
  });
117
217
  }
118
- /**
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.
123
- */
218
+ /** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
124
219
  async stop(finalStatus = 'stopped') {
125
220
  this.beginHalt(finalStatus);
126
221
  if (this.haltPromise)
127
222
  await this.haltPromise;
128
223
  this.pipeline = null;
129
224
  }
130
- /**
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.
141
- */
225
+ // Halt without awaiting the pipeline, so it is safe to call from inside it.
226
+ // `latch` keeps the crawler down across restarts. Use it only for misconfiguration, never for outages.
142
227
  async halt(finalStatus = 'stopped', latch = false) {
143
228
  this.beginHalt(finalStatus, latch);
144
229
  }
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
- */
230
+ /** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
149
231
  beginHalt(finalStatus, latch = false) {
150
232
  if (latch)
151
233
  this.latchOnHalt = true;
@@ -153,7 +235,13 @@ class CardanoCrawler {
153
235
  if (this.finalStatus !== 'error' || finalStatus === 'error')
154
236
  this.finalStatus = finalStatus;
155
237
  this.running = false;
238
+ this.activeSource = null;
239
+ // Background asset enrichment belongs to the crawl and must not outlive it.
240
+ this.indexer.stopAssetEnrichment();
156
241
  this.wake?.(); // cancel a pending poll sleep so the loop exits now
242
+ this.clearIdleWatchdog();
243
+ this.stopChainSyncProbing();
244
+ this.streamEnded?.(); // release the ingest loop, the pipeline is awaited below
157
245
  this.leaseWake?.();
158
246
  for (const cancel of [...this.callCancels])
159
247
  cancel();
@@ -180,6 +268,8 @@ class CardanoCrawler {
180
268
  }
181
269
  if (this.leaseHeartbeat)
182
270
  await this.leaseHeartbeat.catch(() => undefined);
271
+ if (this.chainSyncProbe)
272
+ await this.chainSyncProbe.catch(() => undefined);
183
273
  try {
184
274
  if (this.leaseOwner && this.leaseHeld) {
185
275
  await cds_1.default.tx((tx) => (0, sync_state_1.releaseCrawlerLease)(tx, this.leaseOwner, this.finalStatus, this.latchOnHalt));
@@ -193,22 +283,106 @@ class CardanoCrawler {
193
283
  });
194
284
  }
195
285
  async runIngestPipeline() {
196
- const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
197
- if (chainSync) {
198
- await this.runChainSync(chainSync);
199
- return;
286
+ while (this.running) {
287
+ const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
288
+ if (chainSync) {
289
+ // One pass per chain-sync stream. An unparseable frame ends the stream, not the crawler:
290
+ // pagination fetches that block, then chain-sync takes over again. Other errors halt.
291
+ while (this.running) {
292
+ const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
293
+ try {
294
+ await this.runChainSync(chainSync);
295
+ }
296
+ catch (err) {
297
+ // With 'auto' an open that fails while the node replays falls back to pagination.
298
+ if (!this.running || err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
299
+ throw err;
300
+ if (this.config.source !== 'auto' || !this.client.getPaginatingBackend())
301
+ throw err;
302
+ logger.warn(`chain-sync could not be opened (${err instanceof Error ? err.message : String(err)}), crawling on pagination until it opens again`);
303
+ await this.runPagination({ untilChainSync: true });
304
+ continue;
305
+ }
306
+ if (!this.chainSyncHandle)
307
+ return; // open refused, halted, or stop() raced us
308
+ await streamEnd;
309
+ const failure = this.takeFrameFailure();
310
+ if (!this.running)
311
+ return;
312
+ if (this.reopenStream) {
313
+ this.reopenStream = false;
314
+ continue;
315
+ }
316
+ if (this.streamRefused) {
317
+ this.streamRefused = false;
318
+ if (this.config.source === 'auto' && this.client.getPaginatingBackend())
319
+ await this.runPagination({ untilChainSync: true });
320
+ else
321
+ await this.sleep(CardanoCrawler.NODE_BEHIND_RETRY_MS);
322
+ continue;
323
+ }
324
+ if (failure?.height == null)
325
+ return;
326
+ logger.warn(`chain-sync cannot deliver block ${failure.height}, switching to pagination until it is behind the cursor`);
327
+ await this.runPagination({ untilHeight: failure.height + 1 });
328
+ }
329
+ return;
330
+ }
331
+ if (this.config.source === 'ogmios') {
332
+ // 'ogmios' means chain-sync only. Never fall back to pagination the operator opted out of.
333
+ logger.error("Crawler source is 'ogmios' but no chain-sync backend is available. Crawler not started (use source 'auto' to allow pagination fallback).");
334
+ await this.halt('error', true); // config error: a restart cannot fix it
335
+ return;
336
+ }
337
+ if (this.config.source === 'pagination') {
338
+ await this.runPagination();
339
+ return;
340
+ }
341
+ // 'auto' with no usable chain-sync backend (typical while the node still replays after a
342
+ // restart): crawl on pagination and keep retrying chain-sync.
343
+ logger.warn('No chain-sync backend usable, crawling on pagination and retrying chain-sync periodically');
344
+ await this.runPagination({ untilChainSync: true });
345
+ // Returned because chain-sync came back (or we stopped): the loop reopens it.
200
346
  }
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
347
+ }
348
+ // Retry the chain-sync init on its own timer, because a poll sleep can last an hour.
349
+ // On success the sleep is cut short and the ingest loop reopens chain-sync.
350
+ startChainSyncProbing() {
351
+ this.chainSyncRecovered = false;
352
+ // The startup init has just failed, so give the node a full interval first.
353
+ this.scheduleChainSyncProbe();
354
+ }
355
+ scheduleChainSyncProbe() {
356
+ if (!this.running || this.chainSyncRecovered || this.chainSyncProbeTimer)
206
357
  return;
207
- }
208
- await this.runPagination();
358
+ const timer = setTimeout(() => {
359
+ this.chainSyncProbeTimer = null;
360
+ if (!this.running || this.chainSyncRecovered)
361
+ return;
362
+ this.chainSyncProbe = this.client.recoverChainSyncBackend()
363
+ .then((backend) => {
364
+ if (!backend || !this.running)
365
+ return;
366
+ this.chainSyncRecovered = true;
367
+ this.wake?.(); // a poll sleep must not hold the handover back
368
+ })
369
+ .catch((err) => logger.debug('chain-sync probe failed:', err))
370
+ .finally(() => {
371
+ this.chainSyncProbe = null;
372
+ this.scheduleChainSyncProbe();
373
+ });
374
+ }, CardanoCrawler.CHAIN_SYNC_RETRY_MS);
375
+ timer.unref?.(); // never keep the process alive for a probe
376
+ this.chainSyncProbeTimer = timer;
377
+ }
378
+ stopChainSyncProbing() {
379
+ if (!this.chainSyncProbeTimer)
380
+ return;
381
+ clearTimeout(this.chainSyncProbeTimer);
382
+ this.chainSyncProbeTimer = null;
209
383
  }
210
- /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
211
- withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS) {
384
+ /** Bound a direct backend call. These calls bypass the client's timeout and circuit breaker. */
385
+ withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS, onTimeout) {
212
386
  return new Promise((resolve, reject) => {
213
387
  let settled = false;
214
388
  let timer;
@@ -221,7 +395,7 @@ class CardanoCrawler {
221
395
  this.callCancels.delete(cancel);
222
396
  cb();
223
397
  };
224
- timer = setTimeout(() => finish(() => reject(new errors_1.ProviderUnavailableError(`${label} timed out`, 'crawler', ms))), ms);
398
+ timer = setTimeout(() => finish(() => { onTimeout?.(); reject(new errors_1.ProviderUnavailableError(`${label} timed out`, 'crawler', ms)); }), ms);
225
399
  timer.unref?.(); // never keep the process alive for a watchdog timer
226
400
  cancel = () => finish(() => reject(new CrawlerStoppedError()));
227
401
  this.callCancels.add(cancel);
@@ -229,47 +403,83 @@ class CardanoCrawler {
229
403
  });
230
404
  }
231
405
  // ---------------------------------------------------------------------------
232
- // Chain-sync (Ogmios) — primary, reorg-aware
406
+ // Chain-sync (Ogmios): primary source, reorg-aware
233
407
  // ---------------------------------------------------------------------------
234
408
  async runChainSync(backend) {
235
409
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
236
410
  const points = await this.buildIntersectionPoints(cursor);
237
411
  if (!points.length) {
238
- // Defense in depth — start() already refuses this state.
412
+ // start() already refuses this state.
239
413
  logger.error('Chain-sync refused: no resume point (configured start block or cursor) available.');
240
414
  await this.halt('error', true); // config error: a restart cannot fix it
241
415
  return;
242
416
  }
417
+ this.blocksThisStream = 0;
243
418
  const handle = await backend.openChainSync(points, {
244
419
  rollForward: (block, txs, tip) => this.trackCallback(async () => {
245
420
  if (!this.running)
246
421
  return;
247
- await this.persistBlock(block, txs, tip);
422
+ this.clearIdleWatchdog();
423
+ if (await this.persistBlock(block, txs, tip, true)) {
424
+ this.blocksThisStream++;
425
+ this.idleReopens = 0;
426
+ this.rollbackRefusals = 0;
427
+ }
428
+ this.armIdleWatchdog();
248
429
  }),
249
- rollBackward: (point) => this.trackCallback(async () => {
430
+ rollBackward: (point, tip) => this.trackCallback(async () => {
250
431
  if (!this.running)
251
432
  return;
252
- // Ogmios ALWAYS opens the stream with a rollBackward to the intersection
253
- // point — that is the protocol handshake, not a reorg. Only roll back when
254
- // the point differs from our cursor.
433
+ this.clearIdleWatchdog();
434
+ // Ogmios always opens the stream with a rollBackward to the intersection. That is the
435
+ // handshake, not a reorg, so only roll back when the point differs from the cursor.
255
436
  const current = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
256
437
  if (point !== 'origin' && current?.lastBlockHash === point.hash) {
257
- logger.debug(`chain-sync intersection acknowledged at slot ${point.slot} — no reorg`);
258
- return;
438
+ logger.debug(`chain-sync intersection acknowledged at slot ${point.slot}, no reorg`);
259
439
  }
260
- await this.handleReorg(point);
440
+ else {
441
+ const refusal = await this.rollbackRefusal(point, tip, current);
442
+ if (refusal?.nodeBehind) {
443
+ await this.waitForNode(refusal.reason);
444
+ return;
445
+ }
446
+ if (refusal) {
447
+ await this.refuseRollback(refusal.reason);
448
+ return;
449
+ }
450
+ await this.handleReorg(point);
451
+ }
452
+ this.armIdleWatchdog();
261
453
  }),
262
454
  onError: (err) => this.trackCallback(async () => {
263
455
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
264
456
  return;
265
- // The stream is stalled (mapping/callback failure) — record and halt cleanly
266
- // so the cursor status shows 'error' instead of a healthy-looking hang.
457
+ // An unparseable frame is a fault of that one block. Pagination can still fetch it.
458
+ if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
459
+ await this.degradeToPagination(err);
460
+ return;
461
+ }
462
+ // Socket dropped. After progress, reopen at the cursor. Without progress the server
463
+ // cannot decode the next block, so fetch that block over pagination first.
464
+ if (err instanceof errors_1.ChainSyncClosedError) {
465
+ if (this.blocksThisStream > 0) {
466
+ logger.warn(`${err.message} after ${this.blocksThisStream} block(s), reopening chain-sync at the cursor`);
467
+ await this.endStream(() => { this.reopenStream = true; });
468
+ return;
469
+ }
470
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
471
+ if (cursor && this.config.source !== 'ogmios' && this.client.getPaginatingBackend()) {
472
+ await this.degradeToPagination(new errors_1.ChainSyncStalledError(cursor.lastHeight + 1, err.message));
473
+ return;
474
+ }
475
+ }
476
+ // Record and halt, so the cursor shows 'error' instead of a healthy-looking hang.
267
477
  const streak = await this.recordCrawlerError(err);
268
- logger.error('Chain-sync stream error — stopping crawler:', err);
478
+ logger.error('Chain-sync stream error, stopping crawler:', err);
269
479
  await this.halt(streak < 0 ? 'stopped' : 'error');
270
480
  }),
271
481
  });
272
- // stop() may have raced the async open — close the fresh socket instead of leaking it.
482
+ // stop() may have raced the async open. Close the fresh socket instead of leaking it.
273
483
  if (!this.running) {
274
484
  try {
275
485
  await handle.close();
@@ -278,20 +488,74 @@ class CardanoCrawler {
278
488
  return;
279
489
  }
280
490
  this.chainSyncHandle = handle;
491
+ this.activeSource = 'chain-sync';
492
+ this.armIdleWatchdog();
281
493
  logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
282
494
  }
283
- /**
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.
294
- */
495
+ // Starts the silence timer of the open stream. It runs only between frames, so a block that
496
+ // takes long to store never counts as silence. A half-open socket sends neither frames nor a close.
497
+ armIdleWatchdog() {
498
+ this.clearIdleWatchdog();
499
+ if (!this.running || !this.chainSyncHandle)
500
+ return;
501
+ const idleMs = CardanoCrawler.CHAIN_SYNC_IDLE_MS;
502
+ this.idleTimer = setTimeout(() => {
503
+ this.idleTimer = null;
504
+ if (!this.running || !this.chainSyncHandle)
505
+ return;
506
+ const message = `chain-sync delivered nothing for ${Math.round(idleMs / 1000)} s, reopening at the cursor`;
507
+ if (this.idleReopens++ === 0)
508
+ logger.warn(message);
509
+ else
510
+ logger.debug(message);
511
+ void this.trackCallback(() => this.endStream(() => { this.reopenStream = true; }));
512
+ }, idleMs);
513
+ this.idleTimer.unref?.();
514
+ }
515
+ clearIdleWatchdog() {
516
+ if (this.idleTimer)
517
+ clearTimeout(this.idleTimer);
518
+ this.idleTimer = null;
519
+ }
520
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
521
+ takeFrameFailure() {
522
+ const failure = this.frameFailure;
523
+ this.frameFailure = null;
524
+ return failure;
525
+ }
526
+ canDegradeToPagination(err) {
527
+ return err.height != null
528
+ && this.config.source !== 'ogmios'
529
+ && !!this.client.getPaginatingBackend();
530
+ }
531
+ /** End the stream so the ingest loop passes the bad block on pagination. Records first, so `lastError` names it. */
532
+ async degradeToPagination(err) {
533
+ const streak = await this.recordCrawlerError(err);
534
+ if (streak < 0) {
535
+ await this.halt('stopped');
536
+ return;
537
+ }
538
+ logger.error('Chain-sync cannot deliver a block, continuing on pagination:', err.message);
539
+ await this.endStream(() => { this.frameFailure = err; });
540
+ }
541
+ /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
542
+ async endStream(mark) {
543
+ mark();
544
+ this.clearIdleWatchdog();
545
+ const handle = this.chainSyncHandle;
546
+ this.chainSyncHandle = null;
547
+ if (handle) {
548
+ try {
549
+ await handle.close();
550
+ }
551
+ catch (e) {
552
+ logger.warn('chain-sync close failed:', e);
553
+ }
554
+ }
555
+ this.streamEnded?.();
556
+ }
557
+ // Intersection points, newest first: cursor, crawled ancestors, configured start block.
558
+ // The ancestors let the node find the last common block if the cursor was orphaned.
295
559
  async buildIntersectionPoints(cursor) {
296
560
  const points = [];
297
561
  const seen = new Set();
@@ -303,19 +567,19 @@ class CardanoCrawler {
303
567
  };
304
568
  if (cursor?.lastBlockHash) {
305
569
  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.
570
+ // Dense over the last DENSE_DEPTH blocks (real rollbacks are shallow and must intersect
571
+ // exactly), doubling after that for deep-reorg reach without hundreds of points.
311
572
  const DENSE_DEPTH = 10;
312
573
  const heights = [];
313
574
  const pushHeight = (height) => { if (height > 0 && !heights.includes(height))
314
575
  heights.push(height); };
315
576
  for (let step = 1; step <= DENSE_DEPTH; step++)
316
577
  pushHeight(cursor.lastHeight - step);
317
- for (let step = 16; step <= 1 << 14; step *= 2)
578
+ // A fork is never deeper than k, so no ancestor below that is offered.
579
+ const k = this.securityParam();
580
+ for (let step = 16; step <= k; step *= 2)
318
581
  pushHeight(cursor.lastHeight - step);
582
+ pushHeight(cursor.lastHeight - k);
319
583
  if (heights.length) {
320
584
  const rows = await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.Blocks).columns('height', 'slot', 'hash').where({ height: { in: heights } })));
321
585
  for (const row of (rows ?? []).sort((a, b) => Number(b.height ?? 0) - Number(a.height ?? 0))) {
@@ -329,6 +593,96 @@ class CardanoCrawler {
329
593
  }
330
594
  return points;
331
595
  }
596
+ // The first block of a Byron epoch follows that epoch's boundary block, which has no height and
597
+ // is never stored. Its parent hash names that block, not the last stored one.
598
+ followsByronBoundary(block, parentSlot) {
599
+ const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network];
600
+ if (!cfg || block.slot == null || block.slot >= cfg.shelleyStartSlot)
601
+ return false;
602
+ // a Byron epoch is 10k slots long
603
+ const byronEpoch = (slot) => Math.floor(slot / (10 * cfg.securityParam));
604
+ return byronEpoch(block.slot) > byronEpoch(parentSlot);
605
+ }
606
+ /** Blocks the node can roll back at most (Praos `k`). */
607
+ securityParam() {
608
+ return const_1.EPOCH_CONFIG_BY_NETWORK[this.network]?.securityParam
609
+ ?? const_1.EPOCH_CONFIG_BY_NETWORK.mainnet.securityParam;
610
+ }
611
+ // Why a rollBackward must not be executed, or null for a real fork. A fork is at most k blocks
612
+ // deep, its point is a stored block, and the new chain is not shorter than the cursor.
613
+ // `nodeBehind` = the node's tip is below the cursor, so waiting resolves it; the rest contradict the stored chain.
614
+ async rollbackRefusal(point, tip, cursor) {
615
+ if (!cursor?.lastBlockHash)
616
+ return null;
617
+ if (tip?.height != null && cursor.lastHeight > 0 && tip.height < cursor.lastHeight) {
618
+ return { reason: `the node's tip ${tip.height} is behind the cursor at block ${cursor.lastHeight}`, nodeBehind: true };
619
+ }
620
+ if (point === 'origin')
621
+ return { reason: `the node rolled back to genesis while the cursor is at block ${cursor.lastHeight}`, nodeBehind: false };
622
+ const isStart = point.hash === this.config.startBlockHash;
623
+ let pointHeight = point.height ?? (isStart ? this.config.startHeight : undefined) ?? null;
624
+ if (!isStart) {
625
+ const stored = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Blocks).columns('hash', 'height').where({ hash: point.hash })));
626
+ if (!stored)
627
+ return { reason: `the rollback point ${point.hash} at slot ${point.slot} is not a stored block`, nodeBehind: false };
628
+ if (pointHeight == null && stored.height != null)
629
+ pointHeight = Number(stored.height);
630
+ }
631
+ // The depth is the crawled chain between the point and the cursor; lazily stored tip blocks do not count.
632
+ const k = this.securityParam();
633
+ let depth;
634
+ if (pointHeight != null && cursor.lastHeight > 0) {
635
+ depth = cursor.lastHeight - pointHeight;
636
+ }
637
+ else {
638
+ const after = await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.Blocks).columns('hash').where({ slot: { '>': point.slot, '<=': cursor.lastSlot } }).limit(k + 1)));
639
+ depth = (after ?? []).length;
640
+ }
641
+ if (depth > k)
642
+ return { reason: `a rollback to slot ${point.slot} would remove more than k=${k} blocks`, nodeBehind: false };
643
+ return null;
644
+ }
645
+ // Ends the stream without deleting anything and records why. The ingest loop tries again later,
646
+ // when the node has caught up and intersects at the cursor.
647
+ async waitForNode(reason) {
648
+ const now = Date.now();
649
+ if (now - this.nodeBehindLoggedAt >= CardanoCrawler.NODE_BEHIND_LOG_MS) {
650
+ logger.warn(`chain-sync rollback refused, nothing deleted: ${reason}. Waiting for the node`);
651
+ this.nodeBehindLoggedAt = now;
652
+ }
653
+ else {
654
+ logger.debug(`chain-sync rollback refused, nothing deleted: ${reason}`);
655
+ }
656
+ const recorded = await cds_1.default.tx((tx) => (0, sync_state_1.markNodeBehind)(tx, reason, this.leaseOwner)).catch((err) => {
657
+ logger.error('node-behind state could not be written:', err);
658
+ return true;
659
+ });
660
+ if (!recorded) {
661
+ await this.halt('stopped');
662
+ return;
663
+ }
664
+ await this.endStream(() => { this.streamRefused = true; });
665
+ }
666
+ // A rollback that contradicts the stored chain: nothing is deleted, the status turns error, and
667
+ // after MAX_ROLLBACK_REFUSALS in a row the crawler halts until resumeCrawler.
668
+ async refuseRollback(reason) {
669
+ this.rollbackRefusals++;
670
+ logger.error(`chain-sync rollback refused, nothing deleted: ${reason} (${this.rollbackRefusals} of ${CardanoCrawler.MAX_ROLLBACK_REFUSALS})`);
671
+ const streak = await cds_1.default.tx((tx) => (0, sync_state_1.recordRollbackRefusal)(tx, reason, this.leaseOwner)).catch((err) => {
672
+ logger.error('rollback refusal could not be written:', err);
673
+ return 0;
674
+ });
675
+ if (streak < 0) {
676
+ await this.halt('stopped');
677
+ return;
678
+ }
679
+ if (this.rollbackRefusals >= CardanoCrawler.MAX_ROLLBACK_REFUSALS) {
680
+ logger.error(`chain-sync keeps asking for a rollback the stored chain contradicts; crawler halted until resumeCrawler. Check that Ogmios serves the configured network and node: ${reason}`);
681
+ await this.halt('error', true);
682
+ return;
683
+ }
684
+ await this.endStream(() => { this.streamRefused = true; });
685
+ }
332
686
  /** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
333
687
  trackCallback(callback) {
334
688
  const promise = Promise.resolve().then(callback);
@@ -337,36 +691,54 @@ class CardanoCrawler {
337
691
  return promise;
338
692
  }
339
693
  // ---------------------------------------------------------------------------
340
- // Pagination (Blockfrost/Koios) — fallback
694
+ // Pagination (Blockfrost, Koios): fallback source
341
695
  // ---------------------------------------------------------------------------
342
- async runPagination() {
696
+ /** `untilHeight` returns once the cursor reaches it. `untilChainSync` returns once chain-sync is usable again. */
697
+ async runPagination(opts = {}) {
698
+ if (opts.untilChainSync)
699
+ this.startChainSyncProbing();
700
+ try {
701
+ await this.paginate(opts);
702
+ }
703
+ finally {
704
+ this.stopChainSyncProbing();
705
+ }
706
+ }
707
+ async paginate({ untilHeight, untilChainSync = false }) {
343
708
  const backend = this.client.getPaginatingBackend();
344
709
  if (!backend) {
345
- logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
710
+ logger.error('No paginating backend available: cannot crawl without Ogmios or Blockfrost/Koios');
346
711
  await this.halt('error', true); // config error: a restart cannot fix it
347
712
  return;
348
713
  }
714
+ backend.configureCrawl?.({ certificates: this.config.certificates });
715
+ this.activeSource = 'pagination';
349
716
  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.
717
+ // Tip cache, refreshed only when the cursor reaches the cached target.
353
718
  let tip = null;
354
719
  let target = Number.NEGATIVE_INFINITY;
355
720
  while (this.running) {
356
721
  try {
722
+ if (untilChainSync && this.chainSyncRecovered) {
723
+ logger.info('chain-sync backend usable again, leaving pagination');
724
+ return;
725
+ }
357
726
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
358
727
  if (!cursor?.lastBlockHash) {
359
728
  logger.error('Pagination refused: cursor has no resume block hash.');
360
729
  await this.halt('error', true); // broken precondition: a restart cannot fix it
361
730
  return;
362
731
  }
732
+ if (untilHeight != null && cursor.lastHeight >= untilHeight) {
733
+ logger.info(`pagination reached block ${cursor.lastHeight}, handing back to chain-sync`);
734
+ return;
735
+ }
363
736
  if (!tip || cursor.lastHeight >= target) {
364
737
  tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
365
738
  target = (tip.height ?? 0) - this.config.confirmationDepth;
366
739
  }
367
740
  const tipHeight = tip.height ?? 0;
368
- // Unknown tip slot must mean "NOT at tip" — a 0-fallback would mark every
369
- // block 'synced' (block.slot >= 0 is always true).
741
+ // An unknown tip slot means "not at tip". A 0 fallback would mark every block 'synced'.
370
742
  const tipPoint = tip.slot != null
371
743
  ? { slot: tip.slot, hash: tip.hash, height: tipHeight }
372
744
  : undefined;
@@ -381,34 +753,43 @@ class CardanoCrawler {
381
753
  await this.halt('stopped');
382
754
  return;
383
755
  }
384
- await this.sleep(this.config.pollIntervalMs);
756
+ await this.pollPause(untilChainSync);
385
757
  continue;
386
758
  }
387
759
  const blocks = await this.withTimeout(
388
- // pass the cursor height as anchor hint (>0 only — 0 can mean "unknown"
389
- // on a fresh start without configured startHeight)
760
+ // Cursor height as a hint. Height 0 can mean unknown on a fresh start.
390
761
  backend.getNextBlocks(cursor.lastBlockHash, this.config.batchSize, cursor.lastHeight > 0 ? cursor.lastHeight : undefined), 'getNextBlocks');
391
762
  if (!blocks.length) {
392
- await this.sleep(this.config.pollIntervalMs);
763
+ await this.pollPause(untilChainSync);
393
764
  continue;
394
765
  }
766
+ // Each block must name the one before it. A different parent means the cursor was orphaned.
767
+ let parent = { hash: cursor.lastBlockHash, slot: cursor.lastSlot };
768
+ for (const block of blocks) {
769
+ if (block.previousHash != null && block.previousHash !== parent.hash && !this.followsByronBoundary(block, parent.slot)) {
770
+ throw new Error(`${CHAIN_POINT_MISMATCH_PREFIX} block ${block.hash} at height ${block.height ?? '?'} follows ${block.previousHash}, not ${parent.hash}`);
771
+ }
772
+ parent = { hash: block.hash, slot: block.slot ?? parent.slot };
773
+ }
395
774
  for (const block of blocks) {
396
775
  if (!this.running)
397
776
  break;
398
777
  if ((block.height ?? 0) > target)
399
778
  break; // stay behind the confirmation window
400
- const txs = await this.withTimeout(backend.getBlockTransactions(block.hash), 'getBlockTransactions');
779
+ const txs = await this.withTimeout(backend.getBlockTransactions(block.hash, block.txCount), 'getBlockTransactions');
401
780
  const ok = await this.persistBlock(block, txs, tipPoint);
402
781
  if (!ok)
403
782
  return; // persistBlock already recorded + halted
783
+ // Chain-sync came back mid-batch. Streaming the rest is cheaper than fetching it.
784
+ if (untilChainSync && this.chainSyncRecovered)
785
+ break;
404
786
  }
405
787
  }
406
788
  catch (err) {
407
789
  if (!this.running || err instanceof CrawlerStoppedError)
408
790
  return;
409
- // Only the backend's explicit anchor/hash mismatch proves that our cursor may
410
- // be orphaned. Provider outages and partial tx responses must back off instead
411
- // of launching up to 100 additional provider calls.
791
+ // Only an explicit chain point mismatch suggests an orphaned cursor.
792
+ // Outages back off instead of starting up to 100 more provider calls.
412
793
  if (err instanceof Error && err.message.startsWith(CHAIN_POINT_MISMATCH_PREFIX)) {
413
794
  const recovered = await this.tryReorgRecovery(backend).catch(() => false);
414
795
  if (recovered)
@@ -426,15 +807,18 @@ class CardanoCrawler {
426
807
  await this.halt('error');
427
808
  return;
428
809
  }
429
- await this.sleep(this.config.pollIntervalMs);
810
+ await this.pollPause(untilChainSync);
430
811
  }
431
812
  }
432
813
  }
433
- /**
434
- * Pagination reorg recovery: walk back by height comparing the on-chain block hash with
435
- * our stored one until they agree — that height is the fork point. If the last-indexed
436
- * block still matches on-chain, there is no reorg (returns false → treat as transient).
437
- */
814
+ /** Skipped when a chain-sync handover is due, since the probe's wake-up only reaches a running sleep. */
815
+ async pollPause(untilChainSync) {
816
+ if (untilChainSync && this.chainSyncRecovered)
817
+ return;
818
+ await this.sleep(this.config.pollIntervalMs);
819
+ }
820
+ // Walk back by height until the on-chain hash matches the stored one. That height is the fork point.
821
+ // Returns false if the cursor block still matches, so the error counts as transient.
438
822
  async tryReorgRecovery(backend) {
439
823
  if (!this.running)
440
824
  return false;
@@ -461,10 +845,7 @@ class CardanoCrawler {
461
845
  if (ours?.hash && onChain.hash === ours.hash) {
462
846
  if (h === cursor.lastHeight)
463
847
  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.)
848
+ // A null slot would make forkSlot 0 and wipe all crawled data.
468
849
  if (onChain.slot == null)
469
850
  return false;
470
851
  await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
@@ -476,20 +857,16 @@ class CardanoCrawler {
476
857
  // ---------------------------------------------------------------------------
477
858
  // Persist + reorg (shared)
478
859
  // ---------------------------------------------------------------------------
479
- /**
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.
484
- * @returns true when the block was persisted, false when the crawler was stopped
485
- */
486
- async persistBlock(block, txs, tip) {
860
+ /** Persist one block atomically and advance the cursor. Returns false when the crawler stopped. */
861
+ async persistBlock(block, txs, tip, fromChainSync = false) {
487
862
  if (txs.length !== block.txCount) {
488
863
  throw new errors_1.ProviderUnavailableError(`Incomplete block ${block.hash}: backend returned ${txs.length}/${block.txCount} transactions`, 'crawler');
489
864
  }
490
- const isAtTip = tip != null && block.slot != null && block.slot >= tip.slot;
491
- // Epoch enrichment needs a backend round-trip on epoch boundaries — do it BEFORE
492
- // opening the write transaction so the DB lock is never held across network I/O.
865
+ // Pagination stays confirmationDepth behind the tip on purpose, so that distance counts as synced.
866
+ const isAtTip = tip != null && (tip.height != null && block.height != null
867
+ ? tip.height - block.height <= this.config.confirmationDepth
868
+ : block.slot != null && block.slot >= tip.slot);
869
+ // Fetch epoch data before the write transaction, so no DB lock is held across network I/O.
493
870
  if (block.epoch != null) {
494
871
  await this.indexer.prefetchCrawlEpoch(block.epoch);
495
872
  }
@@ -498,16 +875,29 @@ class CardanoCrawler {
498
875
  return false;
499
876
  try {
500
877
  await cds_1.default.tx(async (tx) => {
501
- if (this.leaseOwner) {
502
- const renewed = await (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner);
503
- if (!renewed)
504
- throw new CrawlerLeaseLostError();
505
- }
506
878
  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');
879
+ // Written with the cursor, so a cursor ahead of this marker means blocks skipped the set.
880
+ const anchor = this.indexer.getUtxoAnchor();
881
+ const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
882
+ // The cursor UPDATE also renews and fences the lease; a lost lease rolls the block back.
883
+ const leaseHeld = 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', {
884
+ ...(ledgerApplied ? { utxoAppliedSlot: block.slot ?? 0 } : {}),
885
+ // only a block from chain-sync shows that the node caught up
886
+ ...(fromChainSync ? { nodeBehindSince: null } : {}),
887
+ }, this.leaseOwner);
888
+ if (!leaseHeld)
889
+ throw new CrawlerLeaseLostError();
508
890
  });
509
- // Notify observers (wallet-worker confirmation tracker) AFTER the commit —
510
- // listener failures are swallowed inside emitBlockIndexed.
891
+ this.leaseRenewedAt = Date.now();
892
+ this.indexer.confirmBlockCommit();
893
+ if (CardanoCrawler.poison?.hash === block.hash)
894
+ CardanoCrawler.poison = null;
895
+ // Applied in memory only after the commit, so a rolled-back attempt changes nothing.
896
+ const invalidation = this.indexer.takeLedgerInvalidation();
897
+ if (invalidation) {
898
+ logger.error(`UTxO set invalidated: ${invalidation}. Ledger tables stop updating until importUtxoSet runs again`);
899
+ }
900
+ // Notify observers after the commit. emitBlockIndexed swallows listener failures.
511
901
  (0, hooks_1.emitBlockIndexed)({
512
902
  hash: block.hash,
513
903
  slot: block.slot ?? null,
@@ -516,6 +906,7 @@ class CardanoCrawler {
516
906
  tipSlot: tip?.slot ?? null,
517
907
  tipHeight: tip?.height ?? null,
518
908
  });
909
+ this.maybeSnapshotEpoch(block, tip);
519
910
  return true;
520
911
  }
521
912
  catch (err) {
@@ -530,31 +921,149 @@ class CardanoCrawler {
530
921
  return false;
531
922
  }
532
923
  if (attempt < CardanoCrawler.PERSIST_RETRIES && streak < sync_state_1.MAX_CONSECUTIVE_ERRORS) {
533
- logger.warn(`persistBlock ${block.hash} failed (attempt ${attempt}/${CardanoCrawler.PERSIST_RETRIES}, streak ${streak}) — retrying:`, err);
924
+ logger.warn(`persistBlock ${block.hash} failed (attempt ${attempt}/${CardanoCrawler.PERSIST_RETRIES}, streak ${streak}), retrying:`, err);
534
925
  await this.sleep(1000 * attempt);
535
926
  continue;
536
927
  }
537
- logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts — stopping crawler (resume re-syncs from cursor):`, err);
928
+ const dataRejection = CardanoCrawler.isDataRejection(err);
929
+ const failures = dataRejection ? CardanoCrawler.notePersistFailure(block.hash) : 0;
930
+ if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
931
+ const cause = err instanceof Error ? err.message : String(err);
932
+ const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
933
+ 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);
934
+ // Memory is cleared only once the latch is stored, so a failed write retries after restart.
935
+ 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; });
936
+ if (latched)
937
+ CardanoCrawler.poison = null;
938
+ await this.halt('error', true);
939
+ return false;
940
+ }
941
+ const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
942
+ logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock}, stopping crawler (resume re-syncs from cursor):`, err);
538
943
  await this.halt('error');
539
944
  return false;
540
945
  }
541
946
  }
542
947
  }
543
- /**
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.
552
- */
948
+ /** Epoch a slot belongs to, from the network's Shelley anchor. */
949
+ epochOfSlot(slot) {
950
+ return (0, epoch_slots_1.epochOfSlot)(this.network, slot);
951
+ }
952
+ // Snapshot pools and DReps once per epoch. Ogmios reads the ledger at a block within k of the tip.
953
+ // Koios reports only current state, so the crawl must be in the tip's epoch. Other epochs are skipped.
954
+ maybeSnapshotEpoch(block, tip) {
955
+ if (!this.config.epochSnapshots || block.epoch == null)
956
+ return;
957
+ if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
958
+ return;
959
+ // Without a tip the crawler cannot prove it is live.
960
+ if (tip == null) {
961
+ logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
962
+ return;
963
+ }
964
+ const fromLedger = this.client.getEpochStateBackend() != null && !!block.hash;
965
+ if (fromLedger) {
966
+ const k = this.securityParam();
967
+ const behind = tip.height != null && block.height != null ? tip.height - block.height : null;
968
+ if (behind == null || behind >= k - CardanoCrawler.SNAPSHOT_WINDOW_MARGIN) {
969
+ logger.debug(`epoch ${block.epoch} snapshot skipped at height ${block.height}: ${behind ?? '?'} blocks behind the tip, outside the node's volatile window (k=${k})`);
970
+ return;
971
+ }
972
+ }
973
+ else {
974
+ const tipEpoch = this.epochOfSlot(tip.slot);
975
+ if (block.epoch !== tipEpoch) {
976
+ logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}); ` +
977
+ `the provider reports the pool/DRep set as it is now, never as it was`);
978
+ return;
979
+ }
980
+ }
981
+ if (Date.now() < this.snapshotRetryAfter)
982
+ return;
983
+ // A timed-out attempt still runs until it sees its abort flag; never start a second one beside it.
984
+ if (this.snapshotWork)
985
+ return;
986
+ const epoch = block.epoch;
987
+ const at = { slot: block.slot ?? 0, time: block.time ?? 0, hash: fromLedger ? block.hash : null };
988
+ const attempt = { aborted: false };
989
+ const stopped = () => attempt.aborted || !this.running;
990
+ this.snapshotInFlight = this.trackCallback(async () => {
991
+ const existing = await cds_1.default.tx(async (tx) => (await tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch').where({ epoch })))
992
+ ?? (await tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch }))));
993
+ if (!existing) {
994
+ await this.attemptWithTimeout(() => this.indexer.snapshotEpoch(epoch, at, stopped), attempt, `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
995
+ const previous = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('max(epoch) as e').where({ epoch: { '<': epoch } })));
996
+ const last = previous?.e == null ? null : Number(previous.e);
997
+ if (last != null && epoch > last + 1) {
998
+ logger.warn(`epoch snapshots missing for epochs ${last + 1}..${epoch - 1}: passed outside the snapshot window`);
999
+ }
1000
+ }
1001
+ await this.maybeSnapshotAccounts(epoch, at, attempt);
1002
+ this.snapshotedEpoch = epoch;
1003
+ this.snapshotFailures = 0;
1004
+ this.snapshotRetryAfter = 0;
1005
+ })
1006
+ .catch((err) => {
1007
+ // Never fatal. The epoch is retried after a backoff, so an outage does not re-run per block.
1008
+ this.snapshotFailures++;
1009
+ const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
1010
+ this.snapshotRetryAfter = Date.now() + backoff;
1011
+ if (this.running)
1012
+ logger.error(`epoch ${epoch} snapshot failed (retry in ${backoff} ms):`, err);
1013
+ })
1014
+ .finally(() => { this.snapshotInFlight = null; });
1015
+ }
1016
+ // The account snapshot of an epoch, after its pool snapshot. Skipped with one warning without a
1017
+ // backend that reads the ledger at a block.
1018
+ async maybeSnapshotAccounts(epoch, at, attempt) {
1019
+ if (!this.config.accountSnapshots)
1020
+ return;
1021
+ const backend = at.hash ? this.client.getRewardAccountStateBackend() : null;
1022
+ if (!backend || !at.hash) {
1023
+ if (!this.accountSnapshotWarned)
1024
+ logger.warn('account snapshots need Ogmios (the ledger at the snapshot block); none is taken');
1025
+ this.accountSnapshotWarned = true;
1026
+ return;
1027
+ }
1028
+ const point = { slot: at.slot, hash: at.hash };
1029
+ await this.attemptWithTimeout(() => (0, account_snapshots_1.snapshotAccounts)({
1030
+ backend, epoch, at: point,
1031
+ withdrawals: this.config.certificates,
1032
+ shouldStop: () => attempt.aborted || !this.running,
1033
+ }), attempt, `snapshotAccounts(${epoch})`, CardanoCrawler.ACCOUNT_SNAPSHOT_TIMEOUT_MS);
1034
+ }
1035
+ // A bounded snapshot step. On a timeout the attempt is marked aborted and its call signal fires,
1036
+ // which closes its ledger-state connection, so the work ends and writes nothing more.
1037
+ attemptWithTimeout(run, attempt, label, ms) {
1038
+ const controller = new AbortController();
1039
+ const work = (0, call_signal_1.withCallSignal)(controller.signal, run);
1040
+ this.snapshotWork = work;
1041
+ const forget = () => { if (this.snapshotWork === work)
1042
+ this.snapshotWork = null; };
1043
+ work.then(forget, forget);
1044
+ return this.withTimeout(work, label, ms, () => {
1045
+ attempt.aborted = true;
1046
+ controller.abort(new Error(`${label} timed out after ${ms} ms`));
1047
+ // A work that does not end once its connection is closed must not block every later attempt.
1048
+ const grace = setTimeout(() => {
1049
+ if (this.snapshotWork !== work)
1050
+ return;
1051
+ logger.warn(`${label} did not end ${CardanoCrawler.SNAPSHOT_ABORT_GRACE_MS} ms after its timeout; its connection is closed and it writes nothing more, so the next attempt may start`);
1052
+ this.snapshotWork = null;
1053
+ }, CardanoCrawler.SNAPSHOT_ABORT_GRACE_MS);
1054
+ grace.unref?.();
1055
+ });
1056
+ }
1057
+ // Roll back in one transaction. Deletes blocks after the fork slot, never by height, and their transactions.
1058
+ // Lazily indexed transactions of other blocks stay. Resets the cursor and logs the reorg.
553
1059
  async handleReorg(point) {
554
1060
  const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
555
1061
  let blocksRolledBack = 0;
556
1062
  let txsRolledBack = 0;
557
1063
  let emittedForkHeight = null;
1064
+ const rolledBackTxHashes = [];
1065
+ const rolledBackUnits = new Set();
1066
+ let ledgerInvalidated = false;
558
1067
  try {
559
1068
  await cds_1.default.tx(async (tx) => {
560
1069
  if (this.leaseOwner) {
@@ -562,7 +1071,7 @@ class CardanoCrawler {
562
1071
  if (!renewed)
563
1072
  throw new CrawlerLeaseLostError();
564
1073
  }
565
- // Fork height is metrics/cursor info only — NEVER a delete axis.
1074
+ // Fork height is for the cursor and the log only, never a delete criterion.
566
1075
  let forkHeight = point === 'origin' ? 0 : point.height;
567
1076
  if (forkHeight == null && point !== 'origin') {
568
1077
  const fb = await tx.run(SELECT.one.from(cardano_1.Blocks).where({ hash: point.hash }));
@@ -570,32 +1079,67 @@ class CardanoCrawler {
570
1079
  }
571
1080
  emittedForkHeight = forkHeight ?? null;
572
1081
  // Blocks strictly after the fork, cut on the absolute-slot axis. Rows without a
573
- // slot (pre-v2.0 lazily indexed blocks) are deliberately excluded.
1082
+ // slot (lazily indexed blocks from an older schema) are deliberately excluded.
574
1083
  const staleBlocks = await tx.run(SELECT.from(cardano_1.Blocks).columns('hash').where({ slot: { '>': forkSlot } }));
575
1084
  const blockHashes = staleBlocks.map((b) => b.hash);
576
1085
  blocksRolledBack = blockHashes.length;
577
1086
  for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
578
- // Only transactions of the rolled-back blocks — resolved via blockHash, so
579
- // lazily-indexed txs of unrelated blocks are not collateral damage.
580
- const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash').where({ blockHash: { in: blockChunk } }));
1087
+ // Select by blockHash, so lazily indexed transactions of other blocks stay.
1088
+ const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ blockHash: { in: blockChunk } }));
581
1089
  const txHashes = staleTxs.map((t) => t.hash);
582
1090
  txsRolledBack += txHashes.length;
1091
+ rolledBackTxHashes.push(...txHashes);
1092
+ // the units the catalogue may have first seen in these transactions: outputs, inputs, mints and burns
1093
+ for (const seqChunk of (0, collections_1.chunk)(staleTxs.map((t) => t.txSeq), collections_1.IN_CHUNK)) {
1094
+ for (const query of [
1095
+ SELECT.distinct.from(cardano_1.TransactionOutputAssets).columns('unit').where({ output_txSeq: { in: seqChunk } }),
1096
+ SELECT.distinct.from(cardano_1.TransactionInputAssets).columns('unit').where({ input_txSeq: { in: seqChunk } }),
1097
+ ]) {
1098
+ for (const u of await tx.run(query) ?? [])
1099
+ rolledBackUnits.add(u.unit);
1100
+ }
1101
+ }
583
1102
  for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
584
- // These denormalized/lazy indexes have no generated FK cascades. Remove
585
- // them before their parent tx/output rows so orphan data cannot leak via OData.
1103
+ const history = await tx.run(SELECT.distinct.from(cardano_1.AssetHistory_).columns('unit').where({ txHash: { in: txChunk } }));
1104
+ for (const u of history ?? [])
1105
+ rolledBackUnits.add(u.unit);
1106
+ }
1107
+ for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
1108
+ // These tables have no cascading delete. Remove them first so no orphans leak via OData.
586
1109
  await tx.run(DELETE.from(cardano_1.UTxOAssets).where({ utxo_hash: { in: txChunk } }));
587
1110
  await tx.run(DELETE.from(cardano_1.AddressUTxOs).where({ hash: { in: txChunk } }));
588
1111
  await tx.run(DELETE.from(cardano_1.AddressTransactions).where({ tx_hash: { in: txChunk } }));
589
1112
  await tx.run(DELETE.from(cardano_1.AssetHistory_).where({ txHash: { in: txChunk } }));
590
- await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_tx_hash: { in: txChunk } }));
591
- await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_tx_hash: { in: txChunk } }));
592
- await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ tx_hash: { in: txChunk } }));
593
- await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ tx_hash: { in: txChunk } }));
594
- await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: txChunk } }));
595
- await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: txChunk } }));
596
1113
  }
1114
+ await (0, transaction_rows_1.deleteTransactionRows)(tx, staleTxs);
597
1115
  await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
598
1116
  }
1117
+ // Epoch snapshots read at a rolled-back block describe a chain that no longer exists.
1118
+ if (blocksRolledBack > 0) {
1119
+ await (0, account_snapshots_1.dropAccountSnapshotsAfter)(tx, forkSlot);
1120
+ for (const entity of [cardano_1.PoolEpochSnapshots, cardano_1.DrepEpochSnapshots, cardano_1.EpochLedgerSnapshots]) {
1121
+ await tx.run(DELETE.from(entity).where({ snapshotSlot: { '>': forkSlot } }));
1122
+ }
1123
+ }
1124
+ // Uses the stored status. A fork after the snapshot slot is undone, one before it invalidates the set.
1125
+ const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
1126
+ if (persisted?.status === 'active' && persisted.anchorSlot != null) {
1127
+ if (forkSlot < persisted.anchorSlot) {
1128
+ await (0, sync_state_1.setUtxoSetState)(tx, {
1129
+ status: 'invalid',
1130
+ error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot}: re-import the set`,
1131
+ });
1132
+ ledgerInvalidated = true;
1133
+ }
1134
+ else {
1135
+ await (0, ledger_state_1.undoLedgerForTransactions)(tx, rolledBackTxHashes, forkSlot);
1136
+ if (persisted.appliedSlot != null && persisted.appliedSlot > forkSlot) {
1137
+ await (0, sync_state_1.setUtxoSetState)(tx, { appliedSlot: forkSlot });
1138
+ }
1139
+ }
1140
+ }
1141
+ if (rolledBackUnits.size)
1142
+ await this.indexer.reconcileRolledBackAssets(tx, [...rolledBackUnits], forkSlot);
599
1143
  await (0, sync_state_1.resetCursorTo)(tx, point === 'origin'
600
1144
  ? { slot: forkSlot, hash: this.config.startBlockHash ?? '', height: 0 }
601
1145
  : { slot: point.slot, hash: point.hash, height: forkHeight ?? 0 });
@@ -618,12 +1162,18 @@ class CardanoCrawler {
618
1162
  }
619
1163
  throw err;
620
1164
  }
621
- // Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
622
- // the rollback commit.
1165
+ if (ledgerInvalidated) {
1166
+ this.indexer.setUtxoAnchor(null);
1167
+ logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor. Ledger tables stop updating until importUtxoSet runs again`);
1168
+ }
1169
+ // The rollback may have removed this epoch's snapshot. The next block re-checks it.
1170
+ this.snapshotedEpoch = null;
1171
+ // Epoch totals cached in memory counted the removed blocks.
1172
+ this.indexer.forgetCrawlEpochs();
623
1173
  (0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
624
1174
  logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
625
1175
  }
626
- /** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
1176
+ /** Renew the lease while no block commits; block writes renew it transactionally. */
627
1177
  startLeaseHeartbeat() {
628
1178
  if (!this.leaseOwner || this.leaseHeartbeat)
629
1179
  return;
@@ -633,6 +1183,9 @@ class CardanoCrawler {
633
1183
  await this.leaseSleep(intervalMs);
634
1184
  if (!this.running)
635
1185
  return;
1186
+ // Block commits renew the lease; the heartbeat only covers idle stretches.
1187
+ if (Date.now() - this.leaseRenewedAt < intervalMs)
1188
+ continue;
636
1189
  try {
637
1190
  const renewed = await cds_1.default.tx((tx) => (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner));
638
1191
  if (!renewed) {
@@ -650,6 +1203,24 @@ class CardanoCrawler {
650
1203
  }
651
1204
  })();
652
1205
  }
1206
+ /** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
1207
+ static isDataRejection(err) {
1208
+ // RangeError: BigInt / number conversions in the mappers; SyntaxError: JSON of the block
1209
+ if (err instanceof RangeError || err instanceof SyntaxError)
1210
+ return true;
1211
+ const message = err instanceof Error ? err.message : String(err);
1212
+ return CardanoCrawler.DATA_REJECTION_PATTERNS.some((p) => p.test(message));
1213
+ }
1214
+ /** Count final persist failures per block hash (a different hash resets the count). */
1215
+ static notePersistFailure(hash) {
1216
+ const p = CardanoCrawler.poison;
1217
+ CardanoCrawler.poison = p && p.hash === hash ? { hash, failures: p.failures + 1 } : { hash, failures: 1 };
1218
+ return CardanoCrawler.poison.failures;
1219
+ }
1220
+ /** Test seam: forget the poison-block memory (process-wide state). */
1221
+ static resetPoisonMemory() {
1222
+ CardanoCrawler.poison = null;
1223
+ }
653
1224
  /** Record state only while this instance still owns the lease. */
654
1225
  async recordCrawlerError(err) {
655
1226
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
@@ -664,7 +1235,7 @@ class CardanoCrawler {
664
1235
  this.leaseWake = () => { clearTimeout(timer); this.leaseWake = null; resolve(); };
665
1236
  });
666
1237
  }
667
- /** Cancellable, unref'd delay — halt() wakes it so shutdown never waits out a poll. */
1238
+ /** Cancellable delay. halt() wakes it so shutdown never waits out a poll. */
668
1239
  sleep(ms) {
669
1240
  return new Promise((resolve) => {
670
1241
  const timer = setTimeout(() => { this.wake = null; resolve(); }, ms);