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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -63,10 +63,23 @@ function creditedAmount(now, before, withdrawn) {
63
63
  const credited = BigInt(now) - before + withdrawn;
64
64
  return credited < 0n ? null : credited.toString();
65
65
  }
66
+ // True when every stored block in (fromSlot, toSlot] carries its withdrawals. A block crawled
67
+ // without them, for example over Blockfrost, would make a credited amount too small.
68
+ async function withdrawalsComplete(fromSlot, toSlot) {
69
+ return cds_1.default.tx(async (tx) => {
70
+ for (const marker of [false, null]) {
71
+ const gap = await tx.run(SELECT.one.from(cardano_1.Blocks).columns('hash')
72
+ .where({ slot: { between: fromSlot + 1, and: toSlot }, withdrawalsReported: marker }));
73
+ if (gap)
74
+ return false;
75
+ }
76
+ return true;
77
+ });
78
+ }
66
79
  async function storePage(tx, reported, opts, previousSlot) {
67
80
  const before = new Map();
68
81
  const withdrawn = new Map();
69
- if (previousSlot != null && opts.withdrawals) {
82
+ if (previousSlot != null) {
70
83
  for (const part of (0, collections_1.chunk)(reported.map(a => a.stakeAddress), collections_1.IN_CHUNK)) {
71
84
  const balances = await tx.run(SELECT.from(cardano_1.AccountEpochSnapshots).columns('stakeAddress', 'withdrawableAmount').where({ epoch: opts.epoch - 1, stakeAddress: { in: part } }));
72
85
  for (const r of balances)
@@ -103,7 +116,11 @@ async function snapshotAccounts(opts) {
103
116
  return { taken: false, asked: 0, accounts: Number(marker.accountCount) };
104
117
  // rows of an attempt that did not finish were read at another block
105
118
  await cds_1.default.tx((tx) => tx.run(DELETE.from(cardano_1.AccountEpochSnapshots).where({ epoch })));
106
- const previousSlot = await accountSnapshotSlot(epoch - 1);
119
+ const previousSnapshotSlot = await accountSnapshotSlot(epoch - 1);
120
+ // Without the withdrawals of the whole interval no credited amount is derived.
121
+ const previousSlot = previousSnapshotSlot != null && opts.withdrawals && await withdrawalsComplete(previousSnapshotSlot, at.slot)
122
+ ? previousSnapshotSlot
123
+ : null;
107
124
  let asked = 0;
108
125
  await backend.rewardAccountsAt({ slot: at.slot, hash: at.hash }, async (ask) => {
109
126
  let ledgerHasAccounts = false;
@@ -127,6 +144,9 @@ async function snapshotAccounts(opts) {
127
144
  }
128
145
  }
129
146
  });
147
+ // A stopped attempt never writes the marker: its rows may be read at another block than the next one's.
148
+ if (opts.shouldStop?.())
149
+ throw new Error(`account snapshot of epoch ${epoch} stopped`);
130
150
  const accounts = await cds_1.default.tx(async (tx) => {
131
151
  const block = await tx.run(SELECT.one.from(cardano_1.Blocks).columns('hash').where({ hash: at.hash }));
132
152
  if (!block) {
@@ -10,6 +10,8 @@ export interface DecimalsBackfillOptions {
10
10
  /** Rows per page. */
11
11
  chunkSize?: number;
12
12
  onProgress?: (p: DecimalsBackfillProgress) => void;
13
+ /** Stops the walk before the next page. */
14
+ shouldStop?: () => boolean;
13
15
  }
14
16
  export declare function backfillAssetDecimals(opts?: DecimalsBackfillOptions): Promise<DecimalsBackfillProgress>;
15
17
  //# sourceMappingURL=asset-decimals-backfill.d.ts.map
@@ -8,48 +8,48 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const cardano_1 = require("#cds-models/odatano/cardano");
9
9
  const cip68_1 = require("../../cbor/cip68");
10
10
  const asset_decimals_1 = require("../asset-decimals");
11
- const { SELECT } = cds_1.default.ql;
11
+ const key_pages_1 = require("./key-pages");
12
12
  const logger = cds_1.default.log('DecimalsBackfill');
13
- // Fill Assets.decimals from the CIP-68 reference datum for label 333 and 444 units. Pages by unit
13
+ // Fill Assets.decimals from the CIP-68 reference datum for label 333 and 444 units. Pages by key
14
14
  // only, so the query plan never depends on column statistics. A repeat run refreshes the values.
15
+ // A unit with more slices than a page holds is resolved per page; each part writes the same value.
15
16
  async function backfillAssetDecimals(opts = {}) {
16
17
  const chunkSize = opts.chunkSize ?? 5000;
17
18
  const progress = { scanned: 0, candidates: 0, filled: 0 };
18
- let cursor = null;
19
- for (;;) {
20
- const done = await cds_1.default.tx(async (tx) => {
21
- const rows = (await tx.run(SELECT.from(cardano_1.Assets).columns('unit', 'initialMintTxHash').where(cursor ? { unit: { '>': cursor } } : {}).orderBy('unit').limit(chunkSize))) ?? [];
22
- if (!rows.length)
23
- return true;
24
- const full = rows.length === chunkSize;
25
- const lastUnit = rows[rows.length - 1].unit;
26
- const allSame = rows.every((r) => r.unit === lastUnit);
27
- // The slices of a unit are adjacent. The last unit of a full page may continue on the next
28
- // one, so its rows wait there; a page holding one unit only is resolved as a whole.
29
- const complete = full && !allSame ? rows.filter((r) => r.unit !== lastUnit) : rows;
30
- const mints = new Map();
31
- for (const r of complete) {
32
- if (!(0, cip68_1.cip68ReferenceUnit)(r.unit))
33
- continue;
34
- if (!mints.has(r.unit) || r.initialMintTxHash)
35
- mints.set(r.unit, r.initialMintTxHash ?? null);
36
- }
19
+ // units are adjacent in key order, so only the last unit of the previous page can go on
20
+ let carried = null;
21
+ await (0, key_pages_1.pageByKey)({
22
+ entity: cardano_1.Assets, keys: ['unit', 'validFrom'], columns: ['initialMintTxHash'], chunkSize, shouldStop: opts.shouldStop,
23
+ }, async (rows) => {
24
+ const mints = new Map();
25
+ for (const r of rows) {
26
+ if (!(0, cip68_1.cip68ReferenceUnit)(r.unit))
27
+ continue;
28
+ if (!mints.has(r.unit) || r.initialMintTxHash)
29
+ mints.set(r.unit, r.initialMintTxHash ?? null);
30
+ }
31
+ const filled = new Set();
32
+ await cds_1.default.tx(async (tx) => {
37
33
  for (const [unit, mintTxHash] of mints) {
38
34
  const decimals = await (0, asset_decimals_1.cip68Decimals)(tx, unit, mintTxHash);
39
35
  if (decimals == null)
40
36
  continue;
41
37
  await (0, asset_decimals_1.setAssetDecimals)(tx, unit, decimals);
42
- progress.filled++;
38
+ filled.add(unit);
43
39
  }
44
- progress.scanned += complete.length;
45
- progress.candidates += mints.size;
46
- cursor = complete[complete.length - 1].unit;
47
- return !full;
48
40
  });
41
+ progress.scanned += rows.length;
42
+ for (const unit of mints.keys()) {
43
+ const continued = carried?.unit === unit;
44
+ if (!continued)
45
+ progress.candidates++;
46
+ if (filled.has(unit) && !(continued && carried.filled))
47
+ progress.filled++;
48
+ }
49
+ const last = rows[rows.length - 1].unit;
50
+ carried = { unit: last, filled: filled.has(last) || (carried?.unit === last && carried.filled) };
49
51
  opts.onProgress?.({ ...progress });
50
- if (done)
51
- break;
52
- }
52
+ });
53
53
  logger.info(`asset decimals filled: ${progress.filled} of ${progress.candidates} CIP-68 units, ${progress.scanned} catalogue rows read`);
54
54
  return progress;
55
55
  }
@@ -20,6 +20,8 @@ export interface RegistryBackfillOptions {
20
20
  /** Backend calls per second; one unit is one call. */
21
21
  unitsPerSecond?: number;
22
22
  onProgress?: (p: RegistryBackfillProgress) => void;
23
+ /** Stops the run before the next unit. */
24
+ shouldStop?: () => boolean;
23
25
  }
24
26
  export declare function backfillAssetRegistry(opts: RegistryBackfillOptions): Promise<RegistryBackfillProgress>;
25
27
  /** The registry values of one unit, as the Assets columns hold them. */
@@ -36,6 +38,7 @@ export declare function parseRegistryEntry(json: string): RegistryEntry | null;
36
38
  export interface RegistryFileOptions {
37
39
  directory: string;
38
40
  onProgress?: (p: RegistryBackfillProgress) => void;
41
+ shouldStop?: () => boolean;
39
42
  }
40
43
  /** The entry files of `directory`; refuses a path that holds none. */
41
44
  export declare function registryEntryFiles(directory: string): Promise<string[]>;
@@ -30,6 +30,8 @@ async function backfillAssetRegistry(opts) {
30
30
  const failuresByError = new Map();
31
31
  let consecutiveFailures = 0;
32
32
  for (const unit of units) {
33
+ if (opts.shouldStop?.())
34
+ break;
33
35
  const started = Date.now();
34
36
  try {
35
37
  await cds_1.default.tx(async (tx) => {
@@ -117,6 +119,8 @@ async function backfillAssetRegistryFromFiles(opts) {
117
119
  const files = await registryEntryFiles(opts.directory);
118
120
  const progress = { units: files.length, processed: 0, filled: 0, failed: 0, absent: 0, skipped: 0 };
119
121
  for (const batch of (0, collections_1.chunk)(files, 200)) {
122
+ if (opts.shouldStop?.())
123
+ break;
120
124
  const entries = [];
121
125
  for (const name of batch) {
122
126
  try {
@@ -0,0 +1,35 @@
1
+ import { type BulkSqlKind } from '../../utils/db-kind';
2
+ export interface AssetSliceBackfillProgress {
3
+ /** Table being walked; null when finished. */
4
+ table: AssetSliceTable['name'] | null;
5
+ outputs: number;
6
+ inputs: number;
7
+ ledgerUtxos: number;
8
+ ledgerAddresses: number;
9
+ utxoSlices: number;
10
+ addressSlices: number;
11
+ }
12
+ export interface AssetSliceBackfillOptions {
13
+ /** Slots per window on the transaction tables. */
14
+ slotWindow?: number;
15
+ /** Units, or addresses on the cached tables, per statement. */
16
+ chunkSize?: number;
17
+ shouldStop?: () => boolean;
18
+ onProgress?: (p: AssetSliceBackfillProgress) => void;
19
+ }
20
+ interface AssetSliceTable {
21
+ name: 'TransactionOutputAssets' | 'TransactionInputAssetCopies' | 'LedgerUTxOAssets' | 'LedgerAddressAssets' | 'UTxOAssets' | 'AddressAssets';
22
+ table: string;
23
+ counter: 'outputs' | 'inputs' | 'ledgerUtxos' | 'ledgerAddresses' | 'utxoSlices' | 'addressSlices';
24
+ /** txSeq column of a table walked by slot window. */
25
+ seqColumn?: string;
26
+ /** Entity whose txSeq bounds the window walk. */
27
+ rangeOf?: unknown;
28
+ /** Address column of a cached table, walked along its address index; every slice of a row is set. */
29
+ addressColumn?: string;
30
+ }
31
+ export declare const ASSET_SLICE_TABLES: readonly AssetSliceTable[];
32
+ export declare function sliceFillStatement(kind: BulkSqlKind, spec: AssetSliceTable, bounds?: [number, number]): string;
33
+ export declare function backfillAssetSlices(opts?: AssetSliceBackfillOptions): Promise<AssetSliceBackfillProgress>;
34
+ export {};
35
+ //# sourceMappingURL=asset-slice-backfill.d.ts.map
@@ -0,0 +1,149 @@
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.ASSET_SLICE_TABLES = void 0;
7
+ exports.sliceFillStatement = sliceFillStatement;
8
+ exports.backfillAssetSlices = backfillAssetSlices;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const mappers_1 = require("../../utils/mappers");
11
+ const collections_1 = require("../../utils/collections");
12
+ const db_kind_1 = require("../../utils/db-kind");
13
+ const window_plan_1 = require("./window-plan");
14
+ const cardano_1 = require("#cds-models/odatano/cardano");
15
+ const logger = cds_1.default.log('AssetSliceBackfill');
16
+ exports.ASSET_SLICE_TABLES = [
17
+ { name: 'TransactionOutputAssets', table: 'odatano_cardano_TransactionOutputAssets', counter: 'outputs', seqColumn: 'output_txSeq', rangeOf: cardano_1.TransactionOutputs },
18
+ { name: 'TransactionInputAssetCopies', table: 'odatano_cardano_TransactionInputAssetCopies', counter: 'inputs', seqColumn: 'input_txSeq', rangeOf: cardano_1.TransactionInputs },
19
+ { name: 'LedgerUTxOAssets', table: 'odatano_cardano_LedgerUTxOAssets', counter: 'ledgerUtxos' },
20
+ { name: 'LedgerAddressAssets', table: 'odatano_cardano_LedgerAddressAssets', counter: 'ledgerAddresses' },
21
+ { name: 'UTxOAssets', table: 'odatano_cardano_UTxOAssets', counter: 'utxoSlices', addressColumn: 'utxo_address_address' },
22
+ { name: 'AddressAssets', table: 'odatano_cardano_AddressAssets', counter: 'addressSlices', addressColumn: 'address_address' },
23
+ ];
24
+ const SLICE_COLUMNS = ['asset_policyId', 'asset_assetNameHex', 'asset_assetName', 'asset_fingerprint'];
25
+ // One UPDATE that sets the slice columns of every row whose unit, and address on a cached table, is in
26
+ // the bound JSON array and whose columns differ. `bounds` limits it to one txSeq window; they are
27
+ // integers, so they are written inline.
28
+ function sliceFillStatement(kind, spec, bounds) {
29
+ const differs = SLICE_COLUMNS.map((c) => `t.${c} IS DISTINCT FROM v.${c}`).join(' OR ');
30
+ const window = bounds && spec.seqColumn
31
+ ? `t.${spec.seqColumn} >= ${Math.trunc(bounds[0])} AND t.${spec.seqColumn} < ${Math.trunc(bounds[1])} AND `
32
+ : '';
33
+ return (0, db_kind_1.jsonFillUpdate)(kind, {
34
+ table: spec.table,
35
+ keys: spec.addressColumn ? [[spec.addressColumn, 'text'], ['unit', 'text']] : [['unit', 'text']],
36
+ values: SLICE_COLUMNS.map((c) => [c, 'text']),
37
+ set: SLICE_COLUMNS.map((c) => `${c} = v.${c}`).join(', '),
38
+ where: `${window}(${differs})`,
39
+ });
40
+ }
41
+ /** Fill records of `units`, the record fields named after the columns in lower case. */
42
+ function records(units, extra = []) {
43
+ return units.map((unit, i) => {
44
+ const s = (0, mappers_1.assetSlice)(unit, 0);
45
+ return {
46
+ ...extra[i],
47
+ unit,
48
+ asset_policyid: s.asset_policyId,
49
+ asset_assetnamehex: s.asset_assetNameHex,
50
+ asset_assetname: s.asset_assetName,
51
+ asset_fingerprint: s.asset_fingerprint,
52
+ };
53
+ });
54
+ }
55
+ /** Rows a plain statement changed; the drivers answer with their own result object. */
56
+ function changed(result) {
57
+ const r = result;
58
+ return typeof r === 'number' ? r : Number(r?.changes ?? r?.rowCount) || 0;
59
+ }
60
+ async function fillUnits(tx, sql, units, chunkSize) {
61
+ let n = 0;
62
+ for (const part of (0, collections_1.chunk)(units, chunkSize))
63
+ n += changed(await tx.run(sql, [JSON.stringify(records(part))]));
64
+ return n;
65
+ }
66
+ // Walks a cached table along its address index: a page of addresses, then every (address, unit) pair
67
+ // in that address range. One pair stands for all slices of the row, so each slice gets the columns.
68
+ async function fillByAddress(kind, spec, opts, add) {
69
+ const column = spec.addressColumn;
70
+ const chunkSize = opts.chunkSize ?? 1000;
71
+ const sql = sliceFillStatement(kind, spec);
72
+ const [p1, p2] = kind === 'postgres' ? ['$1', '$2'] : ['?', '?'];
73
+ const page = `SELECT DISTINCT ${column} AS address FROM ${spec.table} WHERE ${column} > ${p1} ORDER BY ${column} LIMIT ${chunkSize}`;
74
+ const pairs = `SELECT DISTINCT ${column} AS address, unit FROM ${spec.table} WHERE ${column} >= ${p1} AND ${column} <= ${p2}`;
75
+ for (let after = '';;) {
76
+ if (opts.shouldStop?.())
77
+ return false;
78
+ const addresses = (await cds_1.default.tx((tx) => tx.run(page, [after]))).map((r) => r.address);
79
+ if (!addresses.length)
80
+ return true;
81
+ add(await cds_1.default.tx(async (tx) => {
82
+ const rows = await tx.run(pairs, [addresses[0], addresses[addresses.length - 1]]);
83
+ let n = 0;
84
+ for (const part of (0, collections_1.chunk)(rows, chunkSize)) {
85
+ const fill = records(part.map((r) => r.unit), part.map((r) => ({ [column.toLowerCase()]: r.address })));
86
+ n += changed(await tx.run(sql, [JSON.stringify(fill)]));
87
+ }
88
+ return n;
89
+ }));
90
+ after = addresses[addresses.length - 1];
91
+ if (addresses.length < chunkSize)
92
+ return true;
93
+ }
94
+ }
95
+ /** Walks a transaction asset table window by window. False when stopped. */
96
+ async function fillByWindow(kind, spec, opts, add) {
97
+ const range = await (0, window_plan_1.slotRangeOf)(spec.rangeOf);
98
+ if (!range)
99
+ return true;
100
+ const chunkSize = opts.chunkSize ?? 1000;
101
+ // the fill matches the window's rows against a unit list: a hash join, key lookups take 100 times longer
102
+ return (0, window_plan_1.walkSlotWindows)(range, { slotWindow: opts.slotWindow, shouldStop: opts.shouldStop, plan: 'join' }, async (tx, window) => {
103
+ const rows = await tx.run(`SELECT DISTINCT unit FROM ${spec.table} WHERE ${spec.seqColumn} >= ${Math.trunc(window[0])} AND ${spec.seqColumn} < ${Math.trunc(window[1])}`);
104
+ if (rows.length)
105
+ add(await fillUnits(tx, sliceFillStatement(kind, spec, window), rows.map((r) => r.unit), chunkSize));
106
+ });
107
+ }
108
+ /** Walks a ledger asset table unit by unit along its unit index. False when stopped. */
109
+ async function fillByUnit(kind, spec, opts, add) {
110
+ const chunkSize = opts.chunkSize ?? 1000;
111
+ const sql = sliceFillStatement(kind, spec);
112
+ const page = kind === 'postgres'
113
+ ? `SELECT DISTINCT unit FROM ${spec.table} WHERE unit > $1 ORDER BY unit LIMIT ${chunkSize}`
114
+ : `SELECT DISTINCT unit FROM ${spec.table} WHERE unit > ? ORDER BY unit LIMIT ${chunkSize}`;
115
+ for (let after = '';;) {
116
+ if (opts.shouldStop?.())
117
+ return false;
118
+ const units = (await cds_1.default.tx((tx) => tx.run(page, [after]))).map((r) => r.unit);
119
+ if (!units.length)
120
+ return true;
121
+ add(await cds_1.default.tx((tx) => fillUnits(tx, sql, units, chunkSize)));
122
+ after = units[units.length - 1];
123
+ if (units.length < chunkSize)
124
+ return true;
125
+ }
126
+ }
127
+ async function backfillAssetSlices(opts = {}) {
128
+ const kind = (0, db_kind_1.bulkSqlKind)((0, db_kind_1.connectedDbKind)());
129
+ if (!kind)
130
+ throw new Error(`Asset rows are rewritten on PostgreSQL and SQLite only (database kind: ${(0, db_kind_1.connectedDbKind)() || 'none'})`);
131
+ const progress = { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, ledgerAddresses: 0, utxoSlices: 0, addressSlices: 0 };
132
+ for (const spec of exports.ASSET_SLICE_TABLES) {
133
+ progress.table = spec.name;
134
+ opts.onProgress?.({ ...progress });
135
+ const add = (n) => {
136
+ progress[spec.counter] += n;
137
+ opts.onProgress?.({ ...progress });
138
+ };
139
+ const finished = spec.seqColumn ? await fillByWindow(kind, spec, opts, add)
140
+ : spec.addressColumn ? await fillByAddress(kind, spec, opts, add)
141
+ : await fillByUnit(kind, spec, opts, add);
142
+ if (!finished)
143
+ return progress;
144
+ }
145
+ progress.table = null;
146
+ logger.info(`asset rows rewritten: ${progress.outputs} output, ${progress.inputs} input, ${progress.ledgerUtxos} ledger UTxO, ${progress.ledgerAddresses} ledger address, ${progress.utxoSlices} cached UTxO, ${progress.addressSlices} cached address rows`);
147
+ return progress;
148
+ }
149
+ //# sourceMappingURL=asset-slice-backfill.js.map
@@ -24,6 +24,8 @@ export interface CertificateBackfillOptions {
24
24
  /** Rows are written per batch of blocks; smaller batches show progress sooner. */
25
25
  batchBlocks?: number;
26
26
  onProgress?: (p: CertificateBackfillProgress) => void;
27
+ /** Ends the stream after the current batch. */
28
+ shouldStop?: () => boolean;
27
29
  }
28
30
  export interface CertificateBackfillResult extends CertificateBackfillProgress {
29
31
  fromSlot: number;
@@ -46,6 +48,8 @@ export interface CrawledBlockStreamOptions {
46
48
  batchBlocks?: number;
47
49
  /** Error class the range and backend checks throw. */
48
50
  errorType?: new (message: string) => Error;
51
+ /** Ends the stream after the current batch. */
52
+ shouldStop?: () => boolean;
49
53
  }
50
54
  export declare function streamCrawledBlocks<T>(opts: CrawledBlockStreamOptions, collect: (block: BlockData, txs: Transaction[]) => T, writeBatch: (tx: CapTransaction, blocks: StreamedBlock<T>[]) => Promise<void>, afterBatch: (toSlot: number) => void): Promise<ChainPoint | 'origin'>;
51
55
  export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
@@ -12,7 +12,7 @@ const mappers_1 = require("../../utils/mappers");
12
12
  const collections_1 = require("../../utils/collections");
13
13
  const sync_state_1 = require("./sync-state");
14
14
  const cardano_1 = require("#cds-models/odatano/cardano");
15
- const { SELECT, UPSERT, DELETE } = cds_1.default.ql;
15
+ const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
16
16
  const logger = cds_1.default.log('CertificateBackfill');
17
17
  // Fill certificates and withdrawals for already crawled blocks from a second chain-sync stream.
18
18
  // Only those two tables are written, and a repeat run is idempotent. Unknown blocks are skipped.
@@ -29,7 +29,13 @@ async function intersectionBefore(db, slot) {
29
29
  const cursor = await (0, sync_state_1.readCursor)(db);
30
30
  const floor = cursor?.startSlot ?? null;
31
31
  const range = floor != null ? { between: floor, and: slot - 1 } : { '<': slot };
32
- const row = floor != null && slot - 1 < floor ? null : (await db.run(SELECT.one.from(cardano_1.Block).columns('hash', 'slot', 'height').where({ slot: range }).orderBy('slot desc')));
32
+ let row = null;
33
+ if (floor == null || slot - 1 >= floor) {
34
+ const q = SELECT.one.from(cardano_1.Block).columns('hash', 'slot', 'height').where({ slot: range });
35
+ // nulls first is the order a plain index on slot is read backwards in; the range excludes null
36
+ q.SELECT.orderBy = [{ ref: ['slot'], sort: 'desc', nulls: 'first' }];
37
+ row = (await db.run(q));
38
+ }
33
39
  if (row?.hash && row.slot != null)
34
40
  return { slot: Number(row.slot), hash: row.hash, height: row.height == null ? undefined : Number(row.height) };
35
41
  if (floor != null && cursor?.startBlockHash)
@@ -87,7 +93,7 @@ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
87
93
  if (settled)
88
94
  return;
89
95
  const slot = block.slot ?? 0;
90
- if (slot > toSlot) {
96
+ if (slot > toSlot || opts.shouldStop?.()) {
91
97
  finish();
92
98
  return;
93
99
  }
@@ -131,6 +137,8 @@ async function backfillCertificates(opts) {
131
137
  certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
132
138
  withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
133
139
  failed: txs.filter((t) => t.spendsCollaterals).map((t) => t.hash),
140
+ // the rule of the crawl: every transaction of the block reported its withdrawals
141
+ withdrawalsReported: txs.every((t) => t.withdrawals !== undefined),
134
142
  }), async (tx, blocks) => {
135
143
  const certs = blocks.flatMap((b) => b.payload.certs);
136
144
  const withdrawals = blocks.flatMap((b) => b.payload.withdrawals);
@@ -149,6 +157,10 @@ async function backfillCertificates(opts) {
149
157
  progress.removed += Number(await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: part } }))) || 0;
150
158
  progress.removed += Number(await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: part } }))) || 0;
151
159
  }
160
+ // the account snapshot derives credited amounts only over blocks marked here
161
+ for (const part of (0, collections_1.chunk)(blocks.filter((b) => b.payload.withdrawalsReported).map((b) => b.hash), collections_1.IN_CHUNK)) {
162
+ await tx.run(UPDATE.entity(cardano_1.Block).set({ withdrawalsReported: true }).where({ hash: { in: part } }));
163
+ }
152
164
  }, (atSlot) => {
153
165
  started = true;
154
166
  progress.atSlot = atSlot;
@@ -58,11 +58,19 @@ export declare class CardanoCrawler {
58
58
  private static readonly SNAPSHOT_TIMEOUT_MS;
59
59
  /** One node request per 2000 known accounts; an hour covers a mainnet-sized set. */
60
60
  private static readonly ACCOUNT_SNAPSHOT_TIMEOUT_MS;
61
+ /** How long a timed-out snapshot may take to end before the next attempt is allowed. */
62
+ private static readonly SNAPSHOT_ABORT_GRACE_MS;
61
63
  /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
62
64
  private static readonly SNAPSHOT_RETRY_BASE_MS;
63
65
  private static readonly SNAPSHOT_RETRY_MAX_MS;
64
66
  /** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
65
67
  private static readonly CHAIN_SYNC_RETRY_MS;
68
+ /** Wait before chain-sync is reopened after the node was found behind the cursor. */
69
+ private static readonly NODE_BEHIND_RETRY_MS;
70
+ /** Refused rollbacks that contradict the stored chain before the crawler halts with an error. */
71
+ private static readonly MAX_ROLLBACK_REFUSALS;
72
+ /** At most one node-behind warning per this interval; the rest go to debug. */
73
+ private static readonly NODE_BEHIND_LOG_MS;
66
74
  private running;
67
75
  private chainSyncHandle;
68
76
  /** What the ingest loop is currently reading from; null while stopped. */
@@ -84,6 +92,10 @@ export declare class CardanoCrawler {
84
92
  private frameFailure;
85
93
  /** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
86
94
  private reopenStream;
95
+ /** The stream ended on a refused rollback; the ingest loop retries later. */
96
+ private streamRefused;
97
+ private rollbackRefusals;
98
+ private nodeBehindLoggedAt;
87
99
  /** Blocks persisted by the current chain-sync stream. */
88
100
  private blocksThisStream;
89
101
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
@@ -101,6 +113,8 @@ export declare class CardanoCrawler {
101
113
  /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
102
114
  private snapshotedEpoch;
103
115
  private snapshotInFlight;
116
+ /** The snapshot work itself. It can outlive a timed-out attempt until it sees its abort flag. */
117
+ private snapshotWork;
104
118
  /** Consecutive snapshot failures and the earliest time the next attempt may run. */
105
119
  private snapshotFailures;
106
120
  private accountSnapshotWarned;
@@ -142,6 +156,12 @@ export declare class CardanoCrawler {
142
156
  /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
143
157
  private endStream;
144
158
  private buildIntersectionPoints;
159
+ private followsByronBoundary;
160
+ /** Blocks the node can roll back at most (Praos `k`). */
161
+ private securityParam;
162
+ private rollbackRefusal;
163
+ private waitForNode;
164
+ private refuseRollback;
145
165
  /** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
146
166
  private trackCallback;
147
167
  /** `untilHeight` returns once the cursor reaches it. `untilChainSync` returns once chain-sync is usable again. */
@@ -152,10 +172,11 @@ export declare class CardanoCrawler {
152
172
  private tryReorgRecovery;
153
173
  /** Persist one block atomically and advance the cursor. Returns false when the crawler stopped. */
154
174
  private persistBlock;
155
- /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
175
+ /** Epoch a slot belongs to, from the network's Shelley anchor. */
156
176
  private epochOfSlot;
157
177
  private maybeSnapshotEpoch;
158
178
  private maybeSnapshotAccounts;
179
+ private attemptWithTimeout;
159
180
  private handleReorg;
160
181
  /** Renew the lease while no block commits; block writes renew it transactionally. */
161
182
  private startLeaseHeartbeat;