@odatano/core 2.0.0-rc.18 → 2.0.0-rc.19

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 (35) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +52 -0
  2. package/@cds-models/CardanoIndexerService/index.js +7 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +170 -0
  4. package/@cds-models/CardanoODataService/index.js +21 -0
  5. package/@cds-models/odatano/cardano/index.d.ts +176 -0
  6. package/@cds-models/odatano/cardano/index.js +21 -0
  7. package/README.md +3 -3
  8. package/db/schema.cds +277 -0
  9. package/package.json +179 -179
  10. package/srv/blockchain/backends/cardano-backend.d.ts +16 -0
  11. package/srv/blockchain/backends/cardano-backend.js +4 -0
  12. package/srv/blockchain/backends/koios-backend.d.ts +80 -1
  13. package/srv/blockchain/backends/koios-backend.js +128 -48
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +21 -2
  15. package/srv/blockchain/backends/ogmios-backend.js +120 -16
  16. package/srv/blockchain/cardano-client.d.ts +3 -1
  17. package/srv/blockchain/cardano-client.js +9 -0
  18. package/srv/blockchain/cardano-indexer.d.ts +56 -3
  19. package/srv/blockchain/cardano-indexer.js +124 -3
  20. package/srv/blockchain/crawler/crawler.d.ts +11 -1
  21. package/srv/blockchain/crawler/crawler.js +70 -1
  22. package/srv/blockchain/crawler/sync-state.d.ts +27 -1
  23. package/srv/blockchain/crawler/sync-state.js +83 -1
  24. package/srv/blockchain/crawler/utxo-set-import.d.ts +86 -0
  25. package/srv/blockchain/crawler/utxo-set-import.js +289 -0
  26. package/srv/blockchain/ledger-state.d.ts +89 -0
  27. package/srv/blockchain/ledger-state.js +383 -0
  28. package/srv/cardano-indexer-service.cds +26 -0
  29. package/srv/cardano-indexer-service.js +71 -0
  30. package/srv/cardano-service.cds +35 -0
  31. package/srv/server.js +6 -1
  32. package/srv/utils/db-indexes.js +12 -0
  33. package/srv/utils/mappers.d.ts +43 -3
  34. package/srv/utils/mappers.js +115 -1
  35. package/srv/utils/types.d.ts +38 -0
@@ -4,6 +4,7 @@ import type { CardanoTransactionBuilder } from './cardano-tx-builder';
4
4
  import { Transaction as CardanoTransaction, AddressUTxOs, TransactionMetadata, NetworkInformation, Block, Epoch, AssetHistory, Account, Drep, Pool, Asset, Address, LedgerProtocolParameter, AddressTransactions } from '#cds-models/CardanoODataService';
5
5
  import { TransactionBuild, TransactionSubmission } from '#cds-models/CardanoTransactionService';
6
6
  import { TxBuildRequest, Transaction as ProviderTransaction, BlockData } from '../utils/types';
7
+ import { type LedgerAnchor } from './ledger-state';
7
8
  import type { TxCacheTargets } from '../utils/tx-build-helper';
8
9
  /**
9
10
  * CardanoIndexer - Indexer for Cardano blockchain data into OData entities
@@ -38,12 +39,31 @@ export declare class CardanoIndexer {
38
39
  private crawlEpochCurrent;
39
40
  private crawlEpochPrevious;
40
41
  /**
41
- * Analytics coverage of the crawl path (v2.0, FR "crawler coverage for analytics"). The
42
+ * Analytics coverage of the crawl path (v2.0). The
42
43
  * defaults mirror the crawler config defaults, so an indexer the crawler never configured
43
44
  * (unit tests, the lazy-only path) behaves exactly like a configured one.
44
45
  */
45
46
  private crawlAssetHistory;
46
47
  private crawlAssetCatalogue;
48
+ /** Certificates + withdrawals per block (ledger-state coverage). Opt-in. */
49
+ private crawlCertificates;
50
+ /** Logged once per process: the active source reports no certificates (Blockfrost). */
51
+ private certificatesUnreportedWarned;
52
+ /**
53
+ * Crawler-fed ledger state (`crawler.utxoSet`). Blocks after `utxoAnchor` are
54
+ * applied to the Ledger* tables; no anchor (nothing imported, or invalidated by a reorg
55
+ * past it) means the mode is configured but inactive.
56
+ */
57
+ private crawlUtxoSet;
58
+ private utxoAnchor;
59
+ /** The anchor block was found in the crawled chain (checked once, before the first apply). */
60
+ private utxoAnchorVerified;
61
+ /**
62
+ * Invalidation decided inside a block transaction. The in-memory anchor stays until the
63
+ * crawler confirms the commit (`takeLedgerInvalidation`), so a rolled-back attempt neither
64
+ * loses the anchor nor leaves the DB saying `active` while this process stopped applying.
65
+ */
66
+ private ledgerInvalidation;
47
67
  /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
48
68
  private static readonly ASSET_MEMO_CAP;
49
69
  private assetMemo;
@@ -65,7 +85,32 @@ export declare class CardanoIndexer {
65
85
  assetHistory: boolean;
66
86
  assetCatalogue: 'off' | 'bare' | 'enrich';
67
87
  assetEnrichRate?: number;
88
+ certificates?: boolean;
89
+ utxoSet?: boolean;
68
90
  }): void;
91
+ /** The anchor the imported UTxO set describes (null = ledger mode inactive). */
92
+ setUtxoAnchor(anchor: LedgerAnchor | null): void;
93
+ /**
94
+ * The imported set describes the chain AT the anchor block. Before the first block past
95
+ * it is applied, that block has to be the one the crawler actually followed — a snapshot
96
+ * taken on a fork that was dropped again without a rollback the crawler saw (the fork was
97
+ * never in its cursor) would otherwise seed the set with the wrong balances.
98
+ *
99
+ * The check is against the cursor, not the Blocks table: when the first block past the
100
+ * anchor arrives, the cursor (not yet advanced in this transaction) IS the block the
101
+ * crawler followed last, so it must equal the anchor exactly. That also covers the
102
+ * bootstrap case — the configured start block sits in the cursor without a Blocks row of
103
+ * its own. Once a block has been applied (`utxoAppliedSlot` set, same transaction), the
104
+ * anchor was verified and a restart skips the check.
105
+ */
106
+ private verifyUtxoAnchor;
107
+ /** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
108
+ getUtxoAnchor(): LedgerAnchor | null;
109
+ /**
110
+ * Called by the crawler right after a block transaction committed: hands out a pending
111
+ * invalidation (and drops the anchor) exactly once, or null.
112
+ */
113
+ takeLedgerInvalidation(): string | null;
69
114
  /**
70
115
  * Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
71
116
  * its own transaction. The timer is unref'd, so it never holds the process open, and a failing
@@ -224,6 +269,13 @@ export declare class CardanoIndexer {
224
269
  * tx's output in the same block), then batch-reads previously-indexed outputs from the
225
270
  * DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
226
271
  */
272
+ /**
273
+ * `crawler.certificates` is on but the block's transactions carry no `certificates` field at
274
+ * all — the source does not report them (Blockfrost: a per-tx enumeration would be six extra
275
+ * calls per transaction). `[]` means "none", undefined means "unreported"; only the latter is
276
+ * worth a warning, and only once — the crawl itself is unaffected.
277
+ */
278
+ private warnIfCertificatesUnreported;
227
279
  private resolveInputs;
228
280
  /**
229
281
  * Settle the fee of phase-2-invalid transactions and the block total that follows from it.
@@ -241,7 +293,8 @@ export declare class CardanoIndexer {
241
293
  *
242
294
  * Applies to every backend that reports phase-2 validity — the chain-sync path (`spends`)
243
295
  * and Blockfrost (`valid_contract`), whose declared `fees` are likewise never collected on a
244
- * failed script phase. Koios carries `spendsCollaterals` as undefined and passes through
296
+ * failed script phase, and Koios (`valid_contract` + collateral inputs/output on `/tx_info`).
297
+ * A source without the field carries `spendsCollaterals` as undefined and passes through
245
298
  * untouched.
246
299
  */
247
300
  private applyCollateralFees;
@@ -268,7 +321,7 @@ export declare class CardanoIndexer {
268
321
  private buildAssetHistoryRows;
269
322
  /**
270
323
  * Keep the `Assets` catalogue complete for every unit the crawl meets, from the data already
271
- * in hand — no provider call (FR "crawler coverage for analytics", variant "bare row").
324
+ * in hand — no provider call (analytics coverage, variant "bare row").
272
325
  *
273
326
  * `Assets` is temporal, so its key is `(validFrom, unit)` and a row is a slice. The bare row
274
327
  * therefore carries the fixed epoch-zero stamp (`BARE_ASSET_STAMP`), which no wall-clock slice
@@ -13,6 +13,8 @@ const CardanoSignService_1 = require("#cds-models/CardanoSignService");
13
13
  const cardano_1 = require("#cds-models/odatano/cardano");
14
14
  const mappers_1 = require("../utils/mappers");
15
15
  const collections_1 = require("../utils/collections");
16
+ const ledger_state_1 = require("./ledger-state");
17
+ const sync_state_1 = require("./crawler/sync-state");
16
18
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
17
19
  const logger = cds_1.default.log('CardanoIndexer');
18
20
  /**
@@ -48,12 +50,31 @@ class CardanoIndexer {
48
50
  crawlEpochCurrent = null;
49
51
  crawlEpochPrevious = null;
50
52
  /**
51
- * Analytics coverage of the crawl path (v2.0, FR "crawler coverage for analytics"). The
53
+ * Analytics coverage of the crawl path (v2.0). The
52
54
  * defaults mirror the crawler config defaults, so an indexer the crawler never configured
53
55
  * (unit tests, the lazy-only path) behaves exactly like a configured one.
54
56
  */
55
57
  crawlAssetHistory = true;
56
58
  crawlAssetCatalogue = 'bare';
59
+ /** Certificates + withdrawals per block (ledger-state coverage). Opt-in. */
60
+ crawlCertificates = false;
61
+ /** Logged once per process: the active source reports no certificates (Blockfrost). */
62
+ certificatesUnreportedWarned = false;
63
+ /**
64
+ * Crawler-fed ledger state (`crawler.utxoSet`). Blocks after `utxoAnchor` are
65
+ * applied to the Ledger* tables; no anchor (nothing imported, or invalidated by a reorg
66
+ * past it) means the mode is configured but inactive.
67
+ */
68
+ crawlUtxoSet = false;
69
+ utxoAnchor = null;
70
+ /** The anchor block was found in the crawled chain (checked once, before the first apply). */
71
+ utxoAnchorVerified = false;
72
+ /**
73
+ * Invalidation decided inside a block transaction. The in-memory anchor stays until the
74
+ * crawler confirms the commit (`takeLedgerInvalidation`), so a rolled-back attempt neither
75
+ * loses the anchor nor leaves the DB saying `active` while this process stopped applying.
76
+ */
77
+ ledgerInvalidation = null;
57
78
  /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
58
79
  static ASSET_MEMO_CAP = 200_000;
59
80
  assetMemo = new Set();
@@ -74,10 +95,62 @@ class CardanoIndexer {
74
95
  configureCrawlCoverage(coverage) {
75
96
  this.crawlAssetHistory = coverage.assetHistory;
76
97
  this.crawlAssetCatalogue = coverage.assetCatalogue;
98
+ this.crawlCertificates = coverage.certificates ?? false;
99
+ this.crawlUtxoSet = coverage.utxoSet ?? false;
77
100
  this.enrichRate = coverage.assetEnrichRate ?? this.enrichRate;
78
101
  if (coverage.assetCatalogue !== 'enrich')
79
102
  this.stopAssetEnrichment();
80
103
  }
104
+ /** The anchor the imported UTxO set describes (null = ledger mode inactive). */
105
+ setUtxoAnchor(anchor) {
106
+ this.utxoAnchor = anchor;
107
+ this.utxoAnchorVerified = false;
108
+ this.ledgerInvalidation = null;
109
+ }
110
+ /**
111
+ * The imported set describes the chain AT the anchor block. Before the first block past
112
+ * it is applied, that block has to be the one the crawler actually followed — a snapshot
113
+ * taken on a fork that was dropped again without a rollback the crawler saw (the fork was
114
+ * never in its cursor) would otherwise seed the set with the wrong balances.
115
+ *
116
+ * The check is against the cursor, not the Blocks table: when the first block past the
117
+ * anchor arrives, the cursor (not yet advanced in this transaction) IS the block the
118
+ * crawler followed last, so it must equal the anchor exactly. That also covers the
119
+ * bootstrap case — the configured start block sits in the cursor without a Blocks row of
120
+ * its own. Once a block has been applied (`utxoAppliedSlot` set, same transaction), the
121
+ * anchor was verified and a restart skips the check.
122
+ */
123
+ async verifyUtxoAnchor(tx, anchor) {
124
+ const cursor = await (0, sync_state_1.readCursor)(tx);
125
+ if (cursor?.utxoSet.appliedSlot != null)
126
+ return true;
127
+ if (cursor && cursor.lastSlot === anchor.slot && (cursor.lastBlockHash ?? '').toLowerCase() === anchor.hash.toLowerCase())
128
+ return true;
129
+ const reason = cursor
130
+ ? `anchor ${anchor.slot}/${anchor.hash} is not the block the crawler followed (cursor ${cursor.lastSlot}/${cursor.lastBlockHash})`
131
+ : `no crawler cursor to verify the anchor ${anchor.slot}/${anchor.hash} against`;
132
+ logger.error(`UTxO set invalidated: ${reason} — the snapshot describes a fork; re-import at the crawler cursor`);
133
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: reason.slice(0, 500) });
134
+ this.ledgerInvalidation = reason;
135
+ return false;
136
+ }
137
+ /** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
138
+ getUtxoAnchor() {
139
+ return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
140
+ }
141
+ /**
142
+ * Called by the crawler right after a block transaction committed: hands out a pending
143
+ * invalidation (and drops the anchor) exactly once, or null.
144
+ */
145
+ takeLedgerInvalidation() {
146
+ const reason = this.ledgerInvalidation;
147
+ if (reason) {
148
+ this.ledgerInvalidation = null;
149
+ this.utxoAnchor = null;
150
+ this.utxoAnchorVerified = false;
151
+ }
152
+ return reason;
153
+ }
81
154
  /**
82
155
  * Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
83
156
  * its own transaction. The timer is unref'd, so it never holds the process open, and a failing
@@ -572,6 +645,17 @@ class CardanoIndexer {
572
645
  const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.hash, t.outputs ?? []));
573
646
  const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.hash, t.outputs ?? []));
574
647
  const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
648
+ // Certificates + withdrawals are block content the source already delivered (Ogmios
649
+ // chain-sync natively, Koios via the same /tx_info call) — keyed (tx, certIndex, kind) /
650
+ // (tx, stakeAddress), so a re-crawl is idempotent and a reorg removes them with their tx.
651
+ const certificateRows = this.crawlCertificates
652
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? []))
653
+ : [];
654
+ const withdrawalRows = this.crawlCertificates
655
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? []))
656
+ : [];
657
+ if (this.crawlCertificates)
658
+ this.warnIfCertificatesUnreported(txs);
575
659
  // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
576
660
  // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
577
661
  const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
@@ -587,6 +671,26 @@ class CardanoIndexer {
587
671
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
588
672
  if (metadataRows.length)
589
673
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
674
+ if (certificateRows.length)
675
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
676
+ if (withdrawalRows.length)
677
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
678
+ // Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes;
679
+ // same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
680
+ if (this.crawlUtxoSet && this.utxoAnchor && (blockData.slot ?? 0) > this.utxoAnchor.slot) {
681
+ if (this.ledgerInvalidation) {
682
+ // Decided in an earlier attempt of this block whose transaction rolled back: re-write
683
+ // the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
684
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: this.ledgerInvalidation.slice(0, 500) });
685
+ }
686
+ else if (this.utxoAnchorVerified || (this.utxoAnchorVerified = await this.verifyUtxoAnchor(tx, this.utxoAnchor))) {
687
+ const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs);
688
+ if (ledger.missing) {
689
+ logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
690
+ 'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
691
+ }
692
+ }
693
+ }
590
694
  if (assetHistoryRows.length)
591
695
  await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
592
696
  // Catalogue last: it reads what the block just wrote conceptually, and a block without
@@ -604,6 +708,22 @@ class CardanoIndexer {
604
708
  * tx's output in the same block), then batch-reads previously-indexed outputs from the
605
709
  * DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
606
710
  */
711
+ /**
712
+ * `crawler.certificates` is on but the block's transactions carry no `certificates` field at
713
+ * all — the source does not report them (Blockfrost: a per-tx enumeration would be six extra
714
+ * calls per transaction). `[]` means "none", undefined means "unreported"; only the latter is
715
+ * worth a warning, and only once — the crawl itself is unaffected.
716
+ */
717
+ warnIfCertificatesUnreported(txs) {
718
+ if (this.certificatesUnreportedWarned || !txs.length)
719
+ return;
720
+ if (txs.some(t => t.certificates !== undefined))
721
+ return;
722
+ this.certificatesUnreportedWarned = true;
723
+ logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
724
+ '(Blockfrost pagination) — TransactionCertificates/TransactionWithdrawals stay empty until ' +
725
+ 'the crawl runs on Ogmios chain-sync or Koios');
726
+ }
607
727
  async resolveInputs(tx, txs) {
608
728
  // 1. In-memory index of this block's outputs (txHash#outputIndex -> {address, amount})
609
729
  const blockOutputs = new Map();
@@ -677,7 +797,8 @@ class CardanoIndexer {
677
797
  *
678
798
  * Applies to every backend that reports phase-2 validity — the chain-sync path (`spends`)
679
799
  * and Blockfrost (`valid_contract`), whose declared `fees` are likewise never collected on a
680
- * failed script phase. Koios carries `spendsCollaterals` as undefined and passes through
800
+ * failed script phase, and Koios (`valid_contract` + collateral inputs/output on `/tx_info`).
801
+ * A source without the field carries `spendsCollaterals` as undefined and passes through
681
802
  * untouched.
682
803
  */
683
804
  applyCollateralFees(blockData, txs) {
@@ -791,7 +912,7 @@ class CardanoIndexer {
791
912
  }
792
913
  /**
793
914
  * Keep the `Assets` catalogue complete for every unit the crawl meets, from the data already
794
- * in hand — no provider call (FR "crawler coverage for analytics", variant "bare row").
915
+ * in hand — no provider call (analytics coverage, variant "bare row").
795
916
  *
796
917
  * `Assets` is temporal, so its key is `(validFrom, unit)` and a row is a slice. The bare row
797
918
  * therefore carries the fixed epoch-zero stamp (`BARE_ASSET_STAMP`), which no wall-clock slice
@@ -19,7 +19,7 @@ export interface CrawlerConfig {
19
19
  /** Poll cadence when caught up / on transient errors (pagination path). */
20
20
  pollIntervalMs: number;
21
21
  /**
22
- * Analytics coverage of the crawl (FR "crawler coverage for analytics"). All three are
22
+ * Analytics coverage of the crawl. All three are
23
23
  * by-products of blocks the crawler already holds, except `assetCatalogue: 'enrich'` and
24
24
  * `epochSnapshots`, which do talk to a provider.
25
25
  */
@@ -34,6 +34,16 @@ export interface CrawlerConfig {
34
34
  assetEnrichRate: number;
35
35
  /** Snapshot every pool and DRep at each epoch boundary. Requires an enumerating backend (Koios). */
36
36
  epochSnapshots: boolean;
37
+ /**
38
+ * Write TransactionCertificates + TransactionWithdrawals per block (ledger-state
39
+ * coverage). Free on Ogmios chain-sync and Koios; Blockfrost does not report them.
40
+ */
41
+ certificates: boolean;
42
+ /**
43
+ * Maintain the crawler-fed UTxO set (`LedgerUTxOs` / `LedgerAddresses` / `LedgerAccounts`).
44
+ * Needs a one-off snapshot import (`importUtxoSet`) to become active.
45
+ */
46
+ utxoSet: boolean;
37
47
  }
38
48
  /**
39
49
  * CardanoCrawler — pre-sync engine (v2.0). Streams the chain forward from a configured
@@ -9,6 +9,7 @@ const errors_1 = require("../../utils/errors");
9
9
  const collections_1 = require("../../utils/collections");
10
10
  const const_1 = require("../../utils/const");
11
11
  const hooks_1 = require("./hooks");
12
+ const ledger_state_1 = require("../ledger-state");
12
13
  const cardano_1 = require("#cds-models/odatano/cardano");
13
14
  const sync_state_1 = require("./sync-state");
14
15
  const { SELECT, DELETE, INSERT } = cds_1.default.ql;
@@ -190,7 +191,35 @@ class CardanoCrawler {
190
191
  assetHistory: this.config.assetHistory,
191
192
  assetCatalogue: this.config.assetCatalogue,
192
193
  assetEnrichRate: this.config.assetEnrichRate,
194
+ certificates: this.config.certificates,
195
+ utxoSet: this.config.utxoSet,
193
196
  });
197
+ // Ledger state is only ever applied from a known anchor — no snapshot, no writes.
198
+ if (this.config.utxoSet) {
199
+ const u = cursor.utxoSet;
200
+ // Blocks crawled while the mode was off (or after an invalidation that was then
201
+ // flipped back on) never reached the ledger tables: the cursor is ahead of the last
202
+ // applied slot. The set is stale and cannot be caught up — invalidate it explicitly.
203
+ const lastApplied = u.appliedSlot ?? u.anchorSlot;
204
+ if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
205
+ const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied} — blocks were crawled without the set; re-import`;
206
+ await cds_1.default.tx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error }));
207
+ u.status = 'invalid';
208
+ u.error = error;
209
+ }
210
+ if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
211
+ this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
212
+ logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash} — ledger tables are maintained`);
213
+ }
214
+ else {
215
+ this.indexer.setUtxoAnchor(null);
216
+ logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''} — ` +
217
+ 'ledger tables are not maintained until importUtxoSet has run (pause the crawler first)');
218
+ }
219
+ }
220
+ else {
221
+ this.indexer.setUtxoAnchor(null);
222
+ }
194
223
  this.startLeaseHeartbeat();
195
224
  // A pipeline crash (e.g. chain-sync intersection not found after downtime) must
196
225
  // surface on the cursor — otherwise the crawler looks healthy while doing nothing.
@@ -584,6 +613,7 @@ class CardanoCrawler {
584
613
  await this.halt('error', true); // config error: a restart cannot fix it
585
614
  return;
586
615
  }
616
+ backend.configureCrawl?.({ certificates: this.config.certificates });
587
617
  this.activeSource = 'pagination';
588
618
  logger.info('Crawler running (pagination)');
589
619
  // Tip cache: during deep catch-up the exact tip is irrelevant (only "am I still
@@ -766,10 +796,20 @@ class CardanoCrawler {
766
796
  throw new CrawlerLeaseLostError();
767
797
  }
768
798
  await this.indexer.indexBlockFull(tx, block, txs);
769
- 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');
799
+ // Ledger progress marker: written in the same statement as the cursor, so "the
800
+ // cursor is ahead of the marker" always means blocks went by without the set.
801
+ const anchor = this.indexer.getUtxoAnchor();
802
+ const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
803
+ 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);
770
804
  });
771
805
  if (CardanoCrawler.poison?.hash === block.hash)
772
806
  CardanoCrawler.poison = null;
807
+ // A ledger invalidation decided inside the block transaction takes effect in memory
808
+ // only now, after the commit that carries it — a rolled-back attempt changes nothing.
809
+ const invalidation = this.indexer.takeLedgerInvalidation();
810
+ if (invalidation) {
811
+ logger.error(`UTxO set invalidated: ${invalidation} — ledger tables stop updating until importUtxoSet runs again`);
812
+ }
773
813
  // Notify observers (wallet-worker confirmation tracker) AFTER the commit —
774
814
  // listener failures are swallowed inside emitBlockIndexed.
775
815
  (0, hooks_1.emitBlockIndexed)({
@@ -903,6 +943,8 @@ class CardanoCrawler {
903
943
  let blocksRolledBack = 0;
904
944
  let txsRolledBack = 0;
905
945
  let emittedForkHeight = null;
946
+ const rolledBackTxHashes = [];
947
+ let ledgerInvalidated = false;
906
948
  try {
907
949
  await cds_1.default.tx(async (tx) => {
908
950
  if (this.leaseOwner) {
@@ -928,6 +970,7 @@ class CardanoCrawler {
928
970
  const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash').where({ blockHash: { in: blockChunk } }));
929
971
  const txHashes = staleTxs.map((t) => t.hash);
930
972
  txsRolledBack += txHashes.length;
973
+ rolledBackTxHashes.push(...txHashes);
931
974
  for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
932
975
  // These denormalized/lazy indexes have no generated FK cascades. Remove
933
976
  // them before their parent tx/output rows so orphan data cannot leak via OData.
@@ -940,10 +983,32 @@ class CardanoCrawler {
940
983
  await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ tx_hash: { in: txChunk } }));
941
984
  await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ tx_hash: { in: txChunk } }));
942
985
  await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: txChunk } }));
986
+ await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: txChunk } }));
987
+ await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: txChunk } }));
943
988
  await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: txChunk } }));
944
989
  }
945
990
  await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
946
991
  }
992
+ // Crawler-fed ledger state, driven by the PERSISTED state so a process with the mode
993
+ // off still keeps the set consistent: a fork after the anchor is undone (drop created,
994
+ // reopen spent, recount touched addresses) and the progress marker follows the cursor
995
+ // back; a fork before the anchor invalidates the whole set.
996
+ const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
997
+ if (persisted?.status === 'active' && persisted.anchorSlot != null) {
998
+ if (forkSlot < persisted.anchorSlot) {
999
+ await (0, sync_state_1.setUtxoSetState)(tx, {
1000
+ status: 'invalid',
1001
+ error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot} — re-import the set`,
1002
+ });
1003
+ ledgerInvalidated = true;
1004
+ }
1005
+ else {
1006
+ await (0, ledger_state_1.undoLedgerForTransactions)(tx, rolledBackTxHashes);
1007
+ if (persisted.appliedSlot != null && persisted.appliedSlot > forkSlot) {
1008
+ await (0, sync_state_1.setUtxoSetState)(tx, { appliedSlot: forkSlot });
1009
+ }
1010
+ }
1011
+ }
947
1012
  await (0, sync_state_1.resetCursorTo)(tx, point === 'origin'
948
1013
  ? { slot: forkSlot, hash: this.config.startBlockHash ?? '', height: 0 }
949
1014
  : { slot: point.slot, hash: point.hash, height: forkHeight ?? 0 });
@@ -966,6 +1031,10 @@ class CardanoCrawler {
966
1031
  }
967
1032
  throw err;
968
1033
  }
1034
+ if (ledgerInvalidated) {
1035
+ this.indexer.setUtxoAnchor(null);
1036
+ logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor — ledger tables stop updating until importUtxoSet runs again`);
1037
+ }
969
1038
  // Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
970
1039
  // the rollback commit.
971
1040
  (0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
@@ -22,6 +22,17 @@ export interface CrawlPoint {
22
22
  hash: string;
23
23
  height?: number;
24
24
  }
25
+ export type UtxoSetStatusValue = 'none' | 'importing' | 'active' | 'invalid';
26
+ /** Crawler-fed ledger state (crawler.utxoSet): the anchor the imported UTxO set describes. */
27
+ export interface UtxoSetState {
28
+ status: UtxoSetStatusValue;
29
+ anchorSlot: number | null;
30
+ anchorHash: string | null;
31
+ importedAt: string | null;
32
+ /** Slot of the last block applied to the ledger tables (null = nothing applied since the import). */
33
+ appliedSlot: number | null;
34
+ error: string | null;
35
+ }
25
36
  /** Normalized, number-typed view of the cursor row (numeric fields already coerced). */
26
37
  export interface SyncCursor {
27
38
  network: string | null;
@@ -37,6 +48,7 @@ export interface SyncCursor {
37
48
  desiredRunning: boolean;
38
49
  leaseOwner: string | null;
39
50
  leaseUntil: string | null;
51
+ utxoSet: UtxoSetState;
40
52
  }
41
53
  /**
42
54
  * Idempotently ensure the singleton cursor row exists and return it.
@@ -92,7 +104,21 @@ export declare function latchPoisonBlock(db: CapTransaction, message: string): P
92
104
  export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
93
105
  slot: number;
94
106
  height?: number;
95
- }, status?: CrawlSyncStatusValue): Promise<void>;
107
+ }, status?: CrawlSyncStatusValue,
108
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
109
+ extra?: Record<string, unknown>): Promise<void>;
110
+ /**
111
+ * Lease for the UTxO set import: the same `leaseOwner` / `leaseUntil` columns the crawler
112
+ * uses, so a crawler start on ANY instance is refused while the import holds it (its CAS
113
+ * sees a foreign owner with a live deadline) and a second import is refused the same way.
114
+ * Unlike the crawler lease it does not require `desiredRunning` — the cluster is paused
115
+ * during an import by design.
116
+ */
117
+ export declare function tryAcquireImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
118
+ export declare function renewImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
119
+ export declare function releaseImportLease(db: CapTransaction, owner: string): Promise<void>;
120
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
121
+ export declare function setUtxoSetState(db: CapTransaction, state: Partial<UtxoSetState>): Promise<void>;
96
122
  /** Reset the cursor to a rollback point (used by reorg handling). */
97
123
  export declare function resetCursorTo(db: CapTransaction, point: CrawlPoint): Promise<void>;
98
124
  /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
@@ -13,6 +13,10 @@ exports.releaseCrawlerLease = releaseCrawlerLease;
13
13
  exports.setCrawlerDesiredRunning = setCrawlerDesiredRunning;
14
14
  exports.latchPoisonBlock = latchPoisonBlock;
15
15
  exports.advanceCursor = advanceCursor;
16
+ exports.tryAcquireImportLease = tryAcquireImportLease;
17
+ exports.renewImportLease = renewImportLease;
18
+ exports.releaseImportLease = releaseImportLease;
19
+ exports.setUtxoSetState = setUtxoSetState;
16
20
  exports.resetCursorTo = resetCursorTo;
17
21
  exports.setSyncStatus = setSyncStatus;
18
22
  exports.recordError = recordError;
@@ -58,6 +62,16 @@ function timestamp(v) {
58
62
  return v.toISOString();
59
63
  return String(v);
60
64
  }
65
+ /**
66
+ * Import-lease read-back: ownership and deadline only. The crawler variant below also
67
+ * requires `desiredRunning`, which `pauseCrawler` clears — and an import runs exactly then.
68
+ */
69
+ function importLeaseHeld(cursor, owner, expectedMs) {
70
+ if (!cursor || cursor.leaseOwner !== owner || !cursor.leaseUntil)
71
+ return false;
72
+ const actualMs = Date.parse(cursor.leaseUntil);
73
+ return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
74
+ }
61
75
  function leaseDeadlineReached(cursor, owner, expectedMs) {
62
76
  if (cursor?.desiredRunning !== true || cursor.leaseOwner !== owner || !cursor.leaseUntil)
63
77
  return false;
@@ -82,6 +96,14 @@ function toCursor(row) {
82
96
  desiredRunning: row.desiredRunning !== false,
83
97
  leaseOwner: row.leaseOwner ?? null,
84
98
  leaseUntil: timestamp(row.leaseUntil),
99
+ utxoSet: {
100
+ status: (row.utxoSetStatus ?? 'none'),
101
+ anchorSlot: optionalNum(row.utxoAnchorSlot),
102
+ anchorHash: row.utxoAnchorHash ?? null,
103
+ importedAt: timestamp(row.utxoSetImportedAt),
104
+ appliedSlot: optionalNum(row.utxoAppliedSlot),
105
+ error: row.utxoSetError ?? null,
106
+ },
85
107
  };
86
108
  }
87
109
  /**
@@ -114,6 +136,12 @@ async function ensureSyncStateSingleton(db, network, start) {
114
136
  desiredRunning: true,
115
137
  leaseOwner: null,
116
138
  leaseUntil: null,
139
+ utxoSetStatus: 'none',
140
+ utxoAnchorSlot: null,
141
+ utxoAnchorHash: null,
142
+ utxoSetImportedAt: null,
143
+ utxoAppliedSlot: null,
144
+ utxoSetError: null,
117
145
  };
118
146
  await db.run(INSERT.into(cardano_1.CardanoSyncState).entries(row));
119
147
  logger.info(`Sync cursor initialized (network=${network}, start=${start ? `${start.slot}/${start.hash}` : 'none'})`);
@@ -231,7 +259,9 @@ async function latchPoisonBlock(db, message) {
231
259
  * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
232
260
  * lastIndexedAt. Optionally records the latest known tip (for progress).
233
261
  */
234
- async function advanceCursor(db, block, tip, status = 'syncing') {
262
+ async function advanceCursor(db, block, tip, status = 'syncing',
263
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
264
+ extra) {
235
265
  const set = {
236
266
  lastSlot: block.slot,
237
267
  lastBlockHash: block.hash,
@@ -240,6 +270,7 @@ async function advanceCursor(db, block, tip, status = 'syncing') {
240
270
  syncStatus: status,
241
271
  consecutiveErrors: 0,
242
272
  lastError: null,
273
+ ...(extra ?? {}),
243
274
  };
244
275
  if (tip) {
245
276
  set.tipSlot = tip.slot;
@@ -248,6 +279,57 @@ async function advanceCursor(db, block, tip, status = 'syncing') {
248
279
  }
249
280
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
250
281
  }
282
+ /**
283
+ * Lease for the UTxO set import: the same `leaseOwner` / `leaseUntil` columns the crawler
284
+ * uses, so a crawler start on ANY instance is refused while the import holds it (its CAS
285
+ * sees a foreign owner with a live deadline) and a second import is refused the same way.
286
+ * Unlike the crawler lease it does not require `desiredRunning` — the cluster is paused
287
+ * during an import by design.
288
+ */
289
+ async function tryAcquireImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
290
+ const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
291
+ if (!raw)
292
+ return false;
293
+ const current = toCursor(raw);
294
+ const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
295
+ if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
296
+ return false;
297
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
298
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where({
299
+ ID: exports.SINGLETON_ID,
300
+ leaseOwner: raw.leaseOwner ?? null,
301
+ }));
302
+ const verified = await readCursor(db);
303
+ return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
304
+ }
305
+ async function renewImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
306
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
307
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
308
+ const verified = await readCursor(db);
309
+ return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
310
+ }
311
+ async function releaseImportLease(db, owner) {
312
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: null, leaseUntil: null }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
313
+ }
314
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
315
+ async function setUtxoSetState(db, state) {
316
+ const set = {};
317
+ if (state.status !== undefined)
318
+ set.utxoSetStatus = state.status;
319
+ if (state.anchorSlot !== undefined)
320
+ set.utxoAnchorSlot = state.anchorSlot;
321
+ if (state.anchorHash !== undefined)
322
+ set.utxoAnchorHash = state.anchorHash;
323
+ if (state.importedAt !== undefined)
324
+ set.utxoSetImportedAt = state.importedAt;
325
+ if (state.appliedSlot !== undefined)
326
+ set.utxoAppliedSlot = state.appliedSlot;
327
+ if (state.error !== undefined)
328
+ set.utxoSetError = state.error;
329
+ if (!Object.keys(set).length)
330
+ return;
331
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
332
+ }
251
333
  /** Reset the cursor to a rollback point (used by reorg handling). */
252
334
  async function resetCursorTo(db, point) {
253
335
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({