@odatano/core 2.0.0-rc.10 → 2.0.0-rc.12

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 (32) hide show
  1. package/@cds-models/CardanoODataService/index.d.ts +54 -0
  2. package/@cds-models/CardanoODataService/index.js +6 -0
  3. package/@cds-models/odatano/cardano/index.d.ts +54 -0
  4. package/@cds-models/odatano/cardano/index.js +6 -0
  5. package/db/schema.cds +1844 -1738
  6. package/package.json +1 -1
  7. package/srv/blockchain/backends/blockfrost-backend.js +7 -2
  8. package/srv/blockchain/backends/cardano-backend.d.ts +22 -0
  9. package/srv/blockchain/backends/cardano-backend.js +9 -0
  10. package/srv/blockchain/backends/koios-backend.d.ts +34 -2
  11. package/srv/blockchain/backends/koios-backend.js +133 -39
  12. package/srv/blockchain/backends/ogmios-backend.d.ts +6 -1
  13. package/srv/blockchain/backends/ogmios-backend.js +27 -2
  14. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
  15. package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
  16. package/srv/blockchain/cardano-client.d.ts +8 -1
  17. package/srv/blockchain/cardano-client.js +14 -0
  18. package/srv/blockchain/cardano-indexer.d.ts +127 -0
  19. package/srv/blockchain/cardano-indexer.js +345 -3
  20. package/srv/blockchain/crawler/crawler.d.ts +88 -0
  21. package/srv/blockchain/crawler/crawler.js +180 -2
  22. package/srv/cardano-service.cds +10 -0
  23. package/srv/server.js +26 -1
  24. package/srv/utils/const.d.ts +1 -1
  25. package/srv/utils/const.js +1 -1
  26. package/srv/utils/errors.d.ts +18 -0
  27. package/srv/utils/errors.js +24 -1
  28. package/srv/utils/mappers.d.ts +54 -1
  29. package/srv/utils/mappers.js +111 -0
  30. package/srv/utils/types.d.ts +27 -0
  31. package/srv/utils/validators.d.ts +1 -1
  32. package/srv/utils/validators.js +2 -2
@@ -0,0 +1,181 @@
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.widenBigIntegers = widenBigIntegers;
7
+ exports.installOgmiosFrameGuard = installOgmiosFrameGuard;
8
+ exports.resetOgmiosFrameGuardForTests = resetOgmiosFrameGuardForTests;
9
+ /**
10
+ * Guard against Ogmios chain-sync frames that the client's JSON parser cannot handle.
11
+ *
12
+ * `@cardano-ogmios/client` parses every WebSocket frame with `safeJSON.parse`, which is
13
+ * `sanitize(JSONBig.parse(raw))`. Both halves recurse once per nesting level: the
14
+ * `@cardanosolutions/json-bigint` parser is Crockford's recursive descent, and `sanitize`
15
+ * walks the parsed tree recursively. A native script nests one JSON object per clause, and
16
+ * nested clauses cost only a few bytes each in CBOR — so an ordinary-looking block can
17
+ * expand into JSON that is ten thousand levels deep and exhaust the V8 stack.
18
+ *
19
+ * That is not a theoretical shape. Preprod block 5183974 carries a native script nested
20
+ * 10 774 levels deep (`{"clause":"all","from":[ … ]}` down to a single signature clause).
21
+ * The block is 43 kB on chain and 205 kB as a chain-sync frame.
22
+ *
23
+ * The crash is fatal rather than merely annoying, because of where the parse happens
24
+ * (`ChainSynchronization/Client.js`):
25
+ *
26
+ * socket.on('message', async (message) => {
27
+ * await responseHandler(util_1.safeJSON.parse(message));
28
+ * });
29
+ *
30
+ * `safeJSON.parse` throws synchronously inside an `async` handler that nobody awaits, so
31
+ * the `RangeError` surfaces as an unhandled rejection and Node takes the process down. The
32
+ * crawler's poison-block latch cannot help: it guards the persist path, and the server is
33
+ * gone long before a block reaches it. Docker restarts, the crawler resumes at the same
34
+ * block, and the loop repeats — 53 restarts in seven minutes on the hosted box.
35
+ *
36
+ * This guard wraps `safeJSON.parse` (a public export of the client package) so that the
37
+ * fast path is untouched and only an overflowing frame takes the recovery route:
38
+ *
39
+ * 1. the original parser, so every ordinary frame keeps its exact BigInt handling;
40
+ * 2. on `RangeError`, `widenBigIntegers()` rewrites integer literals that a double cannot
41
+ * hold into JSON strings, then plain `JSON.parse` — V8's parser is iterative, so depth
42
+ * is no longer a limit. `sanitize` is skipped, because it would overflow on the very
43
+ * same structure;
44
+ * 3. if even that fails, the frame is reported to the caller and a sentinel is returned.
45
+ * The guard never throws, because throwing here is what kills the process.
46
+ *
47
+ * Measured against the real frame (node 22, 205 728 bytes, depth 10 774): json-bigint and
48
+ * `JSON.parse` with a reviver both overflow — a reviver walk is recursive too — while plain
49
+ * `JSON.parse` completes in 17 ms.
50
+ *
51
+ * Upstream: a recursive parser on untrusted chain data is a denial-of-service against every
52
+ * consumer of the client, mainnet included. This guard is a local mitigation, not the cure.
53
+ */
54
+ const client_1 = require("@cardano-ogmios/client");
55
+ const cds_1 = __importDefault(require("@sap/cds"));
56
+ const logger = cds_1.default.log('OgmiosFrameGuard');
57
+ /**
58
+ * Integers outside the safe double range, written into JSON strings so that plain
59
+ * `JSON.parse` cannot round them. Runs as one linear pass with an explicit in-string state,
60
+ * never recursing, so it is immune to the nesting that sent us here in the first place.
61
+ *
62
+ * Only numbers in value position are touched: digits inside strings (hashes, CBOR, asset
63
+ * names) are skipped, and so are floats and exponents, which are doubles by nature and have
64
+ * no exact integer to preserve.
65
+ */
66
+ function widenBigIntegers(text) {
67
+ const SAFE_DIGITS = String(Number.MAX_SAFE_INTEGER).length; // 16
68
+ let out = '';
69
+ let last = 0;
70
+ let inString = false;
71
+ let escaped = false;
72
+ for (let i = 0; i < text.length; i++) {
73
+ const c = text[i];
74
+ if (inString) {
75
+ if (escaped)
76
+ escaped = false;
77
+ else if (c === '\\')
78
+ escaped = true;
79
+ else if (c === '"')
80
+ inString = false;
81
+ continue;
82
+ }
83
+ if (c === '"') {
84
+ inString = true;
85
+ continue;
86
+ }
87
+ // a number literal starts here only after a structural character
88
+ if (c !== '-' && (c < '0' || c > '9'))
89
+ continue;
90
+ const prev = text[i - 1];
91
+ if (prev !== ':' && prev !== ',' && prev !== '[' && prev !== ' ' && prev !== '\n' && prev !== '\t' && prev !== '\r')
92
+ continue;
93
+ let j = i;
94
+ if (text[j] === '-')
95
+ j++;
96
+ const digitsFrom = j;
97
+ while (j < text.length && text[j] >= '0' && text[j] <= '9')
98
+ j++;
99
+ const digits = j - digitsFrom;
100
+ if (digits === 0)
101
+ continue;
102
+ // a fraction or exponent means it was never an exact integer — leave it alone
103
+ const after = text[j];
104
+ if (after === '.' || after === 'e' || after === 'E') {
105
+ i = j;
106
+ continue;
107
+ }
108
+ if (digits >= SAFE_DIGITS) {
109
+ const literal = text.slice(i, j);
110
+ if (!Number.isSafeInteger(Number(literal))) {
111
+ out += text.slice(last, i) + '"' + literal + '"';
112
+ last = j;
113
+ }
114
+ }
115
+ i = j - 1;
116
+ }
117
+ return last === 0 ? text : out + text.slice(last);
118
+ }
119
+ /**
120
+ * Block header fields out of a frame we could not parse. They sit near the front of a
121
+ * chain-sync response and at shallow depth, so a narrow match finds them even when the
122
+ * body is unusable — enough to name the offending block in a log line and in `lastError`.
123
+ */
124
+ function readBlockHeader(text) {
125
+ const head = text.slice(0, 4096);
126
+ const id = /"id"\s*:\s*"([0-9a-fA-F]{64})"/.exec(head);
127
+ const height = /"height"\s*:\s*(\d{1,15})/.exec(head);
128
+ return { height: height ? Number(height[1]) : null, id: id ? id[1] : null };
129
+ }
130
+ let installed = false;
131
+ /**
132
+ * Wrap `safeJSON.parse` once per process. Idempotent: a second call only replaces the
133
+ * report callback, so reopening the chain-sync stream never stacks wrappers.
134
+ *
135
+ * @param onUnparseableFrame called when a frame survives neither parser. The guard returns
136
+ * a sentinel instead of throwing, so the caller owns what happens next — the stream
137
+ * itself stalls, because the client drops anything that is not a nextBlock response.
138
+ */
139
+ function installOgmiosFrameGuard(onUnparseableFrame) {
140
+ report = onUnparseableFrame;
141
+ if (installed)
142
+ return;
143
+ const original = client_1.safeJSON.parse.bind(client_1.safeJSON);
144
+ installed = true; // only once the original is safely in hand
145
+ client_1.safeJSON.parse = (raw) => {
146
+ try {
147
+ return original(raw);
148
+ }
149
+ catch (err) {
150
+ if (!(err instanceof RangeError))
151
+ throw err; // a genuine syntax error stays a syntax error
152
+ const text = String(raw);
153
+ const where = readBlockHeader(text);
154
+ try {
155
+ const parsed = JSON.parse(widenBigIntegers(text));
156
+ logger.warn(`chain-sync frame too deeply nested for the client's parser (block ${where.height ?? '?'} ` +
157
+ `${where.id ?? ''}, ${text.length} bytes) — parsed without it. Integers beyond 2^53 are ` +
158
+ `strings on this path; the chain-sync mapper stringifies them anyway.`);
159
+ return parsed;
160
+ }
161
+ catch (fallbackErr) {
162
+ const reason = fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr);
163
+ logger.error(`chain-sync frame unparseable (block ${where.height ?? '?'} ${where.id ?? ''}, ` +
164
+ `${text.length} bytes): ${reason}`);
165
+ report({ ...where, reason, bytes: text.length });
166
+ // Never throw: this runs in an async socket handler nobody awaits, so a throw
167
+ // becomes an unhandled rejection and ends the process.
168
+ return {};
169
+ }
170
+ }
171
+ };
172
+ }
173
+ let report = () => { };
174
+ /** Tests only — drop the wrapper so each case starts from the untouched client. */
175
+ function resetOgmiosFrameGuardForTests(originalParse) {
176
+ if (originalParse)
177
+ client_1.safeJSON.parse = originalParse;
178
+ installed = false;
179
+ report = () => { };
180
+ }
181
+ //# sourceMappingURL=ogmios-frame-guard.js.map
@@ -1,4 +1,4 @@
1
- import { ChainSyncBackend, PaginatingBackend } from './backends/cardano-backend';
1
+ import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend } from './backends/cardano-backend';
2
2
  import { type CircuitBreakerConfig } from './circuit-breaker';
3
3
  import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
4
4
  export type Network = 'mainnet' | 'preview' | 'preprod';
@@ -245,6 +245,13 @@ export declare class CardanoClient {
245
245
  * uninitialized backend would wedge it.
246
246
  */
247
247
  getChainSyncBackend(): ChainSyncBackend | null;
248
+ /**
249
+ * Get a backend that can enumerate the full pool/DRep set (Koios), or null. Used by the
250
+ * crawler's epoch-boundary snapshots; without one they stay off rather than degrade into
251
+ * thousands of single requests (see EnumeratingBackend).
252
+ * Skips backends whose init() failed (see getChainSyncBackend).
253
+ */
254
+ getEnumeratingBackend(): EnumeratingBackend | null;
248
255
  /**
249
256
  * Get a backend that can be walked forward by pagination (Blockfrost/Koios), or null.
250
257
  * The crawler's fallback source when no Ogmios chain-sync is available.
@@ -549,6 +549,20 @@ class CardanoClient {
549
549
  }
550
550
  return null;
551
551
  }
552
+ /**
553
+ * Get a backend that can enumerate the full pool/DRep set (Koios), or null. Used by the
554
+ * crawler's epoch-boundary snapshots; without one they stay off rather than degrade into
555
+ * thousands of single requests (see EnumeratingBackend).
556
+ * Skips backends whose init() failed (see getChainSyncBackend).
557
+ */
558
+ getEnumeratingBackend() {
559
+ const candidates = [...this.historicalBackends, this.liveBackend];
560
+ for (const b of candidates) {
561
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isEnumeratingBackend)(b))
562
+ return b;
563
+ }
564
+ return null;
565
+ }
552
566
  /**
553
567
  * Get a backend that can be walked forward by pagination (Blockfrost/Koios), or null.
554
568
  * The crawler's fallback source when no Ogmios chain-sync is available.
@@ -37,6 +37,44 @@ export declare class CardanoIndexer {
37
37
  private crawlEpochCache;
38
38
  private crawlEpochCurrent;
39
39
  private crawlEpochPrevious;
40
+ /**
41
+ * Analytics coverage of the crawl path (v2.0, FR "crawler coverage for analytics"). The
42
+ * defaults mirror the crawler config defaults, so an indexer the crawler never configured
43
+ * (unit tests, the lazy-only path) behaves exactly like a configured one.
44
+ */
45
+ private crawlAssetHistory;
46
+ private crawlAssetCatalogue;
47
+ /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
48
+ private static readonly ASSET_MEMO_CAP;
49
+ private assetMemo;
50
+ /**
51
+ * Background registry enrichment (`assetCatalogue: 'enrich'`). Bare rows are queued here and
52
+ * resolved at a fixed rate OUTSIDE the block transaction, so a mint storm can slow the queue
53
+ * but never the crawl. Above the cap the oldest entries are dropped: the unit keeps its bare
54
+ * row and is still enriched by the lazy path on its first API read.
55
+ */
56
+ private static readonly ENRICH_QUEUE_CAP;
57
+ private enrichQueue;
58
+ private enrichTimer;
59
+ private enrichRate;
60
+ /**
61
+ * Adopt the crawler's coverage settings. Called once from the crawler's start path; the
62
+ * lazy request path never touches these.
63
+ */
64
+ configureCrawlCoverage(coverage: {
65
+ assetHistory: boolean;
66
+ assetCatalogue: 'off' | 'bare' | 'enrich';
67
+ assetEnrichRate?: number;
68
+ }): void;
69
+ /**
70
+ * Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
71
+ * its own transaction. The timer is unref'd, so it never holds the process open, and a failing
72
+ * unit (404 from every backend, provider outage) is dropped rather than retried — its bare row
73
+ * stays and the lazy path can still enrich it later.
74
+ */
75
+ private startAssetEnrichment;
76
+ /** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
77
+ stopAssetEnrichment(): void;
40
78
  /**
41
79
  * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block
42
80
  * write transaction — the backend round-trip must never run while the DB write
@@ -187,6 +225,95 @@ export declare class CardanoIndexer {
187
225
  * DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
188
226
  */
189
227
  private resolveInputs;
228
+ /**
229
+ * Settle the fee of phase-2-invalid transactions and the block total that follows from it.
230
+ *
231
+ * A failed script phase does not pay the fee declared in the body: the ledger consumes the
232
+ * collateral instead, i.e. the collateral inputs minus the collateral return. The Ogmios
233
+ * mapper already uses the body's `total_collateral` when it declares one; what is left are
234
+ * the transactions without it, and those need the collateral inputs that resolveInputs()
235
+ * has just filled in.
236
+ *
237
+ * A collateral input the crawler cannot resolve — spent from an output produced before the
238
+ * crawl start, so no row exists locally — would make the sum silently too small. The
239
+ * declared fee is kept in that case and the transaction is logged: a value that is wrong in
240
+ * a known, named way beats one that looks derived but is short by an unknown amount.
241
+ *
242
+ * Applies to every backend that reports phase-2 validity — the chain-sync path (`spends`)
243
+ * 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
245
+ * untouched.
246
+ */
247
+ private applyCollateralFees;
248
+ /**
249
+ * Mint/burn rows for a whole block, as a by-product of data the crawler already holds —
250
+ * no provider round-trip (v2.1 analytics coverage).
251
+ *
252
+ * Two sources, in this order:
253
+ * 1. `t.mint` — the ledger's own mint field, reported natively by Ogmios (`mint`) and
254
+ * Koios (`assets_minted`). Authoritative: it needs no resolved inputs and states the
255
+ * net per unit directly.
256
+ * 2. Σ outputs − Σ inputs per unit, for backends without that field (Blockfrost), whose
257
+ * inputs all carry their full `amount` so the delta is exact.
258
+ *
259
+ * The delta path excludes what the ledger does not consume or produce: reference inputs are
260
+ * read, never spent, and collateral only moves when the script phase failed — which applies
261
+ * no mint at all, so those transactions are skipped outright. Both exclusions rest on
262
+ * `isReference` / `isCollateral` / `spendsCollaterals`, which every backend that can reach
263
+ * this branch has to set — Blockfrost does since rc.12. A transaction with even one
264
+ * unresolvable consumed input (an output created before the crawl start, so no local row) is
265
+ * skipped and logged rather than reported with a delta that is short by an unknown amount —
266
+ * the same discipline as applyCollateralFees() above.
267
+ */
268
+ private buildAssetHistoryRows;
269
+ /**
270
+ * 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").
272
+ *
273
+ * `Assets` is temporal, so its key is `(validFrom, unit)` and a row is a slice. The bare row
274
+ * therefore carries the fixed epoch-zero stamp (`BARE_ASSET_STAMP`), which no wall-clock slice
275
+ * from mapAsset() can ever alias: the write cannot overwrite enriched registry data, and it
276
+ * stays a single idempotent row per unit. That makes UPSERT safe — and safe is what it has to
277
+ * be, because this runs inside the crawler's block transaction, where a unique-key violation
278
+ * from a lazy-path write racing us would take the whole block down with it (and on PostgreSQL
279
+ * poison the transaction beyond any catch).
280
+ *
281
+ * The existence check is then only an optimization — it keeps a settled catalogue from
282
+ * rewriting every unit of every block. It runs against the DB-LEVEL entity on purpose: the
283
+ * service projection carries the temporal filter (`validFrom < $valid.to AND validTo >
284
+ * $valid.from`), which hides precisely the born-expired rows this check is looking for.
285
+ */
286
+ private ensureAssetRows;
287
+ /**
288
+ * Remember a unit as present in the catalogue. Insertion-ordered Set → the oldest entries
289
+ * are evicted first once the cap is reached, which keeps a long backfill's memory flat while
290
+ * hot policies stay memoized. Losing an entry costs one SELECT, never a wrong write.
291
+ */
292
+ private noteAssetSeen;
293
+ /**
294
+ * Snapshot every stake pool and DRep at an epoch boundary (v2.0 analytics coverage).
295
+ *
296
+ * Runs in its OWN transaction, called by the crawler after a block commit — never inside the
297
+ * block's write transaction: a few thousand rows would inflate an otherwise small atomic
298
+ * write, and a snapshot failure would fail the block and burn its persist retries.
299
+ *
300
+ * Writes two things per entity: the dated snapshot row (authoritative, never expires) and a
301
+ * refresh of the live temporal row, so `Pools` / `Dreps` also stop being empty on a crawled
302
+ * instance. Needs an enumerating backend (Koios); without one it is a logged no-op.
303
+ *
304
+ * @param epoch the epoch the snapshot is taken for
305
+ * @param at slot and block time of the block that triggered the boundary
306
+ * @returns counts actually written, for the caller's log
307
+ */
308
+ snapshotEpoch(epoch: number, at: {
309
+ slot: number;
310
+ time: number;
311
+ }): Promise<{
312
+ pools: number;
313
+ dreps: number;
314
+ }>;
315
+ /** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
316
+ private collectBlockUnits;
190
317
  /**
191
318
  * Index & return the epoch information data
192
319
  * @param tx CAP transaction object