@odatano/core 2.0.0-rc.21 → 2.0.0-rc.24

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 (45) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  2. package/@cds-models/CardanoBackendService/index.js +40 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +18 -0
  4. package/@cds-models/CardanoIndexerService/index.js +3 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +37 -0
  6. package/@cds-models/CardanoODataService/index.js +3 -0
  7. package/@cds-models/odatano/cardano/index.d.ts +37 -0
  8. package/@cds-models/odatano/cardano/index.js +3 -0
  9. package/db/schema.cds +2226 -2133
  10. package/package.json +182 -181
  11. package/srv/blockchain/backends/cardano-backend.d.ts +23 -0
  12. package/srv/blockchain/backends/cardano-backend.js +5 -0
  13. package/srv/blockchain/backends/odatano-backend.d.ts +59 -0
  14. package/srv/blockchain/backends/odatano-backend.js +154 -0
  15. package/srv/blockchain/backends/ogmios-backend.d.ts +92 -9
  16. package/srv/blockchain/backends/ogmios-backend.js +164 -32
  17. package/srv/blockchain/cardano-client.d.ts +19 -5
  18. package/srv/blockchain/cardano-client.js +53 -12
  19. package/srv/blockchain/cardano-indexer.d.ts +100 -4
  20. package/srv/blockchain/cardano-indexer.js +466 -23
  21. package/srv/blockchain/cardano-tx-builder.js +2 -2
  22. package/srv/blockchain/crawler/crawler.d.ts +20 -5
  23. package/srv/blockchain/crawler/crawler.js +78 -15
  24. package/srv/blockchain/crawler/utxo-set-import.js +3 -0
  25. package/srv/blockchain/ledger-state.d.ts +6 -0
  26. package/srv/blockchain/ledger-state.js +29 -0
  27. package/srv/blockchain/stored-chain.d.ts +30 -0
  28. package/srv/blockchain/stored-chain.js +208 -0
  29. package/srv/cardano-backend-service.cds +52 -0
  30. package/srv/cardano-backend-service.d.ts +2 -0
  31. package/srv/cardano-backend-service.js +217 -0
  32. package/srv/cardano-indexer-service.cds +176 -164
  33. package/srv/cardano-indexer-service.js +30 -0
  34. package/srv/cardano-service.cds +6 -1
  35. package/srv/cardano-service.js +5 -2
  36. package/srv/server.js +19 -2
  37. package/srv/utils/agent-grants.js +7 -0
  38. package/srv/utils/const.d.ts +4 -0
  39. package/srv/utils/const.js +4 -3
  40. package/srv/utils/db-indexes.js +1 -0
  41. package/srv/utils/errors.d.ts +8 -0
  42. package/srv/utils/errors.js +14 -1
  43. package/srv/utils/mappers.d.ts +19 -2
  44. package/srv/utils/mappers.js +25 -7
  45. package/srv/utils/types.d.ts +8 -1
@@ -0,0 +1,217 @@
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
+ const cds_1 = __importDefault(require("@sap/cds"));
7
+ const client_1 = require("@cardano-ogmios/client");
8
+ const backend_request_handler_1 = require("./utils/backend-request-handler");
9
+ const errors_1 = require("./utils/errors");
10
+ const validators_1 = require("./utils/validators");
11
+ const server_1 = require("./server");
12
+ const stored_chain_1 = require("./blockchain/stored-chain");
13
+ const logger = cds_1.default.log('CardanoBackendService');
14
+ /** Largest list one call may ask for (hashes, refs, ids, blocks). */
15
+ const MAX_LIST = 500;
16
+ const MAX_LIMIT = 1000;
17
+ /**
18
+ * CardanoBackendService: the provider shape for another ODATANO instance. Stored blocks and
19
+ * transactions come from the index; the rest goes through the indexer's resolvers (crawled data
20
+ * first, then this instance's backends). Answers are JSON strings (safeJSON keeps big integers).
21
+ */
22
+ module.exports = (srv) => {
23
+ const client = () => (0, server_1.getCardanoClient)();
24
+ const indexer = () => (0, server_1.getCardanoIndexer)();
25
+ /** Register an operation: validate, run, answer the JSON of the result. */
26
+ const op = (name, run, validate) => {
27
+ srv.on(name, async (req) => {
28
+ const data = (req.data ?? {});
29
+ validate?.(req, data);
30
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => client_1.safeJSON.stringify(toPlain(await run(data, db))));
31
+ });
32
+ };
33
+ // --- validation helpers ----------------------------------------------------------------------
34
+ const need = (check, field, what) => (req, data) => {
35
+ if (data[field] == null || data[field] === '')
36
+ (0, errors_1.rejectMissing)(req, req.event, field);
37
+ if (!check(data[field]))
38
+ (0, errors_1.rejectInvalid)(req, req.event, `Invalid ${what}`, field);
39
+ };
40
+ const both = (...checks) => (req, data) => checks.forEach(c => c(req, data));
41
+ const limitOf = (data, fallback) => Math.min(Math.max(Number(data.limit) || fallback, 1), MAX_LIMIT);
42
+ const jsonList = (field, check, what) => (req, data) => {
43
+ if (data[field] == null)
44
+ (0, errors_1.rejectMissing)(req, req.event, field);
45
+ let list;
46
+ try {
47
+ list = JSON.parse(String(data[field]));
48
+ }
49
+ catch {
50
+ (0, errors_1.rejectInvalid)(req, req.event, `${field} must be a JSON array`, field);
51
+ }
52
+ if (!Array.isArray(list) || list.length > MAX_LIST || !list.every(check)) {
53
+ (0, errors_1.rejectInvalid)(req, req.event, `${field} must be a JSON array of up to ${MAX_LIST} ${what}`, field);
54
+ }
55
+ data[field] = list;
56
+ };
57
+ const isRef = (r) => {
58
+ const ref = r;
59
+ return (0, validators_1.isTxHash)(ref?.txHash) && Number.isInteger(ref?.outputIndex) && Number(ref.outputIndex) >= 0;
60
+ };
61
+ // --- blocks and transactions -------------------------------------------------------------------
62
+ op('GetTransaction', async ({ hash }, db) => {
63
+ const stored = (await (0, stored_chain_1.readTransactionsByHash)(db, [String(hash)])).get(String(hash));
64
+ if (stored)
65
+ return stored;
66
+ await indexer().refuseOutsideCrawl(db, 'getTransaction', `Transaction ${hash}`);
67
+ return client().getTransaction(String(hash));
68
+ }, need(validators_1.isTxHash, 'hash', 'transaction hash'));
69
+ op('GetTransactionsBatch', async ({ hashes }, db) => {
70
+ const wanted = hashes;
71
+ const found = await (0, stored_chain_1.readTransactionsByHash)(db, wanted);
72
+ const missing = wanted.filter(h => !found.has(h));
73
+ if (missing.length && client().hasBackendFor('getTransactionsBatch')) {
74
+ for (const [h, t] of await client().getTransactionsBatch(missing))
75
+ found.set(h, t);
76
+ }
77
+ return found;
78
+ }, jsonList('hashes', validators_1.isTxHash, 'transaction hashes'));
79
+ op('GetTransactionMetadata', async ({ hash }, db) => {
80
+ const stored = await (0, stored_chain_1.readTransactionMetadata)(db, String(hash));
81
+ if (stored)
82
+ return stored;
83
+ await indexer().refuseOutsideCrawl(db, 'getTransactionMetadata', `Transaction ${hash}`);
84
+ return client().getTransactionMetadata(String(hash));
85
+ }, need(validators_1.isTxHash, 'hash', 'transaction hash'));
86
+ op('GetBlock', async ({ hash }, db) => {
87
+ const stored = await (0, stored_chain_1.readBlock)(db, String(hash));
88
+ if (stored)
89
+ return stored;
90
+ await indexer().refuseOutsideCrawl(db, 'getBlock', `Block ${hash}`);
91
+ return client().getBlock(String(hash));
92
+ }, need(validators_1.isBlockHash, 'hash', 'block hash'));
93
+ op('GetBlockByHeight', async ({ height }, db) => {
94
+ const stored = await (0, stored_chain_1.readBlockByHeight)(db, Number(height));
95
+ if (stored)
96
+ return stored;
97
+ const paging = client().getPaginatingBackend();
98
+ if (!paging)
99
+ throw new errors_1.ProviderUnavailableError(`Block at height ${height} is not indexed here`, 'odatano');
100
+ return paging.getBlockByHeight(Number(height));
101
+ }, need(v => Number.isInteger(Number(v)) && Number(v) >= 0, 'height', 'height'));
102
+ op('GetNextBlocks', async ({ afterHash, count, afterHeight }, db) => {
103
+ const n = Math.min(Math.max(Number(count) || 1, 1), MAX_LIST);
104
+ const anchor = await (0, stored_chain_1.readBlock)(db, String(afterHash));
105
+ if (anchor?.height != null) {
106
+ const next = await (0, stored_chain_1.readNextBlocks)(db, anchor.height, n);
107
+ if (next.length)
108
+ return next;
109
+ }
110
+ // Unknown cursor block where this chain has another block at that height: the caller's
111
+ // cursor was orphaned. The crawler recognises this prefix and enters reorg recovery.
112
+ if (!anchor && afterHeight != null) {
113
+ const canonical = await (0, stored_chain_1.readBlockByHeight)(db, Number(afterHeight));
114
+ if (canonical) {
115
+ throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} at height ${afterHeight} is no longer canonical (canonical block: ${canonical.hash})`, 'odatano');
116
+ }
117
+ }
118
+ const paging = client().getPaginatingBackend();
119
+ if (paging)
120
+ return paging.getNextBlocks(String(afterHash), n, afterHeight == null ? undefined : Number(afterHeight));
121
+ // Nothing indexed past the cursor yet: the caller is at this instance's tip.
122
+ if (anchor)
123
+ return [];
124
+ throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} is unknown to this instance`, 'odatano');
125
+ }, need(validators_1.isBlockHash, 'afterHash', 'block hash'));
126
+ op('GetBlockTransactions', async ({ blockHash }, db) => {
127
+ const stored = await (0, stored_chain_1.readBlockTransactions)(db, String(blockHash));
128
+ if (stored)
129
+ return stored;
130
+ const paging = client().getPaginatingBackend();
131
+ if (!paging)
132
+ throw new errors_1.ProviderUnavailableError(`Transactions of block ${blockHash} are not indexed here`, 'odatano');
133
+ return paging.getBlockTransactions(String(blockHash));
134
+ }, need(validators_1.isBlockHash, 'blockHash', 'block hash'));
135
+ op('GetLatestBlock', async () => client().getLatestBlock());
136
+ op('GetCurrentSlot', async () => client().getCurrentSlot());
137
+ op('GetEpoch', async ({ epoch }) => client().getEpoch(Number(epoch)), need(validators_1.isEpochNumber, 'epoch', 'epoch number'));
138
+ op('GetLatestEpoch', async () => client().getLatestEpoch());
139
+ // --- addresses and UTxOs -------------------------------------------------------------------------
140
+ const address = need(validators_1.isValidBech32Address, 'address', 'bech32 address');
141
+ op('GetAddress', async ({ address: a }, db) => indexer().resolveAddress(db, String(a)), address);
142
+ op('GetAddressUtxos', async ({ address: a }, db) => indexer().resolveAddressUtxos(db, String(a)), address);
143
+ op('GetAddressTransactionHashes', async (data, db) => indexer().resolveAddressTransactionHashes(db, String(data.address), limitOf(data, 10)), address);
144
+ op('GetAddressTransactions', async (data, db) => {
145
+ const hashes = await indexer().resolveAddressTransactionHashes(db, String(data.address), limitOf(data, 10));
146
+ const found = await (0, stored_chain_1.readTransactionsByHash)(db, hashes);
147
+ const missing = hashes.filter(h => !found.has(h));
148
+ if (missing.length)
149
+ for (const [h, t] of await client().getTransactionsBatch(missing))
150
+ found.set(h, t);
151
+ return hashes.map(h => found.get(h)).filter(Boolean);
152
+ }, address);
153
+ op('GetCredentialUtxos', async ({ credential }, db) => indexer().resolveCredentialUtxos(db, String(credential)), need(validators_1.isValidCredential, 'credential', 'payment credential'));
154
+ op('IsUtxoUnspent', async ({ txHash, outputIndex }) => client().isUtxoUnspent(String(txHash), Number(outputIndex)), both(need(validators_1.isTxHash, 'txHash', 'transaction hash'), need(v => Number.isInteger(Number(v)) && Number(v) >= 0, 'outputIndex', 'output index')));
155
+ op('GetUnspentOutputs', async ({ refs }) => {
156
+ const found = await client().getUnspentOutputs(refs);
157
+ if (found == null)
158
+ throw new errors_1.ProviderUnavailableError('Output lookup needs a ledger-state backend (Ogmios)', 'odatano');
159
+ return found;
160
+ }, jsonList('refs', isRef, 'output references'));
161
+ // --- stake, governance, assets, network ------------------------------------------------------
162
+ op('GetAccount', async ({ stakeAddress }, db) => indexer().resolveAccount(db, String(stakeAddress)), need(validators_1.isValidBech32StakeAddress, 'stakeAddress', 'stake address'));
163
+ op('GetPool', async ({ poolId }, db) => indexer().resolvePool(db, String(poolId)), need(validators_1.isValidPoolId, 'poolId', 'pool id'));
164
+ op('GetDrep', async ({ drepId }) => client().getDrep(String(drepId)), need(validators_1.isValidDrepId, 'drepId', 'DRep id'));
165
+ op('GetPoolIds', async () => (await enumeration()).pools.map(p => p.poolId));
166
+ op('GetPools', async ({ ids }) => {
167
+ const wanted = new Set(ids);
168
+ return (await enumeration()).pools.filter(p => wanted.has(p.poolId));
169
+ }, jsonList('ids', validators_1.isValidPoolId, 'pool ids'));
170
+ op('GetDrepIds', async () => (await enumeration()).dreps.map(d => d.drepId));
171
+ op('GetDreps', async ({ ids }) => {
172
+ const wanted = new Set(ids);
173
+ return (await enumeration()).dreps.filter(d => wanted.has(d.drepId));
174
+ }, jsonList('ids', validators_1.isValidDrepId, 'DRep ids'));
175
+ op('GetAssetInfo', async ({ unit }, db) => indexer().resolveAssetInfo(db, String(unit)), need(validators_1.isAssetUnit, 'unit', 'asset unit'));
176
+ op('GetAssetHistory', async (data, db) => indexer().resolveAssetHistory(db, String(data.unit), limitOf(data, 100)), need(validators_1.isAssetUnit, 'unit', 'asset unit'));
177
+ op('GetNetworkInformation', async (_data, db) => indexer().resolveNetworkInformation(db));
178
+ op('GetProtocolParameters', async () => client().getProtocolParameters());
179
+ // --- transactions in flight ------------------------------------------------------------------
180
+ const cbor = need(validators_1.isValidCbor, 'cbor', 'CBOR hex');
181
+ op('EvaluateTransaction', async ({ cbor: c }) => client().evaluateTransaction(String(c)), cbor);
182
+ op('SubmitTransaction', async ({ cbor: c }) => {
183
+ const hash = await client().submitTransaction(String(c));
184
+ logger.info(`submitted ${hash} for a remote instance`);
185
+ return hash;
186
+ }, cbor);
187
+ /**
188
+ * The full pool and DRep set: an enumerating backend (Koios) when configured, else the node's
189
+ * ledger at the latest block (Ogmios). Cached for a minute; callers page through it by id.
190
+ */
191
+ let enumerated = null;
192
+ async function enumeration() {
193
+ if (enumerated && Date.now() - enumerated.at < 60_000)
194
+ return enumerated;
195
+ const koios = client().getEnumeratingBackend();
196
+ if (koios) {
197
+ const [pools, dreps] = await Promise.all([
198
+ koios.getPoolIds().then(ids => koios.getPools(ids)),
199
+ koios.getDrepIds().then(ids => koios.getDreps(ids)),
200
+ ]);
201
+ enumerated = { at: Date.now(), pools, dreps };
202
+ return enumerated;
203
+ }
204
+ const ledger = client().getEpochStateBackend();
205
+ if (!ledger)
206
+ throw new errors_1.ProviderUnavailableError('Pool/DRep enumeration needs Ogmios or Koios', 'odatano');
207
+ const tip = await client().getLatestBlock();
208
+ const state = await ledger.epochStateAt({ slot: tip.slot ?? 0, hash: tip.hash });
209
+ enumerated = { at: Date.now(), pools: state.pools, dreps: state.dreps };
210
+ return enumerated;
211
+ }
212
+ };
213
+ /** Maps become objects, so a batch answer survives JSON. */
214
+ function toPlain(value) {
215
+ return value instanceof Map ? Object.fromEntries(value) : value;
216
+ }
217
+ //# sourceMappingURL=cardano-backend-service.js.map
@@ -1,164 +1,176 @@
1
- using {odatano.cardano as db} from '../db/schema';
2
-
3
- /**
4
- * Cardano Indexer Service (v2.0)
5
- *
6
- * Control + observability surface for the chain crawler / pre-sync engine:
7
- * - read-only projections of the sync cursor and reorg audit log
8
- * - status function + pause/resume actions delegating to the crawler singleton
9
- *
10
- * Security note: see CardanoODataService (cardano-service.cds) for the rationale on
11
- * auth. pause/resume are operational actions — gate behind a dedicated Admin scope.
12
- * Read-only status and audit data remain available to authenticated users.
13
- *
14
- * Deliberately NO service-level @requires: CAP checks a service-level requirement
15
- * on every request BEFORE the operation's own annotation, so an operation-level
16
- * `@requires: 'any'` can never open a single function on an otherwise
17
- * authenticated service (anonymous callers get the 401 challenge first). The
18
- * requirement therefore sits on each element, and getLiveness() alone is 'any'.
19
- */
20
- // Service-level 'any' on purpose: CAP authorizes the service BEFORE the operation and
21
- // treats a service without a service-level @requires as authenticated-user under
22
- // NODE_ENV=production, which would 401 the anonymous operation below despite its own
23
- // 'any'. Every element carries its requirement; the service itself refuses nothing.
24
- @requires: 'any'
25
- service CardanoIndexerService @(impl: './cardano-indexer-service') {
26
-
27
- @readonly
28
- @requires : 'authenticated-user'
29
- @title : 'Sync State'
30
- @description: 'Singleton crawl cursor — pre-sync progress, tip lag, status, errors'
31
- entity SyncState as projection on db.CardanoSyncState;
32
-
33
- @readonly
34
- @requires : 'authenticated-user'
35
- @title : 'Reorg Log'
36
- @description: 'Audit trail of chain rollbacks handled by the crawler'
37
- entity ReorgLog as projection on db.CardanoReorgLog;
38
-
39
- @title : 'Crawler Status'
40
- @description: 'Live crawler status summary (numeric fields as strings, CAP-10 aligned)'
41
- type CrawlerStatus {
42
- running : Boolean;
43
- syncStatus : String;
44
- // 'chain-sync' | 'pagination' for the crawler in this process; null when this
45
- // instance is not the one crawling. Pagination is ~50x slower, and a crawl that
46
- // degraded to it still advances the cursor — this is how an operator tells.
47
- source : String;
48
- lastSlot : String;
49
- lastHeight : String;
50
- tipHeight : String;
51
- syncProgress : String;
52
- consecutiveErrors : Integer;
53
- // crawler-fed ledger state (crawler.utxoSet): snapshot anchor + validity
54
- utxoSet : UtxoSetStatus;
55
- // one-off certificate/withdrawal backfill over already crawled blocks (this process)
56
- certificateBackfill : CertificateBackfillStatus;
57
- }
58
-
59
- @title : 'Certificate Backfill Status'
60
- @description: 'Progress of the certificate/withdrawal backfill started with backfillCertificates; process-local, none after a restart'
61
- type CertificateBackfillStatus {
62
- status : String; // none | running | done | failed
63
- fromSlot : String;
64
- toSlot : String;
65
- atSlot : String; // last slot handled
66
- blocks : Integer64;
67
- certificates : Integer64;
68
- withdrawals : Integer64;
69
- startedAt : Timestamp;
70
- finishedAt : Timestamp;
71
- error : String;
72
- }
73
-
74
- @title : 'Certificate Backfill Result'
75
- type CertificateBackfillResult {
76
- accepted : Boolean;
77
- fromSlot : String;
78
- toSlot : String;
79
- message : String;
80
- }
81
-
82
- @title : 'UTxO Set Status'
83
- @description: 'State of the crawler-maintained UTxO set (crawler.utxoSet)'
84
- type UtxoSetStatus {
85
- enabled : Boolean; // crawler.utxoSet configured
86
- status : String; // none | importing | active | invalid
87
- anchorSlot : String; // null until imported
88
- anchorHash : String;
89
- importedAt : Timestamp;
90
- error : String; // why invalid
91
- }
92
-
93
- @title : 'UTxO Set Import Result'
94
- type UtxoSetImportResult {
95
- accepted : Boolean;
96
- anchorSlot : String;
97
- anchorHash : String;
98
- message : String;
99
- }
100
-
101
- @title : 'Get Crawler Status'
102
- @description: 'Return the current crawler run state and sync progress'
103
- /**
104
- * Emitted AFTER each block is committed. Subscribe instead of polling:
105
- * (await cds.connect.to('CardanoIndexerService')).on('blockIndexed', ({ data }) => …)
106
- * In-process (plugin mode) this needs no messaging service.
107
- */
108
- event blockIndexed {
109
- hash : String(64);
110
- slot : Integer64;
111
- height : Integer64;
112
- txHashes : many String(64);
113
- tipSlot : Integer64;
114
- tipHeight: Integer64;
115
- }
116
-
117
- /** Emitted AFTER a rollback is committed. Everything above `forkSlot` was removed. */
118
- event reorg {
119
- forkSlot : Integer64;
120
- forkHeight : Integer64;
121
- blocksRolledBack : Integer;
122
- }
123
-
124
- @requires : 'authenticated-user'
125
- function getStatus() returns CrawlerStatus;
126
-
127
- @title : 'Liveness'
128
- type Liveness {
129
- status : String; // 'alive'
130
- timestamp : Timestamp;
131
- uptime : Integer; // seconds since process start
132
- version : String; // @odatano/core version
133
- network : String; // configured network
134
- }
135
-
136
- // Anonymous on purpose: a liveness probe carries no credentials. 200 as long
137
- // as the process answers — no backend or DB probe, no secrets, no backend
138
- // names, no API key state. Readiness stays with getStatus and the worker
139
- // status, which remain authenticated.
140
- @title : 'Get Liveness'
141
- @description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
142
- @requires : 'any'
143
- function getLiveness() returns Liveness;
144
-
145
- @title : 'Pause Crawler'
146
- @description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
147
- @requires : 'Admin'
148
- action pauseCrawler() returns Boolean;
149
-
150
- @title : 'Resume Crawler'
151
- @description: 'Start/restart the crawler from the persisted cursor using the configured source.'
152
- @requires : 'Admin'
153
- action resumeCrawler() returns Boolean;
154
-
155
- @title : 'Import UTxO Set'
156
- @description: 'One-off import of the UTxO set that anchors crawler.utxoSet. Pause the crawler first. source=ogmios acquires the set at the crawler cursor (crawl must be at the tip); source=file loads a cardano-cli query utxo --whole-utxo dump (.json, or .ndjson from jq -c to_entries[]) taken at anchorSlot/anchorHash. Runs in the background; progress via getStatus().utxoSet.'
157
- @requires : 'Admin'
158
- action importUtxoSet(source: String, filePath: String, anchorSlot: Integer64, anchorHash: String) returns UtxoSetImportResult;
159
-
160
- @title : 'Backfill Certificates'
161
- @description: 'Fill TransactionCertificates and TransactionWithdrawals for blocks the crawl already holds, from a second chain-sync stream (Ogmios). fromSlot defaults to the crawl start, toSlot to the cursor. Writes only those two tables; the crawler may keep running. Runs in the background; progress via getStatus().certificateBackfill.'
162
- @requires : 'Admin'
163
- action backfillCertificates(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
164
- }
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ /**
4
+ * Cardano Indexer Service (v2.0)
5
+ *
6
+ * Control + observability surface for the chain crawler / pre-sync engine:
7
+ * - read-only projections of the sync cursor and reorg audit log
8
+ * - status function + pause/resume actions delegating to the crawler singleton
9
+ *
10
+ * Security note: see CardanoODataService (cardano-service.cds) for the rationale on
11
+ * auth. pause/resume are operational actions — gate behind a dedicated Admin scope.
12
+ * Read-only status and audit data remain available to authenticated users.
13
+ *
14
+ * Deliberately NO service-level @requires: CAP checks a service-level requirement
15
+ * on every request BEFORE the operation's own annotation, so an operation-level
16
+ * `@requires: 'any'` can never open a single function on an otherwise
17
+ * authenticated service (anonymous callers get the 401 challenge first). The
18
+ * requirement therefore sits on each element, and getLiveness() alone is 'any'.
19
+ */
20
+ // Service-level 'any' on purpose: CAP authorizes the service BEFORE the operation and
21
+ // treats a service without a service-level @requires as authenticated-user under
22
+ // NODE_ENV=production, which would 401 the anonymous operation below despite its own
23
+ // 'any'. Every element carries its requirement; the service itself refuses nothing.
24
+ @requires: 'any'
25
+ service CardanoIndexerService @(impl: './cardano-indexer-service') {
26
+
27
+ @readonly
28
+ @requires : 'authenticated-user'
29
+ @title : 'Sync State'
30
+ @description: 'Singleton crawl cursor — pre-sync progress, tip lag, status, errors'
31
+ entity SyncState as projection on db.CardanoSyncState;
32
+
33
+ @readonly
34
+ @requires : 'authenticated-user'
35
+ @title : 'Reorg Log'
36
+ @description: 'Audit trail of chain rollbacks handled by the crawler'
37
+ entity ReorgLog as projection on db.CardanoReorgLog;
38
+
39
+ @title : 'Crawler Status'
40
+ @description: 'Live crawler status summary (numeric fields as strings, CAP-10 aligned)'
41
+ type CrawlerStatus {
42
+ running : Boolean;
43
+ syncStatus : String;
44
+ // 'chain-sync' | 'pagination' for the crawler in this process; null when this
45
+ // instance is not the one crawling. Pagination is ~50x slower, and a crawl that
46
+ // degraded to it still advances the cursor — this is how an operator tells.
47
+ source : String;
48
+ lastSlot : String;
49
+ lastHeight : String;
50
+ tipHeight : String;
51
+ syncProgress : String;
52
+ consecutiveErrors : Integer;
53
+ // crawler-fed ledger state (crawler.utxoSet): snapshot anchor + validity
54
+ utxoSet : UtxoSetStatus;
55
+ // one-off certificate/withdrawal backfill over already crawled blocks (this process)
56
+ certificateBackfill : CertificateBackfillStatus;
57
+ // per-epoch pool/DRep/pot snapshots (crawler.epochSnapshots)
58
+ epochSnapshots : EpochSnapshotStatus;
59
+ }
60
+
61
+ @title : 'Epoch Snapshot Status'
62
+ @description: 'Latest epoch snapshot and the source this process would use for the next one'
63
+ type EpochSnapshotStatus {
64
+ enabled : Boolean; // crawler.epochSnapshots configured
65
+ source : String; // ogmios | koios | null (no usable backend)
66
+ lastEpoch : Integer; // newest snapshotted epoch; null before the first
67
+ lastSource: String; // source of that snapshot
68
+ lastSlot : String; // block it was taken at
69
+ }
70
+
71
+ @title : 'Certificate Backfill Status'
72
+ @description: 'Progress of the certificate/withdrawal backfill started with backfillCertificates; process-local, none after a restart'
73
+ type CertificateBackfillStatus {
74
+ status : String; // none | running | done | failed
75
+ fromSlot : String;
76
+ toSlot : String;
77
+ atSlot : String; // last slot handled
78
+ blocks : Integer64;
79
+ certificates : Integer64;
80
+ withdrawals : Integer64;
81
+ startedAt : Timestamp;
82
+ finishedAt : Timestamp;
83
+ error : String;
84
+ }
85
+
86
+ @title : 'Certificate Backfill Result'
87
+ type CertificateBackfillResult {
88
+ accepted : Boolean;
89
+ fromSlot : String;
90
+ toSlot : String;
91
+ message : String;
92
+ }
93
+
94
+ @title : 'UTxO Set Status'
95
+ @description: 'State of the crawler-maintained UTxO set (crawler.utxoSet)'
96
+ type UtxoSetStatus {
97
+ enabled : Boolean; // crawler.utxoSet configured
98
+ status : String; // none | importing | active | invalid
99
+ anchorSlot : String; // null until imported
100
+ anchorHash : String;
101
+ importedAt : Timestamp;
102
+ error : String; // why invalid
103
+ }
104
+
105
+ @title : 'UTxO Set Import Result'
106
+ type UtxoSetImportResult {
107
+ accepted : Boolean;
108
+ anchorSlot : String;
109
+ anchorHash : String;
110
+ message : String;
111
+ }
112
+
113
+ @title : 'Get Crawler Status'
114
+ @description: 'Return the current crawler run state and sync progress'
115
+ /**
116
+ * Emitted AFTER each block is committed. Subscribe instead of polling:
117
+ * (await cds.connect.to('CardanoIndexerService')).on('blockIndexed', ({ data }) => …)
118
+ * In-process (plugin mode) this needs no messaging service.
119
+ */
120
+ event blockIndexed {
121
+ hash : String(64);
122
+ slot : Integer64;
123
+ height : Integer64;
124
+ txHashes : many String(64);
125
+ tipSlot : Integer64;
126
+ tipHeight: Integer64;
127
+ }
128
+
129
+ /** Emitted AFTER a rollback is committed. Everything above `forkSlot` was removed. */
130
+ event reorg {
131
+ forkSlot : Integer64;
132
+ forkHeight : Integer64;
133
+ blocksRolledBack : Integer;
134
+ }
135
+
136
+ @requires : 'authenticated-user'
137
+ function getStatus() returns CrawlerStatus;
138
+
139
+ @title : 'Liveness'
140
+ type Liveness {
141
+ status : String; // 'alive'
142
+ timestamp : Timestamp;
143
+ uptime : Integer; // seconds since process start
144
+ version : String; // @odatano/core version
145
+ network : String; // configured network
146
+ }
147
+
148
+ // Anonymous on purpose: a liveness probe carries no credentials. 200 as long
149
+ // as the process answers — no backend or DB probe, no secrets, no backend
150
+ // names, no API key state. Readiness stays with getStatus and the worker
151
+ // status, which remain authenticated.
152
+ @title : 'Get Liveness'
153
+ @description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
154
+ @requires : 'any'
155
+ function getLiveness() returns Liveness;
156
+
157
+ @title : 'Pause Crawler'
158
+ @description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
159
+ @requires : 'Admin'
160
+ action pauseCrawler() returns Boolean;
161
+
162
+ @title : 'Resume Crawler'
163
+ @description: 'Start/restart the crawler from the persisted cursor using the configured source.'
164
+ @requires : 'Admin'
165
+ action resumeCrawler() returns Boolean;
166
+
167
+ @title : 'Import UTxO Set'
168
+ @description: 'One-off import of the UTxO set that anchors crawler.utxoSet. Pause the crawler first. source=ogmios acquires the set at the crawler cursor (crawl must be at the tip); source=file loads a cardano-cli query utxo --whole-utxo dump (.json, or .ndjson from jq -c to_entries[]) taken at anchorSlot/anchorHash. Runs in the background; progress via getStatus().utxoSet.'
169
+ @requires : 'Admin'
170
+ action importUtxoSet(source: String, filePath: String, anchorSlot: Integer64, anchorHash: String) returns UtxoSetImportResult;
171
+
172
+ @title : 'Backfill Certificates'
173
+ @description: 'Fill TransactionCertificates and TransactionWithdrawals for blocks the crawl already holds, from a second chain-sync stream (Ogmios). fromSlot defaults to the crawl start, toSlot to the cursor. Writes only those two tables; the crawler may keep running. Runs in the background; progress via getStatus().certificateBackfill.'
174
+ @requires : 'Admin'
175
+ action backfillCertificates(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
176
+ }
@@ -13,6 +13,8 @@ const certificate_backfill_1 = require("./blockchain/crawler/certificate-backfil
13
13
  const validators_1 = require("./utils/validators");
14
14
  const server_1 = require("./server");
15
15
  const liveness_1 = require("./utils/liveness");
16
+ const cardano_1 = require("#cds-models/odatano/cardano");
17
+ const { SELECT } = cds_1.default.ql;
16
18
  const logger = cds_1.default.log('CardanoIndexerService');
17
19
  /** One import at a time per process; the promise is only used as the busy flag. */
18
20
  let utxoSetImportInFlight = null;
@@ -30,6 +32,26 @@ function utxoSetConfigured() {
30
32
  return false;
31
33
  }
32
34
  }
35
+ function epochSnapshotsConfigured() {
36
+ try {
37
+ return Boolean((0, server_1.loadCrawlerConfigFromEnv)()?.epochSnapshots);
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ /** Source the next epoch snapshot would use: the node's ledger first, Koios second. */
44
+ function epochSnapshotSource() {
45
+ try {
46
+ const client = (0, server_1.getCardanoClient)();
47
+ if (client.getEpochStateBackend())
48
+ return 'ogmios';
49
+ return client.getEnumeratingBackend() ? 'koios' : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
33
55
  /**
34
56
  * CardanoIndexerService handlers: control/observability surface over the crawler
35
57
  * singleton (srv/blockchain/crawler). Reads the cursor and starts/stops the crawler.
@@ -41,6 +63,7 @@ module.exports = (srv) => {
41
63
  srv.on('getStatus', async (req) => {
42
64
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
43
65
  const cursor = await (0, sync_state_1.readCursor)(db);
66
+ const lastSnapshot = await db.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch', 'source', 'snapshotSlot').orderBy('epoch desc'));
44
67
  const lastHeight = cursor?.lastHeight ?? 0;
45
68
  const tipHeight = cursor?.tipHeight ?? 0;
46
69
  const progress = tipHeight > 0 ? Math.min(100, (lastHeight / tipHeight) * 100) : 0;
@@ -74,6 +97,13 @@ module.exports = (srv) => {
74
97
  finishedAt: certificateBackfill.finishedAt,
75
98
  error: certificateBackfill.error,
76
99
  },
100
+ epochSnapshots: {
101
+ enabled: epochSnapshotsConfigured(),
102
+ source: epochSnapshotSource(),
103
+ lastEpoch: lastSnapshot?.epoch ?? null,
104
+ lastSource: lastSnapshot?.source ?? null,
105
+ lastSlot: lastSnapshot?.snapshotSlot == null ? null : String(lastSnapshot.snapshotSlot),
106
+ },
77
107
  };
78
108
  });
79
109
  });
@@ -72,6 +72,11 @@ service CardanoODataService @(impl: './cardano-service') {
72
72
  @description: 'Projection for per-epoch DRep snapshots written by the chain crawler'
73
73
  entity DrepEpochSnapshots as projection on db.DrepEpochSnapshots;
74
74
 
75
+ @readonly
76
+ @title : 'Epoch Ledger Snapshots'
77
+ @description: 'Projection for per-epoch network ledger figures written by the chain crawler'
78
+ entity EpochLedgerSnapshots as projection on db.EpochLedgerSnapshots;
79
+
75
80
  @readonly
76
81
  @title : 'Assets'
77
82
  @description: 'Projection for Native-Asset Information'
@@ -270,7 +275,7 @@ service CardanoODataService @(impl: './cardano-service') {
270
275
  address: Bech32) returns many AddressUTxOs;
271
276
 
272
277
  @title : 'Get UTxOs by Payment Credential'
273
- @description: 'Retrieve UTxOs across all bech32 addresses sharing the given 28-byte payment credential (key hash or script hash). Useful for protocols that write to multiple bech32 forms of the same script (e.g. Indigo CDPs, Liqwid positions). Koios-only — throws ProviderUnavailableError on deployments without Koios. Always fresh, no cache check.'
278
+ @description: 'Retrieve UTxOs across all bech32 addresses sharing the given 28-byte payment credential (key hash or script hash). Useful for protocols that write to multiple bech32 forms of the same script (e.g. Indigo CDPs, Liqwid positions). Served from the crawled UTxO set (crawler.utxoSet active and synced) with outputs read from the node at the tip, else from Koios; throws ProviderUnavailableError when neither is available. Always fresh, no cache check.'
274
279
  action GetUTxOsByCredential(
275
280
  @title: 'Payment Credential'
276
281
  @description: '28-byte payment credential hash as 56-char lowercase hex string'