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

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.10",
3
+ "version": "2.0.0-rc.11",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -253,6 +253,10 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
253
253
  * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
254
254
  * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
255
255
  * the network's Shelley anchor (same config the tx-builder uses).
256
+ *
257
+ * A phase-2 failure whose body declares no `total_collateral` still carries its
258
+ * declared fee here, because the collateral inputs are not resolved yet. The indexer
259
+ * corrects both the transaction and this sum in applyCollateralFees().
256
260
  */
257
261
  private mapOgmiosBlock;
258
262
  /**
@@ -260,7 +264,8 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
260
264
  * and metadata are mapped fully; inputs are kept as bare references (address/amount
261
265
  * resolved downstream by the indexer). `spends` selects the ledger-applied
262
266
  * partition: a phase-2-invalid transaction consumes collaterals and creates only
263
- * its collateral-return output, never its declared regular inputs/outputs.
267
+ * its collateral-return output, never its declared regular inputs/outputs. The fee
268
+ * follows that partition too — see the `spendsCollaterals` branch below.
264
269
  */
265
270
  private mapOgmiosTx;
266
271
  }
@@ -13,6 +13,7 @@ const client_1 = require("@cardano-ogmios/client");
13
13
  const bech32_1 = require("bech32");
14
14
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
15
15
  const errors_1 = require("../../utils/errors");
16
+ const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
16
17
  const mappers_1 = require("../../utils/mappers");
17
18
  const const_1 = require("../../utils/const");
18
19
  const logger = cds_1.default.log('OgmiosBackend');
@@ -798,6 +799,14 @@ class OgmiosBackend {
798
799
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
799
800
  }
800
801
  };
802
+ // A frame the client's own parser cannot handle never reaches this class: it throws
803
+ // inside the library's socket handler, where nothing awaits it, and ends the process.
804
+ // The guard intercepts that and routes the unusable frame here instead, as an ordinary
805
+ // stream error naming the block. Installed per open (one stream at a time) and
806
+ // idempotent, so reopening only swaps the callback.
807
+ (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
808
+ void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
809
+ });
801
810
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
802
811
  logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
803
812
  void reportStreamError(err);
@@ -904,6 +913,10 @@ class OgmiosBackend {
904
913
  * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
905
914
  * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
906
915
  * the network's Shelley anchor (same config the tx-builder uses).
916
+ *
917
+ * A phase-2 failure whose body declares no `total_collateral` still carries its
918
+ * declared fee here, because the collateral inputs are not resolved yet. The indexer
919
+ * corrects both the transaction and this sum in applyCollateralFees().
907
920
  */
908
921
  mapOgmiosBlock(block) {
909
922
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
@@ -932,7 +945,8 @@ class OgmiosBackend {
932
945
  * and metadata are mapped fully; inputs are kept as bare references (address/amount
933
946
  * resolved downstream by the indexer). `spends` selects the ledger-applied
934
947
  * partition: a phase-2-invalid transaction consumes collaterals and creates only
935
- * its collateral-return output, never its declared regular inputs/outputs.
948
+ * its collateral-return output, never its declared regular inputs/outputs. The fee
949
+ * follows that partition too — see the `spendsCollaterals` branch below.
936
950
  */
937
951
  mapOgmiosTx(tx, block, index) {
938
952
  const mapInput = (input, flags = {}) => ({
@@ -972,13 +986,21 @@ class OgmiosBackend {
972
986
  json: v.json,
973
987
  }))
974
988
  : [];
989
+ // A phase-2 failure does not pay the fee declared in the body — the ledger consumes
990
+ // the collateral instead. `total_collateral` is that amount and the ledger enforces
991
+ // the equality, so prefer it; the body omits it often enough that the indexer derives
992
+ // the rest from the resolved collateral inputs once it has them.
993
+ const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
994
+ const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
975
995
  return {
976
996
  hash: tx.id,
977
997
  blockHash: block.id,
978
998
  blockHeight: block.height,
979
999
  slot: block.slot,
980
1000
  index,
981
- fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
1001
+ fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
1002
+ spendsCollaterals,
1003
+ totalCollateral,
982
1004
  deposit: '0',
983
1005
  // null = unknown (chain-sync doesn't surface the serialized size) — matches the
984
1006
  // lazy path's `size ?? null` convention; 0 would masquerade as a real size
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Guard against Ogmios chain-sync frames that the client's JSON parser cannot handle.
3
+ *
4
+ * `@cardano-ogmios/client` parses every WebSocket frame with `safeJSON.parse`, which is
5
+ * `sanitize(JSONBig.parse(raw))`. Both halves recurse once per nesting level: the
6
+ * `@cardanosolutions/json-bigint` parser is Crockford's recursive descent, and `sanitize`
7
+ * walks the parsed tree recursively. A native script nests one JSON object per clause, and
8
+ * nested clauses cost only a few bytes each in CBOR — so an ordinary-looking block can
9
+ * expand into JSON that is ten thousand levels deep and exhaust the V8 stack.
10
+ *
11
+ * That is not a theoretical shape. Preprod block 5183974 carries a native script nested
12
+ * 10 774 levels deep (`{"clause":"all","from":[ … ]}` down to a single signature clause).
13
+ * The block is 43 kB on chain and 205 kB as a chain-sync frame.
14
+ *
15
+ * The crash is fatal rather than merely annoying, because of where the parse happens
16
+ * (`ChainSynchronization/Client.js`):
17
+ *
18
+ * socket.on('message', async (message) => {
19
+ * await responseHandler(util_1.safeJSON.parse(message));
20
+ * });
21
+ *
22
+ * `safeJSON.parse` throws synchronously inside an `async` handler that nobody awaits, so
23
+ * the `RangeError` surfaces as an unhandled rejection and Node takes the process down. The
24
+ * crawler's poison-block latch cannot help: it guards the persist path, and the server is
25
+ * gone long before a block reaches it. Docker restarts, the crawler resumes at the same
26
+ * block, and the loop repeats — 53 restarts in seven minutes on the hosted box.
27
+ *
28
+ * This guard wraps `safeJSON.parse` (a public export of the client package) so that the
29
+ * fast path is untouched and only an overflowing frame takes the recovery route:
30
+ *
31
+ * 1. the original parser, so every ordinary frame keeps its exact BigInt handling;
32
+ * 2. on `RangeError`, `widenBigIntegers()` rewrites integer literals that a double cannot
33
+ * hold into JSON strings, then plain `JSON.parse` — V8's parser is iterative, so depth
34
+ * is no longer a limit. `sanitize` is skipped, because it would overflow on the very
35
+ * same structure;
36
+ * 3. if even that fails, the frame is reported to the caller and a sentinel is returned.
37
+ * The guard never throws, because throwing here is what kills the process.
38
+ *
39
+ * Measured against the real frame (node 22, 205 728 bytes, depth 10 774): json-bigint and
40
+ * `JSON.parse` with a reviver both overflow — a reviver walk is recursive too — while plain
41
+ * `JSON.parse` completes in 17 ms.
42
+ *
43
+ * Upstream: a recursive parser on untrusted chain data is a denial-of-service against every
44
+ * consumer of the client, mainnet included. This guard is a local mitigation, not the cure.
45
+ */
46
+ import { safeJSON } from '@cardano-ogmios/client';
47
+ /** A frame the guard could not turn into an object at all. */
48
+ export interface UnparseableFrame {
49
+ /** Block height, when it could be read off the raw text; null when even that failed. */
50
+ height: number | null;
51
+ /** Block id (hash), when readable. */
52
+ id: string | null;
53
+ reason: string;
54
+ bytes: number;
55
+ }
56
+ /**
57
+ * Integers outside the safe double range, written into JSON strings so that plain
58
+ * `JSON.parse` cannot round them. Runs as one linear pass with an explicit in-string state,
59
+ * never recursing, so it is immune to the nesting that sent us here in the first place.
60
+ *
61
+ * Only numbers in value position are touched: digits inside strings (hashes, CBOR, asset
62
+ * names) are skipped, and so are floats and exponents, which are doubles by nature and have
63
+ * no exact integer to preserve.
64
+ */
65
+ export declare function widenBigIntegers(text: string): string;
66
+ /**
67
+ * Wrap `safeJSON.parse` once per process. Idempotent: a second call only replaces the
68
+ * report callback, so reopening the chain-sync stream never stacks wrappers.
69
+ *
70
+ * @param onUnparseableFrame called when a frame survives neither parser. The guard returns
71
+ * a sentinel instead of throwing, so the caller owns what happens next — the stream
72
+ * itself stalls, because the client drops anything that is not a nextBlock response.
73
+ */
74
+ export declare function installOgmiosFrameGuard(onUnparseableFrame: (frame: UnparseableFrame) => void): void;
75
+ /** Tests only — drop the wrapper so each case starts from the untouched client. */
76
+ export declare function resetOgmiosFrameGuardForTests(originalParse?: typeof safeJSON.parse): void;
77
+ //# sourceMappingURL=ogmios-frame-guard.d.ts.map
@@ -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
@@ -187,6 +187,24 @@ export declare class CardanoIndexer {
187
187
  * DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
188
188
  */
189
189
  private resolveInputs;
190
+ /**
191
+ * Settle the fee of phase-2-invalid transactions and the block total that follows from it.
192
+ *
193
+ * A failed script phase does not pay the fee declared in the body: the ledger consumes the
194
+ * collateral instead, i.e. the collateral inputs minus the collateral return. The Ogmios
195
+ * mapper already uses the body's `total_collateral` when it declares one; what is left are
196
+ * the transactions without it, and those need the collateral inputs that resolveInputs()
197
+ * has just filled in.
198
+ *
199
+ * A collateral input the crawler cannot resolve — spent from an output produced before the
200
+ * crawl start, so no row exists locally — would make the sum silently too small. The
201
+ * declared fee is kept in that case and the transaction is logged: a value that is wrong in
202
+ * a known, named way beats one that looks derived but is short by an unknown amount.
203
+ *
204
+ * Only the chain-sync path sets `spendsCollaterals`; Blockfrost and Koios transactions carry
205
+ * it as undefined and pass through untouched.
206
+ */
207
+ private applyCollateralFees;
190
208
  /**
191
209
  * Index & return the epoch information data
192
210
  * @param tx CAP transaction object
@@ -493,9 +493,12 @@ class CardanoIndexer {
493
493
  if (epochRows.length)
494
494
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
495
495
  }
496
- await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
497
- // Backfill chain-sync inputs (empty address/amount) from local outputs
496
+ // Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
497
+ // the fee of any phase-2 failure. Both run before the block row is written, because a
498
+ // corrected fee changes the block's fee total.
498
499
  await this.resolveInputs(tx, txs);
500
+ this.applyCollateralFees(blockData, txs);
501
+ await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
499
502
  // Accumulate rows across the whole block, then one bulk UPSERT per table.
500
503
  // NUL safety (PostgreSQL rejects U+0000 in text/JSON) is enforced for every write
501
504
  // of this plugin by the db-level hook in srv/utils/db-sanitize.ts, not per call site.
@@ -582,6 +585,56 @@ class CardanoIndexer {
582
585
  input.amount = amt;
583
586
  }
584
587
  }
588
+ /**
589
+ * Settle the fee of phase-2-invalid transactions and the block total that follows from it.
590
+ *
591
+ * A failed script phase does not pay the fee declared in the body: the ledger consumes the
592
+ * collateral instead, i.e. the collateral inputs minus the collateral return. The Ogmios
593
+ * mapper already uses the body's `total_collateral` when it declares one; what is left are
594
+ * the transactions without it, and those need the collateral inputs that resolveInputs()
595
+ * has just filled in.
596
+ *
597
+ * A collateral input the crawler cannot resolve — spent from an output produced before the
598
+ * crawl start, so no row exists locally — would make the sum silently too small. The
599
+ * declared fee is kept in that case and the transaction is logged: a value that is wrong in
600
+ * a known, named way beats one that looks derived but is short by an unknown amount.
601
+ *
602
+ * Only the chain-sync path sets `spendsCollaterals`; Blockfrost and Koios transactions carry
603
+ * it as undefined and pass through untouched.
604
+ */
605
+ applyCollateralFees(blockData, txs) {
606
+ const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
607
+ let corrected = false;
608
+ for (const t of txs) {
609
+ // totalCollateral set = the mapper already put the charged amount in `fee`
610
+ if (!t.spendsCollaterals || t.totalCollateral != null)
611
+ continue;
612
+ const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
613
+ if (!collateral.length)
614
+ continue; // nothing to derive from — leave the declared fee
615
+ const unresolved = collateral.find(i => !i.address);
616
+ if (unresolved) {
617
+ logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
618
+ `— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
619
+ continue;
620
+ }
621
+ const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
622
+ const returned = (t.outputs ?? [])
623
+ .filter(o => o.isCollateral)
624
+ .reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
625
+ const charged = consumed - returned;
626
+ if (charged < 0n) {
627
+ logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
628
+ `— keeping the declared fee ${t.fee}`);
629
+ continue;
630
+ }
631
+ t.fee = charged.toString();
632
+ corrected = true;
633
+ }
634
+ if (corrected) {
635
+ blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
636
+ }
637
+ }
585
638
  /**
586
639
  * Index & return the epoch information data
587
640
  * @param tx CAP transaction object
@@ -71,6 +71,14 @@ export declare class CardanoCrawler {
71
71
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
72
72
  private readonly inFlightCallbacks;
73
73
  private haltPromise;
74
+ /**
75
+ * Set when a chain-sync frame could not be parsed at all. The stream cannot deliver that
76
+ * block, so the ingest loop takes it through the paginating backend and then reopens
77
+ * chain-sync — see runIngestPipeline().
78
+ */
79
+ private frameFailure;
80
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
81
+ private streamEnded;
74
82
  private finalStatus;
75
83
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
76
84
  private latchOnHalt;
@@ -118,6 +126,22 @@ export declare class CardanoCrawler {
118
126
  /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
119
127
  private withTimeout;
120
128
  private runChainSync;
129
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
130
+ private takeFrameFailure;
131
+ /**
132
+ * Can this unparseable frame be worked around by fetching the block over HTTP instead?
133
+ *
134
+ * Requires a height to walk to, a paginating backend to walk with, and an operator who has
135
+ * not pinned the source to 'ogmios' — that setting means chain-sync only, and silently
136
+ * degrading to the weaker pagination reorg handling would defeat the point of it.
137
+ */
138
+ private canDegradeToPagination;
139
+ /**
140
+ * End the chain-sync stream and hand control back to the ingest loop, which continues on
141
+ * pagination past the offending block. Records the error first, so `lastError` names the
142
+ * block rather than leaving the empty status a crashed process used to leave behind.
143
+ */
144
+ private degradeToPagination;
121
145
  /**
122
146
  * Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
123
147
  * spaced ladder of our own already-crawled ancestors, then the configured start
@@ -133,6 +157,12 @@ export declare class CardanoCrawler {
133
157
  private buildIntersectionPoints;
134
158
  /** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
135
159
  private trackCallback;
160
+ /**
161
+ * @param untilHeight when set, return as soon as the cursor has reached it instead of
162
+ * looping forever. Used to walk past a block the chain-sync stream cannot deliver and
163
+ * then hand back to it — pagination is roughly seven times slower, so staying on it
164
+ * for the rest of a backfill would be a poor trade.
165
+ */
136
166
  private runPagination;
137
167
  /**
138
168
  * Pagination reorg recovery: walk back by height comparing the on-chain block hash with
@@ -82,6 +82,14 @@ class CardanoCrawler {
82
82
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
83
83
  inFlightCallbacks = new Set();
84
84
  haltPromise = null;
85
+ /**
86
+ * Set when a chain-sync frame could not be parsed at all. The stream cannot deliver that
87
+ * block, so the ingest loop takes it through the paginating backend and then reopens
88
+ * chain-sync — see runIngestPipeline().
89
+ */
90
+ frameFailure = null;
91
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
92
+ streamEnded = null;
85
93
  finalStatus = 'stopped';
86
94
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
87
95
  latchOnHalt = false;
@@ -185,6 +193,7 @@ class CardanoCrawler {
185
193
  this.finalStatus = finalStatus;
186
194
  this.running = false;
187
195
  this.wake?.(); // cancel a pending poll sleep so the loop exits now
196
+ this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
188
197
  this.leaseWake?.();
189
198
  for (const cancel of [...this.callCancels])
190
199
  cancel();
@@ -226,7 +235,22 @@ class CardanoCrawler {
226
235
  async runIngestPipeline() {
227
236
  const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
228
237
  if (chainSync) {
229
- await this.runChainSync(chainSync);
238
+ // One pass per chain-sync stream. A frame the client's parser cannot turn into an
239
+ // object ends the stream without ending the crawler: pagination fetches that one
240
+ // block over HTTP, and chain-sync takes over again as soon as it is behind the
241
+ // cursor. Any other stream error still halts, as it always did.
242
+ while (this.running) {
243
+ const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
244
+ await this.runChainSync(chainSync);
245
+ if (!this.chainSyncHandle)
246
+ return; // open refused, halted, or stop() raced us
247
+ await streamEnd;
248
+ const failure = this.takeFrameFailure();
249
+ if (!this.running || failure?.height == null)
250
+ return;
251
+ logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
252
+ await this.runPagination(failure.height + 1);
253
+ }
230
254
  return;
231
255
  }
232
256
  if (this.config.source === 'ogmios') {
@@ -293,6 +317,12 @@ class CardanoCrawler {
293
317
  onError: (err) => this.trackCallback(async () => {
294
318
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
295
319
  return;
320
+ // A frame the client's parser cannot handle is a fault of that one block, not of the
321
+ // crawler or the node — pagination can still fetch it, so degrade instead of halting.
322
+ if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
323
+ await this.degradeToPagination(err);
324
+ return;
325
+ }
296
326
  // The stream is stalled (mapping/callback failure) — record and halt cleanly
297
327
  // so the cursor status shows 'error' instead of a healthy-looking hang.
298
328
  const streak = await this.recordCrawlerError(err);
@@ -311,6 +341,49 @@ class CardanoCrawler {
311
341
  this.chainSyncHandle = handle;
312
342
  logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
313
343
  }
344
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
345
+ takeFrameFailure() {
346
+ const failure = this.frameFailure;
347
+ this.frameFailure = null;
348
+ return failure;
349
+ }
350
+ /**
351
+ * Can this unparseable frame be worked around by fetching the block over HTTP instead?
352
+ *
353
+ * Requires a height to walk to, a paginating backend to walk with, and an operator who has
354
+ * not pinned the source to 'ogmios' — that setting means chain-sync only, and silently
355
+ * degrading to the weaker pagination reorg handling would defeat the point of it.
356
+ */
357
+ canDegradeToPagination(err) {
358
+ return err.height != null
359
+ && this.config.source !== 'ogmios'
360
+ && !!this.client.getPaginatingBackend();
361
+ }
362
+ /**
363
+ * End the chain-sync stream and hand control back to the ingest loop, which continues on
364
+ * pagination past the offending block. Records the error first, so `lastError` names the
365
+ * block rather than leaving the empty status a crashed process used to leave behind.
366
+ */
367
+ async degradeToPagination(err) {
368
+ const streak = await this.recordCrawlerError(err);
369
+ if (streak < 0) {
370
+ await this.halt('stopped');
371
+ return;
372
+ }
373
+ logger.error('Chain-sync frame unusable — continuing on pagination:', err.message);
374
+ this.frameFailure = err;
375
+ const handle = this.chainSyncHandle;
376
+ this.chainSyncHandle = null;
377
+ if (handle) {
378
+ try {
379
+ await handle.close();
380
+ }
381
+ catch (e) {
382
+ logger.warn('chain-sync close failed:', e);
383
+ }
384
+ }
385
+ this.streamEnded?.();
386
+ }
314
387
  /**
315
388
  * Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
316
389
  * spaced ladder of our own already-crawled ancestors, then the configured start
@@ -370,7 +443,13 @@ class CardanoCrawler {
370
443
  // ---------------------------------------------------------------------------
371
444
  // Pagination (Blockfrost/Koios) — fallback
372
445
  // ---------------------------------------------------------------------------
373
- async runPagination() {
446
+ /**
447
+ * @param untilHeight when set, return as soon as the cursor has reached it instead of
448
+ * looping forever. Used to walk past a block the chain-sync stream cannot deliver and
449
+ * then hand back to it — pagination is roughly seven times slower, so staying on it
450
+ * for the rest of a backfill would be a poor trade.
451
+ */
452
+ async runPagination(untilHeight) {
374
453
  const backend = this.client.getPaginatingBackend();
375
454
  if (!backend) {
376
455
  logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
@@ -391,6 +470,10 @@ class CardanoCrawler {
391
470
  await this.halt('error', true); // broken precondition: a restart cannot fix it
392
471
  return;
393
472
  }
473
+ if (untilHeight != null && cursor.lastHeight >= untilHeight) {
474
+ logger.info(`pagination reached block ${cursor.lastHeight} — handing back to chain-sync`);
475
+ return;
476
+ }
394
477
  if (!tip || cursor.lastHeight >= target) {
395
478
  tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
396
479
  target = (tip.height ?? 0) - this.config.confirmationDepth;
@@ -222,6 +222,24 @@ export declare class HsmError extends BackendError {
222
222
  export declare class ConfigError extends Error {
223
223
  constructor(message: string);
224
224
  }
225
+ /**
226
+ * ChainSyncFrameError - Ogmios delivered a frame the client cannot turn into an object.
227
+ *
228
+ * Raised by the frame guard (see `backends/ogmios-frame-guard.ts`) once the client's parser
229
+ * and the depth-safe fallback have both failed. The block is named so `lastError` points at
230
+ * it instead of leaving an empty status behind, and so the crawler can take that one block
231
+ * through the paginating backend instead of waiting on a stream that will never deliver it.
232
+ */
233
+ export declare class ChainSyncFrameError extends BackendError {
234
+ readonly height: number | null;
235
+ readonly id: string | null;
236
+ /** Constructor
237
+ * @param height block height the frame belonged to, when it could be read off the raw text
238
+ * @param id block hash, when readable
239
+ * @param reason why the frame could not be parsed
240
+ */
241
+ constructor(height: number | null, id: string | null, reason: string);
242
+ }
225
243
  /**
226
244
  * BackendInitError - Error initializing a specific backend
227
245
  * Captures backend name and original error
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ConfigError = exports.HsmError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
3
+ exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ChainSyncFrameError = exports.ConfigError = exports.HsmError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
4
4
  exports.isNotFoundOnAllBackends = isNotFoundOnAllBackends;
5
5
  exports.isPostgrestServerErrorCode = isPostgrestServerErrorCode;
6
6
  exports.getErrorStatus = getErrorStatus;
@@ -442,6 +442,29 @@ class ConfigError extends Error {
442
442
  }
443
443
  }
444
444
  exports.ConfigError = ConfigError;
445
+ /**
446
+ * ChainSyncFrameError - Ogmios delivered a frame the client cannot turn into an object.
447
+ *
448
+ * Raised by the frame guard (see `backends/ogmios-frame-guard.ts`) once the client's parser
449
+ * and the depth-safe fallback have both failed. The block is named so `lastError` points at
450
+ * it instead of leaving an empty status behind, and so the crawler can take that one block
451
+ * through the paginating backend instead of waiting on a stream that will never deliver it.
452
+ */
453
+ class ChainSyncFrameError extends BackendError {
454
+ height;
455
+ id;
456
+ /** Constructor
457
+ * @param height block height the frame belonged to, when it could be read off the raw text
458
+ * @param id block hash, when readable
459
+ * @param reason why the frame could not be parsed
460
+ */
461
+ constructor(height, id, reason) {
462
+ super(`Ogmios chain-sync frame for block ${height ?? '?'} ${id ?? ''} could not be parsed: ${reason}`, 503, error_codes_1.ERROR_CODES.PROVIDER_UNAVAILABLE, 'ogmios');
463
+ this.height = height;
464
+ this.id = id;
465
+ }
466
+ }
467
+ exports.ChainSyncFrameError = ChainSyncFrameError;
445
468
  /**
446
469
  * BackendInitError - Error initializing a specific backend
447
470
  * Captures backend name and original error
@@ -58,8 +58,27 @@ export interface Transaction {
58
58
  blockHeight: number;
59
59
  slot: number;
60
60
  index: number;
61
+ /**
62
+ * What the ledger charged. For an ordinary transaction that is the fee declared in the
63
+ * body; for a phase-2 failure (`spendsCollaterals`) it is the collateral consumed, which
64
+ * is what the sender actually paid — the declared fee was never collected.
65
+ */
61
66
  fee: Lovelace | string;
62
67
  deposit: Lovelace | string;
68
+ /**
69
+ * Phase-2 validity as the ledger applied it. True when the script phase failed: the
70
+ * declared inputs and outputs were not applied, the collateral inputs were consumed and
71
+ * only the collateral return was produced. Only the Ogmios chain-sync path reports it;
72
+ * the historical backends leave it undefined.
73
+ */
74
+ spendsCollaterals?: boolean;
75
+ /**
76
+ * `total_collateral` from the transaction body, when it declares one. The ledger requires
77
+ * it to equal the collateral actually consumed, so it is the exact value for `fee` on a
78
+ * phase-2 failure without resolving a single input. Null when the body omits it — the
79
+ * charge then has to be derived from the resolved collateral inputs minus the return.
80
+ */
81
+ totalCollateral?: Lovelace | string | null;
63
82
  /** Tx size in bytes; null when the source cannot provide it (Ogmios chain-sync). */
64
83
  size: number | null;
65
84
  blockTime: number;