@odatano/core 2.0.0-rc.23 → 2.0.0-rc.25

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 (80) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  2. package/@cds-models/CardanoBackendService/index.js +40 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +27 -2
  6. package/@cds-models/CardanoODataService/index.js +3 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +23 -1
  8. package/@cds-models/CardanoSignService/index.js +3 -0
  9. package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
  10. package/@cds-models/CardanoTransactionService/index.js +4 -0
  11. package/@cds-models/index.d.ts +18 -0
  12. package/@cds-models/index.js +3 -0
  13. package/@cds-models/odatano/cardano/index.d.ts +49 -2
  14. package/@cds-models/odatano/cardano/index.js +6 -0
  15. package/db/schema.cds +74 -3
  16. package/db/types.cds +27 -0
  17. package/package.json +182 -181
  18. package/srv/blockchain/backends/blockfrost-backend.js +4 -2
  19. package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
  20. package/srv/blockchain/backends/koios-backend.d.ts +1 -1
  21. package/srv/blockchain/backends/koios-backend.js +61 -14
  22. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  23. package/srv/blockchain/backends/odatano-backend.js +166 -0
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
  25. package/srv/blockchain/backends/ogmios-backend.js +91 -21
  26. package/srv/blockchain/cardano-client.d.ts +23 -9
  27. package/srv/blockchain/cardano-client.js +77 -25
  28. package/srv/blockchain/cardano-indexer.d.ts +61 -15
  29. package/srv/blockchain/cardano-indexer.js +248 -79
  30. package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
  31. package/srv/blockchain/cardano-tx-builder.js +59 -4
  32. package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
  33. package/srv/blockchain/crawler/certificate-backfill.js +49 -30
  34. package/srv/blockchain/crawler/crawler.d.ts +3 -1
  35. package/srv/blockchain/crawler/crawler.js +12 -7
  36. package/srv/blockchain/crawler/sync-state.d.ts +3 -1
  37. package/srv/blockchain/crawler/sync-state.js +15 -2
  38. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  39. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  40. package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
  41. package/srv/blockchain/crawler/utxo-set-import.js +138 -47
  42. package/srv/blockchain/ledger-state.d.ts +16 -1
  43. package/srv/blockchain/ledger-state.js +38 -18
  44. package/srv/blockchain/pending-spends.d.ts +28 -0
  45. package/srv/blockchain/pending-spends.js +89 -0
  46. package/srv/blockchain/stored-chain.d.ts +33 -0
  47. package/srv/blockchain/stored-chain.js +234 -0
  48. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
  49. package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
  50. package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
  51. package/srv/blockchain/transaction-rows.d.ts +1 -1
  52. package/srv/blockchain/transaction-rows.js +2 -1
  53. package/srv/blockchain/wallet-worker/build-request.js +1 -1
  54. package/srv/cardano-backend-service.cds +52 -0
  55. package/srv/cardano-backend-service.d.ts +2 -0
  56. package/srv/cardano-backend-service.js +244 -0
  57. package/srv/cardano-indexer-service.cds +201 -176
  58. package/srv/cardano-indexer-service.js +104 -10
  59. package/srv/cardano-service.cds +5 -0
  60. package/srv/cardano-tx-service.cds +39 -0
  61. package/srv/cardano-tx-service.js +88 -14
  62. package/srv/server.js +20 -2
  63. package/srv/utils/agent-grants.js +8 -0
  64. package/srv/utils/const.d.ts +5 -0
  65. package/srv/utils/const.js +6 -1
  66. package/srv/utils/error-codes.d.ts +2 -0
  67. package/srv/utils/error-codes.js +2 -0
  68. package/srv/utils/errors.d.ts +7 -0
  69. package/srv/utils/errors.js +11 -1
  70. package/srv/utils/mappers.d.ts +24 -2
  71. package/srv/utils/mappers.js +49 -0
  72. package/srv/utils/pg-inline-json.d.ts +8 -0
  73. package/srv/utils/pg-inline-json.js +63 -0
  74. package/srv/utils/tx-build-helper.d.ts +2 -0
  75. package/srv/utils/tx-build-helper.js +12 -0
  76. package/srv/utils/tx-request-parsers.d.ts +46 -5
  77. package/srv/utils/tx-request-parsers.js +227 -16
  78. package/srv/utils/types.d.ts +59 -0
  79. package/srv/utils/validators.d.ts +5 -1
  80. package/srv/utils/validators.js +19 -9
@@ -0,0 +1,283 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TransactionBackfillError = void 0;
7
+ exports.inputFillStatement = inputFillStatement;
8
+ exports.backfillTransactions = backfillTransactions;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const mappers_1 = require("../../utils/mappers");
11
+ const collections_1 = require("../../utils/collections");
12
+ const certificate_backfill_1 = require("./certificate-backfill");
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
14
+ const { SELECT, UPDATE, UPSERT, DELETE } = cds_1.default.ql;
15
+ const logger = cds_1.default.log('TransactionBackfill');
16
+ /**
17
+ * Completes transactions the crawl already holds from a second chain-sync stream: input
18
+ * outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
19
+ * hash, a missing input address, and the redeemers. Only empty input fields are filled; a
20
+ * transaction whose stored inputs do not line up with the stream is left as it is.
21
+ */
22
+ class TransactionBackfillError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = 'TransactionBackfillError';
26
+ }
27
+ }
28
+ exports.TransactionBackfillError = TransactionBackfillError;
29
+ const key = (txSeq, inputIndex) => `${Number(txSeq)}#${Number(inputIndex)}`;
30
+ const lovelaceOf = (i) => i.amount?.find((a) => a.unit === 'lovelace')?.quantity ?? null;
31
+ /**
32
+ * Stored input and streamed input describe the same outpoint: same flags, same outpoint where
33
+ * one is stored, same address and lovelace where both sides know them. A stored address the
34
+ * stream cannot resolve is unverifiable, so it does not match.
35
+ */
36
+ function sameInput(row, fresh, storedLovelace) {
37
+ if (Boolean(row.isCollateral) !== Boolean(fresh.isCollateral) || Boolean(row.isReference) !== Boolean(fresh.isReference))
38
+ return false;
39
+ if (row.spentTxHash != null) {
40
+ return row.spentTxHash === fresh.txHash && Number(row.spentOutputIndex) === fresh.outputIndex;
41
+ }
42
+ if (!row.address_address)
43
+ return true;
44
+ if (!fresh.address)
45
+ return false;
46
+ if (row.address_address !== fresh.address)
47
+ return false;
48
+ const freshLovelace = lovelaceOf(fresh);
49
+ return storedLovelace == null || freshLovelace == null || String(storedLovelace) === String(freshLovelace);
50
+ }
51
+ /**
52
+ * Stored rows in the stream's order when they hold the same outpoints with the same flags, each
53
+ * once; null otherwise (a row without outpoint cannot be placed).
54
+ */
55
+ function reorderByOutpoint(rows, fresh) {
56
+ if (rows.length !== fresh.length || rows.some((r) => r.spentTxHash == null))
57
+ return null;
58
+ const byOutpoint = new Map();
59
+ for (const r of rows) {
60
+ const k = `${r.spentTxHash}#${Number(r.spentOutputIndex)}#${Boolean(r.isCollateral)}#${Boolean(r.isReference)}`;
61
+ byOutpoint.set(k, [...(byOutpoint.get(k) ?? []), r]);
62
+ }
63
+ const ordered = [];
64
+ for (const f of fresh) {
65
+ const k = `${f.txHash}#${f.outputIndex}#${Boolean(f.isCollateral)}#${Boolean(f.isReference)}`;
66
+ const r = byOutpoint.get(k)?.shift();
67
+ if (!r)
68
+ return null;
69
+ ordered.push(r);
70
+ }
71
+ return ordered;
72
+ }
73
+ /** Columns of `row` that are empty and `fresh` can fill. */
74
+ function missingFields(row, fresh) {
75
+ const set = {};
76
+ if (row.spentTxHash == null && fresh.txHash) {
77
+ set.spentTxHash = fresh.txHash;
78
+ set.spentOutputIndex = fresh.outputIndex;
79
+ }
80
+ if (row.utxoData_dataHash == null && fresh.dataHash)
81
+ set.utxoData_dataHash = fresh.dataHash;
82
+ if (row.utxoData_inlineDatum == null && fresh.inlineDatum)
83
+ set.utxoData_inlineDatum = fresh.inlineDatum;
84
+ if (row.utxoData_referenceScriptHash == null && fresh.referenceScriptHash)
85
+ set.utxoData_referenceScriptHash = fresh.referenceScriptHash;
86
+ if (!row.address_address && fresh.address) {
87
+ set.address_address = fresh.address;
88
+ set.hasAddresses = true;
89
+ set.hasAssets = (fresh.amount ?? []).length > 0;
90
+ }
91
+ return set;
92
+ }
93
+ const INPUTS_TABLE = 'odatano_cardano_TransactionInputs';
94
+ /** Rows per statement; one JSON parameter each. */
95
+ const FILL_CHUNK = 5000;
96
+ /** Fill columns in the order the JSON records and the SET list use them. */
97
+ const FILL_COLUMNS = [
98
+ ['spentTxHash', 'text'],
99
+ ['spentOutputIndex', 'integer'],
100
+ ['utxoData_dataHash', 'text'],
101
+ ['utxoData_inlineDatum', 'text'],
102
+ ['utxoData_referenceScriptHash', 'text'],
103
+ ['address_address', 'text'],
104
+ ['hasAddresses', 'boolean'],
105
+ ['hasAssets', 'boolean'],
106
+ ];
107
+ /**
108
+ * One UPDATE per chunk: the fills travel as a JSON array and are joined on (txSeq, inputIndex).
109
+ * COALESCE keeps any value that is already there. Postgres and SQLite; other databases get one
110
+ * UPDATE per row.
111
+ */
112
+ function inputFillStatement(kind) {
113
+ const set = FILL_COLUMNS
114
+ .map(([c]) => c.startsWith('has')
115
+ ? `${c} = CASE WHEN v.address_address IS NOT NULL AND t.address_address IS NULL THEN v.${c} ELSE t.${c} END`
116
+ : `${c} = COALESCE(t.${c}, v.${c})`)
117
+ .join(', ');
118
+ if (kind === 'postgres') {
119
+ const cols = [['txSeq', 'bigint'], ['inputIndex', 'integer'], ...FILL_COLUMNS].map(([c, ty]) => `${c.toLowerCase()} ${ty}`).join(', ');
120
+ return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM json_to_recordset($1::json) AS v(${cols}) ` +
121
+ 'WHERE t.txSeq = v.txseq AND t.inputIndex = v.inputindex';
122
+ }
123
+ if (kind === 'sqlite' || kind === 'better-sqlite') {
124
+ const cols = ['txSeq', 'inputIndex', ...FILL_COLUMNS.map(([c]) => c)]
125
+ .map((c) => `json_extract(value, '$.${c.toLowerCase()}') AS ${c}`).join(', ');
126
+ return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM (SELECT ${cols} FROM json_each(?)) AS v ` +
127
+ 'WHERE t.txSeq = v.txSeq AND t.inputIndex = v.inputIndex';
128
+ }
129
+ return null;
130
+ }
131
+ /** Writes the fills of a batch: bulk statement where the database has one, else row by row. */
132
+ async function writeInputFills(tx, fills) {
133
+ if (!fills.length)
134
+ return;
135
+ const sql = inputFillStatement(cds_1.default.db?.kind ?? '');
136
+ if (!sql) {
137
+ for (const f of fills)
138
+ await tx.run(UPDATE.entity(cardano_1.TransactionInputs).set(f.set).where({ txSeq: f.txSeq, inputIndex: f.inputIndex }));
139
+ return;
140
+ }
141
+ for (const part of (0, collections_1.chunk)(fills, FILL_CHUNK)) {
142
+ const records = part.map((f) => {
143
+ const r = { txseq: f.txSeq, inputindex: f.inputIndex };
144
+ for (const [c] of FILL_COLUMNS)
145
+ r[c.toLowerCase()] = f.set[c] ?? null;
146
+ return r;
147
+ });
148
+ await tx.run(sql, [JSON.stringify(records)]);
149
+ }
150
+ }
151
+ /**
152
+ * Rewrites the input rows of one transaction as the ledger view: the kept rows (and their assets)
153
+ * move to their position, rows left out are dropped, empty fields are filled on the way.
154
+ */
155
+ async function rewriteInOrder(tx, seq, ordered, fresh) {
156
+ const assets = (await tx.run(SELECT.from(cardano_1.TransactionInputAssets).where({ input_txSeq: seq }))) ?? [];
157
+ const newIndex = new Map(ordered.map((r, i) => [Number(r.inputIndex), i]));
158
+ const rows = ordered.map((r, i) => ({ ...r, ...missingFields(r, fresh[i]), txSeq: seq, inputIndex: i }));
159
+ // assets of rows the ledger view drops go with them
160
+ const movedAssets = assets
161
+ .filter((a) => newIndex.has(Number(a.input_inputIndex)))
162
+ .map((a) => ({ ...a, input_txSeq: seq, input_inputIndex: newIndex.get(Number(a.input_inputIndex)) }));
163
+ await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_txSeq: seq }));
164
+ await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ txSeq: seq }));
165
+ await tx.run(UPSERT.into(cardano_1.TransactionInputs).entries(rows));
166
+ if (movedAssets.length)
167
+ await tx.run(UPSERT.into(cardano_1.TransactionInputAssets).entries(movedAssets));
168
+ }
169
+ /**
170
+ * Deletes stored outputs the ledger never produced: a provider lists the collateral return of a
171
+ * valid transaction, and the declared outputs of a phase-2 failure. Only when every output of the
172
+ * stream is stored, so a gap is never mistaken for an extra. Returns the transactions touched.
173
+ */
174
+ async function dropUnappliedOutputs(tx, txs) {
175
+ const wanted = new Map(txs.map((t) => [(0, mappers_1.txSeqOf)(t.slot, t.index), new Set((t.outputs ?? []).map((o) => o.outputIndex))]));
176
+ const stored = new Map();
177
+ for (const seqChunk of (0, collections_1.chunk)([...wanted.keys()], collections_1.IN_CHUNK)) {
178
+ const rows = (await tx.run(SELECT.from(cardano_1.TransactionOutputs).columns('txSeq', 'outputIndex').where({ txSeq: { in: seqChunk } })));
179
+ for (const r of rows ?? [])
180
+ stored.set(Number(r.txSeq), [...(stored.get(Number(r.txSeq)) ?? []), Number(r.outputIndex)]);
181
+ }
182
+ const touched = [];
183
+ for (const [seq, indices] of stored) {
184
+ const keep = wanted.get(seq);
185
+ const extra = indices.filter((i) => !keep.has(i));
186
+ if (!extra.length || [...keep].some((i) => !indices.includes(i)))
187
+ continue;
188
+ await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_txSeq: seq, output_outputIndex: { in: extra } }));
189
+ await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ txSeq: seq, outputIndex: { in: extra } }));
190
+ touched.push(seq);
191
+ }
192
+ return touched;
193
+ }
194
+ async function backfillTransactions(opts) {
195
+ const { fromSlot, toSlot, indexer } = opts;
196
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, rewritten: 0, skipped: 0 };
197
+ let started = false;
198
+ const intersection = await (0, certificate_backfill_1.streamCrawledBlocks)({ ...opts, errorType: TransactionBackfillError }, (_block, txs) => txs, async (tx, blocks) => {
199
+ const txs = blocks.flatMap((b) => b.payload);
200
+ progress.blocks += blocks.length;
201
+ progress.transactions += txs.length;
202
+ if (!txs.length)
203
+ return;
204
+ // the UTxO set rows answer too: they keep spent outputs, also those from before the crawl
205
+ await indexer.resolveInputs(tx, txs, { hashes: new Set(), rows: new Map(), assets: new Map() });
206
+ const seqs = txs.map((t) => (0, mappers_1.txSeqOf)(t.slot, t.index));
207
+ const stored = new Map();
208
+ const storedLovelace = new Map();
209
+ const storedCount = new Map();
210
+ const storedBySeq = new Map();
211
+ for (const seqChunk of (0, collections_1.chunk)(seqs, collections_1.IN_CHUNK)) {
212
+ const [rows, lovelace] = await Promise.all([
213
+ tx.run(SELECT.from(cardano_1.TransactionInputs).where({ txSeq: { in: seqChunk } })),
214
+ tx.run(SELECT.from(cardano_1.TransactionInputAssets).columns('input_txSeq', 'input_inputIndex', 'asset_quantity')
215
+ .where({ input_txSeq: { in: seqChunk }, unit: 'lovelace' })),
216
+ ]);
217
+ for (const r of rows ?? []) {
218
+ stored.set(key(r.txSeq, r.inputIndex), r);
219
+ storedCount.set(String(Number(r.txSeq)), (storedCount.get(String(Number(r.txSeq))) ?? 0) + 1);
220
+ storedBySeq.set(String(Number(r.txSeq)), [...(storedBySeq.get(String(Number(r.txSeq))) ?? []), r]);
221
+ }
222
+ for (const a of lovelace ?? [])
223
+ storedLovelace.set(key(a.input_txSeq, a.input_inputIndex), String(a.asset_quantity));
224
+ }
225
+ const fills = [];
226
+ const assetRows = [];
227
+ const reorders = [];
228
+ const rewritten = new Set();
229
+ for (const t of txs) {
230
+ const seq = (0, mappers_1.txSeqOf)(t.slot, t.index);
231
+ const inputs = t.inputs ?? [];
232
+ const rows = inputs.map((_, i) => stored.get(key(seq, i)));
233
+ const lines = (storedCount.get(String(seq)) ?? 0) === inputs.length && rows.every((r, i) => r && sameInput(r, inputs[i], storedLovelace.get(key(seq, i)) ?? null));
234
+ if (!lines) {
235
+ // after a phase-2 failure the ledger applied no regular input: rows a provider stored for them go
236
+ const all = [...(storedBySeq.get(String(seq)) ?? [])].sort((a, b) => Number(a.inputIndex) - Number(b.inputIndex));
237
+ const kept = t.spendsCollaterals ? all.filter((r) => r.isCollateral || r.isReference) : all;
238
+ const inPlace = kept.length === inputs.length &&
239
+ kept.every((r, i) => sameInput(r, inputs[i], storedLovelace.get(key(seq, Number(r.inputIndex))) ?? null));
240
+ const ordered = inPlace ? kept : reorderByOutpoint(kept, inputs);
241
+ if (ordered) {
242
+ reorders.push({ seq, rows: ordered, inputs });
243
+ rewritten.add(seq);
244
+ continue;
245
+ }
246
+ progress.skipped++;
247
+ logger.debug(`Transaction ${t.hash}: stored inputs differ from the stream — left as it is`);
248
+ continue;
249
+ }
250
+ for (let i = 0; i < inputs.length; i++) {
251
+ const set = missingFields(rows[i], inputs[i]);
252
+ if (!Object.keys(set).length)
253
+ continue;
254
+ fills.push({ txSeq: seq, inputIndex: i, set });
255
+ if (set.address_address)
256
+ assetRows.push(...(0, mappers_1.mapTransactionInputAssets)(seq, inputs).filter((a) => a.input_inputIndex === i));
257
+ }
258
+ }
259
+ await writeInputFills(tx, fills);
260
+ progress.inputs += fills.length;
261
+ if (assetRows.length)
262
+ await tx.run(UPSERT.into(cardano_1.TransactionInputAssets).entries(assetRows));
263
+ for (const r of reorders)
264
+ await rewriteInOrder(tx, r.seq, r.rows, r.inputs);
265
+ for (const seq of await dropUnappliedOutputs(tx, txs))
266
+ rewritten.add(seq);
267
+ progress.rewritten += rewritten.size;
268
+ const redeemerRows = txs.flatMap((t) => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
269
+ progress.redeemers += redeemerRows.length;
270
+ if (redeemerRows.length)
271
+ await tx.run(UPSERT.into(cardano_1.TransactionRedeemers).entries(redeemerRows));
272
+ }, (atSlot) => {
273
+ started = true;
274
+ progress.atSlot = atSlot;
275
+ opts.onProgress?.({ ...progress });
276
+ });
277
+ if (!started)
278
+ progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
279
+ logger.info(`Transaction backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.inputs} inputs, ` +
280
+ `${progress.redeemers} redeemers, ${progress.rewritten} transactions rewritten, ${progress.skipped} skipped`);
281
+ return { ...progress, fromSlot, toSlot, intersection };
282
+ }
283
+ //# sourceMappingURL=transaction-backfill.js.map
@@ -66,4 +66,13 @@ export declare function aggregateStatements(): string[];
66
66
  * written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
67
67
  */
68
68
  export declare function importUtxoSet(opts: UtxoSetImportOptions): Promise<UtxoSetImportResult>;
69
+ /**
70
+ * Rebuild only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an
71
+ * earlier import left at the stored anchor, e.g. after the aggregate phase failed. Nothing may have
72
+ * been applied since the anchor; a cursor past it is set back to the anchor, and the blocks after
73
+ * it are crawled again (idempotent writes) so the set follows them.
74
+ */
75
+ export declare function rebuildUtxoSetAggregates(opts: {
76
+ indexer: CardanoIndexer;
77
+ }): Promise<UtxoSetImportResult>;
69
78
  //# sourceMappingURL=utxo-set-import.d.ts.map
@@ -9,6 +9,7 @@ exports.parseCliUtxoEntry = parseCliUtxoEntry;
9
9
  exports.readUtxoSetFile = readUtxoSetFile;
10
10
  exports.aggregateStatements = aggregateStatements;
11
11
  exports.importUtxoSet = importUtxoSet;
12
+ exports.rebuildUtxoSetAggregates = rebuildUtxoSetAggregates;
12
13
  const cds_1 = __importDefault(require("@sap/cds"));
13
14
  const node_fs_1 = require("node:fs");
14
15
  const promises_1 = require("node:fs/promises");
@@ -17,7 +18,7 @@ const ledger_state_1 = require("../ledger-state");
17
18
  const sync_state_1 = require("./sync-state");
18
19
  const cardano_1 = require("#cds-models/odatano/cardano");
19
20
  const collections_1 = require("../../utils/collections");
20
- const { UPSERT, DELETE } = cds_1.default.ql;
21
+ const { UPSERT, DELETE, SELECT } = cds_1.default.ql;
21
22
  const logger = cds_1.default.log('LedgerState');
22
23
  /**
23
24
  * One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
@@ -144,11 +145,11 @@ function aggregateStatements() {
144
145
  `INSERT INTO ${T.addresses} (address, stakeAddress, addressType, isScript, totalLovelace, utxoCount, firstSeenSlot, lastActiveSlot) ` +
145
146
  `SELECT address, MIN(stakeAddress), MIN(addressType), ` +
146
147
  `CASE WHEN MAX(CASE WHEN isScript THEN 1 ELSE 0 END) = 1 THEN TRUE ELSE FALSE END, ` +
147
- `SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} GROUP BY address`,
148
+ `SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} WHERE spentTxHash IS NULL GROUP BY address`,
148
149
  `INSERT INTO ${T.addressAssets} (address_address, unit, asset_quantity, asset_policyId, asset_assetNameHex, asset_assetName) ` +
149
150
  `SELECT u.address, a.unit, SUM(a.asset_quantity), MIN(a.asset_policyId), MIN(a.asset_assetNameHex), MIN(a.asset_assetName) ` +
150
151
  `FROM ${T.utxoAssets} a JOIN ${T.utxos} u ON a.utxo_txHash = u.txHash AND a.utxo_outputIndex = u.outputIndex ` +
151
- `GROUP BY u.address, a.unit`,
152
+ `WHERE u.spentTxHash IS NULL GROUP BY u.address, a.unit`,
152
153
  `INSERT INTO ${T.accounts} (stakeAddress, controlledAmount, addressCount, utxoCount, lastActiveSlot) ` +
153
154
  `SELECT stakeAddress, SUM(totalLovelace), COUNT(*), SUM(utxoCount), NULL FROM ${T.addresses} ` +
154
155
  `WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
@@ -172,32 +173,9 @@ async function importUtxoSet(opts) {
172
173
  }
173
174
  if (source === 'file' && !opts.filePath)
174
175
  throw new UtxoSetImportError('source "file" needs filePath.');
175
- // Cluster-wide exclusion: hold the cursor lease for the whole import. A crawler start on
176
- // any instance (resumeCrawler, standby) and a second import are refused while it is held;
177
- // renewed on a heartbeat, released in `finally`.
178
- const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
179
- const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
180
- if (!acquired)
181
- throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
182
- let leaseLost = false;
183
- const heartbeat = setInterval(() => {
184
- cds_1.default.tx((tx) => (0, sync_state_1.renewImportLease)(tx, leaseOwner))
185
- .then((ok) => { if (!ok)
186
- leaseLost = true; })
187
- .catch(() => { leaseLost = true; });
188
- }, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
189
- heartbeat.unref();
190
- /**
191
- * Every write re-takes the lease INSIDE its transaction (conditional UPDATE + read-back), so
192
- * a successor that took the lease between two batches fails this transaction before commit.
193
- */
194
- const writeTx = (fn) => cds_1.default.tx(async (tx) => {
195
- if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
196
- throw new UtxoSetLeaseLostError();
197
- return fn(tx);
198
- });
199
- opts.indexer.setUtxoAnchor(null);
200
- try {
176
+ return withImportLease(async (lease) => {
177
+ const { writeTx } = lease;
178
+ opts.indexer.setUtxoAnchor(null);
201
179
  await writeTx(async (tx) => {
202
180
  await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null });
203
181
  await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets));
@@ -235,18 +213,7 @@ async function importUtxoSet(opts) {
235
213
  await flush();
236
214
  }
237
215
  await flush();
238
- // Aggregates + activation in ONE lease-checked transaction: the set can never be
239
- // `active` with sums a successor's import has meanwhile truncated.
240
- const importedAt = new Date().toISOString();
241
- await writeTx(async (tx) => {
242
- for (const sql of aggregateStatements())
243
- await tx.run(sql);
244
- await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
245
- });
246
- opts.indexer.setUtxoAnchor(anchor);
247
- // The aggregation leaves paymentCredential empty; filled in the background.
248
- opts.indexer.resetPaymentCredentials();
249
- void opts.indexer.paymentCredentialsReady();
216
+ await activateWithAggregates(lease, opts.indexer, anchor);
250
217
  logger.info(`UTxO set imported: ${imported} entries at anchor ${anchor.slot}/${anchor.hash} (source=${source})`);
251
218
  return { utxos: imported, anchor };
252
219
  }
@@ -255,18 +222,142 @@ async function importUtxoSet(opts) {
255
222
  logger.error(`UTxO set import failed after ${imported} entries: ${message}`);
256
223
  // Only the lease holder may write the failure state; after a takeover the row is the
257
224
  // successor's and the truncated tables are its problem to fill.
258
- if (!(err instanceof UtxoSetLeaseLostError)) {
259
- await cds_1.default.tx(async (tx) => {
260
- if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
261
- await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
262
- }).catch(() => undefined);
263
- }
225
+ if (!(err instanceof UtxoSetLeaseLostError))
226
+ await lease.markInvalid(message);
264
227
  throw err;
265
228
  }
229
+ });
230
+ }
231
+ /**
232
+ * Hold the cursor lease for the whole run: a crawler start on any instance and a second import
233
+ * are refused while it is held; renewed on a heartbeat (one at a time), released at the end.
234
+ */
235
+ async function withImportLease(run) {
236
+ const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
237
+ const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
238
+ if (!acquired)
239
+ throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
240
+ let leaseLost = false;
241
+ let renewing = false;
242
+ const heartbeat = setInterval(() => {
243
+ // A renewal still waiting keeps its connection; a second one would only take another from the pool
244
+ if (renewing)
245
+ return;
246
+ renewing = true;
247
+ cds_1.default.tx(async (tx) => { if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
248
+ leaseLost = true; })
249
+ .catch(() => { leaseLost = true; })
250
+ .finally(() => { renewing = false; });
251
+ }, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
252
+ heartbeat.unref();
253
+ const lease = {
254
+ writeTx: (fn) => cds_1.default.tx(async (tx) => {
255
+ if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
256
+ throw new UtxoSetLeaseLostError();
257
+ return fn(tx);
258
+ }),
259
+ writeTxLeaseLast: (fn) => cds_1.default.tx(async (tx) => {
260
+ const result = await fn(tx);
261
+ if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
262
+ throw new UtxoSetLeaseLostError();
263
+ return result;
264
+ }),
265
+ markInvalid: (message) => cds_1.default.tx(async (tx) => {
266
+ if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
267
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
268
+ }).then(() => undefined, () => undefined),
269
+ };
270
+ try {
271
+ return await run(lease);
266
272
  }
267
273
  finally {
268
274
  clearInterval(heartbeat);
269
275
  await cds_1.default.tx((tx) => (0, sync_state_1.releaseImportLease)(tx, leaseOwner)).catch(() => undefined);
270
276
  }
271
277
  }
278
+ /** A bigger sort/hash budget for the GROUP BY over millions of rows (PostgreSQL only). */
279
+ const AGGREGATE_WORK_MEM = '256MB';
280
+ /**
281
+ * Aggregates + activation in ONE transaction, so the set is never `active` with sums a successor's
282
+ * import has meanwhile truncated. `prepare` runs first; `finish` and the activation run last,
283
+ * together with the lease check, so the cursor row is not locked during the aggregation.
284
+ */
285
+ async function activateWithAggregates(lease, indexer, anchor, hooks = {}) {
286
+ const importedAt = new Date().toISOString();
287
+ await lease.writeTxLeaseLast(async (tx) => {
288
+ const raw = tx;
289
+ if (cds_1.default.db?.kind === 'postgres') {
290
+ await raw.run(`SET LOCAL work_mem = '${AGGREGATE_WORK_MEM}'`);
291
+ // The planner overestimates the join and walks the address index row by row; hash join + hash aggregate read each table once.
292
+ await raw.run('SET LOCAL enable_nestloop = off');
293
+ }
294
+ await hooks.prepare?.(tx);
295
+ for (const sql of aggregateStatements())
296
+ await raw.run(sql);
297
+ await hooks.finish?.(tx);
298
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
299
+ });
300
+ indexer.setUtxoAnchor(anchor);
301
+ // The aggregation leaves paymentCredential empty; filled in the background.
302
+ indexer.resetPaymentCredentials();
303
+ void indexer.paymentCredentialsReady();
304
+ }
305
+ /**
306
+ * Rebuild only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an
307
+ * earlier import left at the stored anchor, e.g. after the aggregate phase failed. Nothing may have
308
+ * been applied since the anchor; a cursor past it is set back to the anchor, and the blocks after
309
+ * it are crawled again (idempotent writes) so the set follows them.
310
+ */
311
+ async function rebuildUtxoSetAggregates(opts) {
312
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
313
+ if (!cursor)
314
+ throw new UtxoSetImportError('No crawler cursor yet.');
315
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
316
+ throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
317
+ const { anchorSlot, anchorHash, appliedSlot, status } = cursor.utxoSet;
318
+ if (anchorSlot == null || !anchorHash)
319
+ throw new UtxoSetImportError('No imported UTxO set to rebuild the sums from — run importUtxoSet first.');
320
+ if (status === 'importing')
321
+ throw new UtxoSetImportError('The import is still loading rows (status "importing").');
322
+ if (appliedSlot != null) {
323
+ throw new UtxoSetImportError(`Blocks up to slot ${appliedSlot} were already applied to the set — its rows are past the anchor; import again.`);
324
+ }
325
+ const anchor = { slot: anchorSlot, hash: anchorHash };
326
+ const rows = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.LedgerUTxOs).columns('count(*) as n')));
327
+ const utxos = Number(rows?.n ?? 0);
328
+ if (utxos === 0)
329
+ throw new UtxoSetImportError('LedgerUTxOs is empty — run importUtxoSet first.');
330
+ let rewindTo = null;
331
+ if (cursor.lastSlot > anchor.slot) {
332
+ const block = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Blocks).columns('height').where({ hash: anchor.hash })));
333
+ if (!block)
334
+ throw new UtxoSetImportError(`Cursor is past the anchor and the anchor block ${anchor.hash} is not stored — cannot set the cursor back.`);
335
+ rewindTo = { slot: anchor.slot, hash: anchor.hash, height: Number(block.height ?? 0) };
336
+ }
337
+ return withImportLease(async (lease) => {
338
+ opts.indexer.setUtxoAnchor(null);
339
+ // The previous failure no longer describes the set; a new one replaces it below
340
+ await lease.writeTx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { error: null }));
341
+ try {
342
+ await activateWithAggregates(lease, opts.indexer, anchor, {
343
+ prepare: async (tx) => {
344
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
345
+ await tx.run(DELETE.from(cardano_1.LedgerAddresses));
346
+ await tx.run(DELETE.from(cardano_1.LedgerAccounts));
347
+ },
348
+ finish: rewindTo ? (tx) => (0, sync_state_1.resetCursorTo)(tx, rewindTo) : undefined,
349
+ });
350
+ }
351
+ catch (err) {
352
+ const message = err instanceof Error ? err.message : String(err);
353
+ logger.error(`UTxO set aggregate rebuild failed: ${message}`);
354
+ if (!(err instanceof UtxoSetLeaseLostError))
355
+ await lease.markInvalid(message);
356
+ throw err;
357
+ }
358
+ logger.info(`UTxO set sums rebuilt from ${utxos} rows at anchor ${anchor.slot}/${anchor.hash}` +
359
+ (rewindTo ? ` (cursor set back from slot ${cursor.lastSlot})` : ''));
360
+ return { utxos, anchor };
361
+ });
362
+ }
272
363
  //# sourceMappingURL=utxo-set-import.js.map
@@ -58,12 +58,27 @@ export declare function buildLedgerUtxoRows(o: LedgerOutputLike, createdSlot: nu
58
58
  row: LedgerUtxoRow;
59
59
  assets: LedgerUtxoAssetRow[];
60
60
  };
61
+ /** `LedgerUTxOs` rows (+ asset rows) of a set of source transactions, keyed `txHash#outputIndex`. */
62
+ export interface LedgerLookup {
63
+ /** Source transaction hashes this lookup covers (found or not). */
64
+ hashes: Set<string>;
65
+ rows: Map<string, LedgerUtxoRow>;
66
+ assets: Map<string, LedgerUtxoAssetRow[]>;
67
+ }
68
+ /**
69
+ * Read the ledger rows of the given source transactions. Asset rows are read only for
70
+ * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
71
+ */
72
+ export declare function readLedgerOutputs(tx: CapTransaction, txHashes: Iterable<string>, into?: LedgerLookup): Promise<LedgerLookup>;
73
+ /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
74
+ export declare function ledgerRowAmount(row: LedgerUtxoRow, assets: LedgerUtxoAssetRow[] | undefined): Amount[];
61
75
  /**
62
76
  * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
77
+ * `lookup` may carry rows the caller already read for this block (input resolution).
63
78
  * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
64
79
  * block transaction rolls back as a whole.
65
80
  */
66
- export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[]): Promise<LedgerApplyResult>;
81
+ export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[], lookup?: LedgerLookup): Promise<LedgerApplyResult>;
67
82
  /**
68
83
  * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
69
84
  * they spent, then recount every address either side touched from the open rows.
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.buildLedgerUtxoRows = buildLedgerUtxoRows;
7
+ exports.readLedgerOutputs = readLedgerOutputs;
8
+ exports.ledgerRowAmount = ledgerRowAmount;
7
9
  exports.applyBlockToLedger = applyBlockToLedger;
8
10
  exports.undoLedgerForTransactions = undoLedgerForTransactions;
9
11
  exports.recountLedgerAddresses = recountLedgerAddresses;
@@ -93,12 +95,46 @@ function applyDelta(d, row, assets, sign) {
93
95
  d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
94
96
  }
95
97
  }
98
+ /**
99
+ * Read the ledger rows of the given source transactions. Asset rows are read only for
100
+ * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
101
+ */
102
+ async function readLedgerOutputs(tx, txHashes, into) {
103
+ const lookup = into ?? { hashes: new Set(), rows: new Map(), assets: new Map() };
104
+ const todo = [...new Set(txHashes)].filter(h => !lookup.hashes.has(h));
105
+ for (const hashChunk of (0, collections_1.chunk)(todo, collections_1.IN_CHUNK)) {
106
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
107
+ for (const r of rows ?? [])
108
+ lookup.rows.set(outpoint(r.txHash, num(r.outputIndex)), r);
109
+ const withAssets = [...new Set((rows ?? []).filter(r => r.hasAssets).map(r => r.txHash))];
110
+ if (withAssets.length) {
111
+ const assets = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: withAssets } }));
112
+ for (const a of assets ?? []) {
113
+ const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
114
+ const list = lookup.assets.get(k) ?? [];
115
+ list.push(a);
116
+ lookup.assets.set(k, list);
117
+ }
118
+ }
119
+ for (const h of hashChunk)
120
+ lookup.hashes.add(h);
121
+ }
122
+ return lookup;
123
+ }
124
+ /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
125
+ function ledgerRowAmount(row, assets) {
126
+ return [
127
+ { unit: 'lovelace', quantity: String(row.lovelace ?? '0') },
128
+ ...(assets ?? []).map(a => ({ unit: a.unit, quantity: String(a.asset_quantity) })),
129
+ ];
130
+ }
96
131
  /**
97
132
  * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
133
+ * `lookup` may carry rows the caller already read for this block (input resolution).
98
134
  * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
99
135
  * block transaction rolls back as a whole.
100
136
  */
101
- async function applyBlockToLedger(tx, block, txs) {
137
+ async function applyBlockToLedger(tx, block, txs, lookup) {
102
138
  const slot = block.slot ?? 0;
103
139
  // 1) everything this block produces
104
140
  const created = new Map();
@@ -125,23 +161,7 @@ async function applyBlockToLedger(tx, block, txs) {
125
161
  }
126
162
  }
127
163
  }
128
- const dbRows = new Map();
129
- const dbAssets = new Map();
130
- const sourceHashes = [...new Set(lookups.map(l => l.txHash))];
131
- for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
132
- const [rows, assets] = await Promise.all([
133
- tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } })),
134
- tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } })),
135
- ]);
136
- for (const r of rows ?? [])
137
- dbRows.set(outpoint(r.txHash, num(r.outputIndex)), r);
138
- for (const a of assets ?? []) {
139
- const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
140
- const list = dbAssets.get(k) ?? [];
141
- list.push(a);
142
- dbAssets.set(k, list);
143
- }
144
- }
164
+ const { rows: dbRows, assets: dbAssets } = await readLedgerOutputs(tx, lookups.map(l => l.txHash), lookup);
145
165
  const spentRows = [];
146
166
  let missing = 0;
147
167
  for (const l of lookups) {